diff --git a/AUTHORS.txt b/AUTHORS.txt index 9deb3eaa9..5bf04b70d 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -1,5 +1,5 @@ -# This file is an addendum to the Chromium AUTHORS file. -# Names should be added to this file like so: -# Name or Organization - +# This file is an addendum to the Chromium AUTHORS file. +# Names should be added to this file like so: +# Name or Organization + Marshall Greenblatt \ No newline at end of file diff --git a/DEPS b/DEPS index 8c0cccb54..6d16a0cec 100644 --- a/DEPS +++ b/DEPS @@ -1,7 +1,7 @@ -hooks = [ - { - # A change to a .gyp, .gypi, or to GYP itself should run the generator. - "pattern": ".", - "action": ["cd", "src\cef", "&", "call", "cef_create_projects.bat", "&", "cd", "..\.."], - }, -] +hooks = [ + { + # A change to a .gyp, .gypi, or to GYP itself should run the generator. + "pattern": ".", + "action": ["cd", "src\cef", "&", "call", "cef_create_projects.bat", "&", "cd", "..\.."], + }, +] diff --git a/LICENSE.txt b/LICENSE.txt index 70a894119..1da80e4cf 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,29 +1,29 @@ -// Copyright (c) 2008-2009 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. +// Copyright (c) 2008-2009 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/cef.gyp b/cef.gyp index 307b8ce98..9d0d1ad1c 100644 --- a/cef.gyp +++ b/cef.gyp @@ -1,414 +1,414 @@ -# 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. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - 'target_name': 'cefclient', - 'type': 'executable', - 'msvs_guid': '6617FED9-C5D4-4907-BF55-A90062A6683F', - 'dependencies': [ - '../third_party/npapi/npapi.gyp:npapi', - 'libcef', - 'libcef_dll_wrapper', - ], - 'defines': [ - 'USING_CEF_SHARED', - ], - 'include_dirs': [ - '.', - '..', - ], - 'sources': [ - 'tests/cefclient/Resource.h', - 'tests/cefclient/binding_test.cpp', - 'tests/cefclient/binding_test.h', - 'tests/cefclient/cefclient.cpp', - 'tests/cefclient/cefclient.h', - 'tests/cefclient/cefclient.ico', - 'tests/cefclient/cefclient.rc', - 'tests/cefclient/clientplugin.cpp', - 'tests/cefclient/clientplugin.h', - 'tests/cefclient/extension_test.cpp', - 'tests/cefclient/extension_test.h', - 'tests/cefclient/plugin_test.cpp', - 'tests/cefclient/plugin_test.h', - 'tests/cefclient/res/cefclient.ico', - 'tests/cefclient/res/logo.jpg', - 'tests/cefclient/res/logoball.jpg', - 'tests/cefclient/res/small.ico', - 'tests/cefclient/res/uiplugin.html', - 'tests/cefclient/resource_util.cpp', - 'tests/cefclient/resource_util.h', - 'tests/cefclient/scheme_test.cpp', - 'tests/cefclient/scheme_test.h', - 'tests/cefclient/string_util.cpp', - 'tests/cefclient/string_util.h', - 'tests/cefclient/uiplugin.cpp', - 'tests/cefclient/uiplugin.h', - 'tests/cefclient/uiplugin_test.cpp', - 'tests/cefclient/uiplugin_test.h', - ], - 'link_settings': { - 'libraries': [ - '-lcomctl32.lib', - '-lshlwapi.lib', - '-lrpcrt4.lib', - '-lopengl32.lib', - '-lglu32.lib', - ], - }, - 'conditions': [ - ['OS=="win"', { - 'msvs_settings': { - 'VCLinkerTool': { - # Set /SUBSYSTEM:WINDOWS. - 'SubSystem': '2', - 'EntryPointSymbol' : 'wWinMainCRTStartup', - }, - }, - }], - ], - }, - { - 'target_name': 'cef_unittests', - 'type': 'executable', - 'msvs_guid': '8500027C-B11A-11DE-A16E-B80256D89593', - 'dependencies': [ - '../base/base.gyp:base', - '../base/base.gyp:base_i18n', - '../base/base.gyp:test_support_base', - '../testing/gtest.gyp:gtest', +# 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. + +{ + 'variables': { + 'chromium_code': 1, + }, + 'targets': [ + { + 'target_name': 'cefclient', + 'type': 'executable', + 'msvs_guid': '6617FED9-C5D4-4907-BF55-A90062A6683F', + 'dependencies': [ + '../third_party/npapi/npapi.gyp:npapi', + 'libcef', + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + '..', + ], + 'sources': [ + 'tests/cefclient/Resource.h', + 'tests/cefclient/binding_test.cpp', + 'tests/cefclient/binding_test.h', + 'tests/cefclient/cefclient.cpp', + 'tests/cefclient/cefclient.h', + 'tests/cefclient/cefclient.ico', + 'tests/cefclient/cefclient.rc', + 'tests/cefclient/clientplugin.cpp', + 'tests/cefclient/clientplugin.h', + 'tests/cefclient/extension_test.cpp', + 'tests/cefclient/extension_test.h', + 'tests/cefclient/plugin_test.cpp', + 'tests/cefclient/plugin_test.h', + 'tests/cefclient/res/cefclient.ico', + 'tests/cefclient/res/logo.jpg', + 'tests/cefclient/res/logoball.jpg', + 'tests/cefclient/res/small.ico', + 'tests/cefclient/res/uiplugin.html', + 'tests/cefclient/resource_util.cpp', + 'tests/cefclient/resource_util.h', + 'tests/cefclient/scheme_test.cpp', + 'tests/cefclient/scheme_test.h', + 'tests/cefclient/string_util.cpp', + 'tests/cefclient/string_util.h', + 'tests/cefclient/uiplugin.cpp', + 'tests/cefclient/uiplugin.h', + 'tests/cefclient/uiplugin_test.cpp', + 'tests/cefclient/uiplugin_test.h', + ], + 'link_settings': { + 'libraries': [ + '-lcomctl32.lib', + '-lshlwapi.lib', + '-lrpcrt4.lib', + '-lopengl32.lib', + '-lglu32.lib', + ], + }, + 'conditions': [ + ['OS=="win"', { + 'msvs_settings': { + 'VCLinkerTool': { + # Set /SUBSYSTEM:WINDOWS. + 'SubSystem': '2', + 'EntryPointSymbol' : 'wWinMainCRTStartup', + }, + }, + }], + ], + }, + { + 'target_name': 'cef_unittests', + 'type': 'executable', + 'msvs_guid': '8500027C-B11A-11DE-A16E-B80256D89593', + 'dependencies': [ + '../base/base.gyp:base', + '../base/base.gyp:base_i18n', + '../base/base.gyp:test_support_base', + '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', - 'libcef', - 'libcef_dll_wrapper', - ], - 'sources': [ - 'tests/unittests/request_unittest.cc', - 'tests/unittests/run_all_unittests.cc', - 'tests/unittests/stream_unittest.cc', - 'tests/unittests/test_handler.h', - 'tests/unittests/test_suite.h', - 'tests/unittests/v8_unittest.cc', - ], - 'include_dirs': [ - '.', - '..', - ], - }, - { - 'target_name': 'patcher', - 'type': 'none', - 'msvs_guid': 'A6D0953E-899E-4C60-AB6B-CAE75A44B8E6', - 'actions': [ - { - 'action_name': 'patch_source', - 'msvs_cygwin_shell': 0, - 'inputs': [ - 'tools/patch_source.bat', - ], - 'outputs': [ - 'tools/patch_source.bat.output', - ], - 'action': ['', '<@(_inputs)'], - }, - ], - }, - { - 'target_name': 'libcef', - 'type': 'shared_library', - 'msvs_guid': 'C13650D5-CF1A-4259-BE45-B1EBA6280E47', - 'dependencies': [ - '../app/app.gyp:app_base', - '../base/base.gyp:base', - '../base/base.gyp:base_i18n', - '../breakpad/breakpad.gyp:breakpad_handler', - '../build/temp_gyp/googleurl.gyp:googleurl', - '../gfx/gfx.gyp:gfx', - '../media/media.gyp:media', - '../net/net.gyp:net', - '../net/net.gyp:net_resources', - '../printing/printing.gyp:printing', - '../sdch/sdch.gyp:sdch', - '../skia/skia.gyp:skia', - '../third_party/bzip2/bzip2.gyp:bzip2', - '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', - '../third_party/icu/icu.gyp:icui18n', - '../third_party/icu/icu.gyp:icuuc', - '../third_party/libjpeg/libjpeg.gyp:libjpeg', - '../third_party/libpng/libpng.gyp:libpng', - '../third_party/libxslt/libxslt.gyp:libxslt', - '../third_party/mesa/mesa.gyp:osmesa', - '../third_party/modp_b64/modp_b64.gyp:modp_b64', - '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:pcre', - '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:wtf', - '../third_party/WebKit/WebCore/WebCore.gyp/WebCore.gyp:webcore', - '../third_party/WebKit/WebKit/chromium/WebKit.gyp:webkit', - '../third_party/zlib/zlib.gyp:zlib', - '../webkit/support/webkit_support.gyp:appcache', - '../webkit/support/webkit_support.gyp:blob', - '../webkit/support/webkit_support.gyp:database', - '../webkit/support/webkit_support.gyp:fileapi', - '../webkit/support/webkit_support.gyp:glue', - '../webkit/support/webkit_support.gyp:webkit_resources', - '../webkit/support/webkit_support.gyp:webkit_strings', - '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': [ - '$(OutDir)/obj/global_intermediate/webkit/webkit_resources.rc', - '$(OutDir)/obj/global_intermediate/webkit/webkit_strings_en-US.rc', - 'include/cef.h', - 'include/cef_capi.h', - 'include/cef_export.h', - 'include/cef_nplugin.h', - 'include/cef_nplugin_capi.h', - 'include/cef_ptr.h', - 'include/cef_string.h', - 'include/cef_string_list.h', - 'include/cef_string_map.h', - 'include/cef_types.h', - 'include/cef_types_win.h', - 'include/cef_win.h', - 'libcef_dll/cef_logging.h', - 'libcef_dll/cpptoc/browser_cpptoc.cc', - 'libcef_dll/cpptoc/browser_cpptoc.h', - 'libcef_dll/cpptoc/cpptoc.h', - 'libcef_dll/cpptoc/frame_cpptoc.cc', - 'libcef_dll/cpptoc/frame_cpptoc.h', - 'libcef_dll/cpptoc/post_data_cpptoc.cc', - 'libcef_dll/cpptoc/post_data_cpptoc.h', - 'libcef_dll/cpptoc/post_data_element_cpptoc.cc', - 'libcef_dll/cpptoc/post_data_element_cpptoc.h', - 'libcef_dll/cpptoc/request_cpptoc.cc', - 'libcef_dll/cpptoc/request_cpptoc.h', - 'libcef_dll/cpptoc/stream_reader_cpptoc.cc', - 'libcef_dll/cpptoc/stream_reader_cpptoc.h', - 'libcef_dll/cpptoc/stream_writer_cpptoc.cc', - 'libcef_dll/cpptoc/stream_writer_cpptoc.h', - 'libcef_dll/cpptoc/v8value_cpptoc.cc', - 'libcef_dll/cpptoc/v8value_cpptoc.h', - 'libcef_dll/ctocpp/ctocpp.h', - 'libcef_dll/ctocpp/handler_ctocpp.cc', - 'libcef_dll/ctocpp/handler_ctocpp.h', - 'libcef_dll/ctocpp/read_handler_ctocpp.cc', - 'libcef_dll/ctocpp/read_handler_ctocpp.h', - 'libcef_dll/ctocpp/scheme_handler_ctocpp.cc', - 'libcef_dll/ctocpp/scheme_handler_ctocpp.h', - 'libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc', - 'libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h', - 'libcef_dll/ctocpp/task_ctocpp.cc', - 'libcef_dll/ctocpp/task_ctocpp.h', - 'libcef_dll/ctocpp/v8handler_ctocpp.cc', - 'libcef_dll/ctocpp/v8handler_ctocpp.h', - 'libcef_dll/ctocpp/write_handler_ctocpp.cc', - 'libcef_dll/ctocpp/write_handler_ctocpp.h', - 'libcef_dll/libcef_dll.cc', - 'libcef_dll/libcef_dll.rc', - 'libcef_dll/resource.h', - 'libcef_dll/transfer_util.cpp', - 'libcef_dll/transfer_util.h', - ], - 'link_settings': { - 'libraries': [ - '-lcomctl32.lib', - ], - }, - }, - { - 'target_name': 'libcef_dll_wrapper', - 'type': 'static_library', - 'msvs_guid': 'A9D6DC71-C0DC-4549-AEA0-3B15B44E86A9', - 'dependencies': [ - '../third_party/npapi/npapi.gyp:npapi', - 'libcef', - ], - 'defines': [ - 'USING_CEF_SHARED', - ], - 'include_dirs': [ - '.', - '..', - ], - 'sources': [ - 'libcef_dll/cef_logging.h', - 'libcef_dll/cpptoc/cpptoc.h', - 'libcef_dll/cpptoc/handler_cpptoc.cc', - 'libcef_dll/cpptoc/handler_cpptoc.h', - 'libcef_dll/cpptoc/read_handler_cpptoc.cc', - 'libcef_dll/cpptoc/read_handler_cpptoc.h', - 'libcef_dll/cpptoc/scheme_handler_cpptoc.cc', - 'libcef_dll/cpptoc/scheme_handler_cpptoc.h', - 'libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc', - 'libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h', - 'libcef_dll/cpptoc/v8handler_cpptoc.cc', - 'libcef_dll/cpptoc/v8handler_cpptoc.h', - 'libcef_dll/cpptoc/write_handler_cpptoc.cc', - 'libcef_dll/cpptoc/write_handler_cpptoc.h', - 'libcef_dll/ctocpp/browser_ctocpp.cc', - 'libcef_dll/ctocpp/browser_ctocpp.h', - 'libcef_dll/ctocpp/ctocpp.h', - 'libcef_dll/ctocpp/frame_ctocpp.cc', - 'libcef_dll/ctocpp/frame_ctocpp.h', - 'libcef_dll/ctocpp/post_data_ctocpp.cc', - 'libcef_dll/ctocpp/post_data_ctocpp.h', - 'libcef_dll/ctocpp/post_data_element_ctocpp.cc', - 'libcef_dll/ctocpp/post_data_element_ctocpp.h', - 'libcef_dll/ctocpp/request_ctocpp.cc', - 'libcef_dll/ctocpp/request_ctocpp.h', - 'libcef_dll/ctocpp/stream_reader_ctocpp.cc', - 'libcef_dll/ctocpp/stream_reader_ctocpp.h', - 'libcef_dll/ctocpp/stream_writer_ctocpp.cc', - 'libcef_dll/ctocpp/stream_writer_ctocpp.h', - 'libcef_dll/cpptoc/task_cpptoc.cc', - 'libcef_dll/cpptoc/task_cpptoc.h', - 'libcef_dll/ctocpp/v8value_ctocpp.cc', - 'libcef_dll/ctocpp/v8value_ctocpp.h', - 'libcef_dll/transfer_util.cpp', - 'libcef_dll/transfer_util.h', - 'libcef_dll/wrapper/libcef_dll_wrapper.cc', - ], - }, - { - 'target_name': 'libcef_static', - 'type': 'static_library', - 'msvs_guid': 'FA39524D-3067-4141-888D-28A86C66F2B9', - 'defines': [ - 'BUILDING_CEF_SHARED', - ], - 'include_dirs': [ - '.', - '..', - '../third_party/WebKit/WebKit/chromium/public' - ], - 'dependencies': [ - '../app/app.gyp:app_base', - '../base/base.gyp:base', - '../base/base.gyp:base_i18n', - '../breakpad/breakpad.gyp:breakpad_handler', - '../build/temp_gyp/googleurl.gyp:googleurl', - '../gfx/gfx.gyp:gfx', - '../media/media.gyp:media', - '../net/net.gyp:net', - '../net/net.gyp:net_resources', - '../printing/printing.gyp:printing', - '../sdch/sdch.gyp:sdch', - '../skia/skia.gyp:skia', - '../third_party/bzip2/bzip2.gyp:bzip2', - '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', - '../third_party/icu/icu.gyp:icui18n', - '../third_party/icu/icu.gyp:icuuc', - '../third_party/libjpeg/libjpeg.gyp:libjpeg', - '../third_party/libpng/libpng.gyp:libpng', - '../third_party/libxslt/libxslt.gyp:libxslt', - '../third_party/mesa/mesa.gyp:osmesa', - '../third_party/modp_b64/modp_b64.gyp:modp_b64', - '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:pcre', - '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:wtf', - '../third_party/WebKit/WebCore/WebCore.gyp/WebCore.gyp:webcore', - '../third_party/WebKit/WebKit/chromium/WebKit.gyp:webkit', - '../third_party/zlib/zlib.gyp:zlib', - '../webkit/support/webkit_support.gyp:appcache', - '../webkit/support/webkit_support.gyp:blob', - '../webkit/support/webkit_support.gyp:database', - '../webkit/support/webkit_support.gyp:fileapi', - '../webkit/support/webkit_support.gyp:glue', - '../webkit/support/webkit_support.gyp:webkit_resources', - '../webkit/support/webkit_support.gyp:webkit_strings', - ], - 'sources': [ - 'include/cef.h', - 'include/cef_export.h', - 'include/cef_nplugin.h', - 'include/cef_ptr.h', - 'include/cef_string.h', - 'include/cef_string_list.h', - 'include/cef_string_map.h', - 'include/cef_types.h', - 'include/cef_types_win.h', - 'include/cef_win.h', - 'libcef/browser_appcache_system.cc', - 'libcef/browser_appcache_system.h', - 'libcef/browser_database_system.cc', - 'libcef/browser_database_system.h', - 'libcef/browser_drag_delegate.cc', - 'libcef/browser_drag_delegate.h', - 'libcef/browser_drop_delegate.cc', - 'libcef/browser_drop_delegate.h', - 'libcef/browser_file_system.cc', - 'libcef/browser_file_system.h', - 'libcef/browser_impl.cc', - 'libcef/browser_impl.h', - 'libcef/browser_impl_win.cc', - 'libcef/browser_navigation_controller.cc', - 'libcef/browser_navigation_controller.h', - 'libcef/browser_request_context.cc', - 'libcef/browser_request_context.h', - 'libcef/browser_resource_loader_bridge.cc', - 'libcef/browser_resource_loader_bridge.h', - 'libcef/browser_socket_stream_bridge.cc', - 'libcef/browser_socket_stream_bridge.h', - 'libcef/browser_webcookiejar_impl.cc', - 'libcef/browser_webcookiejar_impl.h', - 'libcef/browser_webblobregistry_impl.cc', - 'libcef/browser_webblobregistry_impl.h', - 'libcef/browser_webkit_glue.cc', - 'libcef/browser_webkit_glue.h', - 'libcef/browser_webkit_glue_win.cc', - 'libcef/browser_webkit_init.h', - 'libcef/browser_webview_delegate.cc', - 'libcef/browser_webview_delegate.h', - 'libcef/browser_webview_delegate_win.cc', - 'libcef/cef_context.cc', - 'libcef/cef_context.h', - 'libcef/cef_process.cc', - 'libcef/cef_process.h', - 'libcef/cef_process_io_thread.cc', - 'libcef/cef_process_io_thread.h', - 'libcef/cef_process_sub_thread.cc', - 'libcef/cef_process_sub_thread.h', - 'libcef/cef_process_ui_thread.cc', - 'libcef/cef_process_ui_thread.h', - 'libcef/cef_string.c', - 'libcef/cef_string_list.cc', - 'libcef/cef_string_map.cc', - 'libcef/cef_thread.cc', - 'libcef/cef_thread.h', - 'libcef/printing/print_settings.cc', - 'libcef/printing/print_settings.h', - 'libcef/printing/win_printing_context.cc', - 'libcef/printing/win_printing_context.h', - 'libcef/request_impl.cc', - 'libcef/request_impl.h', - 'libcef/scheme_impl.cc', - 'libcef/simple_clipboard_impl.cc', - 'libcef/stream_impl.cc', - 'libcef/stream_impl.h', - 'libcef/tracker.h', - 'libcef/v8_impl.cc', - 'libcef/v8_impl.h', - 'libcef/webview_host.cc', - 'libcef/webview_host.h', - 'libcef/webwidget_host.cc', - 'libcef/webwidget_host.h', - ], - }, - ] -} + 'libcef', + 'libcef_dll_wrapper', + ], + 'sources': [ + 'tests/unittests/request_unittest.cc', + 'tests/unittests/run_all_unittests.cc', + 'tests/unittests/stream_unittest.cc', + 'tests/unittests/test_handler.h', + 'tests/unittests/test_suite.h', + 'tests/unittests/v8_unittest.cc', + ], + 'include_dirs': [ + '.', + '..', + ], + }, + { + 'target_name': 'patcher', + 'type': 'none', + 'msvs_guid': 'A6D0953E-899E-4C60-AB6B-CAE75A44B8E6', + 'actions': [ + { + 'action_name': 'patch_source', + 'msvs_cygwin_shell': 0, + 'inputs': [ + 'tools/patch_source.bat', + ], + 'outputs': [ + 'tools/patch_source.bat.output', + ], + 'action': ['', '<@(_inputs)'], + }, + ], + }, + { + 'target_name': 'libcef', + 'type': 'shared_library', + 'msvs_guid': 'C13650D5-CF1A-4259-BE45-B1EBA6280E47', + 'dependencies': [ + '../app/app.gyp:app_base', + '../base/base.gyp:base', + '../base/base.gyp:base_i18n', + '../breakpad/breakpad.gyp:breakpad_handler', + '../build/temp_gyp/googleurl.gyp:googleurl', + '../gfx/gfx.gyp:gfx', + '../media/media.gyp:media', + '../net/net.gyp:net', + '../net/net.gyp:net_resources', + '../printing/printing.gyp:printing', + '../sdch/sdch.gyp:sdch', + '../skia/skia.gyp:skia', + '../third_party/bzip2/bzip2.gyp:bzip2', + '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', + '../third_party/icu/icu.gyp:icui18n', + '../third_party/icu/icu.gyp:icuuc', + '../third_party/libjpeg/libjpeg.gyp:libjpeg', + '../third_party/libpng/libpng.gyp:libpng', + '../third_party/libxslt/libxslt.gyp:libxslt', + '../third_party/mesa/mesa.gyp:osmesa', + '../third_party/modp_b64/modp_b64.gyp:modp_b64', + '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:pcre', + '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:wtf', + '../third_party/WebKit/WebCore/WebCore.gyp/WebCore.gyp:webcore', + '../third_party/WebKit/WebKit/chromium/WebKit.gyp:webkit', + '../third_party/zlib/zlib.gyp:zlib', + '../webkit/support/webkit_support.gyp:appcache', + '../webkit/support/webkit_support.gyp:blob', + '../webkit/support/webkit_support.gyp:database', + '../webkit/support/webkit_support.gyp:fileapi', + '../webkit/support/webkit_support.gyp:glue', + '../webkit/support/webkit_support.gyp:webkit_resources', + '../webkit/support/webkit_support.gyp:webkit_strings', + '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': [ + '$(OutDir)/obj/global_intermediate/webkit/webkit_resources.rc', + '$(OutDir)/obj/global_intermediate/webkit/webkit_strings_en-US.rc', + 'include/cef.h', + 'include/cef_capi.h', + 'include/cef_export.h', + 'include/cef_nplugin.h', + 'include/cef_nplugin_capi.h', + 'include/cef_ptr.h', + 'include/cef_string.h', + 'include/cef_string_list.h', + 'include/cef_string_map.h', + 'include/cef_types.h', + 'include/cef_types_win.h', + 'include/cef_win.h', + 'libcef_dll/cef_logging.h', + 'libcef_dll/cpptoc/browser_cpptoc.cc', + 'libcef_dll/cpptoc/browser_cpptoc.h', + 'libcef_dll/cpptoc/cpptoc.h', + 'libcef_dll/cpptoc/frame_cpptoc.cc', + 'libcef_dll/cpptoc/frame_cpptoc.h', + 'libcef_dll/cpptoc/post_data_cpptoc.cc', + 'libcef_dll/cpptoc/post_data_cpptoc.h', + 'libcef_dll/cpptoc/post_data_element_cpptoc.cc', + 'libcef_dll/cpptoc/post_data_element_cpptoc.h', + 'libcef_dll/cpptoc/request_cpptoc.cc', + 'libcef_dll/cpptoc/request_cpptoc.h', + 'libcef_dll/cpptoc/stream_reader_cpptoc.cc', + 'libcef_dll/cpptoc/stream_reader_cpptoc.h', + 'libcef_dll/cpptoc/stream_writer_cpptoc.cc', + 'libcef_dll/cpptoc/stream_writer_cpptoc.h', + 'libcef_dll/cpptoc/v8value_cpptoc.cc', + 'libcef_dll/cpptoc/v8value_cpptoc.h', + 'libcef_dll/ctocpp/ctocpp.h', + 'libcef_dll/ctocpp/handler_ctocpp.cc', + 'libcef_dll/ctocpp/handler_ctocpp.h', + 'libcef_dll/ctocpp/read_handler_ctocpp.cc', + 'libcef_dll/ctocpp/read_handler_ctocpp.h', + 'libcef_dll/ctocpp/scheme_handler_ctocpp.cc', + 'libcef_dll/ctocpp/scheme_handler_ctocpp.h', + 'libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc', + 'libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h', + 'libcef_dll/ctocpp/task_ctocpp.cc', + 'libcef_dll/ctocpp/task_ctocpp.h', + 'libcef_dll/ctocpp/v8handler_ctocpp.cc', + 'libcef_dll/ctocpp/v8handler_ctocpp.h', + 'libcef_dll/ctocpp/write_handler_ctocpp.cc', + 'libcef_dll/ctocpp/write_handler_ctocpp.h', + 'libcef_dll/libcef_dll.cc', + 'libcef_dll/libcef_dll.rc', + 'libcef_dll/resource.h', + 'libcef_dll/transfer_util.cpp', + 'libcef_dll/transfer_util.h', + ], + 'link_settings': { + 'libraries': [ + '-lcomctl32.lib', + ], + }, + }, + { + 'target_name': 'libcef_dll_wrapper', + 'type': 'static_library', + 'msvs_guid': 'A9D6DC71-C0DC-4549-AEA0-3B15B44E86A9', + 'dependencies': [ + '../third_party/npapi/npapi.gyp:npapi', + 'libcef', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + '..', + ], + 'sources': [ + 'libcef_dll/cef_logging.h', + 'libcef_dll/cpptoc/cpptoc.h', + 'libcef_dll/cpptoc/handler_cpptoc.cc', + 'libcef_dll/cpptoc/handler_cpptoc.h', + 'libcef_dll/cpptoc/read_handler_cpptoc.cc', + 'libcef_dll/cpptoc/read_handler_cpptoc.h', + 'libcef_dll/cpptoc/scheme_handler_cpptoc.cc', + 'libcef_dll/cpptoc/scheme_handler_cpptoc.h', + 'libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc', + 'libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h', + 'libcef_dll/cpptoc/v8handler_cpptoc.cc', + 'libcef_dll/cpptoc/v8handler_cpptoc.h', + 'libcef_dll/cpptoc/write_handler_cpptoc.cc', + 'libcef_dll/cpptoc/write_handler_cpptoc.h', + 'libcef_dll/ctocpp/browser_ctocpp.cc', + 'libcef_dll/ctocpp/browser_ctocpp.h', + 'libcef_dll/ctocpp/ctocpp.h', + 'libcef_dll/ctocpp/frame_ctocpp.cc', + 'libcef_dll/ctocpp/frame_ctocpp.h', + 'libcef_dll/ctocpp/post_data_ctocpp.cc', + 'libcef_dll/ctocpp/post_data_ctocpp.h', + 'libcef_dll/ctocpp/post_data_element_ctocpp.cc', + 'libcef_dll/ctocpp/post_data_element_ctocpp.h', + 'libcef_dll/ctocpp/request_ctocpp.cc', + 'libcef_dll/ctocpp/request_ctocpp.h', + 'libcef_dll/ctocpp/stream_reader_ctocpp.cc', + 'libcef_dll/ctocpp/stream_reader_ctocpp.h', + 'libcef_dll/ctocpp/stream_writer_ctocpp.cc', + 'libcef_dll/ctocpp/stream_writer_ctocpp.h', + 'libcef_dll/cpptoc/task_cpptoc.cc', + 'libcef_dll/cpptoc/task_cpptoc.h', + 'libcef_dll/ctocpp/v8value_ctocpp.cc', + 'libcef_dll/ctocpp/v8value_ctocpp.h', + 'libcef_dll/transfer_util.cpp', + 'libcef_dll/transfer_util.h', + 'libcef_dll/wrapper/libcef_dll_wrapper.cc', + ], + }, + { + 'target_name': 'libcef_static', + 'type': 'static_library', + 'msvs_guid': 'FA39524D-3067-4141-888D-28A86C66F2B9', + 'defines': [ + 'BUILDING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + '..', + '../third_party/WebKit/WebKit/chromium/public' + ], + 'dependencies': [ + '../app/app.gyp:app_base', + '../base/base.gyp:base', + '../base/base.gyp:base_i18n', + '../breakpad/breakpad.gyp:breakpad_handler', + '../build/temp_gyp/googleurl.gyp:googleurl', + '../gfx/gfx.gyp:gfx', + '../media/media.gyp:media', + '../net/net.gyp:net', + '../net/net.gyp:net_resources', + '../printing/printing.gyp:printing', + '../sdch/sdch.gyp:sdch', + '../skia/skia.gyp:skia', + '../third_party/bzip2/bzip2.gyp:bzip2', + '../third_party/ffmpeg/ffmpeg.gyp:ffmpeg', + '../third_party/icu/icu.gyp:icui18n', + '../third_party/icu/icu.gyp:icuuc', + '../third_party/libjpeg/libjpeg.gyp:libjpeg', + '../third_party/libpng/libpng.gyp:libpng', + '../third_party/libxslt/libxslt.gyp:libxslt', + '../third_party/mesa/mesa.gyp:osmesa', + '../third_party/modp_b64/modp_b64.gyp:modp_b64', + '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:pcre', + '../third_party/WebKit/JavaScriptCore/JavaScriptCore.gyp/JavaScriptCore.gyp:wtf', + '../third_party/WebKit/WebCore/WebCore.gyp/WebCore.gyp:webcore', + '../third_party/WebKit/WebKit/chromium/WebKit.gyp:webkit', + '../third_party/zlib/zlib.gyp:zlib', + '../webkit/support/webkit_support.gyp:appcache', + '../webkit/support/webkit_support.gyp:blob', + '../webkit/support/webkit_support.gyp:database', + '../webkit/support/webkit_support.gyp:fileapi', + '../webkit/support/webkit_support.gyp:glue', + '../webkit/support/webkit_support.gyp:webkit_resources', + '../webkit/support/webkit_support.gyp:webkit_strings', + ], + 'sources': [ + 'include/cef.h', + 'include/cef_export.h', + 'include/cef_nplugin.h', + 'include/cef_ptr.h', + 'include/cef_string.h', + 'include/cef_string_list.h', + 'include/cef_string_map.h', + 'include/cef_types.h', + 'include/cef_types_win.h', + 'include/cef_win.h', + 'libcef/browser_appcache_system.cc', + 'libcef/browser_appcache_system.h', + 'libcef/browser_database_system.cc', + 'libcef/browser_database_system.h', + 'libcef/browser_drag_delegate.cc', + 'libcef/browser_drag_delegate.h', + 'libcef/browser_drop_delegate.cc', + 'libcef/browser_drop_delegate.h', + 'libcef/browser_file_system.cc', + 'libcef/browser_file_system.h', + 'libcef/browser_impl.cc', + 'libcef/browser_impl.h', + 'libcef/browser_impl_win.cc', + 'libcef/browser_navigation_controller.cc', + 'libcef/browser_navigation_controller.h', + 'libcef/browser_request_context.cc', + 'libcef/browser_request_context.h', + 'libcef/browser_resource_loader_bridge.cc', + 'libcef/browser_resource_loader_bridge.h', + 'libcef/browser_socket_stream_bridge.cc', + 'libcef/browser_socket_stream_bridge.h', + 'libcef/browser_webcookiejar_impl.cc', + 'libcef/browser_webcookiejar_impl.h', + 'libcef/browser_webblobregistry_impl.cc', + 'libcef/browser_webblobregistry_impl.h', + 'libcef/browser_webkit_glue.cc', + 'libcef/browser_webkit_glue.h', + 'libcef/browser_webkit_glue_win.cc', + 'libcef/browser_webkit_init.h', + 'libcef/browser_webview_delegate.cc', + 'libcef/browser_webview_delegate.h', + 'libcef/browser_webview_delegate_win.cc', + 'libcef/cef_context.cc', + 'libcef/cef_context.h', + 'libcef/cef_process.cc', + 'libcef/cef_process.h', + 'libcef/cef_process_io_thread.cc', + 'libcef/cef_process_io_thread.h', + 'libcef/cef_process_sub_thread.cc', + 'libcef/cef_process_sub_thread.h', + 'libcef/cef_process_ui_thread.cc', + 'libcef/cef_process_ui_thread.h', + 'libcef/cef_string.c', + 'libcef/cef_string_list.cc', + 'libcef/cef_string_map.cc', + 'libcef/cef_thread.cc', + 'libcef/cef_thread.h', + 'libcef/printing/print_settings.cc', + 'libcef/printing/print_settings.h', + 'libcef/printing/win_printing_context.cc', + 'libcef/printing/win_printing_context.h', + 'libcef/request_impl.cc', + 'libcef/request_impl.h', + 'libcef/scheme_impl.cc', + 'libcef/simple_clipboard_impl.cc', + 'libcef/stream_impl.cc', + 'libcef/stream_impl.h', + 'libcef/tracker.h', + 'libcef/v8_impl.cc', + 'libcef/v8_impl.h', + 'libcef/webview_host.cc', + 'libcef/webview_host.h', + 'libcef/webwidget_host.cc', + 'libcef/webwidget_host.h', + ], + }, + ] +} diff --git a/cef.gypi b/cef.gypi index 8be09902f..678fa326d 100644 --- a/cef.gypi +++ b/cef.gypi @@ -1,10 +1,10 @@ # 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. - + { 'variables': { - # Directory for CEF source files. + # Directory for CEF source files. 'cef_directory' : ' -#include -#include -#include "cef_ptr.h" -#include "cef_types.h" - -class CefBrowser; -class CefFrame; -class CefHandler; -class CefPostData; -class CefPostDataElement; -class CefRequest; -class CefSchemeHandler; -class CefSchemeHandlerFactory; -class CefStreamReader; -class CefStreamWriter; -class CefTask; -class CefV8Handler; -class CefV8Value; - - -// This function should only be called once when the application is started. -// Create the thread to host the UI message loop. A return value of true -// indicates that it succeeded and false indicates that it failed. Set -// |multi_threaded_message_loop| to true to have the message loop run in -// a separate thread. If |multi_threaded_message_loop| is false than -// the CefDoMessageLoopWork() function must be called from your message loop. -// Set |cache_path| to the location where cache data will be stored on disk. -// If |cache_path| is empty an in-memory cache will be used for cache data. -/*--cef()--*/ -bool CefInitialize(bool multi_threaded_message_loop, - const std::wstring& cache_path); - -// This function should only be called once before the application exits. -// Shut down the thread hosting the UI message loop and destroy any created -// windows. -/*--cef()--*/ -void CefShutdown(); - -// Perform message loop processing. Has no affect if the browser UI loop is -// running in a separate thread. -/*--cef()--*/ -void CefDoMessageLoopWork(); - -// 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 = {}; -// // 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()--*/ -bool CefRegisterExtension(const std::wstring& extension_name, - const std::wstring& javascript_code, - CefRefPtr handler); - - -// Register a custom scheme handler factory for the specified |scheme_name| and -// |host_name|. All URLs beginning with scheme_name://host_name/ can be handled -// by CefSchemeHandler instances returned by the factory. Specify an empty -// |host_name| value to match all host names. -/*--cef()--*/ -bool CefRegisterScheme(const std::wstring& scheme_name, - const std::wstring& host_name, - CefRefPtr factory); - - -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() -// was called with a |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 -// method will return true if called on the specified thread. -/*--cef()--*/ -bool CefCurrentlyOn(CefThreadId threadId); - -// Post a task for execution on the specified thread. -/*--cef()--*/ -bool CefPostTask(CefThreadId threadId, CefRefPtr task); - -// Post a task for delayed execution on the specified thread. -/*--cef()--*/ -bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, - long delay_ms); - - -// Interface defining the the reference count implementation methods. All -// framework classes must implement 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; -}; - - -// Bring in platform-specific definitions. -#ifdef _WIN32 -#include "cef_win.h" -#endif - - -// Template that provides atomic implementations of AddRef() and Release() -// along with Lock() and Unlock() methods to protect critical sections of -// code from simultaneous access by multiple threads. -// -// The below example demonstrates how to use the CefThreadSafeBase template. -// -// class MyHandler : public CefThreadSafeBase -// { -// std::wstring m_title; -// -// virtual RetVal HandleTitleChange(const std::wstring& title) -// { -// Lock(); // Begin protecting code -// m_title = title; -// Unlock(); // Done protecting code -// return RV_HANDLED; -// } -// ... -// } -// -template -class CefThreadSafeBase : public ClassName -{ -public: - CefThreadSafeBase() - { - m_dwRef = 0L; - } - virtual ~CefThreadSafeBase() - { - } - - // Atomic reference increment. - virtual int AddRef() - { - return CefAtomicIncrement(&m_dwRef); - } - - // Atomic reference decrement. Delete this object when no references remain. - virtual int Release() - { - int retval = CefAtomicDecrement(&m_dwRef); - if(retval == 0) - delete this; - return retval; - } - - // Return the current number of references. - virtual int GetRefCt() { return m_dwRef; } - - // Use the Lock() and Unlock() methods to protect a section of code from - // simultaneous access by multiple threads. - void Lock() { m_critsec.Lock(); } - void Unlock() { m_critsec.Unlock(); } - -protected: - long m_dwRef; - CefCriticalSection m_critsec; -}; - - -// Class representing a rectangle. -class CefRect : public cef_rect_t -{ -public: - CefRect() - { - x = y = width = height = 0; - } - CefRect(int x, int y, int width, int height) - { - set(x, y, width, height); - } - - CefRect(const cef_rect_t& r) - { - set(r.x, r.y, r.width, r.height); - } - CefRect& operator=(const cef_rect_t& r) - { - x = r.x; - y = r.y; - width = r.width; - height = r.height; - return *this; - } - - 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); -} - -// Implement this interface for task execution. -/*--cef(source=client)--*/ -class CefTask : public CefBase -{ -public: - // Method that will be executed. |threadId| is the thread executing the call. - /*--cef()--*/ - virtual void Execute(CefThreadId threadId) =0; -}; - - -// Class used to represent a browser window. All methods exposed by this class -// should be thread safe. -/*--cef(source=library)--*/ -class CefBrowser : public CefBase -{ -public: - // 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. The |popup| parameter should - // be true if the new window is a popup window. This method call will not - // block. - /*--cef()--*/ - static bool CreateBrowser(CefWindowInfo& windowInfo, bool popup, - CefRefPtr handler, - const std::wstring& url); - - // Create a new browser window using the window parameters specified - // by |windowInfo|. The |popup| parameter should be true if the new window is - // a popup window. This method call will block and can only be used if - // the |multi_threaded_message_loop| parameter to CefInitialize() is false. - /*--cef()--*/ - static CefRefPtr CreateBrowserSync(CefWindowInfo& windowInfo, - bool popup, - CefRefPtr handler, - const std::wstring& url); - - // 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 backwards. - /*--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; - - // Returns true if the window is a popup window. - /*--cef()--*/ - virtual bool IsPopup() =0; - - // Returns the handler for this browser. - /*--cef()--*/ - virtual CefRefPtr GetHandler() =0; - - // Returns the main (top-level) frame for the browser window. - /*--cef()--*/ - virtual CefRefPtr GetMainFrame() =0; - - // Returns the focused frame for the browser window. - /*--cef()--*/ - virtual CefRefPtr GetFocusedFrame() =0; - - // Returns the frame with the specified name, or NULL if not found. - /*--cef()--*/ - virtual CefRefPtr GetFrame(const std::wstring& name) =0; - - // Returns the names of all existing frames. - /*--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 std::wstring& searchText, - bool forward, bool matchCase, bool findNext) =0; - - // Cancel all searches that are currently going on. - /*--cef()--*/ - virtual void StopFinding(bool clearSelection) =0; -}; - - -// Class used to represent a frame in the browser window. All methods exposed -// by this class should be thread safe. -/*--cef(source=library)--*/ -class CefFrame : public 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. - /*--cef()--*/ - virtual std::wstring GetSource() =0; - - // Returns this frame's display text as a string. - /*--cef()--*/ - virtual std::wstring 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 std::wstring& url) =0; - - // Load the contents of |string| with the optional dummy target |url|. - /*--cef()--*/ - virtual void LoadString(const std::wstring& string, - const std::wstring& url) =0; - - // Load the contents of |stream| with the optional dummy target |url|. - /*--cef()--*/ - virtual void LoadStream(CefRefPtr stream, - const std::wstring& 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()--*/ - virtual void ExecuteJavaScript(const std::wstring& jsCode, - const std::wstring& scriptUrl, - int startLine) =0; - - // Returns true if this is the main frame. - /*--cef()--*/ - virtual bool IsMain() =0; - - // Returns true if this is the focused frame. - /*--cef()--*/ - virtual bool IsFocused() =0; - - // Returns this frame's name. - /*--cef()--*/ - virtual std::wstring GetName() =0; - - // Return the URL currently loaded in this frame. - /*--cef()--*/ - virtual std::wstring GetURL() =0; -}; - - -// Interface that should be implemented to handle events generated by the -// browser window. All methods exposed by this class should be thread safe. -// Each method in the interface returns a RetVal value. -/*--cef(source=client)--*/ -class CefHandler : public CefBase -{ -public: - // Define handler return value types. Returning RV_HANDLED indicates - // that the implementation completely handled the method and that no further - // processing is required. Returning RV_CONTINUE indicates that the - // implementation did not handle the method and that the default handler - // should be called. - typedef cef_retval_t RetVal; - - // Event called before a new window is created. The |parentBrowser| parameter - // will point to the parent browser window, if any. The |popup| parameter - // will be true if the new window is a popup window. If you create the window - // yourself you should populate the window handle member of |createInfo| and - // return RV_HANDLED. Otherwise, return RV_CONTINUE and the framework will - // create the window. By default, a newly created window will recieve the - // same handler as the parent window. To change the handler for the new - // window modify the object that |handler| points to. - /*--cef()--*/ - virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, - CefWindowInfo& windowInfo, bool popup, - CefRefPtr& handler, - std::wstring& url) =0; - - // Event called after a new window is created. The return value is currently - // ignored. - /*--cef()--*/ - virtual RetVal HandleAfterCreated(CefRefPtr browser) =0; - - // Event called when a frame's address has changed. The return value is - // currently ignored. - /*--cef()--*/ - virtual RetVal HandleAddressChange(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& url) =0; - - // Event called when the page title changes. The return value is currently - // ignored. - /*--cef()--*/ - virtual RetVal HandleTitleChange(CefRefPtr browser, - const std::wstring& title) =0; - - // Various browser navigation types supported by chrome. - typedef cef_handler_navtype_t NavType; - - // Event called before browser navigation. The client has an opportunity to - // modify the |request| object if desired. Return RV_HANDLED to cancel - // navigation. - /*--cef()--*/ - virtual RetVal HandleBeforeBrowse(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr request, - NavType navType, bool isRedirect) =0; - - // Event called when the browser begins loading a page. The |frame| pointer - // will be empty if the event represents the overall load status and not the - // load status for a particular frame. The return value is currently ignored. - /*--cef()--*/ - virtual RetVal HandleLoadStart(CefRefPtr browser, - CefRefPtr frame) =0; - - // Event called when the browser is done loading a page. The |frame| pointer - // will be empty if the event represents the overall load status and not the - // load status for a particular frame. This event will be generated - // irrespective of whether the request completes successfully. The return - // value is currently ignored. - /*--cef()--*/ - virtual RetVal HandleLoadEnd(CefRefPtr browser, - CefRefPtr frame) =0; - - // Supported error code values. See net\base\net_error_list.h for complete - // descriptions of the error codes. - typedef cef_handler_errorcode_t ErrorCode; - - // 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 - // RV_HANDLED. Otherwise, return RV_CONTINUE for the default error text. - /*--cef()--*/ - virtual RetVal HandleLoadError(CefRefPtr browser, - CefRefPtr frame, - ErrorCode errorCode, - const std::wstring& failedUrl, - std::wstring& errorText) =0; - - // Event called before a resource is loaded. To allow the resource to load - // normally return RV_CONTINUE. To redirect the resource to a new url - // populate the |redirectUrl| value and return RV_CONTINUE. To specify - // data for the resource return a CefStream object in |resourceStream|, set - // |mimeType| to the resource stream's mime type, and return RV_CONTINUE. - // To cancel loading of the resource return RV_HANDLED. 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 RetVal HandleBeforeResourceLoad(CefRefPtr browser, - CefRefPtr request, - std::wstring& redirectUrl, - CefRefPtr& resourceStream, - std::wstring& mimeType, - int loadFlags) =0; - - // Structure representing menu information. - typedef cef_handler_menuinfo_t MenuInfo; - - // Event called before a context menu is displayed. To cancel display of the - // default context menu return RV_HANDLED. - /*--cef()--*/ - virtual RetVal HandleBeforeMenu(CefRefPtr browser, - const MenuInfo& menuInfo) =0; - - // Supported menu ID values. - typedef cef_handler_menuid_t MenuId; - - // Event 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. The return value is currently ignored. - /*--cef()--*/ - virtual RetVal HandleGetMenuLabel(CefRefPtr browser, - MenuId menuId, std::wstring& label) =0; - - // Event called when an option is selected from the default context menu. - // Return RV_HANDLED to cancel default handling of the action. - /*--cef()--*/ - virtual RetVal HandleMenuAction(CefRefPtr browser, - MenuId menuId) =0; - - // Structure representing print options. - typedef cef_print_options_t CefPrintOptions; - - // Event 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 RV_CONTINUE to display the default print options or - // RV_HANDLED to display the modified |printOptions|. - /*--cef()--*/ - virtual RetVal HandlePrintOptions(CefRefPtr browser, - CefPrintOptions& printOptions) = 0; - - // Event 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 RV_HANDLED. Otherwise, populate the approprate - // variables and return RV_CONTINUE. - /*--cef()--*/ - virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, - CefRefPtr frame, - CefPrintInfo& printInfo, - const std::wstring& url, - const std::wstring& title, - int currentPage, int maxPages, - std::wstring& topLeft, - std::wstring& topCenter, - std::wstring& topRight, - std::wstring& bottomLeft, - std::wstring& bottomCenter, - std::wstring& bottomRight) =0; - - // Run a JS alert message. Return RV_CONTINUE to display the default alert - // or RV_HANDLED if you displayed a custom alert. - /*--cef()--*/ - virtual RetVal HandleJSAlert(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message) =0; - - // Run a JS confirm request. Return RV_CONTINUE to display the default alert - // or RV_HANDLED if you displayed a custom alert. If you handled the alert - // set |retval| to true if the user accepted the confirmation. - /*--cef()--*/ - virtual RetVal HandleJSConfirm(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message, bool& retval) =0; - - // Run a JS prompt request. Return RV_CONTINUE to display the default prompt - // or RV_HANDLED 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()--*/ - virtual RetVal HandleJSPrompt(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message, - const std::wstring& defaultValue, - bool& retval, - std::wstring& result) =0; - - // Event called for adding values to a frame's JavaScript 'window' object. The - // return value is currently ignored. - /*--cef()--*/ - virtual RetVal HandleJSBinding(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr object) =0; - - // Called just before a window is closed. The return value is currently - // ignored. - /*--cef()--*/ - virtual RetVal HandleBeforeWindowClose(CefRefPtr browser) =0; - - // 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. - // The return value is currently ignored. - /*--cef()--*/ - virtual RetVal HandleTakeFocus(CefRefPtr browser, - bool reverse) =0; - - // Called when the browser component is requesting focus. |isWidget| will be - // true if the focus is requested for a child widget of the browser window. - // Return RV_CONTINUE to allow the focus to be set or RV_HANDLED to cancel - // setting the focus. - /*--cef()--*/ - virtual RetVal HandleSetFocus(CefRefPtr browser, - bool isWidget) =0; - - // Supported keyboard event types. - typedef cef_handler_keyevent_type_t KeyEventType; - - // Called when the browser component receives a keyboard event. - // |type| is the type of keyboard event (see |KeyEventType|). - // |code| is the windows scan-code for the event. - // |modifiers| is a set of bit-flags describing any pressed modifier keys. - // |isSystemKey| is set if Windows considers this a 'system key' message; - // (see http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx) - // Return RV_HANDLED if the keyboard event was handled or RV_CONTINUE - // to allow the browser component to handle the event. - /*--cef()--*/ - virtual RetVal HandleKeyEvent(CefRefPtr browser, - KeyEventType type, - int code, - int modifiers, - bool isSystemKey) =0; - - // Event 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 RV_HANDLED. Otherwise, - // you can optionally modify |text| and then return RV_CONTINUE to allow - // the browser to display the tooltip. - /*--cef()--*/ - virtual RetVal HandleTooltip(CefRefPtr browser, - std::wstring& text) =0; - - // Called to display a console message. Return RV_HANDLED to stop the message - // from being output to the console. - /*--cef()--*/ - virtual RetVal HandleConsoleMessage(CefRefPtr browser, - const std::wstring& message, - const std::wstring& source, int line) =0; - - // 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. The return value is currently ignored. - /*--cef()--*/ - virtual RetVal HandleFindResult(CefRefPtr browser, - int identifier, int count, - const CefRect& selectionRect, - int activeMatchOrdinal, bool finalUpdate) =0; -}; - - -// Class used to represent a web request. -/*--cef(source=library)--*/ -class CefRequest : public CefBase -{ -public: - typedef std::map HeaderMap; - - // Create a new CefRequest object. - /*--cef()--*/ - static CefRefPtr CreateRequest(); - - // Fully qualified URL to load. - /*--cef()--*/ - virtual std::wstring GetURL() =0; - /*--cef()--*/ - virtual void SetURL(const std::wstring& url) =0; - - // Optional request method type, defaulting to POST if post data is provided - // and GET otherwise. - /*--cef()--*/ - virtual std::wstring GetMethod() =0; - /*--cef()--*/ - virtual void SetMethod(const std::wstring& method) =0; - - // Optional post data. - /*--cef()--*/ - virtual CefRefPtr GetPostData() =0; - /*--cef()--*/ - virtual void SetPostData(CefRefPtr postData) =0; - - // Optional header values. - /*--cef()--*/ - virtual void GetHeaderMap(HeaderMap& headerMap) =0; - /*--cef()--*/ - virtual void SetHeaderMap(const HeaderMap& headerMap) =0; - - // Set all values at one time. - /*--cef()--*/ - virtual void Set(const std::wstring& url, - const std::wstring& method, - CefRefPtr postData, - const HeaderMap& headerMap) =0; -}; - - -// Class used to represent post data for a web request. -/*--cef(source=library)--*/ -class CefPostData : public 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()--*/ - 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. -/*--cef(source=library)--*/ -class CefPostDataElement : public 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 std::wstring& 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()--*/ - virtual Type GetType() =0; - - // Return the file name. - /*--cef()--*/ - virtual std::wstring 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; -}; - - -// Interface the client can implement to provide a custom stream reader. -/*--cef(source=client)--*/ -class CefReadHandler : public 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. - /*--cef()--*/ - virtual int Seek(long offset, int whence) =0; - - // Return the current offset position. - /*--cef()--*/ - virtual long Tell() =0; - - // Return non-zero if at end of file. - /*--cef()--*/ - virtual int Eof() =0; -}; - - -// Class used to read data from a stream. -/*--cef(source=library)--*/ -class CefStreamReader : public CefBase -{ -public: - // Create a new CefStreamReader object. - /*--cef()--*/ - static CefRefPtr CreateForFile(const std::wstring& fileName); - /*--cef()--*/ - static CefRefPtr CreateForData(void* data, size_t size); - /*--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(long offset, int whence) =0; - - // Return the current offset position. - /*--cef()--*/ - virtual long 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. -/*--cef(source=client)--*/ -class CefWriteHandler : public 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. - /*--cef()--*/ - virtual int Seek(long offset, int whence) =0; - - // Return the current offset position. - /*--cef()--*/ - virtual long Tell() =0; - - // Flush the stream. - /*--cef()--*/ - virtual int Flush() =0; -}; - - -// Class used to write data to a stream. -/*--cef(source=library)--*/ -class CefStreamWriter : public CefBase -{ -public: - // Create a new CefStreamWriter object. - /*--cef()--*/ - static CefRefPtr CreateForFile(const std::wstring& fileName); - /*--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. - /*--cef()--*/ - virtual int Seek(long offset, int whence) =0; - - // Return the current offset position. - /*--cef()--*/ - virtual long Tell() =0; - - // Flush the stream. - /*--cef()--*/ - virtual int Flush() =0; -}; - - -typedef std::vector> CefV8ValueList; - -// Interface that should be implemented to handle V8 function calls. -/*--cef(source=client)--*/ -class CefV8Handler : public CefBase -{ -public: - // Execute with the specified argument list and return value. Return true if - // the method was handled. - /*--cef()--*/ - virtual bool Execute(const std::wstring& name, - CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) =0; -}; - - -// Class representing a V8 value. -/*--cef(source=library)--*/ -class CefV8Value : public CefBase -{ -public: - // 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. - /*--cef()--*/ - static CefRefPtr CreateUndefined(); - /*--cef()--*/ - static CefRefPtr CreateNull(); - /*--cef()--*/ - static CefRefPtr CreateBool(bool value); - /*--cef()--*/ - static CefRefPtr CreateInt(int value); - /*--cef()--*/ - static CefRefPtr CreateDouble(double value); - /*--cef()--*/ - static CefRefPtr CreateString(const std::wstring& value); - /*--cef()--*/ - static CefRefPtr CreateObject(CefRefPtr user_data); - /*--cef()--*/ - static CefRefPtr CreateArray(); - /*--cef()--*/ - static CefRefPtr CreateFunction(const std::wstring& name, - CefRefPtr handler); - - // Check the value type. - /*--cef()--*/ - virtual bool IsUndefined() =0; - /*--cef()--*/ - virtual bool IsNull() =0; - /*--cef()--*/ - virtual bool IsBool() =0; - /*--cef()--*/ - virtual bool IsInt() =0; - /*--cef()--*/ - virtual bool IsDouble() =0; - /*--cef()--*/ - virtual bool IsString() =0; - /*--cef()--*/ - virtual bool IsObject() =0; - /*--cef()--*/ - virtual bool IsArray() =0; - /*--cef()--*/ - virtual bool IsFunction() =0; - - // Return a primitive value type. The underlying data will be converted to - // the requested type if necessary. - /*--cef()--*/ - virtual bool GetBoolValue() =0; - /*--cef()--*/ - virtual int GetIntValue() =0; - /*--cef()--*/ - virtual double GetDoubleValue() =0; - /*--cef()--*/ - virtual std::wstring 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. - // Keys beginning with "Cef::" and "v8::" are reserved by the system. - - // Returns true if the object has a value with the specified identifier. - /*--cef(capi_name=has_value_bykey)--*/ - virtual bool HasValue(const std::wstring& key) =0; - /*--cef(capi_name=has_value_byindex)--*/ - virtual bool HasValue(int index) =0; - - // Delete the value with the specified identifier. - /*--cef(capi_name=delete_value_bykey)--*/ - virtual bool DeleteValue(const std::wstring& key) =0; - /*--cef(capi_name=delete_value_byindex)--*/ - virtual bool DeleteValue(int index) =0; - - // Returns the value with the specified identifier. - /*--cef(capi_name=get_value_bykey)--*/ - virtual CefRefPtr GetValue(const std::wstring& key) =0; - /*--cef(capi_name=get_value_byindex)--*/ - virtual CefRefPtr GetValue(int index) =0; - - // Associate value with the specified identifier. - /*--cef(capi_name=set_value_bykey)--*/ - virtual bool SetValue(const std::wstring& key, CefRefPtr value) =0; - /*--cef(capi_name=set_value_byindex)--*/ - virtual bool SetValue(int index, CefRefPtr value) =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; - - // Returns the user data, if any, specified when the object was created. - /*--cef()--*/ - virtual CefRefPtr GetUserData() =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 std::wstring GetFunctionName() =0; - - // Returns the function handler or NULL if not a CEF-created function. - /*--cef()--*/ - virtual CefRefPtr GetFunctionHandler() =0; - - // Execute the function. - /*--cef()--*/ - virtual bool ExecuteFunction(CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) =0; -}; - - -// Class that creates CefSchemeHandler instances. -/*--cef(source=client)--*/ -class CefSchemeHandlerFactory : public CefBase -{ -public: - // Return a new scheme handler instance to handle the request. - /*--cef()--*/ - virtual CefRefPtr Create() =0; -}; - - -// Class used to represent a custom scheme handler interface. -/*--cef(source=client)--*/ -class CefSchemeHandler : public CefBase -{ -public: - // Process the request. All response generation should take place in this - // method. If there is no response set |response_length| to zero and - // ReadResponse() will not be called. If the response length is not known then - // set |response_length| to -1 and ReadResponse() will be called until it - // returns false or until the value of |bytes_read| is set to 0. Otherwise, - // set |response_length| to a positive value and ReadResponse() will be called - // until it returns false, the value of |bytes_read| is set to 0 or the - // specified number of bytes have been read. If there is a response set - // |mime_type| to the mime type for the response. - /*--cef()--*/ - virtual bool ProcessRequest(CefRefPtr request, - std::wstring& mime_type, int* response_length) =0; - - // Cancel processing of the request. - /*--cef()--*/ - virtual void Cancel() =0; - - // Copy up to |bytes_to_read| bytes into |data_out|. If the copy succeeds - // set |bytes_read| to the number of bytes copied and return true. If the - // copy fails return false and ReadResponse() will not be called again. - /*--cef()--*/ - virtual bool ReadResponse(void* data_out, int bytes_to_read, - int* bytes_read) =0; -}; - - -#endif // _CEF_H +// Copyright (c) 2008-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. +// +// --------------------------------------------------------------------------- +// +// 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_H +#define _CEF_H + +#include +#include +#include +#include "cef_ptr.h" +#include "cef_types.h" + +class CefBrowser; +class CefFrame; +class CefHandler; +class CefPostData; +class CefPostDataElement; +class CefRequest; +class CefSchemeHandler; +class CefSchemeHandlerFactory; +class CefStreamReader; +class CefStreamWriter; +class CefTask; +class CefV8Handler; +class CefV8Value; + + +// This function should only be called once when the application is started. +// Create the thread to host the UI message loop. A return value of true +// indicates that it succeeded and false indicates that it failed. Set +// |multi_threaded_message_loop| to true to have the message loop run in +// a separate thread. If |multi_threaded_message_loop| is false than +// the CefDoMessageLoopWork() function must be called from your message loop. +// Set |cache_path| to the location where cache data will be stored on disk. +// If |cache_path| is empty an in-memory cache will be used for cache data. +/*--cef()--*/ +bool CefInitialize(bool multi_threaded_message_loop, + const std::wstring& cache_path); + +// This function should only be called once before the application exits. +// Shut down the thread hosting the UI message loop and destroy any created +// windows. +/*--cef()--*/ +void CefShutdown(); + +// Perform message loop processing. Has no affect if the browser UI loop is +// running in a separate thread. +/*--cef()--*/ +void CefDoMessageLoopWork(); + +// 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 = {}; +// // 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()--*/ +bool CefRegisterExtension(const std::wstring& extension_name, + const std::wstring& javascript_code, + CefRefPtr handler); + + +// Register a custom scheme handler factory for the specified |scheme_name| and +// |host_name|. All URLs beginning with scheme_name://host_name/ can be handled +// by CefSchemeHandler instances returned by the factory. Specify an empty +// |host_name| value to match all host names. +/*--cef()--*/ +bool CefRegisterScheme(const std::wstring& scheme_name, + const std::wstring& host_name, + CefRefPtr factory); + + +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() +// was called with a |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 +// method will return true if called on the specified thread. +/*--cef()--*/ +bool CefCurrentlyOn(CefThreadId threadId); + +// Post a task for execution on the specified thread. +/*--cef()--*/ +bool CefPostTask(CefThreadId threadId, CefRefPtr task); + +// Post a task for delayed execution on the specified thread. +/*--cef()--*/ +bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, + long delay_ms); + + +// Interface defining the the reference count implementation methods. All +// framework classes must implement 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; +}; + + +// Bring in platform-specific definitions. +#ifdef _WIN32 +#include "cef_win.h" +#endif + + +// Template that provides atomic implementations of AddRef() and Release() +// along with Lock() and Unlock() methods to protect critical sections of +// code from simultaneous access by multiple threads. +// +// The below example demonstrates how to use the CefThreadSafeBase template. +// +// class MyHandler : public CefThreadSafeBase +// { +// std::wstring m_title; +// +// virtual RetVal HandleTitleChange(const std::wstring& title) +// { +// Lock(); // Begin protecting code +// m_title = title; +// Unlock(); // Done protecting code +// return RV_HANDLED; +// } +// ... +// } +// +template +class CefThreadSafeBase : public ClassName +{ +public: + CefThreadSafeBase() + { + m_dwRef = 0L; + } + virtual ~CefThreadSafeBase() + { + } + + // Atomic reference increment. + virtual int AddRef() + { + return CefAtomicIncrement(&m_dwRef); + } + + // Atomic reference decrement. Delete this object when no references remain. + virtual int Release() + { + int retval = CefAtomicDecrement(&m_dwRef); + if(retval == 0) + delete this; + return retval; + } + + // Return the current number of references. + virtual int GetRefCt() { return m_dwRef; } + + // Use the Lock() and Unlock() methods to protect a section of code from + // simultaneous access by multiple threads. + void Lock() { m_critsec.Lock(); } + void Unlock() { m_critsec.Unlock(); } + +protected: + long m_dwRef; + CefCriticalSection m_critsec; +}; + + +// Class representing a rectangle. +class CefRect : public cef_rect_t +{ +public: + CefRect() + { + x = y = width = height = 0; + } + CefRect(int x, int y, int width, int height) + { + set(x, y, width, height); + } + + CefRect(const cef_rect_t& r) + { + set(r.x, r.y, r.width, r.height); + } + CefRect& operator=(const cef_rect_t& r) + { + x = r.x; + y = r.y; + width = r.width; + height = r.height; + return *this; + } + + 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); +} + +// Implement this interface for task execution. +/*--cef(source=client)--*/ +class CefTask : public CefBase +{ +public: + // Method that will be executed. |threadId| is the thread executing the call. + /*--cef()--*/ + virtual void Execute(CefThreadId threadId) =0; +}; + + +// Class used to represent a browser window. All methods exposed by this class +// should be thread safe. +/*--cef(source=library)--*/ +class CefBrowser : public CefBase +{ +public: + // 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. The |popup| parameter should + // be true if the new window is a popup window. This method call will not + // block. + /*--cef()--*/ + static bool CreateBrowser(CefWindowInfo& windowInfo, bool popup, + CefRefPtr handler, + const std::wstring& url); + + // Create a new browser window using the window parameters specified + // by |windowInfo|. The |popup| parameter should be true if the new window is + // a popup window. This method call will block and can only be used if + // the |multi_threaded_message_loop| parameter to CefInitialize() is false. + /*--cef()--*/ + static CefRefPtr CreateBrowserSync(CefWindowInfo& windowInfo, + bool popup, + CefRefPtr handler, + const std::wstring& url); + + // 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 backwards. + /*--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; + + // Returns true if the window is a popup window. + /*--cef()--*/ + virtual bool IsPopup() =0; + + // Returns the handler for this browser. + /*--cef()--*/ + virtual CefRefPtr GetHandler() =0; + + // Returns the main (top-level) frame for the browser window. + /*--cef()--*/ + virtual CefRefPtr GetMainFrame() =0; + + // Returns the focused frame for the browser window. + /*--cef()--*/ + virtual CefRefPtr GetFocusedFrame() =0; + + // Returns the frame with the specified name, or NULL if not found. + /*--cef()--*/ + virtual CefRefPtr GetFrame(const std::wstring& name) =0; + + // Returns the names of all existing frames. + /*--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 std::wstring& searchText, + bool forward, bool matchCase, bool findNext) =0; + + // Cancel all searches that are currently going on. + /*--cef()--*/ + virtual void StopFinding(bool clearSelection) =0; +}; + + +// Class used to represent a frame in the browser window. All methods exposed +// by this class should be thread safe. +/*--cef(source=library)--*/ +class CefFrame : public 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. + /*--cef()--*/ + virtual std::wstring GetSource() =0; + + // Returns this frame's display text as a string. + /*--cef()--*/ + virtual std::wstring 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 std::wstring& url) =0; + + // Load the contents of |string| with the optional dummy target |url|. + /*--cef()--*/ + virtual void LoadString(const std::wstring& string, + const std::wstring& url) =0; + + // Load the contents of |stream| with the optional dummy target |url|. + /*--cef()--*/ + virtual void LoadStream(CefRefPtr stream, + const std::wstring& 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()--*/ + virtual void ExecuteJavaScript(const std::wstring& jsCode, + const std::wstring& scriptUrl, + int startLine) =0; + + // Returns true if this is the main frame. + /*--cef()--*/ + virtual bool IsMain() =0; + + // Returns true if this is the focused frame. + /*--cef()--*/ + virtual bool IsFocused() =0; + + // Returns this frame's name. + /*--cef()--*/ + virtual std::wstring GetName() =0; + + // Return the URL currently loaded in this frame. + /*--cef()--*/ + virtual std::wstring GetURL() =0; +}; + + +// Interface that should be implemented to handle events generated by the +// browser window. All methods exposed by this class should be thread safe. +// Each method in the interface returns a RetVal value. +/*--cef(source=client)--*/ +class CefHandler : public CefBase +{ +public: + // Define handler return value types. Returning RV_HANDLED indicates + // that the implementation completely handled the method and that no further + // processing is required. Returning RV_CONTINUE indicates that the + // implementation did not handle the method and that the default handler + // should be called. + typedef cef_retval_t RetVal; + + // Event called before a new window is created. The |parentBrowser| parameter + // will point to the parent browser window, if any. The |popup| parameter + // will be true if the new window is a popup window. If you create the window + // yourself you should populate the window handle member of |createInfo| and + // return RV_HANDLED. Otherwise, return RV_CONTINUE and the framework will + // create the window. By default, a newly created window will recieve the + // same handler as the parent window. To change the handler for the new + // window modify the object that |handler| points to. + /*--cef()--*/ + virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, + CefWindowInfo& windowInfo, bool popup, + CefRefPtr& handler, + std::wstring& url) =0; + + // Event called after a new window is created. The return value is currently + // ignored. + /*--cef()--*/ + virtual RetVal HandleAfterCreated(CefRefPtr browser) =0; + + // Event called when a frame's address has changed. The return value is + // currently ignored. + /*--cef()--*/ + virtual RetVal HandleAddressChange(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& url) =0; + + // Event called when the page title changes. The return value is currently + // ignored. + /*--cef()--*/ + virtual RetVal HandleTitleChange(CefRefPtr browser, + const std::wstring& title) =0; + + // Various browser navigation types supported by chrome. + typedef cef_handler_navtype_t NavType; + + // Event called before browser navigation. The client has an opportunity to + // modify the |request| object if desired. Return RV_HANDLED to cancel + // navigation. + /*--cef()--*/ + virtual RetVal HandleBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, bool isRedirect) =0; + + // Event called when the browser begins loading a page. The |frame| pointer + // will be empty if the event represents the overall load status and not the + // load status for a particular frame. The return value is currently ignored. + /*--cef()--*/ + virtual RetVal HandleLoadStart(CefRefPtr browser, + CefRefPtr frame) =0; + + // Event called when the browser is done loading a page. The |frame| pointer + // will be empty if the event represents the overall load status and not the + // load status for a particular frame. This event will be generated + // irrespective of whether the request completes successfully. The return + // value is currently ignored. + /*--cef()--*/ + virtual RetVal HandleLoadEnd(CefRefPtr browser, + CefRefPtr frame) =0; + + // Supported error code values. See net\base\net_error_list.h for complete + // descriptions of the error codes. + typedef cef_handler_errorcode_t ErrorCode; + + // 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 + // RV_HANDLED. Otherwise, return RV_CONTINUE for the default error text. + /*--cef()--*/ + virtual RetVal HandleLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const std::wstring& failedUrl, + std::wstring& errorText) =0; + + // Event called before a resource is loaded. To allow the resource to load + // normally return RV_CONTINUE. To redirect the resource to a new url + // populate the |redirectUrl| value and return RV_CONTINUE. To specify + // data for the resource return a CefStream object in |resourceStream|, set + // |mimeType| to the resource stream's mime type, and return RV_CONTINUE. + // To cancel loading of the resource return RV_HANDLED. 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 RetVal HandleBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + std::wstring& redirectUrl, + CefRefPtr& resourceStream, + std::wstring& mimeType, + int loadFlags) =0; + + // Structure representing menu information. + typedef cef_handler_menuinfo_t MenuInfo; + + // Event called before a context menu is displayed. To cancel display of the + // default context menu return RV_HANDLED. + /*--cef()--*/ + virtual RetVal HandleBeforeMenu(CefRefPtr browser, + const MenuInfo& menuInfo) =0; + + // Supported menu ID values. + typedef cef_handler_menuid_t MenuId; + + // Event 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. The return value is currently ignored. + /*--cef()--*/ + virtual RetVal HandleGetMenuLabel(CefRefPtr browser, + MenuId menuId, std::wstring& label) =0; + + // Event called when an option is selected from the default context menu. + // Return RV_HANDLED to cancel default handling of the action. + /*--cef()--*/ + virtual RetVal HandleMenuAction(CefRefPtr browser, + MenuId menuId) =0; + + // Structure representing print options. + typedef cef_print_options_t CefPrintOptions; + + // Event 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 RV_CONTINUE to display the default print options or + // RV_HANDLED to display the modified |printOptions|. + /*--cef()--*/ + virtual RetVal HandlePrintOptions(CefRefPtr browser, + CefPrintOptions& printOptions) = 0; + + // Event 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 RV_HANDLED. Otherwise, populate the approprate + // variables and return RV_CONTINUE. + /*--cef()--*/ + virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, + CefPrintInfo& printInfo, + const std::wstring& url, + const std::wstring& title, + int currentPage, int maxPages, + std::wstring& topLeft, + std::wstring& topCenter, + std::wstring& topRight, + std::wstring& bottomLeft, + std::wstring& bottomCenter, + std::wstring& bottomRight) =0; + + // Run a JS alert message. Return RV_CONTINUE to display the default alert + // or RV_HANDLED if you displayed a custom alert. + /*--cef()--*/ + virtual RetVal HandleJSAlert(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message) =0; + + // Run a JS confirm request. Return RV_CONTINUE to display the default alert + // or RV_HANDLED if you displayed a custom alert. If you handled the alert + // set |retval| to true if the user accepted the confirmation. + /*--cef()--*/ + virtual RetVal HandleJSConfirm(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message, bool& retval) =0; + + // Run a JS prompt request. Return RV_CONTINUE to display the default prompt + // or RV_HANDLED 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()--*/ + virtual RetVal HandleJSPrompt(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message, + const std::wstring& defaultValue, + bool& retval, + std::wstring& result) =0; + + // Event called for adding values to a frame's JavaScript 'window' object. The + // return value is currently ignored. + /*--cef()--*/ + virtual RetVal HandleJSBinding(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object) =0; + + // Called just before a window is closed. The return value is currently + // ignored. + /*--cef()--*/ + virtual RetVal HandleBeforeWindowClose(CefRefPtr browser) =0; + + // 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. + // The return value is currently ignored. + /*--cef()--*/ + virtual RetVal HandleTakeFocus(CefRefPtr browser, + bool reverse) =0; + + // Called when the browser component is requesting focus. |isWidget| will be + // true if the focus is requested for a child widget of the browser window. + // Return RV_CONTINUE to allow the focus to be set or RV_HANDLED to cancel + // setting the focus. + /*--cef()--*/ + virtual RetVal HandleSetFocus(CefRefPtr browser, + bool isWidget) =0; + + // Supported keyboard event types. + typedef cef_handler_keyevent_type_t KeyEventType; + + // Called when the browser component receives a keyboard event. + // |type| is the type of keyboard event (see |KeyEventType|). + // |code| is the windows scan-code for the event. + // |modifiers| is a set of bit-flags describing any pressed modifier keys. + // |isSystemKey| is set if Windows considers this a 'system key' message; + // (see http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx) + // Return RV_HANDLED if the keyboard event was handled or RV_CONTINUE + // to allow the browser component to handle the event. + /*--cef()--*/ + virtual RetVal HandleKeyEvent(CefRefPtr browser, + KeyEventType type, + int code, + int modifiers, + bool isSystemKey) =0; + + // Event 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 RV_HANDLED. Otherwise, + // you can optionally modify |text| and then return RV_CONTINUE to allow + // the browser to display the tooltip. + /*--cef()--*/ + virtual RetVal HandleTooltip(CefRefPtr browser, + std::wstring& text) =0; + + // Called to display a console message. Return RV_HANDLED to stop the message + // from being output to the console. + /*--cef()--*/ + virtual RetVal HandleConsoleMessage(CefRefPtr browser, + const std::wstring& message, + const std::wstring& source, int line) =0; + + // 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. The return value is currently ignored. + /*--cef()--*/ + virtual RetVal HandleFindResult(CefRefPtr browser, + int identifier, int count, + const CefRect& selectionRect, + int activeMatchOrdinal, bool finalUpdate) =0; +}; + + +// Class used to represent a web request. +/*--cef(source=library)--*/ +class CefRequest : public CefBase +{ +public: + typedef std::map HeaderMap; + + // Create a new CefRequest object. + /*--cef()--*/ + static CefRefPtr CreateRequest(); + + // Fully qualified URL to load. + /*--cef()--*/ + virtual std::wstring GetURL() =0; + /*--cef()--*/ + virtual void SetURL(const std::wstring& url) =0; + + // Optional request method type, defaulting to POST if post data is provided + // and GET otherwise. + /*--cef()--*/ + virtual std::wstring GetMethod() =0; + /*--cef()--*/ + virtual void SetMethod(const std::wstring& method) =0; + + // Optional post data. + /*--cef()--*/ + virtual CefRefPtr GetPostData() =0; + /*--cef()--*/ + virtual void SetPostData(CefRefPtr postData) =0; + + // Optional header values. + /*--cef()--*/ + virtual void GetHeaderMap(HeaderMap& headerMap) =0; + /*--cef()--*/ + virtual void SetHeaderMap(const HeaderMap& headerMap) =0; + + // Set all values at one time. + /*--cef()--*/ + virtual void Set(const std::wstring& url, + const std::wstring& method, + CefRefPtr postData, + const HeaderMap& headerMap) =0; +}; + + +// Class used to represent post data for a web request. +/*--cef(source=library)--*/ +class CefPostData : public 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()--*/ + 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. +/*--cef(source=library)--*/ +class CefPostDataElement : public 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 std::wstring& 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()--*/ + virtual Type GetType() =0; + + // Return the file name. + /*--cef()--*/ + virtual std::wstring 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; +}; + + +// Interface the client can implement to provide a custom stream reader. +/*--cef(source=client)--*/ +class CefReadHandler : public 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. + /*--cef()--*/ + virtual int Seek(long offset, int whence) =0; + + // Return the current offset position. + /*--cef()--*/ + virtual long Tell() =0; + + // Return non-zero if at end of file. + /*--cef()--*/ + virtual int Eof() =0; +}; + + +// Class used to read data from a stream. +/*--cef(source=library)--*/ +class CefStreamReader : public CefBase +{ +public: + // Create a new CefStreamReader object. + /*--cef()--*/ + static CefRefPtr CreateForFile(const std::wstring& fileName); + /*--cef()--*/ + static CefRefPtr CreateForData(void* data, size_t size); + /*--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(long offset, int whence) =0; + + // Return the current offset position. + /*--cef()--*/ + virtual long 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. +/*--cef(source=client)--*/ +class CefWriteHandler : public 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. + /*--cef()--*/ + virtual int Seek(long offset, int whence) =0; + + // Return the current offset position. + /*--cef()--*/ + virtual long Tell() =0; + + // Flush the stream. + /*--cef()--*/ + virtual int Flush() =0; +}; + + +// Class used to write data to a stream. +/*--cef(source=library)--*/ +class CefStreamWriter : public CefBase +{ +public: + // Create a new CefStreamWriter object. + /*--cef()--*/ + static CefRefPtr CreateForFile(const std::wstring& fileName); + /*--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. + /*--cef()--*/ + virtual int Seek(long offset, int whence) =0; + + // Return the current offset position. + /*--cef()--*/ + virtual long Tell() =0; + + // Flush the stream. + /*--cef()--*/ + virtual int Flush() =0; +}; + + +typedef std::vector> CefV8ValueList; + +// Interface that should be implemented to handle V8 function calls. +/*--cef(source=client)--*/ +class CefV8Handler : public CefBase +{ +public: + // Execute with the specified argument list and return value. Return true if + // the method was handled. + /*--cef()--*/ + virtual bool Execute(const std::wstring& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) =0; +}; + + +// Class representing a V8 value. +/*--cef(source=library)--*/ +class CefV8Value : public CefBase +{ +public: + // 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. + /*--cef()--*/ + static CefRefPtr CreateUndefined(); + /*--cef()--*/ + static CefRefPtr CreateNull(); + /*--cef()--*/ + static CefRefPtr CreateBool(bool value); + /*--cef()--*/ + static CefRefPtr CreateInt(int value); + /*--cef()--*/ + static CefRefPtr CreateDouble(double value); + /*--cef()--*/ + static CefRefPtr CreateString(const std::wstring& value); + /*--cef()--*/ + static CefRefPtr CreateObject(CefRefPtr user_data); + /*--cef()--*/ + static CefRefPtr CreateArray(); + /*--cef()--*/ + static CefRefPtr CreateFunction(const std::wstring& name, + CefRefPtr handler); + + // Check the value type. + /*--cef()--*/ + virtual bool IsUndefined() =0; + /*--cef()--*/ + virtual bool IsNull() =0; + /*--cef()--*/ + virtual bool IsBool() =0; + /*--cef()--*/ + virtual bool IsInt() =0; + /*--cef()--*/ + virtual bool IsDouble() =0; + /*--cef()--*/ + virtual bool IsString() =0; + /*--cef()--*/ + virtual bool IsObject() =0; + /*--cef()--*/ + virtual bool IsArray() =0; + /*--cef()--*/ + virtual bool IsFunction() =0; + + // Return a primitive value type. The underlying data will be converted to + // the requested type if necessary. + /*--cef()--*/ + virtual bool GetBoolValue() =0; + /*--cef()--*/ + virtual int GetIntValue() =0; + /*--cef()--*/ + virtual double GetDoubleValue() =0; + /*--cef()--*/ + virtual std::wstring 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. + // Keys beginning with "Cef::" and "v8::" are reserved by the system. + + // Returns true if the object has a value with the specified identifier. + /*--cef(capi_name=has_value_bykey)--*/ + virtual bool HasValue(const std::wstring& key) =0; + /*--cef(capi_name=has_value_byindex)--*/ + virtual bool HasValue(int index) =0; + + // Delete the value with the specified identifier. + /*--cef(capi_name=delete_value_bykey)--*/ + virtual bool DeleteValue(const std::wstring& key) =0; + /*--cef(capi_name=delete_value_byindex)--*/ + virtual bool DeleteValue(int index) =0; + + // Returns the value with the specified identifier. + /*--cef(capi_name=get_value_bykey)--*/ + virtual CefRefPtr GetValue(const std::wstring& key) =0; + /*--cef(capi_name=get_value_byindex)--*/ + virtual CefRefPtr GetValue(int index) =0; + + // Associate value with the specified identifier. + /*--cef(capi_name=set_value_bykey)--*/ + virtual bool SetValue(const std::wstring& key, CefRefPtr value) =0; + /*--cef(capi_name=set_value_byindex)--*/ + virtual bool SetValue(int index, CefRefPtr value) =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; + + // Returns the user data, if any, specified when the object was created. + /*--cef()--*/ + virtual CefRefPtr GetUserData() =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 std::wstring GetFunctionName() =0; + + // Returns the function handler or NULL if not a CEF-created function. + /*--cef()--*/ + virtual CefRefPtr GetFunctionHandler() =0; + + // Execute the function. + /*--cef()--*/ + virtual bool ExecuteFunction(CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) =0; +}; + + +// Class that creates CefSchemeHandler instances. +/*--cef(source=client)--*/ +class CefSchemeHandlerFactory : public CefBase +{ +public: + // Return a new scheme handler instance to handle the request. + /*--cef()--*/ + virtual CefRefPtr Create() =0; +}; + + +// Class used to represent a custom scheme handler interface. +/*--cef(source=client)--*/ +class CefSchemeHandler : public CefBase +{ +public: + // Process the request. All response generation should take place in this + // method. If there is no response set |response_length| to zero and + // ReadResponse() will not be called. If the response length is not known then + // set |response_length| to -1 and ReadResponse() will be called until it + // returns false or until the value of |bytes_read| is set to 0. Otherwise, + // set |response_length| to a positive value and ReadResponse() will be called + // until it returns false, the value of |bytes_read| is set to 0 or the + // specified number of bytes have been read. If there is a response set + // |mime_type| to the mime type for the response. + /*--cef()--*/ + virtual bool ProcessRequest(CefRefPtr request, + std::wstring& mime_type, int* response_length) =0; + + // Cancel processing of the request. + /*--cef()--*/ + virtual void Cancel() =0; + + // Copy up to |bytes_to_read| bytes into |data_out|. If the copy succeeds + // set |bytes_read| to the number of bytes copied and return true. If the + // copy fails return false and ReadResponse() will not be called again. + /*--cef()--*/ + virtual bool ReadResponse(void* data_out, int bytes_to_read, + int* bytes_read) =0; +}; + + +#endif // _CEF_H diff --git a/include/cef_capi.h b/include/cef_capi.h index 00f0d9809..5a8ed951f 100644 --- a/include/cef_capi.h +++ b/include/cef_capi.h @@ -1,981 +1,981 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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_CAPI_H -#define _CEF_CAPI_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "cef_export.h" -#include "cef_string.h" -#include "cef_string_list.h" -#include "cef_string_map.h" -#include "cef_types.h" - - -// This function should only be called once when the application is started. -// Create the thread to host the UI message loop. A return value of true (1) -// indicates that it succeeded and false (0) indicates that it failed. Set -// |multi_threaded_message_loop| to true (1) to have the message loop run in a -// separate thread. If |multi_threaded_message_loop| is false (0) than the -// cef_do_message_loop_work() function must be called from your message loop. -// Set |cache_path| to the location where cache data will be stored on disk. If -// |cache_path| is NULL an in-memory cache will be used for cache data. -CEF_EXPORT int cef_initialize(int multi_threaded_message_loop, - const wchar_t* cache_path); - -// This function should only be called once before the application exits. Shut -// down the thread hosting the UI message loop and destroy any created windows. -CEF_EXPORT void cef_shutdown(); - -// Perform message loop processing. Has no affect if the browser UI loop is -// running in a separate thread. -CEF_EXPORT void cef_do_message_loop_work(); - -// 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 = {}; -// // 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 wchar_t* extension_name, - const wchar_t* javascript_code, struct _cef_v8handler_t* handler); - -// Register a custom scheme handler factory for the specified |scheme_name| and -// |host_name|. All URLs beginning with scheme_name://host_name/ can be handled -// by cef_scheme_handler_t instances returned by the factory. Specify an NULL -// |host_name| value to match all host names. -CEF_EXPORT int cef_register_scheme(const wchar_t* scheme_name, - const wchar_t* host_name, struct _cef_scheme_handler_factory_t* factory); - -// 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() -// was called with a |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. -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. -CEF_EXPORT int cef_post_delayed_task(cef_thread_id_t threadId, - struct _cef_task_t* task, long delay_ms); - -typedef struct _cef_base_t -{ - // Size of the data structure. - size_t size; - - // Increment the reference count. - int (CEF_CALLBACK *add_ref)(struct _cef_base_t* self); - // Decrement the reference count. Delete this object when no references - // remain. - int (CEF_CALLBACK *release)(struct _cef_base_t* self); - // Returns the current number of references. - int (CEF_CALLBACK *get_refct)(struct _cef_base_t* self); - -} cef_base_t; - - -// Check that the structure |s|, which is defined with a cef_base_t member named -// |base|, is large enough to contain the specified member |f|. -#define CEF_MEMBER_EXISTS(s, f) \ - ((int)&((s)->f) - (int)(s) + sizeof((s)->f) <= (s)->base.size) - -#define CEF_MEMBER_MISSING(s, f) (!CEF_MEMBER_EXISTS(s, f) || !((s)->f)) - - -// Implement this structure for task execution. -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; - - -// Structure used to represent a browser window. All functions exposed by this -// structure should be thread safe. -typedef struct _cef_browser_t -{ - // Base structure. - cef_base_t base; - - // 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 backwards. - 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); - - // Returns true (1) if the window is a popup window. - int (CEF_CALLBACK *is_popup)(struct _cef_browser_t* self); - - // Returns the handler for this browser. - struct _cef_handler_t* (CEF_CALLBACK *get_handler)( - struct _cef_browser_t* self); - - // Returns the main (top-level) frame for the browser window. - struct _cef_frame_t* (CEF_CALLBACK *get_main_frame)( - struct _cef_browser_t* self); - - // Returns the focused frame for the browser window. - struct _cef_frame_t* (CEF_CALLBACK *get_focused_frame)( - struct _cef_browser_t* self); - - // Returns the frame with the specified name, or NULL if not found. - struct _cef_frame_t* (CEF_CALLBACK *get_frame)(struct _cef_browser_t* self, - const wchar_t* name); - - // Returns the names of all existing frames. - 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 wchar_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); - -} 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. The |popup| parameter should be true (1) if the -// new window is a popup window. This function call will not block. -CEF_EXPORT int cef_browser_create(cef_window_info_t* windowInfo, int popup, - struct _cef_handler_t* handler, const wchar_t* url); - -// Create a new browser window using the window parameters specified by -// |windowInfo|. The |popup| parameter should be true (1) if the new window is a -// popup window. This function call will block and can only be used if the -// |multi_threaded_message_loop| parameter to cef_initialize() is false (0). -CEF_EXPORT cef_browser_t* cef_browser_create_sync(cef_window_info_t* windowInfo, - int popup, struct _cef_handler_t* handler, const wchar_t* url); - - -// Structure used to represent a frame in the browser window. All functions -// exposed by this structure should be thread safe. -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. - // The resulting string must be freed by calling cef_string_free(). - cef_string_t (CEF_CALLBACK *get_source)(struct _cef_frame_t* self); - - // Returns this frame's display text as a string. - // The resulting string must be freed by calling cef_string_free(). - cef_string_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 wchar_t* url); - - // Load the contents of |string| with the optional dummy target |url|. - void (CEF_CALLBACK *load_string)(struct _cef_frame_t* self, - const wchar_t* string, const wchar_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 wchar_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 wchar_t* jsCode, const wchar_t* scriptUrl, int startLine); - - // Returns true (1) if this is the main frame. - int (CEF_CALLBACK *is_main)(struct _cef_frame_t* self); - - // Returns true (1) if this is the focused frame. - int (CEF_CALLBACK *is_focused)(struct _cef_frame_t* self); - - // Returns this frame's name. - // The resulting string must be freed by calling cef_string_free(). - cef_string_t (CEF_CALLBACK *get_name)(struct _cef_frame_t* self); - - // Return the URL currently loaded in this frame. - // The resulting string must be freed by calling cef_string_free(). - cef_string_t (CEF_CALLBACK *get_url)(struct _cef_frame_t* self); - -} cef_frame_t; - - -// Structure that should be implemented to handle events generated by the -// browser window. All functions exposed by this structure should be thread -// safe. Each function in the structure returns a RetVal value. -typedef struct _cef_handler_t -{ - // Base structure. - cef_base_t base; - - // Event called before a new window is created. The |parentBrowser| parameter - // will point to the parent browser window, if any. The |popup| parameter will - // be true (1) if the new window is a popup window. If you create the window - // yourself you should populate the window handle member of |createInfo| and - // return RV_HANDLED. Otherwise, return RV_CONTINUE and the framework will - // create the window. By default, a newly created window will recieve the - // same handler as the parent window. To change the handler for the new - // window modify the object that |handler| points to. - enum cef_retval_t (CEF_CALLBACK *handle_before_created)( - struct _cef_handler_t* self, struct _cef_browser_t* parentBrowser, - struct _cef_window_info_t* windowInfo, int popup, - struct _cef_handler_t** handler, cef_string_t* url); - - // Event called after a new window is created. The return value is currently - // ignored. - enum cef_retval_t (CEF_CALLBACK *handle_after_created)( - struct _cef_handler_t* self, struct _cef_browser_t* browser); - - // Event called when a frame's address has changed. The return value is - // currently ignored. - enum cef_retval_t (CEF_CALLBACK *handle_address_change)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_frame_t* frame, const wchar_t* url); - - // Event called when the page title changes. The return value is currently - // ignored. - enum cef_retval_t (CEF_CALLBACK *handle_title_change)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - const wchar_t* title); - - // Event called before browser navigation. The client has an opportunity to - // modify the |request| object if desired. Return RV_HANDLED to cancel - // navigation. - enum cef_retval_t (CEF_CALLBACK *handle_before_browse)( - struct _cef_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); - - // Event called when the browser begins loading a page. The |frame| pointer - // will be NULL if the event represents the overall load status and not the - // load status for a particular frame. The return value is currently ignored. - enum cef_retval_t (CEF_CALLBACK *handle_load_start)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_frame_t* frame); - - // Event called when the browser is done loading a page. The |frame| pointer - // will be NULL if the event represents the overall load status and not the - // load status for a particular frame. This event will be generated - // irrespective of whether the request completes successfully. The return - // value is currently ignored. - enum cef_retval_t (CEF_CALLBACK *handle_load_end)(struct _cef_handler_t* self, - struct _cef_browser_t* browser, struct _cef_frame_t* frame); - - // 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 RV_HANDLED. - // Otherwise, return RV_CONTINUE for the default error text. - enum cef_retval_t (CEF_CALLBACK *handle_load_error)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_frame_t* frame, enum cef_handler_errorcode_t errorCode, - const wchar_t* failedUrl, cef_string_t* errorText); - - // Event called before a resource is loaded. To allow the resource to load - // normally return RV_CONTINUE. To redirect the resource to a new url populate - // the |redirectUrl| value and return RV_CONTINUE. To specify data for the - // resource return a CefStream object in |resourceStream|, set |mimeType| to - // the resource stream's mime type, and return RV_CONTINUE. To cancel loading - // of the resource return RV_HANDLED. 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. - enum cef_retval_t (CEF_CALLBACK *handle_before_resource_load)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_request_t* request, cef_string_t* redirectUrl, - struct _cef_stream_reader_t** resourceStream, cef_string_t* mimeType, - int loadFlags); - - // Event called before a context menu is displayed. To cancel display of the - // default context menu return RV_HANDLED. - enum cef_retval_t (CEF_CALLBACK *handle_before_menu)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - const struct _cef_handler_menuinfo_t* menuInfo); - - // Event 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. The return value is currently ignored. - enum cef_retval_t (CEF_CALLBACK *handle_get_menu_label)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - enum cef_handler_menuid_t menuId, cef_string_t* label); - - // Event called when an option is selected from the default context menu. - // Return RV_HANDLED to cancel default handling of the action. - enum cef_retval_t (CEF_CALLBACK *handle_menu_action)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - enum cef_handler_menuid_t menuId); - - // Event 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 RV_CONTINUE to display the default print options or - // RV_HANDLED to display the modified |printOptions|. - enum cef_retval_t (CEF_CALLBACK *handle_print_options)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_print_options_t* printOptions); - - // Event 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 RV_HANDLED. Otherwise, populate the approprate variables - // and return RV_CONTINUE. - enum cef_retval_t (CEF_CALLBACK *handle_print_header_footer)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_frame_t* frame, struct _cef_print_info_t* printInfo, - const wchar_t* url, const wchar_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); - - // Run a JS alert message. Return RV_CONTINUE to display the default alert or - // RV_HANDLED if you displayed a custom alert. - enum cef_retval_t (CEF_CALLBACK *handle_jsalert)(struct _cef_handler_t* self, - struct _cef_browser_t* browser, struct _cef_frame_t* frame, - const wchar_t* message); - - // Run a JS confirm request. Return RV_CONTINUE to display the default alert - // or RV_HANDLED if you displayed a custom alert. If you handled the alert - // set |retval| to true (1) if the user accepted the confirmation. - enum cef_retval_t (CEF_CALLBACK *handle_jsconfirm)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_frame_t* frame, const wchar_t* message, int* retval); - - // Run a JS prompt request. Return RV_CONTINUE to display the default prompt - // or RV_HANDLED 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. - enum cef_retval_t (CEF_CALLBACK *handle_jsprompt)(struct _cef_handler_t* self, - struct _cef_browser_t* browser, struct _cef_frame_t* frame, - const wchar_t* message, const wchar_t* defaultValue, int* retval, - cef_string_t* result); - - // Event called for adding values to a frame's JavaScript 'window' object. The - // return value is currently ignored. - enum cef_retval_t (CEF_CALLBACK *handle_jsbinding)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - struct _cef_frame_t* frame, struct _cef_v8value_t* object); - - // Called just before a window is closed. The return value is currently - // ignored. - enum cef_retval_t (CEF_CALLBACK *handle_before_window_close)( - struct _cef_handler_t* self, struct _cef_browser_t* browser); - - // 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. The - // return value is currently ignored. - enum cef_retval_t (CEF_CALLBACK *handle_take_focus)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - int reverse); - - // Called when the browser component is requesting focus. |isWidget| will be - // true (1) if the focus is requested for a child widget of the browser - // window. Return RV_CONTINUE to allow the focus to be set or RV_HANDLED to - // cancel setting the focus. - enum cef_retval_t (CEF_CALLBACK *handle_set_focus)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - int isWidget); - - // Called when the browser component receives a keyboard event. |type| is the - // type of keyboard event (see |KeyEventType|). |code| is the windows scan- - // code for the event. |modifiers| is a set of bit-flags describing any - // pressed modifier keys. |isSystemKey| is set if Windows considers this a - // 'system key' message; - // (see http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx) - // Return RV_HANDLED if the keyboard event was handled or RV_CONTINUE to allow - // the browser component to handle the event. - enum cef_retval_t (CEF_CALLBACK *handle_key_event)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - enum cef_handler_keyevent_type_t type, int code, int modifiers, - int isSystemKey); - - // Event 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 RV_HANDLED. Otherwise, you can - // optionally modify |text| and then return RV_CONTINUE to allow the browser - // to display the tooltip. - enum cef_retval_t (CEF_CALLBACK *handle_tooltip)(struct _cef_handler_t* self, - struct _cef_browser_t* browser, cef_string_t* text); - - // Called to display a console message. Return RV_HANDLED to stop the message - // from being output to the console. - enum cef_retval_t (CEF_CALLBACK *handle_console_message)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - const wchar_t* message, const wchar_t* source, int line); - - // 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. The return value is currently - // ignored. - enum cef_retval_t (CEF_CALLBACK *handle_find_result)( - struct _cef_handler_t* self, struct _cef_browser_t* browser, - int identifier, int count, const cef_rect_t* selectionRect, - int activeMatchOrdinal, int finalUpdate); - -} cef_handler_t; - - -// Structure used to represent a web request. -typedef struct _cef_request_t -{ - // Base structure. - cef_base_t base; - - // Fully qualified URL to load. - // The resulting string must be freed by calling cef_string_free(). - cef_string_t (CEF_CALLBACK *get_url)(struct _cef_request_t* self); - void (CEF_CALLBACK *set_url)(struct _cef_request_t* self, const wchar_t* url); - - // Optional request function type, defaulting to POST if post data is provided - // and GET otherwise. - // The resulting string must be freed by calling cef_string_free(). - cef_string_t (CEF_CALLBACK *get_method)(struct _cef_request_t* self); - void (CEF_CALLBACK *set_method)(struct _cef_request_t* self, - const wchar_t* method); - - // Optional post data. - struct _cef_post_data_t* (CEF_CALLBACK *get_post_data)( - struct _cef_request_t* self); - void (CEF_CALLBACK *set_post_data)(struct _cef_request_t* self, - struct _cef_post_data_t* postData); - - // Optional header values. - void (CEF_CALLBACK *get_header_map)(struct _cef_request_t* self, - cef_string_map_t headerMap); - void (CEF_CALLBACK *set_header_map)(struct _cef_request_t* self, - cef_string_map_t headerMap); - - // Set all values at one time. - void (CEF_CALLBACK *set)(struct _cef_request_t* self, const wchar_t* url, - const wchar_t* method, struct _cef_post_data_t* postData, - cef_string_map_t headerMap); - -} 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. -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. - struct _cef_post_data_element_t* (CEF_CALLBACK *get_elements)( - struct _cef_post_data_t* self, int elementIndex); - - // 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. -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 wchar_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_free(). - cef_string_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_tElement object. -CEF_EXPORT cef_post_data_element_t* cef_post_data_element_create(); - - -// Structure the client can implement to provide a custom stream reader. -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. - int (CEF_CALLBACK *seek)(struct _cef_read_handler_t* self, long offset, - int whence); - - // Return the current offset position. - long (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. -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, long offset, - int whence); - - // Return the current offset position. - long (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. -CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_file( - const wchar_t* fileName); -CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_data(void* data, - size_t size); -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. -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. - int (CEF_CALLBACK *seek)(struct _cef_write_handler_t* self, long offset, - int whence); - - // Return the current offset position. - long (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. -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. - int (CEF_CALLBACK *seek)(struct _cef_stream_writer_t* self, long offset, - int whence); - - // Return the current offset position. - long (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. -CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_file( - const wchar_t* fileName); -CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_handler( - cef_write_handler_t* handler); - - -// Structure that should be implemented to handle V8 function calls. -typedef struct _cef_v8handler_t -{ - // Base structure. - cef_base_t base; - - // Execute with the specified argument list and return value. Return true (1) - // if the function was handled. - int (CEF_CALLBACK *execute)(struct _cef_v8handler_t* self, - const wchar_t* name, struct _cef_v8value_t* object, size_t argumentCount, - struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, - cef_string_t* exception); - -} cef_v8handler_t; - - -// Structure representing a V8 value. -typedef struct _cef_v8value_t -{ - // Base structure. - cef_base_t base; - - // Check the value type. - int (CEF_CALLBACK *is_undefined)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_null)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_bool)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_int)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_double)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_string)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_object)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_array)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *is_function)(struct _cef_v8value_t* self); - - // Return a primitive value type. The underlying data will be converted to - // the requested type if necessary. - int (CEF_CALLBACK *get_bool_value)(struct _cef_v8value_t* self); - int (CEF_CALLBACK *get_int_value)(struct _cef_v8value_t* self); - double (CEF_CALLBACK *get_double_value)(struct _cef_v8value_t* self); - // The resulting string must be freed by calling cef_string_free(). - cef_string_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. - // Keys beginning with "Cef::" and "v8::" are reserved by the system. - - // 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 wchar_t* key); - int (CEF_CALLBACK *has_value_byindex)(struct _cef_v8value_t* self, int index); - - // Delete the value with the specified identifier. - int (CEF_CALLBACK *delete_value_bykey)(struct _cef_v8value_t* self, - const wchar_t* key); - int (CEF_CALLBACK *delete_value_byindex)(struct _cef_v8value_t* self, - int index); - - // Returns the value with the specified identifier. - struct _cef_v8value_t* (CEF_CALLBACK *get_value_bykey)( - struct _cef_v8value_t* self, const wchar_t* key); - struct _cef_v8value_t* (CEF_CALLBACK *get_value_byindex)( - struct _cef_v8value_t* self, int index); - - // Associate value with the specified identifier. - int (CEF_CALLBACK *set_value_bykey)(struct _cef_v8value_t* self, - const wchar_t* key, struct _cef_v8value_t* value); - int (CEF_CALLBACK *set_value_byindex)(struct _cef_v8value_t* self, int index, - struct _cef_v8value_t* value); - - // 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); - - // Returns the user data, if any, specified when the object was created. - struct _cef_base_t* (CEF_CALLBACK *get_user_data)( - struct _cef_v8value_t* self); - - - // 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_free(). - cef_string_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. - int (CEF_CALLBACK *execute_function)(struct _cef_v8value_t* self, - struct _cef_v8value_t* object, size_t argumentCount, - struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, - cef_string_t* exception); - -} cef_v8value_t; - - -// 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. -CEF_EXPORT cef_v8value_t* cef_v8value_create_undefined(); -CEF_EXPORT cef_v8value_t* cef_v8value_create_null(); -CEF_EXPORT cef_v8value_t* cef_v8value_create_bool(int value); -CEF_EXPORT cef_v8value_t* cef_v8value_create_int(int value); -CEF_EXPORT cef_v8value_t* cef_v8value_create_double(double value); -CEF_EXPORT cef_v8value_t* cef_v8value_create_string(const wchar_t* value); -CEF_EXPORT cef_v8value_t* cef_v8value_create_object(cef_base_t* user_data); -CEF_EXPORT cef_v8value_t* cef_v8value_create_array(); -CEF_EXPORT cef_v8value_t* cef_v8value_create_function(const wchar_t* name, - cef_v8handler_t* handler); - - -// Structure that creates cef_scheme_handler_t instances. -typedef struct _cef_scheme_handler_factory_t -{ - // Base structure. - cef_base_t base; - - // Return a new scheme handler instance to handle the request. - struct _cef_scheme_handler_t* (CEF_CALLBACK *create)( - struct _cef_scheme_handler_factory_t* self); - -} cef_scheme_handler_factory_t; - - -// Structure used to represent a custom scheme handler structure. -typedef struct _cef_scheme_handler_t -{ - // Base structure. - cef_base_t base; - - // Process the request. All response generation should take place in this - // function. If there is no response set |response_length| to zero and - // read_response() will not be called. If the response length is not known - // then set |response_length| to -1 and read_response() will be called until - // it returns false (0) or until the value of |bytes_read| is set to 0. - // Otherwise, set |response_length| to a positive value and read_response() - // will be called until it returns false (0), the value of |bytes_read| is set - // to 0 or the specified number of bytes have been read. If there is a - // response set |mime_type| to the mime type for the response. - int (CEF_CALLBACK *process_request)(struct _cef_scheme_handler_t* self, - struct _cef_request_t* request, cef_string_t* mime_type, - int* response_length); - - // Cancel processing of the request. - void (CEF_CALLBACK *cancel)(struct _cef_scheme_handler_t* self); - - // Copy up to |bytes_to_read| bytes into |data_out|. If the copy succeeds set - // |bytes_read| to the number of bytes copied and return true (1). If the copy - // fails return false (0) and read_response() will not be called again. - int (CEF_CALLBACK *read_response)(struct _cef_scheme_handler_t* self, - void* data_out, int bytes_to_read, int* bytes_read); - -} cef_scheme_handler_t; - - -#ifdef __cplusplus -} -#endif - -#endif // _CEF_CAPI_H +// 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. +// +// --------------------------------------------------------------------------- +// +// 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_CAPI_H +#define _CEF_CAPI_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cef_export.h" +#include "cef_string.h" +#include "cef_string_list.h" +#include "cef_string_map.h" +#include "cef_types.h" + + +// This function should only be called once when the application is started. +// Create the thread to host the UI message loop. A return value of true (1) +// indicates that it succeeded and false (0) indicates that it failed. Set +// |multi_threaded_message_loop| to true (1) to have the message loop run in a +// separate thread. If |multi_threaded_message_loop| is false (0) than the +// cef_do_message_loop_work() function must be called from your message loop. +// Set |cache_path| to the location where cache data will be stored on disk. If +// |cache_path| is NULL an in-memory cache will be used for cache data. +CEF_EXPORT int cef_initialize(int multi_threaded_message_loop, + const wchar_t* cache_path); + +// This function should only be called once before the application exits. Shut +// down the thread hosting the UI message loop and destroy any created windows. +CEF_EXPORT void cef_shutdown(); + +// Perform message loop processing. Has no affect if the browser UI loop is +// running in a separate thread. +CEF_EXPORT void cef_do_message_loop_work(); + +// 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 = {}; +// // 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 wchar_t* extension_name, + const wchar_t* javascript_code, struct _cef_v8handler_t* handler); + +// Register a custom scheme handler factory for the specified |scheme_name| and +// |host_name|. All URLs beginning with scheme_name://host_name/ can be handled +// by cef_scheme_handler_t instances returned by the factory. Specify an NULL +// |host_name| value to match all host names. +CEF_EXPORT int cef_register_scheme(const wchar_t* scheme_name, + const wchar_t* host_name, struct _cef_scheme_handler_factory_t* factory); + +// 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() +// was called with a |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. +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. +CEF_EXPORT int cef_post_delayed_task(cef_thread_id_t threadId, + struct _cef_task_t* task, long delay_ms); + +typedef struct _cef_base_t +{ + // Size of the data structure. + size_t size; + + // Increment the reference count. + int (CEF_CALLBACK *add_ref)(struct _cef_base_t* self); + // Decrement the reference count. Delete this object when no references + // remain. + int (CEF_CALLBACK *release)(struct _cef_base_t* self); + // Returns the current number of references. + int (CEF_CALLBACK *get_refct)(struct _cef_base_t* self); + +} cef_base_t; + + +// Check that the structure |s|, which is defined with a cef_base_t member named +// |base|, is large enough to contain the specified member |f|. +#define CEF_MEMBER_EXISTS(s, f) \ + ((int)&((s)->f) - (int)(s) + sizeof((s)->f) <= (s)->base.size) + +#define CEF_MEMBER_MISSING(s, f) (!CEF_MEMBER_EXISTS(s, f) || !((s)->f)) + + +// Implement this structure for task execution. +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; + + +// Structure used to represent a browser window. All functions exposed by this +// structure should be thread safe. +typedef struct _cef_browser_t +{ + // Base structure. + cef_base_t base; + + // 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 backwards. + 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); + + // Returns true (1) if the window is a popup window. + int (CEF_CALLBACK *is_popup)(struct _cef_browser_t* self); + + // Returns the handler for this browser. + struct _cef_handler_t* (CEF_CALLBACK *get_handler)( + struct _cef_browser_t* self); + + // Returns the main (top-level) frame for the browser window. + struct _cef_frame_t* (CEF_CALLBACK *get_main_frame)( + struct _cef_browser_t* self); + + // Returns the focused frame for the browser window. + struct _cef_frame_t* (CEF_CALLBACK *get_focused_frame)( + struct _cef_browser_t* self); + + // Returns the frame with the specified name, or NULL if not found. + struct _cef_frame_t* (CEF_CALLBACK *get_frame)(struct _cef_browser_t* self, + const wchar_t* name); + + // Returns the names of all existing frames. + 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 wchar_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); + +} 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. The |popup| parameter should be true (1) if the +// new window is a popup window. This function call will not block. +CEF_EXPORT int cef_browser_create(cef_window_info_t* windowInfo, int popup, + struct _cef_handler_t* handler, const wchar_t* url); + +// Create a new browser window using the window parameters specified by +// |windowInfo|. The |popup| parameter should be true (1) if the new window is a +// popup window. This function call will block and can only be used if the +// |multi_threaded_message_loop| parameter to cef_initialize() is false (0). +CEF_EXPORT cef_browser_t* cef_browser_create_sync(cef_window_info_t* windowInfo, + int popup, struct _cef_handler_t* handler, const wchar_t* url); + + +// Structure used to represent a frame in the browser window. All functions +// exposed by this structure should be thread safe. +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. + // The resulting string must be freed by calling cef_string_free(). + cef_string_t (CEF_CALLBACK *get_source)(struct _cef_frame_t* self); + + // Returns this frame's display text as a string. + // The resulting string must be freed by calling cef_string_free(). + cef_string_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 wchar_t* url); + + // Load the contents of |string| with the optional dummy target |url|. + void (CEF_CALLBACK *load_string)(struct _cef_frame_t* self, + const wchar_t* string, const wchar_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 wchar_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 wchar_t* jsCode, const wchar_t* scriptUrl, int startLine); + + // Returns true (1) if this is the main frame. + int (CEF_CALLBACK *is_main)(struct _cef_frame_t* self); + + // Returns true (1) if this is the focused frame. + int (CEF_CALLBACK *is_focused)(struct _cef_frame_t* self); + + // Returns this frame's name. + // The resulting string must be freed by calling cef_string_free(). + cef_string_t (CEF_CALLBACK *get_name)(struct _cef_frame_t* self); + + // Return the URL currently loaded in this frame. + // The resulting string must be freed by calling cef_string_free(). + cef_string_t (CEF_CALLBACK *get_url)(struct _cef_frame_t* self); + +} cef_frame_t; + + +// Structure that should be implemented to handle events generated by the +// browser window. All functions exposed by this structure should be thread +// safe. Each function in the structure returns a RetVal value. +typedef struct _cef_handler_t +{ + // Base structure. + cef_base_t base; + + // Event called before a new window is created. The |parentBrowser| parameter + // will point to the parent browser window, if any. The |popup| parameter will + // be true (1) if the new window is a popup window. If you create the window + // yourself you should populate the window handle member of |createInfo| and + // return RV_HANDLED. Otherwise, return RV_CONTINUE and the framework will + // create the window. By default, a newly created window will recieve the + // same handler as the parent window. To change the handler for the new + // window modify the object that |handler| points to. + enum cef_retval_t (CEF_CALLBACK *handle_before_created)( + struct _cef_handler_t* self, struct _cef_browser_t* parentBrowser, + struct _cef_window_info_t* windowInfo, int popup, + struct _cef_handler_t** handler, cef_string_t* url); + + // Event called after a new window is created. The return value is currently + // ignored. + enum cef_retval_t (CEF_CALLBACK *handle_after_created)( + struct _cef_handler_t* self, struct _cef_browser_t* browser); + + // Event called when a frame's address has changed. The return value is + // currently ignored. + enum cef_retval_t (CEF_CALLBACK *handle_address_change)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, const wchar_t* url); + + // Event called when the page title changes. The return value is currently + // ignored. + enum cef_retval_t (CEF_CALLBACK *handle_title_change)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + const wchar_t* title); + + // Event called before browser navigation. The client has an opportunity to + // modify the |request| object if desired. Return RV_HANDLED to cancel + // navigation. + enum cef_retval_t (CEF_CALLBACK *handle_before_browse)( + struct _cef_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); + + // Event called when the browser begins loading a page. The |frame| pointer + // will be NULL if the event represents the overall load status and not the + // load status for a particular frame. The return value is currently ignored. + enum cef_retval_t (CEF_CALLBACK *handle_load_start)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame); + + // Event called when the browser is done loading a page. The |frame| pointer + // will be NULL if the event represents the overall load status and not the + // load status for a particular frame. This event will be generated + // irrespective of whether the request completes successfully. The return + // value is currently ignored. + enum cef_retval_t (CEF_CALLBACK *handle_load_end)(struct _cef_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame); + + // 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 RV_HANDLED. + // Otherwise, return RV_CONTINUE for the default error text. + enum cef_retval_t (CEF_CALLBACK *handle_load_error)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, enum cef_handler_errorcode_t errorCode, + const wchar_t* failedUrl, cef_string_t* errorText); + + // Event called before a resource is loaded. To allow the resource to load + // normally return RV_CONTINUE. To redirect the resource to a new url populate + // the |redirectUrl| value and return RV_CONTINUE. To specify data for the + // resource return a CefStream object in |resourceStream|, set |mimeType| to + // the resource stream's mime type, and return RV_CONTINUE. To cancel loading + // of the resource return RV_HANDLED. 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. + enum cef_retval_t (CEF_CALLBACK *handle_before_resource_load)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_request_t* request, cef_string_t* redirectUrl, + struct _cef_stream_reader_t** resourceStream, cef_string_t* mimeType, + int loadFlags); + + // Event called before a context menu is displayed. To cancel display of the + // default context menu return RV_HANDLED. + enum cef_retval_t (CEF_CALLBACK *handle_before_menu)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + const struct _cef_handler_menuinfo_t* menuInfo); + + // Event 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. The return value is currently ignored. + enum cef_retval_t (CEF_CALLBACK *handle_get_menu_label)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + enum cef_handler_menuid_t menuId, cef_string_t* label); + + // Event called when an option is selected from the default context menu. + // Return RV_HANDLED to cancel default handling of the action. + enum cef_retval_t (CEF_CALLBACK *handle_menu_action)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + enum cef_handler_menuid_t menuId); + + // Event 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 RV_CONTINUE to display the default print options or + // RV_HANDLED to display the modified |printOptions|. + enum cef_retval_t (CEF_CALLBACK *handle_print_options)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_print_options_t* printOptions); + + // Event 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 RV_HANDLED. Otherwise, populate the approprate variables + // and return RV_CONTINUE. + enum cef_retval_t (CEF_CALLBACK *handle_print_header_footer)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_print_info_t* printInfo, + const wchar_t* url, const wchar_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); + + // Run a JS alert message. Return RV_CONTINUE to display the default alert or + // RV_HANDLED if you displayed a custom alert. + enum cef_retval_t (CEF_CALLBACK *handle_jsalert)(struct _cef_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const wchar_t* message); + + // Run a JS confirm request. Return RV_CONTINUE to display the default alert + // or RV_HANDLED if you displayed a custom alert. If you handled the alert + // set |retval| to true (1) if the user accepted the confirmation. + enum cef_retval_t (CEF_CALLBACK *handle_jsconfirm)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, const wchar_t* message, int* retval); + + // Run a JS prompt request. Return RV_CONTINUE to display the default prompt + // or RV_HANDLED 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. + enum cef_retval_t (CEF_CALLBACK *handle_jsprompt)(struct _cef_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const wchar_t* message, const wchar_t* defaultValue, int* retval, + cef_string_t* result); + + // Event called for adding values to a frame's JavaScript 'window' object. The + // return value is currently ignored. + enum cef_retval_t (CEF_CALLBACK *handle_jsbinding)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_v8value_t* object); + + // Called just before a window is closed. The return value is currently + // ignored. + enum cef_retval_t (CEF_CALLBACK *handle_before_window_close)( + struct _cef_handler_t* self, struct _cef_browser_t* browser); + + // 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. The + // return value is currently ignored. + enum cef_retval_t (CEF_CALLBACK *handle_take_focus)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + int reverse); + + // Called when the browser component is requesting focus. |isWidget| will be + // true (1) if the focus is requested for a child widget of the browser + // window. Return RV_CONTINUE to allow the focus to be set or RV_HANDLED to + // cancel setting the focus. + enum cef_retval_t (CEF_CALLBACK *handle_set_focus)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + int isWidget); + + // Called when the browser component receives a keyboard event. |type| is the + // type of keyboard event (see |KeyEventType|). |code| is the windows scan- + // code for the event. |modifiers| is a set of bit-flags describing any + // pressed modifier keys. |isSystemKey| is set if Windows considers this a + // 'system key' message; + // (see http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx) + // Return RV_HANDLED if the keyboard event was handled or RV_CONTINUE to allow + // the browser component to handle the event. + enum cef_retval_t (CEF_CALLBACK *handle_key_event)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + enum cef_handler_keyevent_type_t type, int code, int modifiers, + int isSystemKey); + + // Event 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 RV_HANDLED. Otherwise, you can + // optionally modify |text| and then return RV_CONTINUE to allow the browser + // to display the tooltip. + enum cef_retval_t (CEF_CALLBACK *handle_tooltip)(struct _cef_handler_t* self, + struct _cef_browser_t* browser, cef_string_t* text); + + // Called to display a console message. Return RV_HANDLED to stop the message + // from being output to the console. + enum cef_retval_t (CEF_CALLBACK *handle_console_message)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + const wchar_t* message, const wchar_t* source, int line); + + // 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. The return value is currently + // ignored. + enum cef_retval_t (CEF_CALLBACK *handle_find_result)( + struct _cef_handler_t* self, struct _cef_browser_t* browser, + int identifier, int count, const cef_rect_t* selectionRect, + int activeMatchOrdinal, int finalUpdate); + +} cef_handler_t; + + +// Structure used to represent a web request. +typedef struct _cef_request_t +{ + // Base structure. + cef_base_t base; + + // Fully qualified URL to load. + // The resulting string must be freed by calling cef_string_free(). + cef_string_t (CEF_CALLBACK *get_url)(struct _cef_request_t* self); + void (CEF_CALLBACK *set_url)(struct _cef_request_t* self, const wchar_t* url); + + // Optional request function type, defaulting to POST if post data is provided + // and GET otherwise. + // The resulting string must be freed by calling cef_string_free(). + cef_string_t (CEF_CALLBACK *get_method)(struct _cef_request_t* self); + void (CEF_CALLBACK *set_method)(struct _cef_request_t* self, + const wchar_t* method); + + // Optional post data. + struct _cef_post_data_t* (CEF_CALLBACK *get_post_data)( + struct _cef_request_t* self); + void (CEF_CALLBACK *set_post_data)(struct _cef_request_t* self, + struct _cef_post_data_t* postData); + + // Optional header values. + void (CEF_CALLBACK *get_header_map)(struct _cef_request_t* self, + cef_string_map_t headerMap); + void (CEF_CALLBACK *set_header_map)(struct _cef_request_t* self, + cef_string_map_t headerMap); + + // Set all values at one time. + void (CEF_CALLBACK *set)(struct _cef_request_t* self, const wchar_t* url, + const wchar_t* method, struct _cef_post_data_t* postData, + cef_string_map_t headerMap); + +} 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. +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. + struct _cef_post_data_element_t* (CEF_CALLBACK *get_elements)( + struct _cef_post_data_t* self, int elementIndex); + + // 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. +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 wchar_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_free(). + cef_string_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_tElement object. +CEF_EXPORT cef_post_data_element_t* cef_post_data_element_create(); + + +// Structure the client can implement to provide a custom stream reader. +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. + int (CEF_CALLBACK *seek)(struct _cef_read_handler_t* self, long offset, + int whence); + + // Return the current offset position. + long (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. +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, long offset, + int whence); + + // Return the current offset position. + long (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. +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_file( + const wchar_t* fileName); +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_data(void* data, + size_t size); +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. +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. + int (CEF_CALLBACK *seek)(struct _cef_write_handler_t* self, long offset, + int whence); + + // Return the current offset position. + long (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. +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. + int (CEF_CALLBACK *seek)(struct _cef_stream_writer_t* self, long offset, + int whence); + + // Return the current offset position. + long (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. +CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_file( + const wchar_t* fileName); +CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_handler( + cef_write_handler_t* handler); + + +// Structure that should be implemented to handle V8 function calls. +typedef struct _cef_v8handler_t +{ + // Base structure. + cef_base_t base; + + // Execute with the specified argument list and return value. Return true (1) + // if the function was handled. + int (CEF_CALLBACK *execute)(struct _cef_v8handler_t* self, + const wchar_t* name, struct _cef_v8value_t* object, size_t argumentCount, + struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, + cef_string_t* exception); + +} cef_v8handler_t; + + +// Structure representing a V8 value. +typedef struct _cef_v8value_t +{ + // Base structure. + cef_base_t base; + + // Check the value type. + int (CEF_CALLBACK *is_undefined)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_null)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_bool)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_int)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_double)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_string)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_object)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_array)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *is_function)(struct _cef_v8value_t* self); + + // Return a primitive value type. The underlying data will be converted to + // the requested type if necessary. + int (CEF_CALLBACK *get_bool_value)(struct _cef_v8value_t* self); + int (CEF_CALLBACK *get_int_value)(struct _cef_v8value_t* self); + double (CEF_CALLBACK *get_double_value)(struct _cef_v8value_t* self); + // The resulting string must be freed by calling cef_string_free(). + cef_string_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. + // Keys beginning with "Cef::" and "v8::" are reserved by the system. + + // 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 wchar_t* key); + int (CEF_CALLBACK *has_value_byindex)(struct _cef_v8value_t* self, int index); + + // Delete the value with the specified identifier. + int (CEF_CALLBACK *delete_value_bykey)(struct _cef_v8value_t* self, + const wchar_t* key); + int (CEF_CALLBACK *delete_value_byindex)(struct _cef_v8value_t* self, + int index); + + // Returns the value with the specified identifier. + struct _cef_v8value_t* (CEF_CALLBACK *get_value_bykey)( + struct _cef_v8value_t* self, const wchar_t* key); + struct _cef_v8value_t* (CEF_CALLBACK *get_value_byindex)( + struct _cef_v8value_t* self, int index); + + // Associate value with the specified identifier. + int (CEF_CALLBACK *set_value_bykey)(struct _cef_v8value_t* self, + const wchar_t* key, struct _cef_v8value_t* value); + int (CEF_CALLBACK *set_value_byindex)(struct _cef_v8value_t* self, int index, + struct _cef_v8value_t* value); + + // 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); + + // Returns the user data, if any, specified when the object was created. + struct _cef_base_t* (CEF_CALLBACK *get_user_data)( + struct _cef_v8value_t* self); + + + // 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_free(). + cef_string_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. + int (CEF_CALLBACK *execute_function)(struct _cef_v8value_t* self, + struct _cef_v8value_t* object, size_t argumentCount, + struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, + cef_string_t* exception); + +} cef_v8value_t; + + +// 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. +CEF_EXPORT cef_v8value_t* cef_v8value_create_undefined(); +CEF_EXPORT cef_v8value_t* cef_v8value_create_null(); +CEF_EXPORT cef_v8value_t* cef_v8value_create_bool(int value); +CEF_EXPORT cef_v8value_t* cef_v8value_create_int(int value); +CEF_EXPORT cef_v8value_t* cef_v8value_create_double(double value); +CEF_EXPORT cef_v8value_t* cef_v8value_create_string(const wchar_t* value); +CEF_EXPORT cef_v8value_t* cef_v8value_create_object(cef_base_t* user_data); +CEF_EXPORT cef_v8value_t* cef_v8value_create_array(); +CEF_EXPORT cef_v8value_t* cef_v8value_create_function(const wchar_t* name, + cef_v8handler_t* handler); + + +// Structure that creates cef_scheme_handler_t instances. +typedef struct _cef_scheme_handler_factory_t +{ + // Base structure. + cef_base_t base; + + // Return a new scheme handler instance to handle the request. + struct _cef_scheme_handler_t* (CEF_CALLBACK *create)( + struct _cef_scheme_handler_factory_t* self); + +} cef_scheme_handler_factory_t; + + +// Structure used to represent a custom scheme handler structure. +typedef struct _cef_scheme_handler_t +{ + // Base structure. + cef_base_t base; + + // Process the request. All response generation should take place in this + // function. If there is no response set |response_length| to zero and + // read_response() will not be called. If the response length is not known + // then set |response_length| to -1 and read_response() will be called until + // it returns false (0) or until the value of |bytes_read| is set to 0. + // Otherwise, set |response_length| to a positive value and read_response() + // will be called until it returns false (0), the value of |bytes_read| is set + // to 0 or the specified number of bytes have been read. If there is a + // response set |mime_type| to the mime type for the response. + int (CEF_CALLBACK *process_request)(struct _cef_scheme_handler_t* self, + struct _cef_request_t* request, cef_string_t* mime_type, + int* response_length); + + // Cancel processing of the request. + void (CEF_CALLBACK *cancel)(struct _cef_scheme_handler_t* self); + + // Copy up to |bytes_to_read| bytes into |data_out|. If the copy succeeds set + // |bytes_read| to the number of bytes copied and return true (1). If the copy + // fails return false (0) and read_response() will not be called again. + int (CEF_CALLBACK *read_response)(struct _cef_scheme_handler_t* self, + void* data_out, int bytes_to_read, int* bytes_read); + +} cef_scheme_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // _CEF_CAPI_H diff --git a/include/cef_export.h b/include/cef_export.h index 738487b0f..9d5b0a565 100644 --- a/include/cef_export.h +++ b/include/cef_export.h @@ -1,41 +1,41 @@ -// 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. - - -#ifdef _MSC_VER // MSVC -#ifdef BUILDING_CEF_SHARED -#define CEF_EXPORT __declspec(dllexport) -#elif USING_CEF_SHARED -#define CEF_EXPORT __declspec(dllimport) -#else -#define CEF_EXPORT -#endif // BUILDING_CEF_SHARED -#define CEF_CALLBACK __stdcall -#endif // MSVC +// 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. + + +#ifdef _MSC_VER // MSVC +#ifdef BUILDING_CEF_SHARED +#define CEF_EXPORT __declspec(dllexport) +#elif USING_CEF_SHARED +#define CEF_EXPORT __declspec(dllimport) +#else +#define CEF_EXPORT +#endif // BUILDING_CEF_SHARED +#define CEF_CALLBACK __stdcall +#endif // MSVC diff --git a/include/cef_nplugin.h b/include/cef_nplugin.h index dfa80efb9..82b5b3960 100644 --- a/include/cef_nplugin.h +++ b/include/cef_nplugin.h @@ -1,85 +1,85 @@ -// 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_PLUGIN_H -#define _CEF_PLUGIN_H - -#include -#include -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/nphostapi.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 structure describes a mime type entry for a plugin. -struct CefPluginMimeType { - // The actual mime type. - std::wstring mime_type; - - // A list of all the file extensions for this mime type. - std::vector file_extensions; - - // Description of the mime type. - std::wstring description; -}; - -// This structure provides attribute information and entry point functions for -// a plugin. -struct CefPluginInfo { - // The unique name that identifies the plugin. - std::wstring unique_name; - - // The friendly display name of the plugin. - std::wstring display_name; - - // The version string of the plugin. - std::wstring version; - - // A description of the plugin. - std::wstring description; - - // A list of all the mime types that this plugin supports. - std::vector mime_types; - - // Entry point function pointers. - NP_GetEntryPointsFunc np_getentrypoints; - NP_InitializeFunc np_initialize; - NP_ShutdownFunc np_shutdown; -}; - -// Register a plugin with the system. -bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info); - -#endif // _CEF_PLUGIN_H +// 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_PLUGIN_H +#define _CEF_PLUGIN_H + +#include +#include +#include "third_party/npapi/bindings/npapi.h" +#include "third_party/npapi/bindings/nphostapi.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 structure describes a mime type entry for a plugin. +struct CefPluginMimeType { + // The actual mime type. + std::wstring mime_type; + + // A list of all the file extensions for this mime type. + std::vector file_extensions; + + // Description of the mime type. + std::wstring description; +}; + +// This structure provides attribute information and entry point functions for +// a plugin. +struct CefPluginInfo { + // The unique name that identifies the plugin. + std::wstring unique_name; + + // The friendly display name of the plugin. + std::wstring display_name; + + // The version string of the plugin. + std::wstring version; + + // A description of the plugin. + std::wstring description; + + // A list of all the mime types that this plugin supports. + std::vector mime_types; + + // Entry point function pointers. + NP_GetEntryPointsFunc np_getentrypoints; + NP_InitializeFunc np_initialize; + NP_ShutdownFunc np_shutdown; +}; + +// Register a plugin with the system. +bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info); + +#endif // _CEF_PLUGIN_H diff --git a/include/cef_nplugin_capi.h b/include/cef_nplugin_capi.h index 4a01e36ec..da37e729e 100644 --- a/include/cef_nplugin_capi.h +++ b/include/cef_nplugin_capi.h @@ -1,90 +1,90 @@ -// 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_PLUGIN_CAPI_H -#define _CEF_PLUGIN_CAPI_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "cef_export.h" -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/nphostapi.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 structure provides attribute information and entry point functions for -// a plugin. -typedef struct _cef_plugin_info_t { - // The unique name that identifies the plugin. - const wchar_t* unique_name; - - // The friendly display name of the plugin. - const wchar_t* display_name; - - // The version string of the plugin. - const wchar_t* version; - - // A description of the plugin. - const wchar_t* description; - - // A pipe (|) delimited list of mime type values that the plugin supports. - const wchar_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 (,). - const wchar_t* file_extensions; - - // A pipe (|) delimited list of description values. Each value is associated - // with the mime type value at the same position. - const wchar_t* type_descriptions; - - // Entry point function pointers. - NP_GetEntryPointsFunc np_getentrypoints; - NP_InitializeFunc np_initialize; - NP_ShutdownFunc np_shutdown; -} cef_plugin_info_t; - -// 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_PLUGIN_CAPI_H +// 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_PLUGIN_CAPI_H +#define _CEF_PLUGIN_CAPI_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cef_export.h" +#include "third_party/npapi/bindings/npapi.h" +#include "third_party/npapi/bindings/nphostapi.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 structure provides attribute information and entry point functions for +// a plugin. +typedef struct _cef_plugin_info_t { + // The unique name that identifies the plugin. + const wchar_t* unique_name; + + // The friendly display name of the plugin. + const wchar_t* display_name; + + // The version string of the plugin. + const wchar_t* version; + + // A description of the plugin. + const wchar_t* description; + + // A pipe (|) delimited list of mime type values that the plugin supports. + const wchar_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 (,). + const wchar_t* file_extensions; + + // A pipe (|) delimited list of description values. Each value is associated + // with the mime type value at the same position. + const wchar_t* type_descriptions; + + // Entry point function pointers. + NP_GetEntryPointsFunc np_getentrypoints; + NP_InitializeFunc np_initialize; + NP_ShutdownFunc np_shutdown; +} cef_plugin_info_t; + +// 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_PLUGIN_CAPI_H diff --git a/include/cef_ptr.h b/include/cef_ptr.h index cdba1ceb4..50e93e2c5 100644 --- a/include/cef_ptr.h +++ b/include/cef_ptr.h @@ -1,193 +1,193 @@ -// 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_PTR_H -#define _CEF_PTR_H - -// 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 foo = new MyFoo(); -// foo->Method(param); -// // |foo| is released when this function returns -// } -// -// void some_other_function() { -// CefRefPtr foo = new MyFoo(); -// ... -// foo = NULL; // explicitly releases |foo| -// ... -// if (foo) -// foo->Method(param); -// } -// -// The above examples show how CefRefPtr acts like a pointer to T. -// Given two CefRefPtr classes, it is also possible to exchange -// references between the two objects, like so: -// -// { -// CefRefPtr a = new MyFoo(); -// CefRefPtr 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 a = new MyFoo(); -// CefRefPtr 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 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 some_func_with_retval() { -// // The MyFoo object that |foox| represents starts with a single -// // reference. -// CefRefPtr 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 foo = new MyFoo(); -// -// // pass |foo| as a parameter. -// some_function(foo); -// -// CefRefPtr 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 > MyFooVec; -// -// // The MyFoo object that |foo| represents starts with a single -// // reference. -// CefRefPtr 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) { - 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_); - } - - private: - T* ptr_; -}; - -#endif // _CEF_PTR_H +// 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_PTR_H +#define _CEF_PTR_H + +// 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 foo = new MyFoo(); +// foo->Method(param); +// // |foo| is released when this function returns +// } +// +// void some_other_function() { +// CefRefPtr foo = new MyFoo(); +// ... +// foo = NULL; // explicitly releases |foo| +// ... +// if (foo) +// foo->Method(param); +// } +// +// The above examples show how CefRefPtr acts like a pointer to T. +// Given two CefRefPtr classes, it is also possible to exchange +// references between the two objects, like so: +// +// { +// CefRefPtr a = new MyFoo(); +// CefRefPtr 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 a = new MyFoo(); +// CefRefPtr 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 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 some_func_with_retval() { +// // The MyFoo object that |foox| represents starts with a single +// // reference. +// CefRefPtr 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 foo = new MyFoo(); +// +// // pass |foo| as a parameter. +// some_function(foo); +// +// CefRefPtr 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 > MyFooVec; +// +// // The MyFoo object that |foo| represents starts with a single +// // reference. +// CefRefPtr 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) { + 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_); + } + + private: + T* ptr_; +}; + +#endif // _CEF_PTR_H diff --git a/include/cef_string.h b/include/cef_string.h index 47469040e..8eef8af0d 100644 --- a/include/cef_string.h +++ b/include/cef_string.h @@ -1,86 +1,86 @@ -// 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_STRING_H -#define _CEF_STRING_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "cef_export.h" -#include - -// CEF strings are NUL-terminated wide character strings prefixed with a size -// value, similar to the Microsoft BSTR type. Use the below API functions for -// allocating, managing and freeing CEF strings. -typedef wchar_t* cef_string_t; - -// Return the wide character length of the CEF string as allocated by -// cef_string_alloc_len(). The returned value does not include the NUL -// terminating character. This length may differ from the string length -// as returned by wcslen(). -CEF_EXPORT size_t cef_string_length(cef_string_t str); - -// Allocate and return a new CEF string that is a copy of |str|. If |str| is -// NULL or if allocation fails NULL will be returned. If |str| is of length -// 0 a valid empty CEF string will be returned. -CEF_EXPORT cef_string_t cef_string_alloc(const wchar_t* str); - -// Allocate and return a new CEF string that is a copy of |str|. |len| is the -// wide character length of the new CEF string not including the NUL -// terminating character. |str| will be copied without checking for a NUL -// terminating character. If |str| is NULL or if allocation fails NULL will -// be returned. If |str| is of length 0 a valid empty CEF string will be -// returned. -CEF_EXPORT cef_string_t cef_string_alloc_length(const wchar_t* str, - size_t len); - -// Reallocate an existing CEF string. The contents of |oldstr| will be -// replaced with the contents of |newstr|; |newstr| may not be NULL. Returns 1 -// on success and 0 on failure. -CEF_EXPORT int cef_string_realloc(cef_string_t* oldstr, const wchar_t* newstr); - -// Reallocate an existing CEF string. If |newstr| is NULL the contents of -// |oldstr| will remain unchanged; otherwise, they will be replaced with the -// contents of |newstr|. |len| is the new wide character length of the string -// not including the NUL terminating character. Returns 1 on success and 0 -// on failure. -CEF_EXPORT int cef_string_realloc_length(cef_string_t* oldstr, - const wchar_t* newstr, - size_t len); - -// Free a CEF string. If |str| is NULL this function does nothing. -CEF_EXPORT void cef_string_free(cef_string_t str); - -#ifdef __cplusplus -} -#endif - -#endif // _CEF_STRING_H +// 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_STRING_H +#define _CEF_STRING_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cef_export.h" +#include + +// CEF strings are NUL-terminated wide character strings prefixed with a size +// value, similar to the Microsoft BSTR type. Use the below API functions for +// allocating, managing and freeing CEF strings. +typedef wchar_t* cef_string_t; + +// Return the wide character length of the CEF string as allocated by +// cef_string_alloc_len(). The returned value does not include the NUL +// terminating character. This length may differ from the string length +// as returned by wcslen(). +CEF_EXPORT size_t cef_string_length(cef_string_t str); + +// Allocate and return a new CEF string that is a copy of |str|. If |str| is +// NULL or if allocation fails NULL will be returned. If |str| is of length +// 0 a valid empty CEF string will be returned. +CEF_EXPORT cef_string_t cef_string_alloc(const wchar_t* str); + +// Allocate and return a new CEF string that is a copy of |str|. |len| is the +// wide character length of the new CEF string not including the NUL +// terminating character. |str| will be copied without checking for a NUL +// terminating character. If |str| is NULL or if allocation fails NULL will +// be returned. If |str| is of length 0 a valid empty CEF string will be +// returned. +CEF_EXPORT cef_string_t cef_string_alloc_length(const wchar_t* str, + size_t len); + +// Reallocate an existing CEF string. The contents of |oldstr| will be +// replaced with the contents of |newstr|; |newstr| may not be NULL. Returns 1 +// on success and 0 on failure. +CEF_EXPORT int cef_string_realloc(cef_string_t* oldstr, const wchar_t* newstr); + +// Reallocate an existing CEF string. If |newstr| is NULL the contents of +// |oldstr| will remain unchanged; otherwise, they will be replaced with the +// contents of |newstr|. |len| is the new wide character length of the string +// not including the NUL terminating character. Returns 1 on success and 0 +// on failure. +CEF_EXPORT int cef_string_realloc_length(cef_string_t* oldstr, + const wchar_t* newstr, + size_t len); + +// Free a CEF string. If |str| is NULL this function does nothing. +CEF_EXPORT void cef_string_free(cef_string_t str); + +#ifdef __cplusplus +} +#endif + +#endif // _CEF_STRING_H diff --git a/include/cef_string_list.h b/include/cef_string_list.h index 759520db6..4d80ecff3 100644 --- a/include/cef_string_list.h +++ b/include/cef_string_list.h @@ -1,67 +1,67 @@ -// 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_STRING_LIST_H -#define _CEF_STRING_LIST_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "cef_export.h" -#include "cef_string.h" -#include - -// 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); - -// Return the value at the specified zero-based string list index. -CEF_EXPORT cef_string_t cef_string_list_value(cef_string_list_t list, int index); - -// Append a new key/value pair at the end of the string list. -CEF_EXPORT void cef_string_list_append(cef_string_list_t list, const wchar_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); - - -#ifdef __cplusplus -} -#endif - -#endif // _CEF_STRING_LIST_H +// 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_STRING_LIST_H +#define _CEF_STRING_LIST_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cef_export.h" +#include "cef_string.h" +#include + +// 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); + +// Return the value at the specified zero-based string list index. +CEF_EXPORT cef_string_t cef_string_list_value(cef_string_list_t list, int index); + +// Append a new key/value pair at the end of the string list. +CEF_EXPORT void cef_string_list_append(cef_string_list_t list, const wchar_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); + + +#ifdef __cplusplus +} +#endif + +#endif // _CEF_STRING_LIST_H diff --git a/include/cef_string_map.h b/include/cef_string_map.h index 5f1f689cd..689eef0b8 100644 --- a/include/cef_string_map.h +++ b/include/cef_string_map.h @@ -1,75 +1,75 @@ -// 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_STRING_MAP_H -#define _CEF_STRING_MAP_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "cef_export.h" -#include "cef_string.h" -#include - -// 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 cef_string_t cef_string_map_find(cef_string_map_t map, - const wchar_t* key); - -// Return the key at the specified zero-based string map index. -CEF_EXPORT cef_string_t cef_string_map_key(cef_string_map_t map, int index); - -// Return the value at the specified zero-based string map index. -CEF_EXPORT cef_string_t cef_string_map_value(cef_string_map_t map, int index); - -// Append a new key/value pair at the end of the string map. -CEF_EXPORT void cef_string_map_append(cef_string_map_t map, const wchar_t* key, - const wchar_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_STRING_MAP_H +// 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_STRING_MAP_H +#define _CEF_STRING_MAP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cef_export.h" +#include "cef_string.h" +#include + +// 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 cef_string_t cef_string_map_find(cef_string_map_t map, + const wchar_t* key); + +// Return the key at the specified zero-based string map index. +CEF_EXPORT cef_string_t cef_string_map_key(cef_string_map_t map, int index); + +// Return the value at the specified zero-based string map index. +CEF_EXPORT cef_string_t cef_string_map_value(cef_string_map_t map, int index); + +// Append a new key/value pair at the end of the string map. +CEF_EXPORT void cef_string_map_append(cef_string_map_t map, const wchar_t* key, + const wchar_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_STRING_MAP_H diff --git a/include/cef_types.h b/include/cef_types.h index f09890dad..57e1654f2 100644 --- a/include/cef_types.h +++ b/include/cef_types.h @@ -1,297 +1,297 @@ -// 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_TYPES_H -#define _CEF_TYPES_H - -#ifdef __cplusplus -extern "C" { -#endif - - -// Bring in platform-specific definitions. -#ifdef _WIN32 -#include "cef_types_win.h" -#endif - - -// Define handler return value types. Returning RV_HANDLED indicates -// that the implementation completely handled the method and that no further -// processing is required. Returning RV_CONTINUE indicates that the -// implementation did not handle the method and that the default handler -// should be called. -enum cef_retval_t -{ - RV_HANDLED = 0, - RV_CONTINUE = 1, -}; - -// 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, -}; - -// 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, -}; - -// Structure representing menu information. -typedef struct _cef_handler_menuinfo_t -{ - int typeFlags; - int x; - int y; - const wchar_t* linkUrl; - const wchar_t* imageUrl; - const wchar_t* pageUrl; - const wchar_t* frameUrl; - const wchar_t* selectionText; - const wchar_t* misspelledWord; - int editFlags; - const wchar_t* securityInfo; -} cef_handler_menuinfo_t; - -// The cef_handler_menuinfo_t typeFlags value will be a combination of the -// following values. -enum cef_handler_menutypebits_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_handler_menuinfo_t editFlags value will be a combination of the -// following values. -enum cef_handler_menucapabilitybits_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_handler_menuid_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, -}; - -// Post data elements may represent either bytes or files. -enum cef_postdataelement_type_t -{ - PDE_TYPE_EMPTY = 0, - PDE_TYPE_BYTES, - PDE_TYPE_FILE, -}; - -// 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 -}; - -// 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; - -#ifdef __cplusplus -} -#endif - -#endif // _CEF_TYPES_H +// 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_TYPES_H +#define _CEF_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + + +// Bring in platform-specific definitions. +#ifdef _WIN32 +#include "cef_types_win.h" +#endif + + +// Define handler return value types. Returning RV_HANDLED indicates +// that the implementation completely handled the method and that no further +// processing is required. Returning RV_CONTINUE indicates that the +// implementation did not handle the method and that the default handler +// should be called. +enum cef_retval_t +{ + RV_HANDLED = 0, + RV_CONTINUE = 1, +}; + +// 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, +}; + +// 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, +}; + +// Structure representing menu information. +typedef struct _cef_handler_menuinfo_t +{ + int typeFlags; + int x; + int y; + const wchar_t* linkUrl; + const wchar_t* imageUrl; + const wchar_t* pageUrl; + const wchar_t* frameUrl; + const wchar_t* selectionText; + const wchar_t* misspelledWord; + int editFlags; + const wchar_t* securityInfo; +} cef_handler_menuinfo_t; + +// The cef_handler_menuinfo_t typeFlags value will be a combination of the +// following values. +enum cef_handler_menutypebits_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_handler_menuinfo_t editFlags value will be a combination of the +// following values. +enum cef_handler_menucapabilitybits_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_handler_menuid_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, +}; + +// Post data elements may represent either bytes or files. +enum cef_postdataelement_type_t +{ + PDE_TYPE_EMPTY = 0, + PDE_TYPE_BYTES, + PDE_TYPE_FILE, +}; + +// 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 +}; + +// 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; + +#ifdef __cplusplus +} +#endif + +#endif // _CEF_TYPES_H diff --git a/include/cef_types_win.h b/include/cef_types_win.h index 6b3059753..e7d76cffa 100644 --- a/include/cef_types_win.h +++ b/include/cef_types_win.h @@ -1,76 +1,76 @@ -// 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_TYPES_WIN_H -#define _CEF_TYPES_WIN_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef _WIN32 -#include -#include "cef_string.h" - -// 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; - HWND m_hWndParent; - HMENU m_hMenu; - - // Handle for the new browser window. - HWND 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; - -// Window handle. -#define cef_window_handle_t HWND -#endif // _WIN32 - -#ifdef __cplusplus -} -#endif - -#endif // _CEF_TYPES_WIN_H +// 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_TYPES_WIN_H +#define _CEF_TYPES_WIN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 +#include +#include "cef_string.h" + +// 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; + HWND m_hWndParent; + HMENU m_hMenu; + + // Handle for the new browser window. + HWND 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; + +// Window handle. +#define cef_window_handle_t HWND +#endif // _WIN32 + +#ifdef __cplusplus +} +#endif + +#endif // _CEF_TYPES_WIN_H diff --git a/include/cef_win.h b/include/cef_win.h index c8d05b583..f6d33d5dc 100644 --- a/include/cef_win.h +++ b/include/cef_win.h @@ -1,209 +1,209 @@ -// 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_WIN_H -#define _CEF_WIN_H - -#ifdef _WIN32 -#include -#include "cef_types_win.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); - } - ~CefCriticalSection() - { - DeleteCriticalSection(&m_sec); - } - void Lock() - { - EnterCriticalSection(&m_sec); - } - void Unlock() - { - LeaveCriticalSection(&m_sec); - } - - CRITICAL_SECTION m_sec; -}; - -// Class representing window information. -class CefWindowInfo : public cef_window_info_t -{ -public: - CefWindowInfo() - { - Init(); - } - ~CefWindowInfo() - { - if(m_windowName) - cef_string_free(m_windowName); - } - - CefWindowInfo(const CefWindowInfo& r) - { - Init(); - *this = r; - } - CefWindowInfo(const cef_window_info_t& r) - { - Init(); - *this = r; - } - - void Init() - { - m_dwExStyle = 0; - m_windowName = NULL; - m_dwStyle = 0; - m_x = 0; - m_y = 0; - m_nWidth = 0; - m_nHeight = 0; - m_hWndParent = NULL; - m_hMenu = 0; - m_hWnd = NULL; - } - - CefWindowInfo& operator=(const CefWindowInfo& r) - { - return operator=(static_cast(r)); - } - CefWindowInfo& operator=(const cef_window_info_t& r) - { - m_dwExStyle = r.m_dwExStyle; - if(m_windowName) - cef_string_free(m_windowName); - if(r.m_windowName) - m_windowName = cef_string_alloc(r.m_windowName); - else - m_windowName = NULL; - m_dwStyle = r.m_dwStyle; - m_x = r.m_x; - m_y = r.m_y; - m_nWidth = r.m_nWidth; - m_nHeight = r.m_nHeight; - m_hWndParent = r.m_hWndParent; - m_hMenu = r.m_hMenu; - m_hWnd = r.m_hWnd; - return *this; - } - - void SetAsChild(HWND hWndParent, RECT windowRect) - { - m_dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN - | WS_CLIPSIBLINGS | WS_TABSTOP; - 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, LPCWSTR windowName) - { - m_dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; - m_hWndParent = hWndParent; - m_x = CW_USEDEFAULT; - m_y = CW_USEDEFAULT; - m_nWidth = CW_USEDEFAULT; - m_nHeight = CW_USEDEFAULT; - - if(m_windowName) - cef_string_free(m_windowName); - if(windowName) - m_windowName = cef_string_alloc(windowName); - else - m_windowName = NULL; - } -}; - -// Class representing print context information. -class CefPrintInfo : public cef_print_info_t -{ -public: - CefPrintInfo() - { - Init(); - } - ~CefPrintInfo() - { - } - - CefPrintInfo(const CefPrintInfo& r) - { - Init(); - *this = r; - } - CefPrintInfo(const cef_print_info_t& r) - { - Init(); - *this = r; - } - - void Init() - { - m_hDC = NULL; - m_Rect.left = m_Rect.right = m_Rect.top = m_Rect.bottom = 0; - m_Scale = 0; - } - - CefPrintInfo& operator=(const CefPrintInfo& r) - { - return operator=(static_cast(r)); - } - CefPrintInfo& operator=(const cef_print_info_t& r) - { - m_hDC = r.m_hDC; - m_Rect.left = r.m_Rect.left; - m_Rect.right = r.m_Rect.right; - m_Rect.top = r.m_Rect.top; - m_Rect.bottom = r.m_Rect.bottom; - m_Scale = r.m_Scale; - return *this; - } -}; - -// Window handle. -#define CefWindowHandle cef_window_handle_t -#endif // _WIN32 - -#endif // _CEF_WIN_H +// 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_WIN_H +#define _CEF_WIN_H + +#ifdef _WIN32 +#include +#include "cef_types_win.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); + } + ~CefCriticalSection() + { + DeleteCriticalSection(&m_sec); + } + void Lock() + { + EnterCriticalSection(&m_sec); + } + void Unlock() + { + LeaveCriticalSection(&m_sec); + } + + CRITICAL_SECTION m_sec; +}; + +// Class representing window information. +class CefWindowInfo : public cef_window_info_t +{ +public: + CefWindowInfo() + { + Init(); + } + ~CefWindowInfo() + { + if(m_windowName) + cef_string_free(m_windowName); + } + + CefWindowInfo(const CefWindowInfo& r) + { + Init(); + *this = r; + } + CefWindowInfo(const cef_window_info_t& r) + { + Init(); + *this = r; + } + + void Init() + { + m_dwExStyle = 0; + m_windowName = NULL; + m_dwStyle = 0; + m_x = 0; + m_y = 0; + m_nWidth = 0; + m_nHeight = 0; + m_hWndParent = NULL; + m_hMenu = 0; + m_hWnd = NULL; + } + + CefWindowInfo& operator=(const CefWindowInfo& r) + { + return operator=(static_cast(r)); + } + CefWindowInfo& operator=(const cef_window_info_t& r) + { + m_dwExStyle = r.m_dwExStyle; + if(m_windowName) + cef_string_free(m_windowName); + if(r.m_windowName) + m_windowName = cef_string_alloc(r.m_windowName); + else + m_windowName = NULL; + m_dwStyle = r.m_dwStyle; + m_x = r.m_x; + m_y = r.m_y; + m_nWidth = r.m_nWidth; + m_nHeight = r.m_nHeight; + m_hWndParent = r.m_hWndParent; + m_hMenu = r.m_hMenu; + m_hWnd = r.m_hWnd; + return *this; + } + + void SetAsChild(HWND hWndParent, RECT windowRect) + { + m_dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN + | WS_CLIPSIBLINGS | WS_TABSTOP; + 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, LPCWSTR windowName) + { + m_dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; + m_hWndParent = hWndParent; + m_x = CW_USEDEFAULT; + m_y = CW_USEDEFAULT; + m_nWidth = CW_USEDEFAULT; + m_nHeight = CW_USEDEFAULT; + + if(m_windowName) + cef_string_free(m_windowName); + if(windowName) + m_windowName = cef_string_alloc(windowName); + else + m_windowName = NULL; + } +}; + +// Class representing print context information. +class CefPrintInfo : public cef_print_info_t +{ +public: + CefPrintInfo() + { + Init(); + } + ~CefPrintInfo() + { + } + + CefPrintInfo(const CefPrintInfo& r) + { + Init(); + *this = r; + } + CefPrintInfo(const cef_print_info_t& r) + { + Init(); + *this = r; + } + + void Init() + { + m_hDC = NULL; + m_Rect.left = m_Rect.right = m_Rect.top = m_Rect.bottom = 0; + m_Scale = 0; + } + + CefPrintInfo& operator=(const CefPrintInfo& r) + { + return operator=(static_cast(r)); + } + CefPrintInfo& operator=(const cef_print_info_t& r) + { + m_hDC = r.m_hDC; + m_Rect.left = r.m_Rect.left; + m_Rect.right = r.m_Rect.right; + m_Rect.top = r.m_Rect.top; + m_Rect.bottom = r.m_Rect.bottom; + m_Scale = r.m_Scale; + return *this; + } +}; + +// Window handle. +#define CefWindowHandle cef_window_handle_t +#endif // _WIN32 + +#endif // _CEF_WIN_H diff --git a/libcef/browser_appcache_system.h b/libcef/browser_appcache_system.h index 5896eaa8c..b03ff9e6a 100644 --- a/libcef/browser_appcache_system.h +++ b/libcef/browser_appcache_system.h @@ -1,168 +1,168 @@ -// 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 _BROWSER_APPCACHE_SYSTEM_H -#define _BROWSER_APPCACHE_SYSTEM_H - -#include "base/file_path.h" -#include "base/message_loop.h" -#include "base/thread.h" -#include "webkit/appcache/appcache_backend_impl.h" -#include "webkit/appcache/appcache_frontend_impl.h" -#include "webkit/appcache/appcache_service.h" -#include "webkit/appcache/appcache_thread.h" -#include "webkit/glue/resource_type.h" - -namespace WebKit { -class WebApplicationCacheHost; -class WebApplicationCacheHostClient; -} -class BrowserBackendProxy; -class BrowserFrontendProxy; -class URLRequest; -class URLRequestContext; - -// 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 MessageLoop::DestructionObserver { - 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(URLRequestContext* request_context) { - if (instance_) - instance_->InitOnIOThread(request_context); - } - - // 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(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(URLRequest* request, - int64* cache_id, - GURL* manifest_url) { - if (instance_) - instance_->GetExtraResponseBits(request, cache_id, manifest_url); - } - - // Some unittests create their own IO and DB threads. - - enum AppCacheThreadID { - DB_THREAD_ID, - IO_THREAD_ID, - }; - - class ThreadProvider { - public: - virtual ~ThreadProvider() {} - virtual bool PostTask( - int id, - const tracked_objects::Location& from_here, - Task* task) = 0; - virtual bool CurrentlyOn(int id) = 0; - }; - - static void set_thread_provider(ThreadProvider* provider) { - DCHECK(instance_); - DCHECK(!provider || !instance_->thread_provider_); - instance_->thread_provider_ = provider; - } - - static ThreadProvider* thread_provider() { - return instance_ ? instance_->thread_provider_ : NULL; - } - - private: - friend class BrowserBackendProxy; - friend class BrowserFrontendProxy; - friend class appcache::AppCacheThread; - - // Instance methods called by our static public methods - void InitOnUIThread(const FilePath& cache_directory); - void InitOnIOThread(URLRequestContext* request_context); - WebKit::WebApplicationCacheHost* CreateCacheHostForWebKit( - WebKit::WebApplicationCacheHostClient* client); - void SetExtraRequestBits(URLRequest* request, - int host_id, - ResourceType::Type resource_type); - void GetExtraResponseBits(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; - } - static MessageLoop* GetMessageLoop(int id) { - if (instance_) { - if (id == IO_THREAD_ID) - return instance_->io_message_loop_; - if (id == DB_THREAD_ID) - return instance_->db_thread_.message_loop(); - NOTREACHED() << "Invalid AppCacheThreadID value"; - } - return NULL; - } - - // IOThread DestructionObserver - virtual void WillDestroyCurrentMessageLoop(); - - 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_; - - // Some unittests create there own IO and DB threads. - ThreadProvider* thread_provider_; - - // A low-tech singleton. - static BrowserAppCacheSystem* instance_; -}; - -#endif // _BROWSER_APPCACHE_SYSTEM_H +// 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 _BROWSER_APPCACHE_SYSTEM_H +#define _BROWSER_APPCACHE_SYSTEM_H + +#include "base/file_path.h" +#include "base/message_loop.h" +#include "base/thread.h" +#include "webkit/appcache/appcache_backend_impl.h" +#include "webkit/appcache/appcache_frontend_impl.h" +#include "webkit/appcache/appcache_service.h" +#include "webkit/appcache/appcache_thread.h" +#include "webkit/glue/resource_type.h" + +namespace WebKit { +class WebApplicationCacheHost; +class WebApplicationCacheHostClient; +} +class BrowserBackendProxy; +class BrowserFrontendProxy; +class URLRequest; +class URLRequestContext; + +// 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 MessageLoop::DestructionObserver { + 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(URLRequestContext* request_context) { + if (instance_) + instance_->InitOnIOThread(request_context); + } + + // 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(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(URLRequest* request, + int64* cache_id, + GURL* manifest_url) { + if (instance_) + instance_->GetExtraResponseBits(request, cache_id, manifest_url); + } + + // Some unittests create their own IO and DB threads. + + enum AppCacheThreadID { + DB_THREAD_ID, + IO_THREAD_ID, + }; + + class ThreadProvider { + public: + virtual ~ThreadProvider() {} + virtual bool PostTask( + int id, + const tracked_objects::Location& from_here, + Task* task) = 0; + virtual bool CurrentlyOn(int id) = 0; + }; + + static void set_thread_provider(ThreadProvider* provider) { + DCHECK(instance_); + DCHECK(!provider || !instance_->thread_provider_); + instance_->thread_provider_ = provider; + } + + static ThreadProvider* thread_provider() { + return instance_ ? instance_->thread_provider_ : NULL; + } + + private: + friend class BrowserBackendProxy; + friend class BrowserFrontendProxy; + friend class appcache::AppCacheThread; + + // Instance methods called by our static public methods + void InitOnUIThread(const FilePath& cache_directory); + void InitOnIOThread(URLRequestContext* request_context); + WebKit::WebApplicationCacheHost* CreateCacheHostForWebKit( + WebKit::WebApplicationCacheHostClient* client); + void SetExtraRequestBits(URLRequest* request, + int host_id, + ResourceType::Type resource_type); + void GetExtraResponseBits(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; + } + static MessageLoop* GetMessageLoop(int id) { + if (instance_) { + if (id == IO_THREAD_ID) + return instance_->io_message_loop_; + if (id == DB_THREAD_ID) + return instance_->db_thread_.message_loop(); + NOTREACHED() << "Invalid AppCacheThreadID value"; + } + return NULL; + } + + // IOThread DestructionObserver + virtual void WillDestroyCurrentMessageLoop(); + + 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_; + + // Some unittests create there own IO and DB threads. + ThreadProvider* thread_provider_; + + // A low-tech singleton. + static BrowserAppCacheSystem* instance_; +}; + +#endif // _BROWSER_APPCACHE_SYSTEM_H diff --git a/libcef/browser_database_system.cc b/libcef/browser_database_system.cc index 436a57002..c48bb77d1 100644 --- a/libcef/browser_database_system.cc +++ b/libcef/browser_database_system.cc @@ -1,190 +1,190 @@ -// 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 "browser_database_system.h" - -#include "base/auto_reset.h" -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/platform_thread.h" -#include "base/process_util.h" -#include "base/utf_string_conversions.h" -#include "third_party/sqlite/sqlite3.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" -#include "third_party/WebKit/WebKit/chromium/public/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::VfsBackend; - -BrowserDatabaseSystem* BrowserDatabaseSystem::instance_ = NULL; - -BrowserDatabaseSystem* BrowserDatabaseSystem::GetInstance() { - DCHECK(instance_); - return instance_; -} - -BrowserDatabaseSystem::BrowserDatabaseSystem() - : waiting_for_dbs_to_close_(false) { - temp_dir_.CreateUniqueTempDir(); - db_tracker_ = new DatabaseTracker(temp_dir_.path(), false); - db_tracker_->AddObserver(this); - DCHECK(!instance_); - instance_ = this; -} - -BrowserDatabaseSystem::~BrowserDatabaseSystem() { - db_tracker_->RemoveObserver(this); - instance_ = NULL; -} - -base::PlatformFile BrowserDatabaseSystem::OpenFile( - const string16& vfs_file_name, int desired_flags) { - base::PlatformFile file_handle = base::kInvalidPlatformFileValue; - 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); - } - - return file_handle; -} - -int BrowserDatabaseSystem::DeleteFile( - const string16& vfs_file_name, bool sync_dir) { - // 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; - int error_code = SQLITE_OK; - FilePath file_name = GetFullFilePathForVfsFile(vfs_file_name); - do { - error_code = VfsBackend::DeleteFile(file_name, sync_dir); - } while ((++num_retries < kNumDeleteRetries) && - (error_code == SQLITE_IOERR_DELETE) && - (PlatformThread::Sleep(10), 1)); - - return error_code; -} - -long BrowserDatabaseSystem::GetFileAttributes(const string16& vfs_file_name) { - return VfsBackend::GetFileAttributes( - GetFullFilePathForVfsFile(vfs_file_name)); -} - -long long BrowserDatabaseSystem::GetFileSize(const string16& vfs_file_name) { - return VfsBackend::GetFileSize(GetFullFilePathForVfsFile(vfs_file_name)); -} - -void BrowserDatabaseSystem::DatabaseOpened(const string16& origin_identifier, - const string16& database_name, - const string16& description, - int64 estimated_size) { - int64 database_size = 0; - int64 space_available = 0; - database_connections_.AddConnection(origin_identifier, database_name); - db_tracker_->DatabaseOpened(origin_identifier, database_name, description, - estimated_size, &database_size, &space_available); - SetFullFilePathsForVfsFile(origin_identifier, database_name); - - OnDatabaseSizeChanged(origin_identifier, database_name, - database_size, space_available); -} - -void BrowserDatabaseSystem::DatabaseModified(const string16& origin_identifier, - const string16& database_name) { - DCHECK(database_connections_.IsDatabaseOpened( - origin_identifier, database_name)); - db_tracker_->DatabaseModified(origin_identifier, database_name); -} - -void BrowserDatabaseSystem::DatabaseClosed(const string16& origin_identifier, - const string16& database_name) { - DCHECK(database_connections_.IsDatabaseOpened( - origin_identifier, database_name)); - db_tracker_->DatabaseClosed(origin_identifier, database_name); - database_connections_.RemoveConnection(origin_identifier, database_name); - - if (waiting_for_dbs_to_close_ && database_connections_.IsEmpty()) - MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); -} - -void BrowserDatabaseSystem::OnDatabaseSizeChanged( - const string16& origin_identifier, - const string16& database_name, - int64 database_size, - int64 space_available) { - if (database_connections_.IsOriginUsed(origin_identifier)) { - WebKit::WebDatabase::updateDatabaseSize( - origin_identifier, database_name, database_size, space_available); - } -} - -void BrowserDatabaseSystem::OnDatabaseScheduledForDeletion( - const string16& origin_identifier, - const string16& database_name) { - WebKit::WebDatabase::closeDatabaseImmediately( - origin_identifier, database_name); -} - -void BrowserDatabaseSystem::databaseOpened(const WebKit::WebDatabase& database) { - DatabaseOpened(database.securityOrigin().databaseIdentifier(), - database.name(), database.displayName(), - database.estimatedSize()); -} - -void BrowserDatabaseSystem::databaseModified( - const WebKit::WebDatabase& database) { - DatabaseModified(database.securityOrigin().databaseIdentifier(), - database.name()); -} - -void BrowserDatabaseSystem::databaseClosed(const WebKit::WebDatabase& database) { - DatabaseClosed(database.securityOrigin().databaseIdentifier(), - database.name()); -} - -void BrowserDatabaseSystem::ClearAllDatabases() { - // Wait for all databases to be closed. - if (!database_connections_.IsEmpty()) { - AutoReset waiting_for_dbs_auto_reset(&waiting_for_dbs_to_close_, true); - MessageLoop::ScopedNestableTaskAllower nestable(MessageLoop::current()); - MessageLoop::current()->Run(); - } - - db_tracker_->CloseTrackerDatabaseAndClearCaches(); - file_util::Delete(db_tracker_->DatabaseDirectory(), true); - file_names_.clear(); -} - -void BrowserDatabaseSystem::SetDatabaseQuota(int64 quota) { - db_tracker_->SetDefaultQuota(quota); -} - -void BrowserDatabaseSystem::SetFullFilePathsForVfsFile( - const string16& origin_identifier, - const string16& database_name) { - string16 vfs_file_name = origin_identifier + ASCIIToUTF16("/") + - database_name + ASCIIToUTF16("#"); - FilePath file_name = - DatabaseUtil::GetFullFilePathForVfsFile(db_tracker_, vfs_file_name); - - AutoLock file_names_auto_lock(file_names_lock_); - file_names_[vfs_file_name] = file_name; - file_names_[vfs_file_name + ASCIIToUTF16("-journal")] = - FilePath::FromWStringHack(file_name.ToWStringHack() + - ASCIIToWide("-journal")); -} - -FilePath BrowserDatabaseSystem::GetFullFilePathForVfsFile( - const string16& vfs_file_name) { - AutoLock file_names_auto_lock(file_names_lock_); - DCHECK(file_names_.find(vfs_file_name) != file_names_.end()); - return file_names_[vfs_file_name]; +// 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 "browser_database_system.h" + +#include "base/auto_reset.h" +#include "base/file_util.h" +#include "base/message_loop.h" +#include "base/platform_thread.h" +#include "base/process_util.h" +#include "base/utf_string_conversions.h" +#include "third_party/sqlite/sqlite3.h" +#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" +#include "third_party/WebKit/WebKit/chromium/public/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::VfsBackend; + +BrowserDatabaseSystem* BrowserDatabaseSystem::instance_ = NULL; + +BrowserDatabaseSystem* BrowserDatabaseSystem::GetInstance() { + DCHECK(instance_); + return instance_; +} + +BrowserDatabaseSystem::BrowserDatabaseSystem() + : waiting_for_dbs_to_close_(false) { + temp_dir_.CreateUniqueTempDir(); + db_tracker_ = new DatabaseTracker(temp_dir_.path(), false); + db_tracker_->AddObserver(this); + DCHECK(!instance_); + instance_ = this; +} + +BrowserDatabaseSystem::~BrowserDatabaseSystem() { + db_tracker_->RemoveObserver(this); + instance_ = NULL; +} + +base::PlatformFile BrowserDatabaseSystem::OpenFile( + const string16& vfs_file_name, int desired_flags) { + base::PlatformFile file_handle = base::kInvalidPlatformFileValue; + 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); + } + + return file_handle; +} + +int BrowserDatabaseSystem::DeleteFile( + const string16& vfs_file_name, bool sync_dir) { + // 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; + int error_code = SQLITE_OK; + FilePath file_name = GetFullFilePathForVfsFile(vfs_file_name); + do { + error_code = VfsBackend::DeleteFile(file_name, sync_dir); + } while ((++num_retries < kNumDeleteRetries) && + (error_code == SQLITE_IOERR_DELETE) && + (PlatformThread::Sleep(10), 1)); + + return error_code; +} + +long BrowserDatabaseSystem::GetFileAttributes(const string16& vfs_file_name) { + return VfsBackend::GetFileAttributes( + GetFullFilePathForVfsFile(vfs_file_name)); +} + +long long BrowserDatabaseSystem::GetFileSize(const string16& vfs_file_name) { + return VfsBackend::GetFileSize(GetFullFilePathForVfsFile(vfs_file_name)); +} + +void BrowserDatabaseSystem::DatabaseOpened(const string16& origin_identifier, + const string16& database_name, + const string16& description, + int64 estimated_size) { + int64 database_size = 0; + int64 space_available = 0; + database_connections_.AddConnection(origin_identifier, database_name); + db_tracker_->DatabaseOpened(origin_identifier, database_name, description, + estimated_size, &database_size, &space_available); + SetFullFilePathsForVfsFile(origin_identifier, database_name); + + OnDatabaseSizeChanged(origin_identifier, database_name, + database_size, space_available); +} + +void BrowserDatabaseSystem::DatabaseModified(const string16& origin_identifier, + const string16& database_name) { + DCHECK(database_connections_.IsDatabaseOpened( + origin_identifier, database_name)); + db_tracker_->DatabaseModified(origin_identifier, database_name); +} + +void BrowserDatabaseSystem::DatabaseClosed(const string16& origin_identifier, + const string16& database_name) { + DCHECK(database_connections_.IsDatabaseOpened( + origin_identifier, database_name)); + db_tracker_->DatabaseClosed(origin_identifier, database_name); + database_connections_.RemoveConnection(origin_identifier, database_name); + + if (waiting_for_dbs_to_close_ && database_connections_.IsEmpty()) + MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); +} + +void BrowserDatabaseSystem::OnDatabaseSizeChanged( + const string16& origin_identifier, + const string16& database_name, + int64 database_size, + int64 space_available) { + if (database_connections_.IsOriginUsed(origin_identifier)) { + WebKit::WebDatabase::updateDatabaseSize( + origin_identifier, database_name, database_size, space_available); + } +} + +void BrowserDatabaseSystem::OnDatabaseScheduledForDeletion( + const string16& origin_identifier, + const string16& database_name) { + WebKit::WebDatabase::closeDatabaseImmediately( + origin_identifier, database_name); +} + +void BrowserDatabaseSystem::databaseOpened(const WebKit::WebDatabase& database) { + DatabaseOpened(database.securityOrigin().databaseIdentifier(), + database.name(), database.displayName(), + database.estimatedSize()); +} + +void BrowserDatabaseSystem::databaseModified( + const WebKit::WebDatabase& database) { + DatabaseModified(database.securityOrigin().databaseIdentifier(), + database.name()); +} + +void BrowserDatabaseSystem::databaseClosed(const WebKit::WebDatabase& database) { + DatabaseClosed(database.securityOrigin().databaseIdentifier(), + database.name()); +} + +void BrowserDatabaseSystem::ClearAllDatabases() { + // Wait for all databases to be closed. + if (!database_connections_.IsEmpty()) { + AutoReset waiting_for_dbs_auto_reset(&waiting_for_dbs_to_close_, true); + MessageLoop::ScopedNestableTaskAllower nestable(MessageLoop::current()); + MessageLoop::current()->Run(); + } + + db_tracker_->CloseTrackerDatabaseAndClearCaches(); + file_util::Delete(db_tracker_->DatabaseDirectory(), true); + file_names_.clear(); +} + +void BrowserDatabaseSystem::SetDatabaseQuota(int64 quota) { + db_tracker_->SetDefaultQuota(quota); +} + +void BrowserDatabaseSystem::SetFullFilePathsForVfsFile( + const string16& origin_identifier, + const string16& database_name) { + string16 vfs_file_name = origin_identifier + ASCIIToUTF16("/") + + database_name + ASCIIToUTF16("#"); + FilePath file_name = + DatabaseUtil::GetFullFilePathForVfsFile(db_tracker_, vfs_file_name); + + AutoLock file_names_auto_lock(file_names_lock_); + file_names_[vfs_file_name] = file_name; + file_names_[vfs_file_name + ASCIIToUTF16("-journal")] = + FilePath::FromWStringHack(file_name.ToWStringHack() + + ASCIIToWide("-journal")); +} + +FilePath BrowserDatabaseSystem::GetFullFilePathForVfsFile( + const string16& vfs_file_name) { + AutoLock file_names_auto_lock(file_names_lock_); + DCHECK(file_names_.find(vfs_file_name) != file_names_.end()); + return file_names_[vfs_file_name]; } \ No newline at end of file diff --git a/libcef/browser_database_system.h b/libcef/browser_database_system.h index 3fa6e2d71..c0dc22b13 100644 --- a/libcef/browser_database_system.h +++ b/libcef/browser_database_system.h @@ -1,84 +1,84 @@ -// 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 _BROWSER_DATABASE_SYSTEM_H -#define _BROWSER_DATABASE_SYSTEM_H - -#include "base/file_path.h" -#include "base/hash_tables.h" -#include "base/lock.h" -#include "base/platform_file.h" -#include "base/ref_counted.h" -#include "base/scoped_temp_dir.h" -#include "base/string16.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDatabaseObserver.h" -#include "webkit/database/database_connections.h" -#include "webkit/database/database_tracker.h" - -class BrowserDatabaseSystem : public webkit_database::DatabaseTracker::Observer, - public WebKit::WebDatabaseObserver { - public: - static BrowserDatabaseSystem* GetInstance(); - BrowserDatabaseSystem(); - ~BrowserDatabaseSystem(); - - // VFS functions - base::PlatformFile OpenFile(const string16& vfs_file_name, int desired_flags); - int DeleteFile(const string16& vfs_file_name, bool sync_dir); - long GetFileAttributes(const string16& vfs_file_name); - long long GetFileSize(const string16& vfs_file_name); - - // database tracker functions - 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, - int64 space_available); - virtual void OnDatabaseScheduledForDeletion(const string16& origin_identifier, - const string16& database_name); - - // WebDatabaseObserver implementation - virtual void databaseOpened(const WebKit::WebDatabase& database); - virtual void databaseModified(const WebKit::WebDatabase& database); - virtual void databaseClosed(const WebKit::WebDatabase& database); - - void ClearAllDatabases(); - void SetDatabaseQuota(int64 quota); - - private: - // The calls that come from the database tracker run on the main thread. - // Therefore, we can only call DatabaseUtil::GetFullFilePathForVfsFile() - // on the main thread. However, the VFS calls run on the DB thread and - // they need to crack VFS file paths. To resolve this problem, we store - // a map of vfs_file_names to file_paths. The map is updated on the main - // thread on each DatabaseOpened() call that comes from the database - // tracker, and is read on the DB thread by each VFS call. - void SetFullFilePathsForVfsFile(const string16& origin_identifier, - const string16& database_name); - FilePath GetFullFilePathForVfsFile(const string16& vfs_file_name); - - static BrowserDatabaseSystem* instance_; - - bool waiting_for_dbs_to_close_; - - ScopedTempDir temp_dir_; - - scoped_refptr db_tracker_; - - Lock file_names_lock_; - base::hash_map file_names_; - - webkit_database::DatabaseConnections database_connections_; -}; - -#endif // _BROWSER_DATABASE_SYSTEM_H +// 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 _BROWSER_DATABASE_SYSTEM_H +#define _BROWSER_DATABASE_SYSTEM_H + +#include "base/file_path.h" +#include "base/hash_tables.h" +#include "base/lock.h" +#include "base/platform_file.h" +#include "base/ref_counted.h" +#include "base/scoped_temp_dir.h" +#include "base/string16.h" +#include "third_party/WebKit/WebKit/chromium/public/WebDatabaseObserver.h" +#include "webkit/database/database_connections.h" +#include "webkit/database/database_tracker.h" + +class BrowserDatabaseSystem : public webkit_database::DatabaseTracker::Observer, + public WebKit::WebDatabaseObserver { + public: + static BrowserDatabaseSystem* GetInstance(); + BrowserDatabaseSystem(); + ~BrowserDatabaseSystem(); + + // VFS functions + base::PlatformFile OpenFile(const string16& vfs_file_name, int desired_flags); + int DeleteFile(const string16& vfs_file_name, bool sync_dir); + long GetFileAttributes(const string16& vfs_file_name); + long long GetFileSize(const string16& vfs_file_name); + + // database tracker functions + 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, + int64 space_available); + virtual void OnDatabaseScheduledForDeletion(const string16& origin_identifier, + const string16& database_name); + + // WebDatabaseObserver implementation + virtual void databaseOpened(const WebKit::WebDatabase& database); + virtual void databaseModified(const WebKit::WebDatabase& database); + virtual void databaseClosed(const WebKit::WebDatabase& database); + + void ClearAllDatabases(); + void SetDatabaseQuota(int64 quota); + + private: + // The calls that come from the database tracker run on the main thread. + // Therefore, we can only call DatabaseUtil::GetFullFilePathForVfsFile() + // on the main thread. However, the VFS calls run on the DB thread and + // they need to crack VFS file paths. To resolve this problem, we store + // a map of vfs_file_names to file_paths. The map is updated on the main + // thread on each DatabaseOpened() call that comes from the database + // tracker, and is read on the DB thread by each VFS call. + void SetFullFilePathsForVfsFile(const string16& origin_identifier, + const string16& database_name); + FilePath GetFullFilePathForVfsFile(const string16& vfs_file_name); + + static BrowserDatabaseSystem* instance_; + + bool waiting_for_dbs_to_close_; + + ScopedTempDir temp_dir_; + + scoped_refptr db_tracker_; + + Lock file_names_lock_; + base::hash_map file_names_; + + webkit_database::DatabaseConnections database_connections_; +}; + +#endif // _BROWSER_DATABASE_SYSTEM_H diff --git a/libcef/browser_drag_delegate.cc b/libcef/browser_drag_delegate.cc index cdbb3b7cf..1db7d13e0 100644 --- a/libcef/browser_drag_delegate.cc +++ b/libcef/browser_drag_delegate.cc @@ -1,42 +1,42 @@ -// 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 "browser_drag_delegate.h" - -#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" - -using WebKit::WebPoint; -using WebKit::WebView; - -namespace { - -void GetCursorPositions(HWND hwnd, gfx::Point* client, gfx::Point* screen) { - // GetCursorPos will fail if the input desktop isn't the current desktop. - // See http://b/1173534. (0,0) is wrong, but better than uninitialized. - POINT pos; - if (!GetCursorPos(&pos)) { - pos.x = 0; - pos.y = 0; - } - - *screen = gfx::Point(pos); - ScreenToClient(hwnd, &pos); - *client = gfx::Point(pos); -} - -} // anonymous namespace - -void BrowserDragDelegate::OnDragSourceCancel() { - OnDragSourceDrop(); -} - -void BrowserDragDelegate::OnDragSourceDrop() { - gfx::Point client; - gfx::Point screen; - GetCursorPositions(source_hwnd_, &client, &screen); - webview_->dragSourceEndedAt(client, screen, WebKit::WebDragOperationCopy); - // TODO(snej): Pass the real drag operation instead -} +// 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 "browser_drag_delegate.h" + +#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" + +using WebKit::WebPoint; +using WebKit::WebView; + +namespace { + +void GetCursorPositions(HWND hwnd, gfx::Point* client, gfx::Point* screen) { + // GetCursorPos will fail if the input desktop isn't the current desktop. + // See http://b/1173534. (0,0) is wrong, but better than uninitialized. + POINT pos; + if (!GetCursorPos(&pos)) { + pos.x = 0; + pos.y = 0; + } + + *screen = gfx::Point(pos); + ScreenToClient(hwnd, &pos); + *client = gfx::Point(pos); +} + +} // anonymous namespace + +void BrowserDragDelegate::OnDragSourceCancel() { + OnDragSourceDrop(); +} + +void BrowserDragDelegate::OnDragSourceDrop() { + gfx::Point client; + gfx::Point screen; + GetCursorPositions(source_hwnd_, &client, &screen); + webview_->dragSourceEndedAt(client, screen, WebKit::WebDragOperationCopy); + // TODO(snej): Pass the real drag operation instead +} diff --git a/libcef/browser_drag_delegate.h b/libcef/browser_drag_delegate.h index 34e80a723..6ff9dae63 100644 --- a/libcef/browser_drag_delegate.h +++ b/libcef/browser_drag_delegate.h @@ -1,39 +1,39 @@ -// 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. -// -// A class that implements BaseDragSource for the test shell webview delegate. - -#ifndef _BROWSER_DRAG_DELEGATE_H -#define _BROWSER_DRAG_DELEGATE_H - -#include "base/base_drag_source.h" - -namespace WebKit { -class WebView; -} - -class BrowserDragDelegate : public BaseDragSource { - public: - BrowserDragDelegate(HWND source_hwnd, WebKit::WebView* webview) - : BaseDragSource(), - source_hwnd_(source_hwnd), - webview_(webview) { } - - protected: - // BaseDragSource - virtual void OnDragSourceCancel(); - virtual void OnDragSourceDrop(); - virtual void OnDragSourceMove(); - - private: - WebKit::WebView* webview_; - - // A HWND for the source we are associated with, used for translating - // mouse coordinates from screen to client coordinates. - HWND source_hwnd_; -}; - -#endif // _BROWSER_DRAG_DELEGATE_H - +// 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. +// +// A class that implements BaseDragSource for the test shell webview delegate. + +#ifndef _BROWSER_DRAG_DELEGATE_H +#define _BROWSER_DRAG_DELEGATE_H + +#include "base/base_drag_source.h" + +namespace WebKit { +class WebView; +} + +class BrowserDragDelegate : public BaseDragSource { + public: + BrowserDragDelegate(HWND source_hwnd, WebKit::WebView* webview) + : BaseDragSource(), + source_hwnd_(source_hwnd), + webview_(webview) { } + + protected: + // BaseDragSource + virtual void OnDragSourceCancel(); + virtual void OnDragSourceDrop(); + virtual void OnDragSourceMove(); + + private: + WebKit::WebView* webview_; + + // A HWND for the source we are associated with, used for translating + // mouse coordinates from screen to client coordinates. + HWND source_hwnd_; +}; + +#endif // _BROWSER_DRAG_DELEGATE_H + diff --git a/libcef/browser_drop_delegate.cc b/libcef/browser_drop_delegate.cc index 87e57166a..570ea5f49 100644 --- a/libcef/browser_drop_delegate.cc +++ b/libcef/browser_drop_delegate.cc @@ -1,71 +1,71 @@ -// 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 "browser_drop_delegate.h" - -#include "third_party/WebKit/WebKit/chromium/public/WebDragData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/webdropdata.h" - -using WebKit::WebDragOperation; -using WebKit::WebDragOperationCopy; -using WebKit::WebPoint; -using WebKit::WebView; - -// BaseDropTarget methods ---------------------------------------------------- - -DWORD BrowserDropDelegate::OnDragEnter(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - WebDropData drop_data; - WebDropData::PopulateWebDropData(data_object, &drop_data); - - POINT client_pt = cursor_position; - ScreenToClient(GetHWND(), &client_pt); - WebDragOperation op = webview_->dragTargetDragEnter( - drop_data.ToDragData(), drop_data.identity, - WebPoint(client_pt.x, client_pt.y), - WebPoint(cursor_position.x, cursor_position.y), - WebDragOperationCopy); - // TODO(snej): Pass the real drag operation instead - return op ? DROPEFFECT_COPY : DROPEFFECT_NONE; - // TODO(snej): Return the real drop effect constant matching 'op' -} - -DWORD BrowserDropDelegate::OnDragOver(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - POINT client_pt = cursor_position; - ScreenToClient(GetHWND(), &client_pt); - WebDragOperation op = webview_->dragTargetDragOver( - WebPoint(client_pt.x, client_pt.y), - WebPoint(cursor_position.x, cursor_position.y), - WebDragOperationCopy); - // TODO(snej): Pass the real drag operation instead - return op ? DROPEFFECT_COPY : DROPEFFECT_NONE; - // TODO(snej): Return the real drop effect constant matching 'op' -} - -void BrowserDropDelegate::OnDragLeave(IDataObject* data_object) { - webview_->dragTargetDragLeave(); -} - -DWORD BrowserDropDelegate::OnDrop(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - POINT client_pt = cursor_position; - ScreenToClient(GetHWND(), &client_pt); - webview_->dragTargetDrop( - WebPoint(client_pt.x, client_pt.y), - WebPoint(cursor_position.x, cursor_position.y)); - - // webkit win port always returns DROPEFFECT_NONE - return DROPEFFECT_NONE; -} - +// 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 "browser_drop_delegate.h" + +#include "third_party/WebKit/WebKit/chromium/public/WebDragData.h" +#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webdropdata.h" + +using WebKit::WebDragOperation; +using WebKit::WebDragOperationCopy; +using WebKit::WebPoint; +using WebKit::WebView; + +// BaseDropTarget methods ---------------------------------------------------- + +DWORD BrowserDropDelegate::OnDragEnter(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect) { + WebDropData drop_data; + WebDropData::PopulateWebDropData(data_object, &drop_data); + + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + WebDragOperation op = webview_->dragTargetDragEnter( + drop_data.ToDragData(), drop_data.identity, + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y), + WebDragOperationCopy); + // TODO(snej): Pass the real drag operation instead + return op ? DROPEFFECT_COPY : DROPEFFECT_NONE; + // TODO(snej): Return the real drop effect constant matching 'op' +} + +DWORD BrowserDropDelegate::OnDragOver(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect) { + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + WebDragOperation op = webview_->dragTargetDragOver( + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y), + WebDragOperationCopy); + // TODO(snej): Pass the real drag operation instead + return op ? DROPEFFECT_COPY : DROPEFFECT_NONE; + // TODO(snej): Return the real drop effect constant matching 'op' +} + +void BrowserDropDelegate::OnDragLeave(IDataObject* data_object) { + webview_->dragTargetDragLeave(); +} + +DWORD BrowserDropDelegate::OnDrop(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect) { + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + webview_->dragTargetDrop( + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y)); + + // webkit win port always returns DROPEFFECT_NONE + return DROPEFFECT_NONE; +} + diff --git a/libcef/browser_drop_delegate.h b/libcef/browser_drop_delegate.h index 80af8cd6f..1308b7fd7 100644 --- a/libcef/browser_drop_delegate.h +++ b/libcef/browser_drop_delegate.h @@ -1,45 +1,45 @@ -// 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. -// -// A class that implements BaseDropTarget for the test shell webview delegate. - -#ifndef _BROWSER_DROP_DELEGATE_H -#define _BROWSER_DROP_DELEGATE_H - -#include "base/base_drop_target.h" - -namespace WebKit { -class WebView; -} - -class BrowserDropDelegate : public BaseDropTarget { - public: - BrowserDropDelegate(HWND source_hwnd, WebKit::WebView* webview) - : BaseDropTarget(source_hwnd), - webview_(webview) { } - - protected: - // BaseDropTarget methods - 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: - WebKit::WebView* webview_; -}; - -#endif // _BROWSER_DROP_DELEGATE_H - +// 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. +// +// A class that implements BaseDropTarget for the test shell webview delegate. + +#ifndef _BROWSER_DROP_DELEGATE_H +#define _BROWSER_DROP_DELEGATE_H + +#include "base/base_drop_target.h" + +namespace WebKit { +class WebView; +} + +class BrowserDropDelegate : public BaseDropTarget { + public: + BrowserDropDelegate(HWND source_hwnd, WebKit::WebView* webview) + : BaseDropTarget(source_hwnd), + webview_(webview) { } + + protected: + // BaseDropTarget methods + 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: + WebKit::WebView* webview_; +}; + +#endif // _BROWSER_DROP_DELEGATE_H + diff --git a/libcef/browser_impl.cc b/libcef/browser_impl.cc index 0ce51a1ff..82ea472a5 100644 --- a/libcef/browser_impl.cc +++ b/libcef/browser_impl.cc @@ -1,1112 +1,1112 @@ -// 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 "cef_context.h" -#include "browser_impl.h" -#include "browser_webkit_glue.h" -#include "request_impl.h" -#include "stream_impl.h" - -#include "base/utf_string_conversions.h" -#include "base/waitable_event.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPlugin.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginDocument.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRange.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/glue_serialize.h" -#include "webkit/glue/plugins/webplugin_delegate.h" -#include "webkit/glue/plugins/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; -using webkit_glue::StdStringToWebString; -using webkit_glue::WebStringToStdString; - - -CefBrowserImpl::CefBrowserImpl(CefWindowInfo& windowInfo, bool popup, - CefRefPtr handler) - : window_info_(windowInfo), is_popup_(popup), is_modal_(false), - handler_(handler), webviewhost_(NULL), popuphost_(NULL), unique_id_(0), - frame_main_(NULL) -{ - 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()); - } -} - - -bool CefBrowserImpl::CanGoBack() -{ - if(!CefThread::CurrentlyOn(CefThread::UI)) - { - // We need to send the request to the UI thread and wait for the result - - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - base::WaitableEvent event(false, false); - - bool retVal = true; - - // Request the data from the UI thread - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_CanGoBackNotify, &retVal, &event)); - - // Wait for the UI thread callback to tell us that the data is available - event.Wait(); - - return retVal; - } - else - { - // Call the method directly - return UIT_CanGoBack(); - } -} - -void CefBrowserImpl::GoBack() -{ - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_BACK)); -} - -bool CefBrowserImpl::CanGoForward() -{ - if(!CefThread::CurrentlyOn(CefThread::UI)) - { - // We need to send the request to the UI thread and wait for the result - - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - base::WaitableEvent event(false, false); - - bool retVal = true; - - // Request the data from the UI thread - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_CanGoForwardNotify, &retVal, &event)); - - // Wait for the UI thread callback to tell us that the data is available - event.Wait(); - - return retVal; - } - else - { - // Call the method directly - return UIT_CanGoForward(); - } -} - -void CefBrowserImpl::GoForward() -{ - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_FORWARD)); -} - -void CefBrowserImpl::Reload() -{ - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_RELOAD)); -} - -void CefBrowserImpl::ReloadIgnoreCache() -{ - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_RELOAD_NOCACHE)); -} - -void CefBrowserImpl::StopLoad() -{ - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_STOP)); -} - -void CefBrowserImpl::SetFocus(bool enable) -{ - if (CefThread::CurrentlyOn(CefThread::UI)) - { - UIT_SetFocus(GetWebViewHost(), enable); - } - else - { - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_SetFocus, GetWebViewHost(), enable)); - } -} - -bool CefBrowserImpl::IsPopup() -{ - Lock(); - bool popup = is_popup_; - Unlock(); - return popup; -} - -CefRefPtr CefBrowserImpl::GetHandler() -{ - return handler_; -} - -CefRefPtr CefBrowserImpl::GetMainFrame() -{ - return GetWebView() ? GetCefFrame(GetWebView()->mainFrame()) : NULL; -} - -CefRefPtr CefBrowserImpl::GetFocusedFrame() -{ - return GetWebView() ? GetCefFrame(GetWebView()->focusedFrame()) : NULL; -} - -CefRefPtr CefBrowserImpl::GetFrame(const std::wstring& name) -{ - WebView* view = GetWebView(); - if (!view) - return NULL; - - WebFrame* frame = view->findFrameByName(name); - if(frame) - return GetCefFrame(frame); - return NULL; -} - -void CefBrowserImpl::GetFrameNames(std::vector& names) -{ - WebView* view = GetWebView(); - if (!view) - return; - - WebFrame* main_frame = view->mainFrame(); - WebFrame* it = main_frame; - do { - if(it != main_frame) - names.push_back(UTF16ToWideHack(it->name())); - it = it->traverseNext(true); - } while (it != main_frame); -} - -void CefBrowserImpl::Find(int identifier, const std::wstring& 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, NewRunnableMethod(this, - &CefBrowserImpl::UIT_Find, identifier, searchText, options)); -} - -void CefBrowserImpl::StopFinding(bool clearSelection) -{ - // Execute the request on the UI thread. - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_StopFinding, clearSelection)); -} - -CefRefPtr CefBrowserImpl::GetCefFrame(WebFrame* frame) -{ - CefRefPtr cef_frame; - Lock(); - - WebView *view = GetWebView(); - if(view) { - if(frame == view->mainFrame()) { - // Use or create the single main frame reference. - if(frame_main_ == NULL) - frame_main_ = new CefFrameImpl(this, std::wstring()); - cef_frame = frame_main_; - } else { - // Locate or create the appropriate named reference. - std::wstring name = UTF16ToWideHack(frame->name()); - DCHECK(!name.empty()); - FrameMap::const_iterator it = frames_.find(name); - if(it != frames_.end()) - cef_frame = it->second; - else { - cef_frame = new CefFrameImpl(this, name); - frames_.insert(std::make_pair(name, cef_frame.get())); - } - } - } - - Unlock(); - return cef_frame; -} - -void CefBrowserImpl::RemoveCefFrame(const std::wstring& name) -{ - Lock(); - - if(name.empty()) - frame_main_ = NULL; - else { - FrameMap::iterator it = frames_.find(name); - if(it != frames_.end()) - frames_.erase(it); - } - - Unlock(); -} - -WebFrame* CefBrowserImpl::GetWebFrame(CefRefPtr frame) -{ - WebView* view = GetWebView(); - if (!view) - return NULL; - - std::wstring name = frame->GetName(); - if(name.empty()) - return view ->mainFrame(); - return view ->findFrameByName(name); -} - -void CefBrowserImpl::Undo(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_UNDO, frame.get())); -} - -void CefBrowserImpl::Redo(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_REDO, frame.get())); -} - -void CefBrowserImpl::Cut(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_CUT, frame.get())); -} - -void CefBrowserImpl::Copy(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_COPY, frame.get())); -} - -void CefBrowserImpl::Paste(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_PASTE, frame.get())); -} - -void CefBrowserImpl::Delete(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_DELETE, frame.get())); -} - -void CefBrowserImpl::SelectAll(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_SELECTALL, frame.get())); -} - - -void CefBrowserImpl::Print(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_PRINT, frame.get())); -} - -void CefBrowserImpl::ViewSource(CefRefPtr frame) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_VIEWSOURCE, frame.get())); -} - -std::wstring CefBrowserImpl::GetSource(CefRefPtr frame) -{ - if(!CefThread::CurrentlyOn(CefThread::UI)) - { - // We need to send the request to the UI thread and wait for the result - - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - base::WaitableEvent event(false, false); - - CefRefPtr stream(new CefBytesWriter(BUFFER_SIZE)); - - // Request the data from the UI thread - frame->AddRef(); - stream->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_GetDocumentStringNotify, frame.get(), stream.get(), - &event)); - - // Wait for the UI thread callback to tell us that the data is available - event.Wait(); - - return UTF8ToWide( - static_cast(stream.get())->GetDataString()); - } - else - { - // Retrieve the document string directly - WebKit::WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) { - std::string markup = web_frame->contentAsMarkup().utf8(); - return UTF8ToWide(markup); - } - return std::wstring(); - } -} - -std::wstring CefBrowserImpl::GetText(CefRefPtr frame) -{ - if(!CefThread::CurrentlyOn(CefThread::UI)) - { - // We need to send the request to the UI thread and wait for the result - - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - base::WaitableEvent event(false, false); - - CefRefPtr stream(new CefBytesWriter(BUFFER_SIZE)); - - // Request the data from the UI thread - frame->AddRef(); - stream->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_GetDocumentTextNotify, frame.get(), stream.get(), - &event)); - - // Wait for the UI thread callback to tell us that the data is available - event.Wait(); - - return UTF8ToWide( - static_cast(stream.get())->GetDataString()); - } - else - { - // Retrieve the document text directly - WebKit::WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) - return webkit_glue::DumpDocumentText(web_frame); - return std::wstring(); - } -} - -void CefBrowserImpl::LoadRequest(CefRefPtr frame, - CefRefPtr request) -{ - DCHECK(request.get() != NULL); - frame->AddRef(); - request->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_LoadURLForRequestRef, frame.get(), request.get())); -} - -void CefBrowserImpl::LoadURL(CefRefPtr frame, - const std::wstring& url) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_LoadURL, frame.get(), url)); -} - -void CefBrowserImpl::LoadString(CefRefPtr frame, - const std::wstring& string, - const std::wstring& url) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_LoadHTML, frame.get(), string, url)); -} - -void CefBrowserImpl::LoadStream(CefRefPtr frame, - CefRefPtr stream, - const std::wstring& url) -{ - DCHECK(stream.get() != NULL); - frame->AddRef(); - stream->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_LoadHTMLForStreamRef, frame.get(), stream.get(), - url)); -} - -void CefBrowserImpl::ExecuteJavaScript(CefRefPtr frame, - const std::wstring& jsCode, - const std::wstring& scriptUrl, - int startLine) -{ - frame->AddRef(); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_ExecuteJavaScript, frame.get(), jsCode, scriptUrl, - startLine)); -} - -std::wstring CefBrowserImpl::GetURL(CefRefPtr frame) -{ - WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) { - std::string spec = web_frame->url().spec(); - return UTF8ToWide(spec); - } - return std::wstring(); -} - -bool CefBrowser::CreateBrowser(CefWindowInfo& windowInfo, bool popup, - CefRefPtr handler, - const std::wstring& url) -{ - if(!_Context.get()) - return false; - - std::wstring newUrl = url; - - if(handler.get()) - { - // Give the handler an opportunity to modify window attributes, handler, - // or cancel the window creation. - CefHandler::RetVal rv = - handler->HandleBeforeCreated(NULL, windowInfo, popup, handler, newUrl); - if(rv == RV_HANDLED) - return false; - } - - CefRefPtr browser( - new CefBrowserImpl(windowInfo, popup, handler)); - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(browser.get(), - &CefBrowserImpl::UIT_CreateBrowser, newUrl)); - return true; -} - -CefRefPtr CefBrowser::CreateBrowserSync(CefWindowInfo& windowInfo, - bool popup, - CefRefPtr handler, - const std::wstring& url) -{ - if(!_Context.get() || !CefThread::CurrentlyOn(CefThread::UI)) - return NULL; - - std::wstring newUrl = url; - CefRefPtr alternateBrowser; - - if(handler.get()) - { - // Give the handler an opportunity to modify window attributes, handler, - // or cancel the window creation. - CefHandler::RetVal rv = handler->HandleBeforeCreated(NULL, windowInfo, - popup, handler, newUrl); - if(rv == RV_HANDLED) - return false; - } - - CefRefPtr browser(new CefBrowserImpl(windowInfo, popup, handler)); - static_cast(browser.get())->UIT_CreateBrowser(newUrl); - - return browser; -} - -void CefBrowserImpl::UIT_LoadURL(CefFrame* frame, - const std::wstring& url) -{ - UIT_LoadURLForRequest(frame, url, std::wstring(), WebHTTPBody(), - CefRequest::HeaderMap()); -} - -void CefBrowserImpl::UIT_LoadURLForRequestRef(CefFrame* frame, - CefRequest* request) -{ - std::wstring url = request->GetURL(); - std::wstring method = request->GetMethod(); - - CefRequestImpl *impl = static_cast(request); - - 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); - - request->Release(); -} - -void CefBrowserImpl::UIT_LoadURLForRequest(CefFrame* frame, - const std::wstring& url, - const std::wstring& method, - const WebKit::WebHTTPBody& upload_data, - const CefRequest::HeaderMap& headers) -{ - REQUIRE_UIT(); - - if (url.empty()) - return; - - GURL gurl(url); - - if (!gurl.is_valid() && !gurl.has_scheme()) { - // Try to add "http://" at the beginning - gurl = GURL(std::wstring(L"http://") + url); - if (!gurl.is_valid()) - return; - } - - nav_controller_->LoadEntry( - new BrowserNavigationEntry(-1, gurl, std::wstring(), frame->GetName(), - method, upload_data, headers)); - - frame->Release(); -} - -void CefBrowserImpl::UIT_LoadHTML(CefFrame* frame, - const std::wstring& html, - const std::wstring& url) -{ - REQUIRE_UIT(); - - GURL gurl(url); - - if (!gurl.is_valid() && !gurl.has_scheme()) { - // Try to add "http://" at the beginning - gurl = GURL(std::wstring(L"http://") + url); - if (!gurl.is_valid()) - return; - } - - WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) - web_frame->loadHTMLString(WideToUTF8(html), gurl); - - frame->Release(); -} - -void CefBrowserImpl::UIT_LoadHTMLForStreamRef(CefFrame* frame, - CefStreamReader* stream, - const std::wstring& url) -{ - REQUIRE_UIT(); - - GURL gurl(url); - - if (!gurl.is_valid() && !gurl.has_scheme()) { - // Try to add "http://" at the beginning - gurl = GURL(std::wstring(L"http://") + 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 = GetWebFrame(frame); - if(web_frame) - web_frame->loadHTMLString(ss.str(), gurl); - - stream->Release(); - frame->Release(); -} - -void CefBrowserImpl::UIT_ExecuteJavaScript(CefFrame* frame, - const std::wstring& js_code, - const std::wstring& script_url, - int start_line) -{ - REQUIRE_UIT(); - - WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) { - web_frame->executeScript( - WebScriptSource(WebString(js_code), WebURL(GURL(script_url)), - start_line)); - } - - frame->Release(); -} - -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 = GetWebView(); - if (!view) - return false; - - // Get the right target frame for the entry. - WebFrame* frame; - if (!entry.GetTargetFrame().empty()) - frame = view->findFrameByName(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(entry.GetPageID() != -1); - frame->loadHistoryItem( - webkit_glue::HistoryItemFromString(entry.GetContentState())); - } else { - DCHECK(entry.GetPageID() == -1); - WebURLRequest request(entry.GetURL()); - - if(entry.GetMethod().size() > 0) { - request.setHTTPMethod( - StdStringToWebString(WideToUTF8(entry.GetMethod()))); - } - - if(entry.GetHeaders().size() > 0) - CefRequestImpl::SetHeaderMap(entry.GetHeaders(), request); - - if(!entry.GetUploadData().isNull()) - { - std::string method = WebStringToStdString(request.httpMethod()); - if(method == "GET" || method == "HEAD") { - request.setHTTPMethod(StdStringToWebString("POST")); - } - if(request.httpHeaderField(StdStringToWebString("Content-Type")).length() - == 0) { - request.setHTTPHeaderField( - StdStringToWebString("Content-Type"), - StdStringToWebString("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 (handler_.get() && handler_->HandleSetFocus(this, false) == RV_CONTINUE) { - // 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); - UIT_SetFocus(GetWebViewHost(), true); - } - - return true; -} - -CefRefPtr CefBrowserImpl::UIT_CreatePopupWindow(const std::wstring& url) -{ - REQUIRE_UIT(); - - CefWindowInfo info; - info.SetAsPopup(NULL, url.c_str()); - CefRefPtr handler = handler_; - std::wstring newUrl = url; - - if(handler_.get()) - { - // Give the handler an opportunity to modify window attributes, handler, - // or cancel the window creation. - CefHandler::RetVal rv = - handler_->HandleBeforeCreated(this, info, true, handler, newUrl); - if(rv == RV_HANDLED) - return NULL; - } - - CefRefPtr browser(new CefBrowserImpl(info, true, handler)); - browser->UIT_CreateBrowser(newUrl); - - return browser; -} - -void CefBrowserImpl::UIT_Show(WebKit::WebNavigationPolicy policy) -{ - REQUIRE_UIT(); - delegate_->show(policy); -} - -void CefBrowserImpl::UIT_HandleActionView(CefHandler::MenuId menuId) -{ - return UIT_HandleAction(menuId, NULL); -} - -void CefBrowserImpl::UIT_HandleAction(CefHandler::MenuId menuId, - CefFrame* frame) -{ - REQUIRE_UIT(); - - WebFrame* web_frame = NULL; - if(frame) - web_frame = 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 (GetWebView()) - 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; - } - - if(frame) - frame->Release(); -} - -void CefBrowserImpl::UIT_GetDocumentStringNotify(CefFrame* frame, - CefStreamWriter* writer, - base::WaitableEvent* event) -{ - REQUIRE_UIT(); - - WebKit::WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) { - // Retrieve the document string - std::string markup = web_frame->contentAsMarkup().utf8(); - // Write the document string to the stream - writer->Write(markup.c_str(), markup.size(), 1); - } - - // Notify the calling thread that the data is now available - event->Signal(); - - writer->Release(); - frame->Release(); -} - -void CefBrowserImpl::UIT_GetDocumentTextNotify(CefFrame* frame, - CefStreamWriter* writer, - base::WaitableEvent* event) -{ - REQUIRE_UIT(); - - WebKit::WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) { - // Retrieve the document string - std::wstring str = webkit_glue::DumpDocumentText(web_frame); - std::string cstr = WideToUTF8(str); - // Write the document string to the stream - writer->Write(cstr.c_str(), cstr.size(), 1); - } - - // Notify the calling thread that the data is now available - event->Signal(); - - writer->Release(); - frame->Release(); -} - -void CefBrowserImpl::UIT_CanGoBackNotify(bool *retVal, - base::WaitableEvent* event) -{ - REQUIRE_UIT(); - - *retVal = UIT_CanGoBack(); - - // Notify the calling thread that the data is now available - event->Signal(); -} - -void CefBrowserImpl::UIT_CanGoForwardNotify(bool *retVal, - base::WaitableEvent* event) -{ - REQUIRE_UIT(); - - *retVal = UIT_CanGoForward(); - - // Notify the calling thread that the data is now available - event->Signal(); -} - -void CefBrowserImpl::UIT_Find(int identifier, const std::wstring& search_text, - const WebKit::WebFindOptions& options) -{ - WebView* view = GetWebView(); - if (!view) - return; - - WebFrame* main_frame = view->mainFrame(); - - if (main_frame->document().isPluginDocument()) { - WebPlugin* plugin = main_frame->document().to().plugin(); - webkit_glue::WebPluginDelegate* delegate = - static_cast(plugin)->delegate(); - if (options.findNext) { - // Just navigate back/forward. - delegate->SelectFindResult(options.forward); - } else { - if (delegate->StartFind(search_text.c_str(), 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, search_text, 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, search_text, 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, - search_text, - 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 = GetWebView(); - if (!view) - return; - - WebDocument doc = view->mainFrame()->document(); - if (doc.isPluginDocument()) { - WebPlugin* plugin = view->mainFrame()->document(). - to().plugin(); - webkit_glue::WebPluginDelegate* delegate = - static_cast(plugin)->delegate(); - delegate->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(handler_.get()) - { - CefRect rect(selection_rect.x, selection_rect.y, selection_rect.width, - selection_rect.height); - handler_->HandleFindResult(this, identifier, count, rect, - active_match_ordinal, final_update); - } -} - - -// CefFrameImpl - -bool CefFrameImpl::IsFocused() -{ - return (browser_->GetWebView() && - (browser_->GetWebFrame(this) == - browser_->GetWebView()->focusedFrame())); -} +// 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 "cef_context.h" +#include "browser_impl.h" +#include "browser_webkit_glue.h" +#include "request_impl.h" +#include "stream_impl.h" + +#include "base/utf_string_conversions.h" +#include "base/waitable_event.h" +#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" +#include "third_party/WebKit/WebKit/chromium/public/WebPlugin.h" +#include "third_party/WebKit/WebKit/chromium/public/WebPluginDocument.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRange.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" +#include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h" +#include "third_party/WebKit/WebKit/chromium/public/WebString.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" +#include "webkit/glue/glue_serialize.h" +#include "webkit/glue/plugins/webplugin_delegate.h" +#include "webkit/glue/plugins/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; +using webkit_glue::StdStringToWebString; +using webkit_glue::WebStringToStdString; + + +CefBrowserImpl::CefBrowserImpl(CefWindowInfo& windowInfo, bool popup, + CefRefPtr handler) + : window_info_(windowInfo), is_popup_(popup), is_modal_(false), + handler_(handler), webviewhost_(NULL), popuphost_(NULL), unique_id_(0), + frame_main_(NULL) +{ + 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()); + } +} + + +bool CefBrowserImpl::CanGoBack() +{ + if(!CefThread::CurrentlyOn(CefThread::UI)) + { + // We need to send the request to the UI thread and wait for the result + + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + base::WaitableEvent event(false, false); + + bool retVal = true; + + // Request the data from the UI thread + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_CanGoBackNotify, &retVal, &event)); + + // Wait for the UI thread callback to tell us that the data is available + event.Wait(); + + return retVal; + } + else + { + // Call the method directly + return UIT_CanGoBack(); + } +} + +void CefBrowserImpl::GoBack() +{ + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_BACK)); +} + +bool CefBrowserImpl::CanGoForward() +{ + if(!CefThread::CurrentlyOn(CefThread::UI)) + { + // We need to send the request to the UI thread and wait for the result + + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + base::WaitableEvent event(false, false); + + bool retVal = true; + + // Request the data from the UI thread + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_CanGoForwardNotify, &retVal, &event)); + + // Wait for the UI thread callback to tell us that the data is available + event.Wait(); + + return retVal; + } + else + { + // Call the method directly + return UIT_CanGoForward(); + } +} + +void CefBrowserImpl::GoForward() +{ + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_FORWARD)); +} + +void CefBrowserImpl::Reload() +{ + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_RELOAD)); +} + +void CefBrowserImpl::ReloadIgnoreCache() +{ + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_RELOAD_NOCACHE)); +} + +void CefBrowserImpl::StopLoad() +{ + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_STOP)); +} + +void CefBrowserImpl::SetFocus(bool enable) +{ + if (CefThread::CurrentlyOn(CefThread::UI)) + { + UIT_SetFocus(GetWebViewHost(), enable); + } + else + { + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_SetFocus, GetWebViewHost(), enable)); + } +} + +bool CefBrowserImpl::IsPopup() +{ + Lock(); + bool popup = is_popup_; + Unlock(); + return popup; +} + +CefRefPtr CefBrowserImpl::GetHandler() +{ + return handler_; +} + +CefRefPtr CefBrowserImpl::GetMainFrame() +{ + return GetWebView() ? GetCefFrame(GetWebView()->mainFrame()) : NULL; +} + +CefRefPtr CefBrowserImpl::GetFocusedFrame() +{ + return GetWebView() ? GetCefFrame(GetWebView()->focusedFrame()) : NULL; +} + +CefRefPtr CefBrowserImpl::GetFrame(const std::wstring& name) +{ + WebView* view = GetWebView(); + if (!view) + return NULL; + + WebFrame* frame = view->findFrameByName(name); + if(frame) + return GetCefFrame(frame); + return NULL; +} + +void CefBrowserImpl::GetFrameNames(std::vector& names) +{ + WebView* view = GetWebView(); + if (!view) + return; + + WebFrame* main_frame = view->mainFrame(); + WebFrame* it = main_frame; + do { + if(it != main_frame) + names.push_back(UTF16ToWideHack(it->name())); + it = it->traverseNext(true); + } while (it != main_frame); +} + +void CefBrowserImpl::Find(int identifier, const std::wstring& 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, NewRunnableMethod(this, + &CefBrowserImpl::UIT_Find, identifier, searchText, options)); +} + +void CefBrowserImpl::StopFinding(bool clearSelection) +{ + // Execute the request on the UI thread. + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_StopFinding, clearSelection)); +} + +CefRefPtr CefBrowserImpl::GetCefFrame(WebFrame* frame) +{ + CefRefPtr cef_frame; + Lock(); + + WebView *view = GetWebView(); + if(view) { + if(frame == view->mainFrame()) { + // Use or create the single main frame reference. + if(frame_main_ == NULL) + frame_main_ = new CefFrameImpl(this, std::wstring()); + cef_frame = frame_main_; + } else { + // Locate or create the appropriate named reference. + std::wstring name = UTF16ToWideHack(frame->name()); + DCHECK(!name.empty()); + FrameMap::const_iterator it = frames_.find(name); + if(it != frames_.end()) + cef_frame = it->second; + else { + cef_frame = new CefFrameImpl(this, name); + frames_.insert(std::make_pair(name, cef_frame.get())); + } + } + } + + Unlock(); + return cef_frame; +} + +void CefBrowserImpl::RemoveCefFrame(const std::wstring& name) +{ + Lock(); + + if(name.empty()) + frame_main_ = NULL; + else { + FrameMap::iterator it = frames_.find(name); + if(it != frames_.end()) + frames_.erase(it); + } + + Unlock(); +} + +WebFrame* CefBrowserImpl::GetWebFrame(CefRefPtr frame) +{ + WebView* view = GetWebView(); + if (!view) + return NULL; + + std::wstring name = frame->GetName(); + if(name.empty()) + return view ->mainFrame(); + return view ->findFrameByName(name); +} + +void CefBrowserImpl::Undo(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_UNDO, frame.get())); +} + +void CefBrowserImpl::Redo(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_REDO, frame.get())); +} + +void CefBrowserImpl::Cut(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_CUT, frame.get())); +} + +void CefBrowserImpl::Copy(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_COPY, frame.get())); +} + +void CefBrowserImpl::Paste(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_PASTE, frame.get())); +} + +void CefBrowserImpl::Delete(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_DELETE, frame.get())); +} + +void CefBrowserImpl::SelectAll(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_SELECTALL, frame.get())); +} + + +void CefBrowserImpl::Print(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_PRINT, frame.get())); +} + +void CefBrowserImpl::ViewSource(CefRefPtr frame) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_HandleAction, MENU_ID_VIEWSOURCE, frame.get())); +} + +std::wstring CefBrowserImpl::GetSource(CefRefPtr frame) +{ + if(!CefThread::CurrentlyOn(CefThread::UI)) + { + // We need to send the request to the UI thread and wait for the result + + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + base::WaitableEvent event(false, false); + + CefRefPtr stream(new CefBytesWriter(BUFFER_SIZE)); + + // Request the data from the UI thread + frame->AddRef(); + stream->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_GetDocumentStringNotify, frame.get(), stream.get(), + &event)); + + // Wait for the UI thread callback to tell us that the data is available + event.Wait(); + + return UTF8ToWide( + static_cast(stream.get())->GetDataString()); + } + else + { + // Retrieve the document string directly + WebKit::WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) { + std::string markup = web_frame->contentAsMarkup().utf8(); + return UTF8ToWide(markup); + } + return std::wstring(); + } +} + +std::wstring CefBrowserImpl::GetText(CefRefPtr frame) +{ + if(!CefThread::CurrentlyOn(CefThread::UI)) + { + // We need to send the request to the UI thread and wait for the result + + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + base::WaitableEvent event(false, false); + + CefRefPtr stream(new CefBytesWriter(BUFFER_SIZE)); + + // Request the data from the UI thread + frame->AddRef(); + stream->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_GetDocumentTextNotify, frame.get(), stream.get(), + &event)); + + // Wait for the UI thread callback to tell us that the data is available + event.Wait(); + + return UTF8ToWide( + static_cast(stream.get())->GetDataString()); + } + else + { + // Retrieve the document text directly + WebKit::WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) + return webkit_glue::DumpDocumentText(web_frame); + return std::wstring(); + } +} + +void CefBrowserImpl::LoadRequest(CefRefPtr frame, + CefRefPtr request) +{ + DCHECK(request.get() != NULL); + frame->AddRef(); + request->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_LoadURLForRequestRef, frame.get(), request.get())); +} + +void CefBrowserImpl::LoadURL(CefRefPtr frame, + const std::wstring& url) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_LoadURL, frame.get(), url)); +} + +void CefBrowserImpl::LoadString(CefRefPtr frame, + const std::wstring& string, + const std::wstring& url) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_LoadHTML, frame.get(), string, url)); +} + +void CefBrowserImpl::LoadStream(CefRefPtr frame, + CefRefPtr stream, + const std::wstring& url) +{ + DCHECK(stream.get() != NULL); + frame->AddRef(); + stream->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_LoadHTMLForStreamRef, frame.get(), stream.get(), + url)); +} + +void CefBrowserImpl::ExecuteJavaScript(CefRefPtr frame, + const std::wstring& jsCode, + const std::wstring& scriptUrl, + int startLine) +{ + frame->AddRef(); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_ExecuteJavaScript, frame.get(), jsCode, scriptUrl, + startLine)); +} + +std::wstring CefBrowserImpl::GetURL(CefRefPtr frame) +{ + WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) { + std::string spec = web_frame->url().spec(); + return UTF8ToWide(spec); + } + return std::wstring(); +} + +bool CefBrowser::CreateBrowser(CefWindowInfo& windowInfo, bool popup, + CefRefPtr handler, + const std::wstring& url) +{ + if(!_Context.get()) + return false; + + std::wstring newUrl = url; + + if(handler.get()) + { + // Give the handler an opportunity to modify window attributes, handler, + // or cancel the window creation. + CefHandler::RetVal rv = + handler->HandleBeforeCreated(NULL, windowInfo, popup, handler, newUrl); + if(rv == RV_HANDLED) + return false; + } + + CefRefPtr browser( + new CefBrowserImpl(windowInfo, popup, handler)); + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(browser.get(), + &CefBrowserImpl::UIT_CreateBrowser, newUrl)); + return true; +} + +CefRefPtr CefBrowser::CreateBrowserSync(CefWindowInfo& windowInfo, + bool popup, + CefRefPtr handler, + const std::wstring& url) +{ + if(!_Context.get() || !CefThread::CurrentlyOn(CefThread::UI)) + return NULL; + + std::wstring newUrl = url; + CefRefPtr alternateBrowser; + + if(handler.get()) + { + // Give the handler an opportunity to modify window attributes, handler, + // or cancel the window creation. + CefHandler::RetVal rv = handler->HandleBeforeCreated(NULL, windowInfo, + popup, handler, newUrl); + if(rv == RV_HANDLED) + return false; + } + + CefRefPtr browser(new CefBrowserImpl(windowInfo, popup, handler)); + static_cast(browser.get())->UIT_CreateBrowser(newUrl); + + return browser; +} + +void CefBrowserImpl::UIT_LoadURL(CefFrame* frame, + const std::wstring& url) +{ + UIT_LoadURLForRequest(frame, url, std::wstring(), WebHTTPBody(), + CefRequest::HeaderMap()); +} + +void CefBrowserImpl::UIT_LoadURLForRequestRef(CefFrame* frame, + CefRequest* request) +{ + std::wstring url = request->GetURL(); + std::wstring method = request->GetMethod(); + + CefRequestImpl *impl = static_cast(request); + + 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); + + request->Release(); +} + +void CefBrowserImpl::UIT_LoadURLForRequest(CefFrame* frame, + const std::wstring& url, + const std::wstring& method, + const WebKit::WebHTTPBody& upload_data, + const CefRequest::HeaderMap& headers) +{ + REQUIRE_UIT(); + + if (url.empty()) + return; + + GURL gurl(url); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + gurl = GURL(std::wstring(L"http://") + url); + if (!gurl.is_valid()) + return; + } + + nav_controller_->LoadEntry( + new BrowserNavigationEntry(-1, gurl, std::wstring(), frame->GetName(), + method, upload_data, headers)); + + frame->Release(); +} + +void CefBrowserImpl::UIT_LoadHTML(CefFrame* frame, + const std::wstring& html, + const std::wstring& url) +{ + REQUIRE_UIT(); + + GURL gurl(url); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + gurl = GURL(std::wstring(L"http://") + url); + if (!gurl.is_valid()) + return; + } + + WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) + web_frame->loadHTMLString(WideToUTF8(html), gurl); + + frame->Release(); +} + +void CefBrowserImpl::UIT_LoadHTMLForStreamRef(CefFrame* frame, + CefStreamReader* stream, + const std::wstring& url) +{ + REQUIRE_UIT(); + + GURL gurl(url); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + gurl = GURL(std::wstring(L"http://") + 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 = GetWebFrame(frame); + if(web_frame) + web_frame->loadHTMLString(ss.str(), gurl); + + stream->Release(); + frame->Release(); +} + +void CefBrowserImpl::UIT_ExecuteJavaScript(CefFrame* frame, + const std::wstring& js_code, + const std::wstring& script_url, + int start_line) +{ + REQUIRE_UIT(); + + WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) { + web_frame->executeScript( + WebScriptSource(WebString(js_code), WebURL(GURL(script_url)), + start_line)); + } + + frame->Release(); +} + +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 = GetWebView(); + if (!view) + return false; + + // Get the right target frame for the entry. + WebFrame* frame; + if (!entry.GetTargetFrame().empty()) + frame = view->findFrameByName(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(entry.GetPageID() != -1); + frame->loadHistoryItem( + webkit_glue::HistoryItemFromString(entry.GetContentState())); + } else { + DCHECK(entry.GetPageID() == -1); + WebURLRequest request(entry.GetURL()); + + if(entry.GetMethod().size() > 0) { + request.setHTTPMethod( + StdStringToWebString(WideToUTF8(entry.GetMethod()))); + } + + if(entry.GetHeaders().size() > 0) + CefRequestImpl::SetHeaderMap(entry.GetHeaders(), request); + + if(!entry.GetUploadData().isNull()) + { + std::string method = WebStringToStdString(request.httpMethod()); + if(method == "GET" || method == "HEAD") { + request.setHTTPMethod(StdStringToWebString("POST")); + } + if(request.httpHeaderField(StdStringToWebString("Content-Type")).length() + == 0) { + request.setHTTPHeaderField( + StdStringToWebString("Content-Type"), + StdStringToWebString("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 (handler_.get() && handler_->HandleSetFocus(this, false) == RV_CONTINUE) { + // 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); + UIT_SetFocus(GetWebViewHost(), true); + } + + return true; +} + +CefRefPtr CefBrowserImpl::UIT_CreatePopupWindow(const std::wstring& url) +{ + REQUIRE_UIT(); + + CefWindowInfo info; + info.SetAsPopup(NULL, url.c_str()); + CefRefPtr handler = handler_; + std::wstring newUrl = url; + + if(handler_.get()) + { + // Give the handler an opportunity to modify window attributes, handler, + // or cancel the window creation. + CefHandler::RetVal rv = + handler_->HandleBeforeCreated(this, info, true, handler, newUrl); + if(rv == RV_HANDLED) + return NULL; + } + + CefRefPtr browser(new CefBrowserImpl(info, true, handler)); + browser->UIT_CreateBrowser(newUrl); + + return browser; +} + +void CefBrowserImpl::UIT_Show(WebKit::WebNavigationPolicy policy) +{ + REQUIRE_UIT(); + delegate_->show(policy); +} + +void CefBrowserImpl::UIT_HandleActionView(CefHandler::MenuId menuId) +{ + return UIT_HandleAction(menuId, NULL); +} + +void CefBrowserImpl::UIT_HandleAction(CefHandler::MenuId menuId, + CefFrame* frame) +{ + REQUIRE_UIT(); + + WebFrame* web_frame = NULL; + if(frame) + web_frame = 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 (GetWebView()) + 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; + } + + if(frame) + frame->Release(); +} + +void CefBrowserImpl::UIT_GetDocumentStringNotify(CefFrame* frame, + CefStreamWriter* writer, + base::WaitableEvent* event) +{ + REQUIRE_UIT(); + + WebKit::WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) { + // Retrieve the document string + std::string markup = web_frame->contentAsMarkup().utf8(); + // Write the document string to the stream + writer->Write(markup.c_str(), markup.size(), 1); + } + + // Notify the calling thread that the data is now available + event->Signal(); + + writer->Release(); + frame->Release(); +} + +void CefBrowserImpl::UIT_GetDocumentTextNotify(CefFrame* frame, + CefStreamWriter* writer, + base::WaitableEvent* event) +{ + REQUIRE_UIT(); + + WebKit::WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) { + // Retrieve the document string + std::wstring str = webkit_glue::DumpDocumentText(web_frame); + std::string cstr = WideToUTF8(str); + // Write the document string to the stream + writer->Write(cstr.c_str(), cstr.size(), 1); + } + + // Notify the calling thread that the data is now available + event->Signal(); + + writer->Release(); + frame->Release(); +} + +void CefBrowserImpl::UIT_CanGoBackNotify(bool *retVal, + base::WaitableEvent* event) +{ + REQUIRE_UIT(); + + *retVal = UIT_CanGoBack(); + + // Notify the calling thread that the data is now available + event->Signal(); +} + +void CefBrowserImpl::UIT_CanGoForwardNotify(bool *retVal, + base::WaitableEvent* event) +{ + REQUIRE_UIT(); + + *retVal = UIT_CanGoForward(); + + // Notify the calling thread that the data is now available + event->Signal(); +} + +void CefBrowserImpl::UIT_Find(int identifier, const std::wstring& search_text, + const WebKit::WebFindOptions& options) +{ + WebView* view = GetWebView(); + if (!view) + return; + + WebFrame* main_frame = view->mainFrame(); + + if (main_frame->document().isPluginDocument()) { + WebPlugin* plugin = main_frame->document().to().plugin(); + webkit_glue::WebPluginDelegate* delegate = + static_cast(plugin)->delegate(); + if (options.findNext) { + // Just navigate back/forward. + delegate->SelectFindResult(options.forward); + } else { + if (delegate->StartFind(search_text.c_str(), 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, search_text, 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, search_text, 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, + search_text, + 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 = GetWebView(); + if (!view) + return; + + WebDocument doc = view->mainFrame()->document(); + if (doc.isPluginDocument()) { + WebPlugin* plugin = view->mainFrame()->document(). + to().plugin(); + webkit_glue::WebPluginDelegate* delegate = + static_cast(plugin)->delegate(); + delegate->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(handler_.get()) + { + CefRect rect(selection_rect.x, selection_rect.y, selection_rect.width, + selection_rect.height); + handler_->HandleFindResult(this, identifier, count, rect, + active_match_ordinal, final_update); + } +} + + +// CefFrameImpl + +bool CefFrameImpl::IsFocused() +{ + return (browser_->GetWebView() && + (browser_->GetWebFrame(this) == + browser_->GetWebView()->focusedFrame())); +} diff --git a/libcef/browser_impl.h b/libcef/browser_impl.h index 16ed926f0..b20650f1a 100644 --- a/libcef/browser_impl.h +++ b/libcef/browser_impl.h @@ -1,309 +1,309 @@ -// 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 _BROWSER_IMPL_H -#define _BROWSER_IMPL_H - -#include "include/cef.h" - -#include "webview_host.h" -#include "browser_webview_delegate.h" -#include "browser_navigation_controller.h" -#include "cef_thread.h" -#if defined(OS_WIN) -#include "printing/win_printing_context.h" -#endif - -#include "base/scoped_temp_dir.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFindOptions.h" - -namespace base { -class WaitableEvent; -} -namespace WebKit { -class WebView; -} - -#define BUFFER_SIZE 32768 - - -// Implementation of CefBrowser. -class CefBrowserImpl : public CefThreadSafeBase -{ -public: - CefBrowserImpl(CefWindowInfo& windowInfo, bool popup, - CefRefPtr handler); - 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 bool CanGoBack(); - virtual void GoBack(); - virtual bool CanGoForward(); - virtual void GoForward(); - virtual void Reload(); - virtual void ReloadIgnoreCache(); - virtual void StopLoad(); - virtual void SetFocus(bool enable); - virtual CefWindowHandle GetWindowHandle(); - virtual bool IsPopup(); - virtual CefRefPtr GetHandler(); - virtual CefRefPtr GetMainFrame(); - virtual CefRefPtr GetFocusedFrame(); - virtual CefRefPtr GetFrame(const std::wstring& name); - virtual void GetFrameNames(std::vector& names); - virtual void Find(int identifier, const std::wstring& searchText, - bool forward, bool matchCase, bool findNext); - virtual void StopFinding(bool clearSelection); - - // CefFrames are light-weight objects managed by the browser and loosely - // coupled to a WebFrame object by name. If a CefFrame object does not - // already exist for the specified WebFrame one will be created. There is no - // guarantee that the same CefFrame object will be returned across different - // calls to this function. - CefRefPtr GetCefFrame(WebKit::WebFrame* frame); - void RemoveCefFrame(const std::wstring& name); - - // Return the WebFrame object associated with the specified CefFrame. This - // may return NULL if no WebFrame with the CefFrame's name exists. - WebKit::WebFrame* GetWebFrame(CefRefPtr frame); - - // 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); - std::wstring GetSource(CefRefPtr frame); - std::wstring GetText(CefRefPtr frame); - void LoadRequest(CefRefPtr frame, - CefRefPtr request); - void LoadURL(CefRefPtr frame, - const std::wstring& url); - void LoadString(CefRefPtr frame, - const std::wstring& string, - const std::wstring& url); - void LoadStream(CefRefPtr frame, - CefRefPtr stream, - const std::wstring& url); - void ExecuteJavaScript(CefRefPtr frame, - const std::wstring& jsCode, - const std::wstring& scriptUrl, - int startLine); - std::wstring GetURL(CefRefPtr frame); - - WebKit::WebView* GetWebView() const { - return webviewhost_.get() ? webviewhost_->webview() : NULL; - } - WebViewHost* GetWebViewHost() const { - return webviewhost_.get(); - } - BrowserWebViewDelegate* GetWebViewDelegate() const { - return delegate_.get(); - } - HWND GetWebViewWndHandle() const { - return webviewhost_->view_handle(); - } - WebKit::WebWidget* GetPopup() const { - return popuphost_ ? popuphost_->webwidget() : NULL; - } - WebWidgetHost* GetPopupHost() const { - return popuphost_; - } - BrowserWebViewDelegate* GetPopupDelegate() const { - return popup_delegate_.get(); - } - HWND GetPopupWndHandle() const { - return popuphost_->view_handle(); - } - HWND GetMainWndHandle() const { - return window_info_.m_hWnd; - } - - - //////////////////////////////////////////////////////////// - // ALL UIT_* METHODS MUST ONLY BE CALLED ON THE UI THREAD // - //////////////////////////////////////////////////////////// - - 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; - } - - void UIT_SetTitle(const std::wstring& title) { - REQUIRE_UIT(); - title_ = title; - } - std::wstring UIT_GetTitle() { - REQUIRE_UIT(); - return title_; - } - - void UIT_CreateBrowser(const std::wstring& url); - - void UIT_LoadURL(CefFrame* frame, - const std::wstring& url); - void UIT_LoadURLForRequest(CefFrame* frame, - const std::wstring& url, - const std::wstring& method, - const WebKit::WebHTTPBody& upload_data, - const CefRequest::HeaderMap& headers); - void UIT_LoadURLForRequestRef(CefFrame* frame, - CefRequest* request); - void UIT_LoadHTML(CefFrame* frame, - const std::wstring& html, - const std::wstring& url); - void UIT_LoadHTMLForStreamRef(CefFrame* frame, - CefStreamReader* stream, - const std::wstring& url); - void UIT_ExecuteJavaScript(CefFrame* frame, - const std::wstring& js_code, - const std::wstring& 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); - - CefRefPtr UIT_CreatePopupWindow(const std::wstring& url); - WebKit::WebWidget* UIT_CreatePopupWidget(); - void UIT_ClosePopupWidget(); - - void UIT_Show(WebKit::WebNavigationPolicy policy); - - // Handles most simple browser actions - void UIT_HandleActionView(CefHandler::MenuId menuId); - void UIT_HandleAction(CefHandler::MenuId menuId, CefFrame* frame); - - // Save the document HTML to a temporary file and open in the default viewing - // application - bool UIT_ViewDocumentString(WebKit::WebFrame *frame); - void UIT_GetDocumentStringNotify(CefFrame* frame, - CefStreamWriter* writer, - base::WaitableEvent* event); - void UIT_GetDocumentTextNotify(CefFrame* frame, CefStreamWriter* writer, - base::WaitableEvent* event); - void UIT_CanGoBackNotify(bool *retVal, base::WaitableEvent* event); - void UIT_CanGoForwardNotify(bool *retVal, base::WaitableEvent* event); - - 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 std::wstring& 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); - - static bool ImplementsThreadSafeReferenceCounting() { return true; } - - const FilePath& file_system_root() const { return file_system_root_.path(); } - -protected: - CefWindowInfo window_info_; - bool is_popup_; - bool is_modal_; - CefRefPtr handler_; - scoped_ptr webviewhost_; - WebWidgetHost* popuphost_; - scoped_ptr delegate_; - scoped_ptr popup_delegate_; - scoped_ptr nav_controller_; - - std::wstring title_; - - // Context object used to manage printing. - printing::PrintingContext print_context_; - - typedef std::map FrameMap; - FrameMap frames_; - CefFrame* frame_main_; - - // Unique browser ID assigned by the context. - int unique_id_; - - // A temporary directory for FileSystem API. - ScopedTempDir file_system_root_; -}; - - -// Implementation of CefFrame. -class CefFrameImpl : public CefThreadSafeBase -{ -public: - CefFrameImpl(CefBrowserImpl* browser, const std::wstring& name) - : browser_(browser), name_(name) {} - virtual ~CefFrameImpl() { browser_->RemoveCefFrame(name_); } - - // CefFrame methods - virtual void Undo() { browser_->Undo(this); } - virtual void Redo() { browser_->Redo(this); } - virtual void Cut() { browser_->Cut(this); } - virtual void Copy() { browser_->Copy(this); } - virtual void Paste() { browser_->Paste(this); } - virtual void Delete() { browser_->Delete(this); } - virtual void SelectAll() { browser_->SelectAll(this); } - virtual void Print() { browser_->Print(this); } - virtual void ViewSource() { browser_->ViewSource(this); } - virtual std::wstring GetSource() { return browser_->GetSource(this); } - virtual std::wstring GetText() { return browser_->GetText(this); } - virtual void LoadRequest(CefRefPtr request) - { return browser_->LoadRequest(this, request); } - virtual void LoadURL(const std::wstring& url) - { return browser_->LoadURL(this, url); } - virtual void LoadString(const std::wstring& string, - const std::wstring& url) - { return browser_->LoadString(this, string, url); } - virtual void LoadStream(CefRefPtr stream, - const std::wstring& url) - { return browser_->LoadStream(this, stream, url); } - virtual void ExecuteJavaScript(const std::wstring& jsCode, - const std::wstring& scriptUrl, - int startLine) - { return browser_->ExecuteJavaScript(this, jsCode, scriptUrl, startLine); } - virtual bool IsMain() { return name_.empty(); } - virtual bool IsFocused(); - virtual std::wstring GetName() { return name_; } - virtual std::wstring GetURL() { return browser_->GetURL(this); } - -private: - CefRefPtr browser_; - std::wstring name_; -}; - -#endif // _BROWSER_IMPL_H +// 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 _BROWSER_IMPL_H +#define _BROWSER_IMPL_H + +#include "include/cef.h" + +#include "webview_host.h" +#include "browser_webview_delegate.h" +#include "browser_navigation_controller.h" +#include "cef_thread.h" +#if defined(OS_WIN) +#include "printing/win_printing_context.h" +#endif + +#include "base/scoped_temp_dir.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFindOptions.h" + +namespace base { +class WaitableEvent; +} +namespace WebKit { +class WebView; +} + +#define BUFFER_SIZE 32768 + + +// Implementation of CefBrowser. +class CefBrowserImpl : public CefThreadSafeBase +{ +public: + CefBrowserImpl(CefWindowInfo& windowInfo, bool popup, + CefRefPtr handler); + 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 bool CanGoBack(); + virtual void GoBack(); + virtual bool CanGoForward(); + virtual void GoForward(); + virtual void Reload(); + virtual void ReloadIgnoreCache(); + virtual void StopLoad(); + virtual void SetFocus(bool enable); + virtual CefWindowHandle GetWindowHandle(); + virtual bool IsPopup(); + virtual CefRefPtr GetHandler(); + virtual CefRefPtr GetMainFrame(); + virtual CefRefPtr GetFocusedFrame(); + virtual CefRefPtr GetFrame(const std::wstring& name); + virtual void GetFrameNames(std::vector& names); + virtual void Find(int identifier, const std::wstring& searchText, + bool forward, bool matchCase, bool findNext); + virtual void StopFinding(bool clearSelection); + + // CefFrames are light-weight objects managed by the browser and loosely + // coupled to a WebFrame object by name. If a CefFrame object does not + // already exist for the specified WebFrame one will be created. There is no + // guarantee that the same CefFrame object will be returned across different + // calls to this function. + CefRefPtr GetCefFrame(WebKit::WebFrame* frame); + void RemoveCefFrame(const std::wstring& name); + + // Return the WebFrame object associated with the specified CefFrame. This + // may return NULL if no WebFrame with the CefFrame's name exists. + WebKit::WebFrame* GetWebFrame(CefRefPtr frame); + + // 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); + std::wstring GetSource(CefRefPtr frame); + std::wstring GetText(CefRefPtr frame); + void LoadRequest(CefRefPtr frame, + CefRefPtr request); + void LoadURL(CefRefPtr frame, + const std::wstring& url); + void LoadString(CefRefPtr frame, + const std::wstring& string, + const std::wstring& url); + void LoadStream(CefRefPtr frame, + CefRefPtr stream, + const std::wstring& url); + void ExecuteJavaScript(CefRefPtr frame, + const std::wstring& jsCode, + const std::wstring& scriptUrl, + int startLine); + std::wstring GetURL(CefRefPtr frame); + + WebKit::WebView* GetWebView() const { + return webviewhost_.get() ? webviewhost_->webview() : NULL; + } + WebViewHost* GetWebViewHost() const { + return webviewhost_.get(); + } + BrowserWebViewDelegate* GetWebViewDelegate() const { + return delegate_.get(); + } + HWND GetWebViewWndHandle() const { + return webviewhost_->view_handle(); + } + WebKit::WebWidget* GetPopup() const { + return popuphost_ ? popuphost_->webwidget() : NULL; + } + WebWidgetHost* GetPopupHost() const { + return popuphost_; + } + BrowserWebViewDelegate* GetPopupDelegate() const { + return popup_delegate_.get(); + } + HWND GetPopupWndHandle() const { + return popuphost_->view_handle(); + } + HWND GetMainWndHandle() const { + return window_info_.m_hWnd; + } + + + //////////////////////////////////////////////////////////// + // ALL UIT_* METHODS MUST ONLY BE CALLED ON THE UI THREAD // + //////////////////////////////////////////////////////////// + + 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; + } + + void UIT_SetTitle(const std::wstring& title) { + REQUIRE_UIT(); + title_ = title; + } + std::wstring UIT_GetTitle() { + REQUIRE_UIT(); + return title_; + } + + void UIT_CreateBrowser(const std::wstring& url); + + void UIT_LoadURL(CefFrame* frame, + const std::wstring& url); + void UIT_LoadURLForRequest(CefFrame* frame, + const std::wstring& url, + const std::wstring& method, + const WebKit::WebHTTPBody& upload_data, + const CefRequest::HeaderMap& headers); + void UIT_LoadURLForRequestRef(CefFrame* frame, + CefRequest* request); + void UIT_LoadHTML(CefFrame* frame, + const std::wstring& html, + const std::wstring& url); + void UIT_LoadHTMLForStreamRef(CefFrame* frame, + CefStreamReader* stream, + const std::wstring& url); + void UIT_ExecuteJavaScript(CefFrame* frame, + const std::wstring& js_code, + const std::wstring& 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); + + CefRefPtr UIT_CreatePopupWindow(const std::wstring& url); + WebKit::WebWidget* UIT_CreatePopupWidget(); + void UIT_ClosePopupWidget(); + + void UIT_Show(WebKit::WebNavigationPolicy policy); + + // Handles most simple browser actions + void UIT_HandleActionView(CefHandler::MenuId menuId); + void UIT_HandleAction(CefHandler::MenuId menuId, CefFrame* frame); + + // Save the document HTML to a temporary file and open in the default viewing + // application + bool UIT_ViewDocumentString(WebKit::WebFrame *frame); + void UIT_GetDocumentStringNotify(CefFrame* frame, + CefStreamWriter* writer, + base::WaitableEvent* event); + void UIT_GetDocumentTextNotify(CefFrame* frame, CefStreamWriter* writer, + base::WaitableEvent* event); + void UIT_CanGoBackNotify(bool *retVal, base::WaitableEvent* event); + void UIT_CanGoForwardNotify(bool *retVal, base::WaitableEvent* event); + + 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 std::wstring& 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); + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + + const FilePath& file_system_root() const { return file_system_root_.path(); } + +protected: + CefWindowInfo window_info_; + bool is_popup_; + bool is_modal_; + CefRefPtr handler_; + scoped_ptr webviewhost_; + WebWidgetHost* popuphost_; + scoped_ptr delegate_; + scoped_ptr popup_delegate_; + scoped_ptr nav_controller_; + + std::wstring title_; + + // Context object used to manage printing. + printing::PrintingContext print_context_; + + typedef std::map FrameMap; + FrameMap frames_; + CefFrame* frame_main_; + + // Unique browser ID assigned by the context. + int unique_id_; + + // A temporary directory for FileSystem API. + ScopedTempDir file_system_root_; +}; + + +// Implementation of CefFrame. +class CefFrameImpl : public CefThreadSafeBase +{ +public: + CefFrameImpl(CefBrowserImpl* browser, const std::wstring& name) + : browser_(browser), name_(name) {} + virtual ~CefFrameImpl() { browser_->RemoveCefFrame(name_); } + + // CefFrame methods + virtual void Undo() { browser_->Undo(this); } + virtual void Redo() { browser_->Redo(this); } + virtual void Cut() { browser_->Cut(this); } + virtual void Copy() { browser_->Copy(this); } + virtual void Paste() { browser_->Paste(this); } + virtual void Delete() { browser_->Delete(this); } + virtual void SelectAll() { browser_->SelectAll(this); } + virtual void Print() { browser_->Print(this); } + virtual void ViewSource() { browser_->ViewSource(this); } + virtual std::wstring GetSource() { return browser_->GetSource(this); } + virtual std::wstring GetText() { return browser_->GetText(this); } + virtual void LoadRequest(CefRefPtr request) + { return browser_->LoadRequest(this, request); } + virtual void LoadURL(const std::wstring& url) + { return browser_->LoadURL(this, url); } + virtual void LoadString(const std::wstring& string, + const std::wstring& url) + { return browser_->LoadString(this, string, url); } + virtual void LoadStream(CefRefPtr stream, + const std::wstring& url) + { return browser_->LoadStream(this, stream, url); } + virtual void ExecuteJavaScript(const std::wstring& jsCode, + const std::wstring& scriptUrl, + int startLine) + { return browser_->ExecuteJavaScript(this, jsCode, scriptUrl, startLine); } + virtual bool IsMain() { return name_.empty(); } + virtual bool IsFocused(); + virtual std::wstring GetName() { return name_; } + virtual std::wstring GetURL() { return browser_->GetURL(this); } + +private: + CefRefPtr browser_; + std::wstring name_; +}; + +#endif // _BROWSER_IMPL_H diff --git a/libcef/browser_impl_win.cc b/libcef/browser_impl_win.cc index 40a5cc78c..96141b026 100644 --- a/libcef/browser_impl_win.cc +++ b/libcef/browser_impl_win.cc @@ -1,478 +1,478 @@ -// 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 "cef_context.h" -#include "browser_impl.h" -#include "printing/units.h" - -#include "base/utf_string_conversions.h" -#include "base/win_util.h" -#include "skia/ext/vector_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSize.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" - -#include -#include -#include -#include - -using WebKit::WebRect; -using WebKit::WebSize; - - -LPCTSTR CefBrowserImpl::GetWndClass() -{ - return L"CefBrowserWindow"; -} - -LRESULT CALLBACK CefBrowserImpl::WndProc(HWND hwnd, UINT message, - WPARAM wParam, LPARAM lParam) -{ - CefBrowserImpl* browser = - static_cast(win_util::GetWindowUserData(hwnd)); - - switch (message) { - case WM_COMMAND: - { - int wmId = LOWORD(wParam); - int wmEvent = HIWORD(wParam); - - - } - break; - - case WM_DESTROY: - if (browser) - { - CefRefPtr handler = browser->GetHandler(); - if(handler.get()) { - // Notify the handler that the window is about to be closed - handler->HandleBeforeWindowClose(browser); - } - browser->GetWebViewDelegate()->RevokeDragDrop(); - - // Clean up anything associated with the WebViewHost widget. - browser->GetWebViewHost()->webwidget()->close(); - browser->webviewhost_.reset(); - - // Clear the user data pointer. - win_util::SetWindowUserData(hwnd, NULL); - // Remove the reference added in UIT_CreateBrowser(). - browser->Release(); - - // Remove the browser from the list maintained by the context - _Context->RemoveBrowser(browser); - } - return 0; - - case WM_SIZE: - if (browser && browser->GetWebView()) { - // resize the web view window to the full size of the browser window - RECT rc; - GetClientRect(browser->GetMainWndHandle(), &rc); - MoveWindow(browser->GetWebViewWndHandle(), 0, 0, rc.right, rc.bottom, - TRUE); - } - return 0; - - case WM_SETFOCUS: - if (browser && browser->GetWebView()) - browser->GetWebView()->setFocus(true); - return 0; - - case WM_KILLFOCUS: - if (browser && browser->GetWebView()) - browser->GetWebView()->setFocus(false); - return 0; - - case WM_ERASEBKGND: - return 0; - } - - return DefWindowProc(hwnd, message, wParam, lParam); -} - -CefWindowHandle CefBrowserImpl::GetWindowHandle() -{ - Lock(); - CefWindowHandle handle = window_info_.m_hWnd; - Unlock(); - return handle; -} - -void CefBrowserImpl::UIT_CreateBrowser(const std::wstring& url) -{ - REQUIRE_UIT(); - - // Create the new browser window - window_info_.m_hWnd = CreateWindowEx(window_info_.m_dwExStyle, GetWndClass(), - window_info_.m_windowName, 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); - DCHECK(window_info_.m_hWnd != NULL); - - // Set window user data to this object for future reference from the window - // procedure - win_util::SetWindowUserData(window_info_.m_hWnd, this); - // Add a reference that will be released on WM_DESTROY. - AddRef(); - - // Add the new browser to the list maintained by the context - _Context->AddBrowser(this); - - // Create the webview host object - webviewhost_.reset( - WebViewHost::Create(window_info_.m_hWnd, delegate_.get(), NULL, - *_Context->web_preferences())); - delegate_->RegisterDragDrop(); - - // Size the web view window to the browser window - RECT cr; - GetClientRect(window_info_.m_hWnd, &cr); - SetWindowPos(GetWebViewWndHandle(), NULL, cr.left, cr.top, cr.right, - cr.bottom, SWP_NOZORDER | SWP_SHOWWINDOW); - - if(handler_.get()) { - // Notify the handler that we're done creating the new window - handler_->HandleAfterCreated(this); - } - - if(url.size() > 0) { - CefRefPtr frame = GetMainFrame(); - frame->AddRef(); - UIT_LoadURL(frame, url.c_str()); - } -} - -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); -} - -WebKit::WebWidget* CefBrowserImpl::UIT_CreatePopupWidget() -{ - REQUIRE_UIT(); - - DCHECK(!popuphost_); - popuphost_ = WebWidgetHost::Create(NULL, popup_delegate_.get()); - ShowWindow(GetPopupWndHandle(), SW_SHOW); - - return popuphost_->webwidget(); -} - -void CefBrowserImpl::UIT_ClosePopupWidget() -{ - REQUIRE_UIT(); - - PostMessage(GetPopupWndHandle(), WM_CLOSE, 0, 0); - popuphost_ = 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 = (int)ShellExecute(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); - - skia::VectorCanvas canvas(hDC, dest_size_x, dest_size_y); - - //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); - - 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; - - std::string spec = frame->url().spec(); - std::wstring url = UTF8ToWide(spec); - std::wstring title = title_; - - std::wstring topLeft, topCenter, topRight; - std::wstring bottomLeft, bottomCenter, bottomRight; - - // allow the handler to format print header and/or footer - CefHandler::RetVal rv = handler_->HandlePrintHeaderFooter(this, - GetCefFrame(frame), printInfo, url, title, page_number+1, total_pages, - topLeft, topCenter, topRight, bottomLeft, bottomCenter, bottomRight); - - if(rv != RV_HANDLED) { - // Draw handler-defined headers and/or footers. - LOGFONT lf; - memset(&lf, 0, sizeof(lf)); - lf.lfHeight = (int)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.size() > 0) { - DrawText(hDC, topLeft.c_str(), topLeft.size(), &rect, - DT_LEFT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(topCenter.size() > 0) { - DrawText(hDC, topCenter.c_str(), topCenter.size(), &rect, - DT_CENTER | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(topRight.size() > 0) { - DrawText(hDC, topRight.c_str(), topRight.size(), &rect, - DT_RIGHT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(bottomLeft.size() > 0) { - DrawText(hDC, bottomLeft.c_str(), bottomLeft.size(), &rect, - DT_LEFT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(bottomCenter.size() > 0) { - DrawText(hDC, bottomCenter.c_str(), bottomCenter.size(), &rect, - DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(bottomRight.size() > 0) { - DrawText(hDC, bottomRight.c_str(), bottomRight.size(), &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(); - cef_print_options_t print_options; - settings.UpdatePrintOptions(print_options); - - // Ask the handler if they want to update the print options. - if (handler_.get() && RV_HANDLED == handler_->HandlePrintOptions(this, print_options)) { - settings.UpdateFromPrintOptions(print_options); - print_context_.InitWithSettings(settings); - } - } - - if(print_context_.AskUserForSettings( - 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)); - page_count = frame->printBegin(WebSize(canvas_size)); - - 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; -} +// 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 "cef_context.h" +#include "browser_impl.h" +#include "printing/units.h" + +#include "base/utf_string_conversions.h" +#include "base/win_util.h" +#include "skia/ext/vector_canvas.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" +#include "third_party/WebKit/WebKit/chromium/public/WebSize.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" + +#include +#include +#include +#include + +using WebKit::WebRect; +using WebKit::WebSize; + + +LPCTSTR CefBrowserImpl::GetWndClass() +{ + return L"CefBrowserWindow"; +} + +LRESULT CALLBACK CefBrowserImpl::WndProc(HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam) +{ + CefBrowserImpl* browser = + static_cast(win_util::GetWindowUserData(hwnd)); + + switch (message) { + case WM_COMMAND: + { + int wmId = LOWORD(wParam); + int wmEvent = HIWORD(wParam); + + + } + break; + + case WM_DESTROY: + if (browser) + { + CefRefPtr handler = browser->GetHandler(); + if(handler.get()) { + // Notify the handler that the window is about to be closed + handler->HandleBeforeWindowClose(browser); + } + browser->GetWebViewDelegate()->RevokeDragDrop(); + + // Clean up anything associated with the WebViewHost widget. + browser->GetWebViewHost()->webwidget()->close(); + browser->webviewhost_.reset(); + + // Clear the user data pointer. + win_util::SetWindowUserData(hwnd, NULL); + // Remove the reference added in UIT_CreateBrowser(). + browser->Release(); + + // Remove the browser from the list maintained by the context + _Context->RemoveBrowser(browser); + } + return 0; + + case WM_SIZE: + if (browser && browser->GetWebView()) { + // resize the web view window to the full size of the browser window + RECT rc; + GetClientRect(browser->GetMainWndHandle(), &rc); + MoveWindow(browser->GetWebViewWndHandle(), 0, 0, rc.right, rc.bottom, + TRUE); + } + return 0; + + case WM_SETFOCUS: + if (browser && browser->GetWebView()) + browser->GetWebView()->setFocus(true); + return 0; + + case WM_KILLFOCUS: + if (browser && browser->GetWebView()) + browser->GetWebView()->setFocus(false); + return 0; + + case WM_ERASEBKGND: + return 0; + } + + return DefWindowProc(hwnd, message, wParam, lParam); +} + +CefWindowHandle CefBrowserImpl::GetWindowHandle() +{ + Lock(); + CefWindowHandle handle = window_info_.m_hWnd; + Unlock(); + return handle; +} + +void CefBrowserImpl::UIT_CreateBrowser(const std::wstring& url) +{ + REQUIRE_UIT(); + + // Create the new browser window + window_info_.m_hWnd = CreateWindowEx(window_info_.m_dwExStyle, GetWndClass(), + window_info_.m_windowName, 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); + DCHECK(window_info_.m_hWnd != NULL); + + // Set window user data to this object for future reference from the window + // procedure + win_util::SetWindowUserData(window_info_.m_hWnd, this); + // Add a reference that will be released on WM_DESTROY. + AddRef(); + + // Add the new browser to the list maintained by the context + _Context->AddBrowser(this); + + // Create the webview host object + webviewhost_.reset( + WebViewHost::Create(window_info_.m_hWnd, delegate_.get(), NULL, + *_Context->web_preferences())); + delegate_->RegisterDragDrop(); + + // Size the web view window to the browser window + RECT cr; + GetClientRect(window_info_.m_hWnd, &cr); + SetWindowPos(GetWebViewWndHandle(), NULL, cr.left, cr.top, cr.right, + cr.bottom, SWP_NOZORDER | SWP_SHOWWINDOW); + + if(handler_.get()) { + // Notify the handler that we're done creating the new window + handler_->HandleAfterCreated(this); + } + + if(url.size() > 0) { + CefRefPtr frame = GetMainFrame(); + frame->AddRef(); + UIT_LoadURL(frame, url.c_str()); + } +} + +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); +} + +WebKit::WebWidget* CefBrowserImpl::UIT_CreatePopupWidget() +{ + REQUIRE_UIT(); + + DCHECK(!popuphost_); + popuphost_ = WebWidgetHost::Create(NULL, popup_delegate_.get()); + ShowWindow(GetPopupWndHandle(), SW_SHOW); + + return popuphost_->webwidget(); +} + +void CefBrowserImpl::UIT_ClosePopupWidget() +{ + REQUIRE_UIT(); + + PostMessage(GetPopupWndHandle(), WM_CLOSE, 0, 0); + popuphost_ = 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 = (int)ShellExecute(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); + + skia::VectorCanvas canvas(hDC, dest_size_x, dest_size_y); + + //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); + + 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; + + std::string spec = frame->url().spec(); + std::wstring url = UTF8ToWide(spec); + std::wstring title = title_; + + std::wstring topLeft, topCenter, topRight; + std::wstring bottomLeft, bottomCenter, bottomRight; + + // allow the handler to format print header and/or footer + CefHandler::RetVal rv = handler_->HandlePrintHeaderFooter(this, + GetCefFrame(frame), printInfo, url, title, page_number+1, total_pages, + topLeft, topCenter, topRight, bottomLeft, bottomCenter, bottomRight); + + if(rv != RV_HANDLED) { + // Draw handler-defined headers and/or footers. + LOGFONT lf; + memset(&lf, 0, sizeof(lf)); + lf.lfHeight = (int)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.size() > 0) { + DrawText(hDC, topLeft.c_str(), topLeft.size(), &rect, + DT_LEFT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(topCenter.size() > 0) { + DrawText(hDC, topCenter.c_str(), topCenter.size(), &rect, + DT_CENTER | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(topRight.size() > 0) { + DrawText(hDC, topRight.c_str(), topRight.size(), &rect, + DT_RIGHT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(bottomLeft.size() > 0) { + DrawText(hDC, bottomLeft.c_str(), bottomLeft.size(), &rect, + DT_LEFT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(bottomCenter.size() > 0) { + DrawText(hDC, bottomCenter.c_str(), bottomCenter.size(), &rect, + DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(bottomRight.size() > 0) { + DrawText(hDC, bottomRight.c_str(), bottomRight.size(), &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(); + cef_print_options_t print_options; + settings.UpdatePrintOptions(print_options); + + // Ask the handler if they want to update the print options. + if (handler_.get() && RV_HANDLED == handler_->HandlePrintOptions(this, print_options)) { + settings.UpdateFromPrintOptions(print_options); + print_context_.InitWithSettings(settings); + } + } + + if(print_context_.AskUserForSettings( + 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)); + page_count = frame->printBegin(WebSize(canvas_size)); + + 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; +} diff --git a/libcef/browser_navigation_controller.cc b/libcef/browser_navigation_controller.cc index 89c73ea24..c594c7006 100644 --- a/libcef/browser_navigation_controller.cc +++ b/libcef/browser_navigation_controller.cc @@ -1,241 +1,241 @@ -// 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 "browser_navigation_controller.h" -#include "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 std::wstring& title, - const std::wstring& target_frame, - const std::wstring& method, - const WebKit::WebHTTPBody& upload, - const CefRequest::HeaderMap& headers) - : page_id_(page_id), - url_(url), - title_(title), - target_frame_(target_frame), - method_(method), - headers_(headers) { - if(!upload.isNull()) - upload_ = upload; -} - -BrowserNavigationEntry::~BrowserNavigationEntry() { -} - -void BrowserNavigationEntry::SetContentState(const std::string& state) { - state_ = state; -} - -// ---------------------------------------------------------------------------- -// BrowserNavigationController - -BrowserNavigationController::BrowserNavigationController(CefBrowserImpl* shell) - : pending_entry_(NULL), - last_committed_entry_index_(-1), - pending_entry_index_(-1), - browser_(shell), - max_page_id_(-1) { -} - -BrowserNavigationController::~BrowserNavigationController() { - DiscardPendingEntry(); -} - -void BrowserNavigationController::Reset() { - entries_.clear(); - DiscardPendingEntry(); - - last_committed_entry_index_ = -1; -} - -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(index >= 0); - DCHECK(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(); - - // 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(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()); -} +// 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 "browser_navigation_controller.h" +#include "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 std::wstring& title, + const std::wstring& target_frame, + const std::wstring& method, + const WebKit::WebHTTPBody& upload, + const CefRequest::HeaderMap& headers) + : page_id_(page_id), + url_(url), + title_(title), + target_frame_(target_frame), + method_(method), + headers_(headers) { + if(!upload.isNull()) + upload_ = upload; +} + +BrowserNavigationEntry::~BrowserNavigationEntry() { +} + +void BrowserNavigationEntry::SetContentState(const std::string& state) { + state_ = state; +} + +// ---------------------------------------------------------------------------- +// BrowserNavigationController + +BrowserNavigationController::BrowserNavigationController(CefBrowserImpl* shell) + : pending_entry_(NULL), + last_committed_entry_index_(-1), + pending_entry_index_(-1), + browser_(shell), + max_page_id_(-1) { +} + +BrowserNavigationController::~BrowserNavigationController() { + DiscardPendingEntry(); +} + +void BrowserNavigationController::Reset() { + entries_.clear(); + DiscardPendingEntry(); + + last_committed_entry_index_ = -1; +} + +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(index >= 0); + DCHECK(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(); + + // 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(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/libcef/browser_navigation_controller.h b/libcef/browser_navigation_controller.h index edbf79a3e..c618e2122 100644 --- a/libcef/browser_navigation_controller.h +++ b/libcef/browser_navigation_controller.h @@ -1,212 +1,212 @@ -// 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 _BROWSER_NAVIGATION_CONTROLLER_H -#define _BROWSER_NAVIGATION_CONTROLLER_H - -#include -#include - -#include "base/basictypes.h" -#include "base/linked_ptr.h" -#include "base/ref_counted.h" -#include "googleurl/src/gurl.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDataSource.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" - -#include "include/cef.h" - -class GURL; -class CefBrowserImpl; - -// Associated with browser-initated navigations to hold tracking data. -class BrowserExtraData : public WebKit::WebDataSource::ExtraData { - public: - 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 std::wstring& title, - const std::wstring& target_frame, - const std::wstring& 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 std::wstring& a_title) { title_ = a_title; } - const std::wstring& 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 std::wstring& GetTargetFrame() const { return target_frame_; } - - const std::wstring& 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_; - std::wstring title_; - std::string state_; - std::wstring method_; - WebKit::WebHTTPBody upload_; - CefRequest::HeaderMap headers_; - - std::wstring 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: - BrowserNavigationController(CefBrowserImpl* shell); - ~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 // _BROWSER_NAVIGATION_CONTROLLER_H - +// 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 _BROWSER_NAVIGATION_CONTROLLER_H +#define _BROWSER_NAVIGATION_CONTROLLER_H + +#include +#include + +#include "base/basictypes.h" +#include "base/linked_ptr.h" +#include "base/ref_counted.h" +#include "googleurl/src/gurl.h" +#include "third_party/WebKit/WebKit/chromium/public/WebDataSource.h" +#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" + +#include "include/cef.h" + +class GURL; +class CefBrowserImpl; + +// Associated with browser-initated navigations to hold tracking data. +class BrowserExtraData : public WebKit::WebDataSource::ExtraData { + public: + 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 std::wstring& title, + const std::wstring& target_frame, + const std::wstring& 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 std::wstring& a_title) { title_ = a_title; } + const std::wstring& 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 std::wstring& GetTargetFrame() const { return target_frame_; } + + const std::wstring& 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_; + std::wstring title_; + std::string state_; + std::wstring method_; + WebKit::WebHTTPBody upload_; + CefRequest::HeaderMap headers_; + + std::wstring 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: + BrowserNavigationController(CefBrowserImpl* shell); + ~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 // _BROWSER_NAVIGATION_CONTROLLER_H + diff --git a/libcef/browser_request_context.cc b/libcef/browser_request_context.cc index 8c637822d..2561133fa 100644 --- a/libcef/browser_request_context.cc +++ b/libcef/browser_request_context.cc @@ -1,94 +1,94 @@ -// 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 "browser_request_context.h" -#include "browser_resource_loader_bridge.h" -#include "build/build_config.h" - -#include "base/file_path.h" -#include "net/base/cookie_monster.h" -#include "net/base/host_resolver.h" -#include "net/base/ssl_config_service.h" -#include "net/base/static_cookie_policy.h" -#include "net/ftp/ftp_network_layer.h" -#include "net/http/http_auth_handler_factory.h" -#include "net/proxy/proxy_config_service.h" -#include "net/proxy/proxy_config_service_fixed.h" -#include "net/proxy/proxy_service.h" -#include "webkit/blob/blob_storage_controller.h" -#include "webkit/glue/webkit_glue.h" - -BrowserRequestContext::BrowserRequestContext() { - Init(FilePath(), net::HttpCache::NORMAL, false); -} - -BrowserRequestContext::BrowserRequestContext( - const FilePath& cache_path, - net::HttpCache::Mode cache_mode, - bool no_proxy) { - Init(cache_path, cache_mode, no_proxy); -} - -void BrowserRequestContext::Init( - const FilePath& cache_path, - net::HttpCache::Mode cache_mode, - bool no_proxy) { - cookie_store_ = new net::CookieMonster(NULL, NULL); - cookie_policy_ = new net::StaticCookiePolicy(); - - // hard-code A-L and A-C for test shells - accept_language_ = "en-us,en"; - accept_charset_ = "iso-8859-1,*,utf-8"; - - // Use the system proxy settings. - scoped_ptr proxy_config_service( - net::ProxyService::CreateSystemProxyConfigService( - MessageLoop::current(), NULL)); - host_resolver_ = - net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, - NULL); - proxy_service_ = net::ProxyService::Create(proxy_config_service.release(), - false, NULL, NULL, NULL, NULL); - ssl_config_service_ = net::SSLConfigService::CreateSystemSSLConfigService(); - - http_auth_handler_factory_ = - net::HttpAuthHandlerFactory::CreateDefault(host_resolver_); - - 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_, proxy_service_, ssl_config_service_, - http_auth_handler_factory_, NULL, NULL, backend); - - cache->set_mode(cache_mode); - http_transaction_factory_ = cache; - - ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); - - blob_storage_controller_.reset(new webkit_blob::BlobStorageController()); -} - -BrowserRequestContext::~BrowserRequestContext() { - delete ftp_transaction_factory_; - delete http_transaction_factory_; - delete http_auth_handler_factory_; - delete static_cast(cookie_policy_); - delete host_resolver_; -} - -void BrowserRequestContext::SetAcceptAllCookies(bool accept_all_cookies) { - net::StaticCookiePolicy::Type policy_type = accept_all_cookies ? - net::StaticCookiePolicy::ALLOW_ALL_COOKIES : - net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES; - static_cast(cookie_policy())->set_type(policy_type); -} - -const std::string& BrowserRequestContext::GetUserAgent( - const GURL& url) const { - return webkit_glue::GetUserAgent(url); -} - +// 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 "browser_request_context.h" +#include "browser_resource_loader_bridge.h" +#include "build/build_config.h" + +#include "base/file_path.h" +#include "net/base/cookie_monster.h" +#include "net/base/host_resolver.h" +#include "net/base/ssl_config_service.h" +#include "net/base/static_cookie_policy.h" +#include "net/ftp/ftp_network_layer.h" +#include "net/http/http_auth_handler_factory.h" +#include "net/proxy/proxy_config_service.h" +#include "net/proxy/proxy_config_service_fixed.h" +#include "net/proxy/proxy_service.h" +#include "webkit/blob/blob_storage_controller.h" +#include "webkit/glue/webkit_glue.h" + +BrowserRequestContext::BrowserRequestContext() { + Init(FilePath(), net::HttpCache::NORMAL, false); +} + +BrowserRequestContext::BrowserRequestContext( + const FilePath& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy) { + Init(cache_path, cache_mode, no_proxy); +} + +void BrowserRequestContext::Init( + const FilePath& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy) { + cookie_store_ = new net::CookieMonster(NULL, NULL); + cookie_policy_ = new net::StaticCookiePolicy(); + + // hard-code A-L and A-C for test shells + accept_language_ = "en-us,en"; + accept_charset_ = "iso-8859-1,*,utf-8"; + + // Use the system proxy settings. + scoped_ptr proxy_config_service( + net::ProxyService::CreateSystemProxyConfigService( + MessageLoop::current(), NULL)); + host_resolver_ = + net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, + NULL); + proxy_service_ = net::ProxyService::Create(proxy_config_service.release(), + false, NULL, NULL, NULL, NULL); + ssl_config_service_ = net::SSLConfigService::CreateSystemSSLConfigService(); + + http_auth_handler_factory_ = + net::HttpAuthHandlerFactory::CreateDefault(host_resolver_); + + 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_, proxy_service_, ssl_config_service_, + http_auth_handler_factory_, NULL, NULL, backend); + + cache->set_mode(cache_mode); + http_transaction_factory_ = cache; + + ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); + + blob_storage_controller_.reset(new webkit_blob::BlobStorageController()); +} + +BrowserRequestContext::~BrowserRequestContext() { + delete ftp_transaction_factory_; + delete http_transaction_factory_; + delete http_auth_handler_factory_; + delete static_cast(cookie_policy_); + delete host_resolver_; +} + +void BrowserRequestContext::SetAcceptAllCookies(bool accept_all_cookies) { + net::StaticCookiePolicy::Type policy_type = accept_all_cookies ? + net::StaticCookiePolicy::ALLOW_ALL_COOKIES : + net::StaticCookiePolicy::BLOCK_THIRD_PARTY_COOKIES; + static_cast(cookie_policy())->set_type(policy_type); +} + +const std::string& BrowserRequestContext::GetUserAgent( + const GURL& url) const { + return webkit_glue::GetUserAgent(url); +} + diff --git a/libcef/browser_request_context.h b/libcef/browser_request_context.h index 9774eb562..1c968eb61 100644 --- a/libcef/browser_request_context.h +++ b/libcef/browser_request_context.h @@ -1,46 +1,46 @@ -// 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 _BROWSER_REQUEST_CONTEXT_H -#define _BROWSER_REQUEST_CONTEXT_H - -#include "net/http/http_cache.h" -#include "net/url_request/url_request_context.h" - -class FilePath; -namespace webkit_blob { -class BlobStorageController; -} - -// A basic URLRequestContext that only provides an in-memory cookie store. -class BrowserRequestContext : public URLRequestContext { - public: - // Use an in-memory cache - BrowserRequestContext(); - ~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; - - void SetAcceptAllCookies(bool accept_all_cookies); - - 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); - - scoped_ptr blob_storage_controller_; -}; - -#endif // _BROWSER_REQUEST_CONTEXT_H - +// 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 _BROWSER_REQUEST_CONTEXT_H +#define _BROWSER_REQUEST_CONTEXT_H + +#include "net/http/http_cache.h" +#include "net/url_request/url_request_context.h" + +class FilePath; +namespace webkit_blob { +class BlobStorageController; +} + +// A basic URLRequestContext that only provides an in-memory cookie store. +class BrowserRequestContext : public URLRequestContext { + public: + // Use an in-memory cache + BrowserRequestContext(); + ~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; + + void SetAcceptAllCookies(bool accept_all_cookies); + + 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); + + scoped_ptr blob_storage_controller_; +}; + +#endif // _BROWSER_REQUEST_CONTEXT_H + diff --git a/libcef/browser_resource_loader_bridge.cc b/libcef/browser_resource_loader_bridge.cc index b8c9b77c2..9c7de2294 100644 --- a/libcef/browser_resource_loader_bridge.cc +++ b/libcef/browser_resource_loader_bridge.cc @@ -1,882 +1,882 @@ -// 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. -// -// This file contains an implementation of the ResourceLoaderBridge class. -// The class is implemented using URLRequest, meaning it is a "simple" version -// that directly issues requests. The more complicated one used in the -// browser uses IPC. -// -// Because URLRequest only provides an asynchronous resource loading API, this -// file makes use of 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) -// \ -> URLRequest -// o-------> SyncRequestProxy (synchronous case) -// -> URLRequest -// SetCookie <------------------------> CookieSetter -// -> net_util::SetCookie -// GetCookies <-----------------------> CookieGetter -// -> net_util::GetCookies -// -// 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 URLRequest to -// perform URL loads. See renderer/resource_dispatcher.h for details on an -// alternate implementation that defers fetching to another process. - -#include "browser_appcache_system.h" -#include "browser_resource_loader_bridge.h" -#include "browser_request_context.h" -#include "browser_socket_stream_bridge.h" -#include "browser_impl.h" -#include "cef_context.h" -#include "cef_process.h" -#include "cef_process_io_thread.h" -#include "request_impl.h" - -#include "base/file_path.h" -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/message_loop_proxy.h" -#if defined(OS_MACOSX) || defined(OS_WIN) -#include "base/nss_util.h" -#endif -#include "base/ref_counted.h" -#include "base/time.h" -#include "base/timer.h" -#include "base/thread.h" -#include "base/utf_string_conversions.h" -#include "base/waitable_event.h" -#include "net/base/cookie_store.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" -#if defined(OS_WIN) -#include "net/socket/ssl_client_socket_nss_factory.h" -#endif -#include "net/url_request/url_request.h" -#include "webkit/appcache/appcache_interfaces.h" -#include "webkit/blob/blob_storage_controller.h" -#include "webkit/blob/deletable_file_reference.h" -#include "webkit/glue/resource_loader_bridge.h" - -using net::HttpResponseHeaders; -using net::StaticCookiePolicy; -using webkit_blob::DeletableFileReference; -using webkit_glue::ResourceLoaderBridge; - - -namespace { - -struct RequestParams { - std::string method; - GURL url; - GURL first_party_for_cookies; - GURL referrer; - std::string headers; - int load_flags; - ResourceType::Type request_type; - int appcache_host_id; - bool download_to_file; - scoped_refptr upload; -}; - -// The interval for calls to RequestProxy::MaybeUpdateUploadProgress -static const int kUpdateUploadProgressIntervalMsec = 100; - -// 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 URLRequest object -// is instantiated. -class RequestProxy : public URLRequest::Delegate, - public base::RefCountedThreadSafe { - public: - // Takes ownership of the params. - RequestProxy(CefRefPtr browser) - : browser_(browser), - download_to_file_(false), - buf_(new net::IOBuffer(kDataSize)), - last_upload_position_(0) - { - } - - void DropPeer() { - peer_ = NULL; - } - - void Start(ResourceLoaderBridge::Peer* peer, RequestParams* params) { - peer_ = peer; - owner_loop_ = MessageLoop::current(); - - // proxy over to the io thread - CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( - this, &RequestProxy::AsyncStart, params)); - } - - void Cancel() { - // proxy over to the io thread - CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( - this, &RequestProxy::AsyncCancel)); - } - - 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)); - } - - // -------------------------------------------------------------------------- - // The following methods are called on the owner's thread in response to - // various URLRequest callbacks. The event hooks, defined below, trigger - // these methods asynchronously. - - void NotifyReceivedRedirect(const GURL& new_url, - const ResourceLoaderBridge::ResponseInfo& info) { - 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, NewRunnableMethod( - this, &RequestProxy::AsyncFollowDeferredRedirect, - has_new_first_party_for_cookies, new_first_party_for_cookies)); - } else { - Cancel(); - } - } - - void NotifyReceivedResponse(const ResourceLoaderBridge::ResponseInfo& info, - bool content_filtered) { - if (peer_) - peer_->OnReceivedResponse(info, content_filtered); - } - - void NotifyReceivedData(int bytes_read) { - 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 reponse 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, NewRunnableMethod( - this, &RequestProxy::AsyncReadData)); - - peer_->OnReceivedData(buf_copy.get(), bytes_read); - } - - void NotifyDownloadedData(int bytes_read) { - if (!peer_) - return; - - // Continue reading more data, see the comment in NotifyReceivedData. - CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( - this, &RequestProxy::AsyncReadData)); - - peer_->OnDownloadedData(bytes_read); - } - - void NotifyCompletedRequest(const URLRequestStatus& status, - const std::string& security_info, - const base::Time& complete_time) { - if (peer_) { - peer_->OnCompletedRequest(status, security_info, complete_time); - DropPeer(); // ensure no further notifications - } - } - - void NotifyUploadProgress(uint64 position, uint64 size) { - 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) { - bool handled = false; - - if (browser_.get()) { - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) - { - // Build the request object for passing to the handler - CefRefPtr request(new CefRequestImpl()); - CefRequestImpl* requestimpl = static_cast(request.get()); - - const std::wstring originalUrl = UTF8ToWide(params->url.spec()); - requestimpl->SetURL(originalUrl); - requestimpl->SetMethod(UTF8ToWide(params->method)); - - // Transfer request headers - CefRequest::HeaderMap headerMap; - CefRequestImpl::ParseHeaders(params->headers, headerMap); - headerMap.insert( - std::make_pair(L"Referrer", UTF8ToWide(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 - std::wstring redirectUrl; - CefRefPtr resourceStream; - std::wstring mimeType; - - CefHandler::RetVal rv = handler->HandleBeforeResourceLoad( - browser_, request, redirectUrl, resourceStream, mimeType, loadFlags); - - // Observe URL from request. - const std::wstring requestUrl = request->GetURL(); - if(requestUrl != originalUrl) { - params->url = GURL(WideToUTF8(requestUrl)); - redirectUrl.clear(); // Request URL trumps redirect URL - } - - // Observe method from request. - params->method = WideToUTF8(request->GetMethod()); - - // Observe headers from request. - request->GetHeaderMap(headerMap); - CefRequest::HeaderMap::iterator referrer = headerMap.find(L"Referrer"); - if(referrer == headerMap.end()) { - params->referrer = GURL(); - } else { - params->referrer = GURL(WideToUTF8(referrer->second)); - headerMap.erase(referrer); - } - params->headers = CefRequestImpl::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(rv == RV_HANDLED) { - // cancel the resource load - handled = true; - OnCompletedRequest( - URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED), - std::string(), base::Time()); - } else if(!redirectUrl.empty()) { - // redirect to the specified URL - params->url = GURL(WideToUTF8(redirectUrl)); - ResourceLoaderBridge::ResponseInfo info; - bool defer_redirect; - OnReceivedRedirect(params->url, info, &defer_redirect); - } else if(resourceStream.get()) { - // load from the provided resource stream - handled = true; - - resourceStream->Seek(0, SEEK_END); - long offset = resourceStream->Tell(); - resourceStream->Seek(0, SEEK_SET); - - resource_stream_ = resourceStream; - - ResourceLoaderBridge::ResponseInfo info; - info.content_length = static_cast(offset); - if(!mimeType.empty()) - info.mime_type = WideToUTF8(mimeType); - OnReceivedResponse(info, false); - AsyncReadData(); - } - } - } - - 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 URLRequest(params->url, this)); - request_->set_method(params->method); - request_->set_first_party_for_cookies(params->first_party_for_cookies); - request_->set_referrer(params->referrer.spec()); - 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(_Context->request_context()); - 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_ = DeletableFileReference::GetOrCreate( - path, base::MessageLoopProxy::CreateForCurrentThread()); - file_stream_.Open( - path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_WRITE); - } - } - - request_->Start(); - - if (request_->has_upload() && - params->load_flags & net::LOAD_ENABLE_UPLOAD_PROGRESS) { - upload_progress_timer_.Start( - base::TimeDelta::FromMilliseconds(kUpdateUploadProgressIntervalMsec), - this, &RequestProxy::MaybeUpdateUploadProgress); - } - } - - delete params; - } - - void AsyncCancel() { - // 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) { - // 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 AsyncReadData() { - 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 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 ResourceLoaderBridge::ResponseInfo& info, - bool* defer_redirect) { - *defer_redirect = true; // See AsyncFollowDeferredRedirect - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyReceivedRedirect, new_url, info)); - } - - virtual void OnReceivedResponse( - const ResourceLoaderBridge::ResponseInfo& info, - bool content_filtered) { - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyReceivedResponse, info, content_filtered)); - } - - virtual void OnReceivedData(int bytes_read) { - if (download_to_file_) { - file_stream_.Write(buf_->data(), bytes_read, NULL); - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyDownloadedData, bytes_read)); - return; - } - - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyReceivedData, bytes_read)); - } - - virtual void OnCompletedRequest(const URLRequestStatus& status, - const std::string& security_info, - const base::Time& complete_time) { - if (download_to_file_) - file_stream_.Close(); - - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyCompletedRequest, status, security_info, - complete_time)); - } - - // -------------------------------------------------------------------------- - // URLRequest::Delegate implementation: - - virtual void OnReceivedRedirect(URLRequest* request, - const GURL& new_url, - bool* defer_redirect) { - DCHECK(request->status().is_success()); - ResourceLoaderBridge::ResponseInfo info; - PopulateResponseInfo(request, &info); - OnReceivedRedirect(new_url, info, defer_redirect); - } - - virtual void OnResponseStarted(URLRequest* request) { - if (request->status().is_success()) { - ResourceLoaderBridge::ResponseInfo info; - PopulateResponseInfo(request, &info); - OnReceivedResponse(info, false); - AsyncReadData(); // start reading - } else { - Done(); - } - } - - virtual void OnSSLCertificateError(URLRequest* request, - int cert_error, - net::X509Certificate* cert) { - // Allow all certificate errors. - request->ContinueDespiteLastError(); - } - - virtual void OnReadCompleted(URLRequest* request, int bytes_read) { - if (request->status().is_success() && bytes_read > 0) { - OnReceivedData(bytes_read); - } else { - Done(); - } - } - - // -------------------------------------------------------------------------- - // Helpers and data: - - void Done() { - if(resource_stream_.get()) { - // Resource stream reads always complete successfully - OnCompletedRequest(URLRequestStatus(URLRequestStatus::SUCCESS, 0), - std::string(), base::Time()); - 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::Time()); - request_.reset(); // destroy on the io thread - } - } - - // Called on the IO thread. - void MaybeUpdateUploadProgress() { - // If a redirect is received upload is cancelled in 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; - } - - uint64 size = request_->get_upload()->GetContentLength(); - 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, NewRunnableMethod( - this, &RequestProxy::NotifyUploadProgress, position, size)); - last_upload_ticks_ = base::TimeTicks::Now(); - last_upload_position_ = position; - } - } - - void PopulateResponseInfo(URLRequest* request, - ResourceLoaderBridge::ResponseInfo* info) const { - 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 - static const int kDataSize = 16*1024; - - // 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_; -}; - -//----------------------------------------------------------------------------- - -class SyncRequestProxy : public RequestProxy { - public: - explicit SyncRequestProxy(CefRefPtr browser, - ResourceLoaderBridge::SyncLoadResponse* result) - : RequestProxy(browser), result_(result), event_(true, false) { - } - - void WaitForCompletion() { - if (!event_.Wait()) - NOTREACHED(); - } - - // -------------------------------------------------------------------------- - // Event hooks that run on the IO thread: - - virtual void OnReceivedRedirect( - const GURL& new_url, - const ResourceLoaderBridge::ResponseInfo& info, - bool* defer_redirect) { - // 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 ResourceLoaderBridge::ResponseInfo& info, - bool content_filtered) { - *static_cast(result_) = info; - } - - virtual void OnReceivedData(int bytes_read) { - if (download_to_file_) - file_stream_.Write(buf_->data(), bytes_read, NULL); - else - result_->data.append(buf_->data(), bytes_read); - AsyncReadData(); // read more (may recurse) - } - - virtual void OnCompletedRequest(const URLRequestStatus& status, - const std::string& security_info, - const base::Time& complete_time) { - if (download_to_file_) - file_stream_.Close(); - - result_->status = status; - event_.Signal(); - } - - private: - ResourceLoaderBridge::SyncLoadResponse* result_; - base::WaitableEvent event_; -}; - -//----------------------------------------------------------------------------- - -class ResourceLoaderBridgeImpl : public ResourceLoaderBridge { - 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_->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_); - } - } - - // -------------------------------------------------------------------------- - // ResourceLoaderBridge implementation: - - virtual void AppendDataToUpload(const char* data, int data_len) { - 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) { - 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) { - DCHECK(params_.get()); - if (!params_->upload) - params_->upload = new net::UploadData(); - params_->upload->AppendBlob(blob_url); - } - - virtual void SetUploadIdentifier(int64 identifier) { - DCHECK(params_.get()); - if (!params_->upload) - params_->upload = new net::UploadData(); - params_->upload->set_identifier(identifier); - } - - virtual bool Start(Peer* peer) { - DCHECK(!proxy_); - - proxy_ = new RequestProxy(browser_); - proxy_->AddRef(); - - proxy_->Start(peer, params_.release()); - - return true; // Any errors will be reported asynchronously. - } - - virtual void Cancel() { - DCHECK(proxy_); - proxy_->Cancel(); - } - - virtual void SetDefersLoading(bool value) { - // TODO(darin): implement me - } - - virtual void SyncLoad(SyncLoadResponse* response) { - DCHECK(!proxy_); - - // this may change as the result of a redirect - response->url = params_->url; - - proxy_ = new SyncRequestProxy(browser_, response); - proxy_->AddRef(); - - proxy_->Start(NULL, params_.release()); - - static_cast(proxy_)->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. - RequestProxy* proxy_; -}; - -//----------------------------------------------------------------------------- - -class CookieSetter : public base::RefCountedThreadSafe { - public: - void Set(const GURL& url, const std::string& cookie) { - REQUIRE_IOT(); - _Context->request_context()->cookie_store()->SetCookie(url, cookie); - } - - private: - friend class base::RefCountedThreadSafe; - - ~CookieSetter() {} -}; - -class CookieGetter : public base::RefCountedThreadSafe { - public: - CookieGetter() : event_(false, false) { - } - - void Get(const GURL& url) { - result_ = _Context->request_context()->cookie_store()->GetCookies(url); - event_.Signal(); - } - - std::string GetResult() { - if (!event_.Wait()) - NOTREACHED(); - return result_; - } - - private: - friend class base::RefCountedThreadSafe; - - ~CookieGetter() {} - - base::WaitableEvent event_; - std::string result_; -}; - -} // anonymous namespace - -//----------------------------------------------------------------------------- - -namespace webkit_glue { - -// Factory function. -ResourceLoaderBridge* ResourceLoaderBridge::Create( - const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) { - CefRefPtr browser = - _Context->GetBrowserByID(request_info.routing_id); - return new ResourceLoaderBridgeImpl(browser, request_info); -} - -// Issue the proxy resolve request on the io thread, and wait -// for the result. -bool FindProxyForUrl(const GURL& url, std::string* proxy_list) { - DCHECK(_Context->request_context()); - - scoped_refptr sync_proxy_service( - new net::SyncProxyServiceHelper( - _Context->process()->io_thread()->message_loop(), - _Context->request_context()->proxy_service())); - - net::ProxyInfo proxy_info; - int rv = sync_proxy_service->ResolveProxy(url, &proxy_info, - net::BoundNetLog()); - if (rv == net::OK) { - *proxy_list = proxy_info.ToPacString(); - } - - return rv == net::OK; -} - -} // namespace webkit_glue - -//----------------------------------------------------------------------------- - -// static -void BrowserResourceLoaderBridge::SetCookie(const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie) { - // Proxy to IO thread to synchronize w/ network loading. - - scoped_refptr cookie_setter = new CookieSetter(); - CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( - cookie_setter.get(), &CookieSetter::Set, url, cookie)); -} - -// static -std::string BrowserResourceLoaderBridge::GetCookies( - const GURL& url, const GURL& first_party_for_cookies) { - // Proxy to IO thread to synchronize w/ network loading - - scoped_refptr getter = new CookieGetter(); - - CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( - getter.get(), &CookieGetter::Get, url)); - - return getter->GetResult(); -} - -// static -void BrowserResourceLoaderBridge::SetAcceptAllCookies(bool accept_all_cookies) { - // Proxy to IO thread to synchronize w/ network loading - CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( - _Context->request_context().get(), - &BrowserRequestContext::SetAcceptAllCookies, accept_all_cookies)); -} - -//static -scoped_refptr - BrowserResourceLoaderBridge::GetCacheThread() { - return CefThread::GetMessageLoopProxyForThread(CefThread::FILE); -} +// 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. +// +// This file contains an implementation of the ResourceLoaderBridge class. +// The class is implemented using URLRequest, meaning it is a "simple" version +// that directly issues requests. The more complicated one used in the +// browser uses IPC. +// +// Because URLRequest only provides an asynchronous resource loading API, this +// file makes use of 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) +// \ -> URLRequest +// o-------> SyncRequestProxy (synchronous case) +// -> URLRequest +// SetCookie <------------------------> CookieSetter +// -> net_util::SetCookie +// GetCookies <-----------------------> CookieGetter +// -> net_util::GetCookies +// +// 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 URLRequest to +// perform URL loads. See renderer/resource_dispatcher.h for details on an +// alternate implementation that defers fetching to another process. + +#include "browser_appcache_system.h" +#include "browser_resource_loader_bridge.h" +#include "browser_request_context.h" +#include "browser_socket_stream_bridge.h" +#include "browser_impl.h" +#include "cef_context.h" +#include "cef_process.h" +#include "cef_process_io_thread.h" +#include "request_impl.h" + +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/message_loop.h" +#include "base/message_loop_proxy.h" +#if defined(OS_MACOSX) || defined(OS_WIN) +#include "base/nss_util.h" +#endif +#include "base/ref_counted.h" +#include "base/time.h" +#include "base/timer.h" +#include "base/thread.h" +#include "base/utf_string_conversions.h" +#include "base/waitable_event.h" +#include "net/base/cookie_store.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" +#if defined(OS_WIN) +#include "net/socket/ssl_client_socket_nss_factory.h" +#endif +#include "net/url_request/url_request.h" +#include "webkit/appcache/appcache_interfaces.h" +#include "webkit/blob/blob_storage_controller.h" +#include "webkit/blob/deletable_file_reference.h" +#include "webkit/glue/resource_loader_bridge.h" + +using net::HttpResponseHeaders; +using net::StaticCookiePolicy; +using webkit_blob::DeletableFileReference; +using webkit_glue::ResourceLoaderBridge; + + +namespace { + +struct RequestParams { + std::string method; + GURL url; + GURL first_party_for_cookies; + GURL referrer; + std::string headers; + int load_flags; + ResourceType::Type request_type; + int appcache_host_id; + bool download_to_file; + scoped_refptr upload; +}; + +// The interval for calls to RequestProxy::MaybeUpdateUploadProgress +static const int kUpdateUploadProgressIntervalMsec = 100; + +// 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 URLRequest object +// is instantiated. +class RequestProxy : public URLRequest::Delegate, + public base::RefCountedThreadSafe { + public: + // Takes ownership of the params. + RequestProxy(CefRefPtr browser) + : browser_(browser), + download_to_file_(false), + buf_(new net::IOBuffer(kDataSize)), + last_upload_position_(0) + { + } + + void DropPeer() { + peer_ = NULL; + } + + void Start(ResourceLoaderBridge::Peer* peer, RequestParams* params) { + peer_ = peer; + owner_loop_ = MessageLoop::current(); + + // proxy over to the io thread + CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( + this, &RequestProxy::AsyncStart, params)); + } + + void Cancel() { + // proxy over to the io thread + CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( + this, &RequestProxy::AsyncCancel)); + } + + 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)); + } + + // -------------------------------------------------------------------------- + // The following methods are called on the owner's thread in response to + // various URLRequest callbacks. The event hooks, defined below, trigger + // these methods asynchronously. + + void NotifyReceivedRedirect(const GURL& new_url, + const ResourceLoaderBridge::ResponseInfo& info) { + 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, NewRunnableMethod( + this, &RequestProxy::AsyncFollowDeferredRedirect, + has_new_first_party_for_cookies, new_first_party_for_cookies)); + } else { + Cancel(); + } + } + + void NotifyReceivedResponse(const ResourceLoaderBridge::ResponseInfo& info, + bool content_filtered) { + if (peer_) + peer_->OnReceivedResponse(info, content_filtered); + } + + void NotifyReceivedData(int bytes_read) { + 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 reponse 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, NewRunnableMethod( + this, &RequestProxy::AsyncReadData)); + + peer_->OnReceivedData(buf_copy.get(), bytes_read); + } + + void NotifyDownloadedData(int bytes_read) { + if (!peer_) + return; + + // Continue reading more data, see the comment in NotifyReceivedData. + CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( + this, &RequestProxy::AsyncReadData)); + + peer_->OnDownloadedData(bytes_read); + } + + void NotifyCompletedRequest(const URLRequestStatus& status, + const std::string& security_info, + const base::Time& complete_time) { + if (peer_) { + peer_->OnCompletedRequest(status, security_info, complete_time); + DropPeer(); // ensure no further notifications + } + } + + void NotifyUploadProgress(uint64 position, uint64 size) { + 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) { + bool handled = false; + + if (browser_.get()) { + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) + { + // Build the request object for passing to the handler + CefRefPtr request(new CefRequestImpl()); + CefRequestImpl* requestimpl = static_cast(request.get()); + + const std::wstring originalUrl = UTF8ToWide(params->url.spec()); + requestimpl->SetURL(originalUrl); + requestimpl->SetMethod(UTF8ToWide(params->method)); + + // Transfer request headers + CefRequest::HeaderMap headerMap; + CefRequestImpl::ParseHeaders(params->headers, headerMap); + headerMap.insert( + std::make_pair(L"Referrer", UTF8ToWide(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 + std::wstring redirectUrl; + CefRefPtr resourceStream; + std::wstring mimeType; + + CefHandler::RetVal rv = handler->HandleBeforeResourceLoad( + browser_, request, redirectUrl, resourceStream, mimeType, loadFlags); + + // Observe URL from request. + const std::wstring requestUrl = request->GetURL(); + if(requestUrl != originalUrl) { + params->url = GURL(WideToUTF8(requestUrl)); + redirectUrl.clear(); // Request URL trumps redirect URL + } + + // Observe method from request. + params->method = WideToUTF8(request->GetMethod()); + + // Observe headers from request. + request->GetHeaderMap(headerMap); + CefRequest::HeaderMap::iterator referrer = headerMap.find(L"Referrer"); + if(referrer == headerMap.end()) { + params->referrer = GURL(); + } else { + params->referrer = GURL(WideToUTF8(referrer->second)); + headerMap.erase(referrer); + } + params->headers = CefRequestImpl::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(rv == RV_HANDLED) { + // cancel the resource load + handled = true; + OnCompletedRequest( + URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED), + std::string(), base::Time()); + } else if(!redirectUrl.empty()) { + // redirect to the specified URL + params->url = GURL(WideToUTF8(redirectUrl)); + ResourceLoaderBridge::ResponseInfo info; + bool defer_redirect; + OnReceivedRedirect(params->url, info, &defer_redirect); + } else if(resourceStream.get()) { + // load from the provided resource stream + handled = true; + + resourceStream->Seek(0, SEEK_END); + long offset = resourceStream->Tell(); + resourceStream->Seek(0, SEEK_SET); + + resource_stream_ = resourceStream; + + ResourceLoaderBridge::ResponseInfo info; + info.content_length = static_cast(offset); + if(!mimeType.empty()) + info.mime_type = WideToUTF8(mimeType); + OnReceivedResponse(info, false); + AsyncReadData(); + } + } + } + + 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 URLRequest(params->url, this)); + request_->set_method(params->method); + request_->set_first_party_for_cookies(params->first_party_for_cookies); + request_->set_referrer(params->referrer.spec()); + 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(_Context->request_context()); + 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_ = DeletableFileReference::GetOrCreate( + path, base::MessageLoopProxy::CreateForCurrentThread()); + file_stream_.Open( + path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_WRITE); + } + } + + request_->Start(); + + if (request_->has_upload() && + params->load_flags & net::LOAD_ENABLE_UPLOAD_PROGRESS) { + upload_progress_timer_.Start( + base::TimeDelta::FromMilliseconds(kUpdateUploadProgressIntervalMsec), + this, &RequestProxy::MaybeUpdateUploadProgress); + } + } + + delete params; + } + + void AsyncCancel() { + // 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) { + // 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 AsyncReadData() { + 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 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 ResourceLoaderBridge::ResponseInfo& info, + bool* defer_redirect) { + *defer_redirect = true; // See AsyncFollowDeferredRedirect + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyReceivedRedirect, new_url, info)); + } + + virtual void OnReceivedResponse( + const ResourceLoaderBridge::ResponseInfo& info, + bool content_filtered) { + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyReceivedResponse, info, content_filtered)); + } + + virtual void OnReceivedData(int bytes_read) { + if (download_to_file_) { + file_stream_.Write(buf_->data(), bytes_read, NULL); + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyDownloadedData, bytes_read)); + return; + } + + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyReceivedData, bytes_read)); + } + + virtual void OnCompletedRequest(const URLRequestStatus& status, + const std::string& security_info, + const base::Time& complete_time) { + if (download_to_file_) + file_stream_.Close(); + + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyCompletedRequest, status, security_info, + complete_time)); + } + + // -------------------------------------------------------------------------- + // URLRequest::Delegate implementation: + + virtual void OnReceivedRedirect(URLRequest* request, + const GURL& new_url, + bool* defer_redirect) { + DCHECK(request->status().is_success()); + ResourceLoaderBridge::ResponseInfo info; + PopulateResponseInfo(request, &info); + OnReceivedRedirect(new_url, info, defer_redirect); + } + + virtual void OnResponseStarted(URLRequest* request) { + if (request->status().is_success()) { + ResourceLoaderBridge::ResponseInfo info; + PopulateResponseInfo(request, &info); + OnReceivedResponse(info, false); + AsyncReadData(); // start reading + } else { + Done(); + } + } + + virtual void OnSSLCertificateError(URLRequest* request, + int cert_error, + net::X509Certificate* cert) { + // Allow all certificate errors. + request->ContinueDespiteLastError(); + } + + virtual void OnReadCompleted(URLRequest* request, int bytes_read) { + if (request->status().is_success() && bytes_read > 0) { + OnReceivedData(bytes_read); + } else { + Done(); + } + } + + // -------------------------------------------------------------------------- + // Helpers and data: + + void Done() { + if(resource_stream_.get()) { + // Resource stream reads always complete successfully + OnCompletedRequest(URLRequestStatus(URLRequestStatus::SUCCESS, 0), + std::string(), base::Time()); + 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::Time()); + request_.reset(); // destroy on the io thread + } + } + + // Called on the IO thread. + void MaybeUpdateUploadProgress() { + // If a redirect is received upload is cancelled in 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; + } + + uint64 size = request_->get_upload()->GetContentLength(); + 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, NewRunnableMethod( + this, &RequestProxy::NotifyUploadProgress, position, size)); + last_upload_ticks_ = base::TimeTicks::Now(); + last_upload_position_ = position; + } + } + + void PopulateResponseInfo(URLRequest* request, + ResourceLoaderBridge::ResponseInfo* info) const { + 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 + static const int kDataSize = 16*1024; + + // 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_; +}; + +//----------------------------------------------------------------------------- + +class SyncRequestProxy : public RequestProxy { + public: + explicit SyncRequestProxy(CefRefPtr browser, + ResourceLoaderBridge::SyncLoadResponse* result) + : RequestProxy(browser), result_(result), event_(true, false) { + } + + void WaitForCompletion() { + if (!event_.Wait()) + NOTREACHED(); + } + + // -------------------------------------------------------------------------- + // Event hooks that run on the IO thread: + + virtual void OnReceivedRedirect( + const GURL& new_url, + const ResourceLoaderBridge::ResponseInfo& info, + bool* defer_redirect) { + // 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 ResourceLoaderBridge::ResponseInfo& info, + bool content_filtered) { + *static_cast(result_) = info; + } + + virtual void OnReceivedData(int bytes_read) { + if (download_to_file_) + file_stream_.Write(buf_->data(), bytes_read, NULL); + else + result_->data.append(buf_->data(), bytes_read); + AsyncReadData(); // read more (may recurse) + } + + virtual void OnCompletedRequest(const URLRequestStatus& status, + const std::string& security_info, + const base::Time& complete_time) { + if (download_to_file_) + file_stream_.Close(); + + result_->status = status; + event_.Signal(); + } + + private: + ResourceLoaderBridge::SyncLoadResponse* result_; + base::WaitableEvent event_; +}; + +//----------------------------------------------------------------------------- + +class ResourceLoaderBridgeImpl : public ResourceLoaderBridge { + 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_->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_); + } + } + + // -------------------------------------------------------------------------- + // ResourceLoaderBridge implementation: + + virtual void AppendDataToUpload(const char* data, int data_len) { + 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) { + 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) { + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->AppendBlob(blob_url); + } + + virtual void SetUploadIdentifier(int64 identifier) { + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->set_identifier(identifier); + } + + virtual bool Start(Peer* peer) { + DCHECK(!proxy_); + + proxy_ = new RequestProxy(browser_); + proxy_->AddRef(); + + proxy_->Start(peer, params_.release()); + + return true; // Any errors will be reported asynchronously. + } + + virtual void Cancel() { + DCHECK(proxy_); + proxy_->Cancel(); + } + + virtual void SetDefersLoading(bool value) { + // TODO(darin): implement me + } + + virtual void SyncLoad(SyncLoadResponse* response) { + DCHECK(!proxy_); + + // this may change as the result of a redirect + response->url = params_->url; + + proxy_ = new SyncRequestProxy(browser_, response); + proxy_->AddRef(); + + proxy_->Start(NULL, params_.release()); + + static_cast(proxy_)->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. + RequestProxy* proxy_; +}; + +//----------------------------------------------------------------------------- + +class CookieSetter : public base::RefCountedThreadSafe { + public: + void Set(const GURL& url, const std::string& cookie) { + REQUIRE_IOT(); + _Context->request_context()->cookie_store()->SetCookie(url, cookie); + } + + private: + friend class base::RefCountedThreadSafe; + + ~CookieSetter() {} +}; + +class CookieGetter : public base::RefCountedThreadSafe { + public: + CookieGetter() : event_(false, false) { + } + + void Get(const GURL& url) { + result_ = _Context->request_context()->cookie_store()->GetCookies(url); + event_.Signal(); + } + + std::string GetResult() { + if (!event_.Wait()) + NOTREACHED(); + return result_; + } + + private: + friend class base::RefCountedThreadSafe; + + ~CookieGetter() {} + + base::WaitableEvent event_; + std::string result_; +}; + +} // anonymous namespace + +//----------------------------------------------------------------------------- + +namespace webkit_glue { + +// Factory function. +ResourceLoaderBridge* ResourceLoaderBridge::Create( + const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) { + CefRefPtr browser = + _Context->GetBrowserByID(request_info.routing_id); + return new ResourceLoaderBridgeImpl(browser, request_info); +} + +// Issue the proxy resolve request on the io thread, and wait +// for the result. +bool FindProxyForUrl(const GURL& url, std::string* proxy_list) { + DCHECK(_Context->request_context()); + + scoped_refptr sync_proxy_service( + new net::SyncProxyServiceHelper( + _Context->process()->io_thread()->message_loop(), + _Context->request_context()->proxy_service())); + + net::ProxyInfo proxy_info; + int rv = sync_proxy_service->ResolveProxy(url, &proxy_info, + net::BoundNetLog()); + if (rv == net::OK) { + *proxy_list = proxy_info.ToPacString(); + } + + return rv == net::OK; +} + +} // namespace webkit_glue + +//----------------------------------------------------------------------------- + +// static +void BrowserResourceLoaderBridge::SetCookie(const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie) { + // Proxy to IO thread to synchronize w/ network loading. + + scoped_refptr cookie_setter = new CookieSetter(); + CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( + cookie_setter.get(), &CookieSetter::Set, url, cookie)); +} + +// static +std::string BrowserResourceLoaderBridge::GetCookies( + const GURL& url, const GURL& first_party_for_cookies) { + // Proxy to IO thread to synchronize w/ network loading + + scoped_refptr getter = new CookieGetter(); + + CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( + getter.get(), &CookieGetter::Get, url)); + + return getter->GetResult(); +} + +// static +void BrowserResourceLoaderBridge::SetAcceptAllCookies(bool accept_all_cookies) { + // Proxy to IO thread to synchronize w/ network loading + CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( + _Context->request_context().get(), + &BrowserRequestContext::SetAcceptAllCookies, accept_all_cookies)); +} + +//static +scoped_refptr + BrowserResourceLoaderBridge::GetCacheThread() { + return CefThread::GetMessageLoopProxyForThread(CefThread::FILE); +} diff --git a/libcef/browser_resource_loader_bridge.h b/libcef/browser_resource_loader_bridge.h index b49c5cc89..ad02542b7 100644 --- a/libcef/browser_resource_loader_bridge.h +++ b/libcef/browser_resource_loader_bridge.h @@ -1,28 +1,28 @@ -// 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 _BROWSER_RESOURCE_LOADER_BRIDGE_H -#define _BROWSER_RESOURCE_LOADER_BRIDGE_H - -#include -#include "base/message_loop_proxy.h" - -class GURL; - -class BrowserResourceLoaderBridge { - public: - // May only be called after Init. - static void SetCookie(const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie); - static std::string GetCookies(const GURL& url, - const GURL& first_party_for_cookies); - static void SetAcceptAllCookies(bool accept_all_cookies); - - static scoped_refptr GetCacheThread(); -}; - -#endif // _BROWSER_RESOURCE_LOADER_BRIDGE_H - +// 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 _BROWSER_RESOURCE_LOADER_BRIDGE_H +#define _BROWSER_RESOURCE_LOADER_BRIDGE_H + +#include +#include "base/message_loop_proxy.h" + +class GURL; + +class BrowserResourceLoaderBridge { + public: + // May only be called after Init. + static void SetCookie(const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie); + static std::string GetCookies(const GURL& url, + const GURL& first_party_for_cookies); + static void SetAcceptAllCookies(bool accept_all_cookies); + + static scoped_refptr GetCacheThread(); +}; + +#endif // _BROWSER_RESOURCE_LOADER_BRIDGE_H + diff --git a/libcef/browser_socket_stream_bridge.cc b/libcef/browser_socket_stream_bridge.cc index 89662e74a..3e06f07ef 100644 --- a/libcef/browser_socket_stream_bridge.cc +++ b/libcef/browser_socket_stream_bridge.cc @@ -1,242 +1,242 @@ -// 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 - -#include "browser_socket_stream_bridge.h" - -#include "base/message_loop.h" -#include "base/ref_counted.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 "webkit/glue/websocketstreamhandle_bridge.h" -#include "webkit/glue/websocketstreamhandle_delegate.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSocketStreamHandle.h" - -using webkit_glue::WebSocketStreamHandleBridge; - -static const int kNoSocketId = 0; - -namespace { - -MessageLoop* g_io_thread; -scoped_refptr 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. - int 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, - NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoConnect, - url)); - if (delegate_) - delegate_->WillOpenStream(handle_, url); -} - -bool WebSocketStreamHandleBridgeImpl::Send( - const std::vector& data) { - DCHECK(g_io_thread); - g_io_thread->PostTask( - FROM_HERE, - NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoSend, - new std::vector(data))); - return true; -} - -void WebSocketStreamHandleBridgeImpl::Close() { - DCHECK(g_io_thread); - g_io_thread->PostTask( - FROM_HERE, - NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoClose)); -} - -void WebSocketStreamHandleBridgeImpl::OnConnected( - net::SocketStream* socket, int max_pending_send_allowed) { - ++num_pending_tasks_; - message_loop_->PostTask( - FROM_HERE, - NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoOnConnected, - max_pending_send_allowed)); -} - -void WebSocketStreamHandleBridgeImpl::OnSentData( - net::SocketStream* socket, int amount_sent) { - ++num_pending_tasks_; - message_loop_->PostTask( - FROM_HERE, - NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoOnSentData, - amount_sent)); -} - -void WebSocketStreamHandleBridgeImpl::OnReceivedData( - net::SocketStream* socket, const char* data, int len) { - ++num_pending_tasks_; - message_loop_->PostTask( - FROM_HERE, - NewRunnableMethod(this, - &WebSocketStreamHandleBridgeImpl::DoOnReceivedData, - new std::vector(data, data + len))); -} - -void WebSocketStreamHandleBridgeImpl::OnClose(net::SocketStream* socket) { - ++num_pending_tasks_; - // Release socket_ on IO thread. - socket_ = NULL; - socket_id_ = kNoSocketId; - message_loop_->PostTask( - FROM_HERE, - NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoOnClose)); -} - -void WebSocketStreamHandleBridgeImpl::DoConnect(const GURL& url) { - DCHECK(MessageLoop::current() == g_io_thread); - socket_ = net::SocketStreamJob::CreateSocketStreamJob(url, this); - 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_); - --num_pending_tasks_; - if (delegate_) - delegate_->DidOpenStream(handle_, max_pending_send_allowed); -} - -void WebSocketStreamHandleBridgeImpl::DoOnSentData(int amount_sent) { - DCHECK(MessageLoop::current() == message_loop_); - --num_pending_tasks_; - if (delegate_) - delegate_->DidSendData(handle_, amount_sent); -} - -void WebSocketStreamHandleBridgeImpl::DoOnReceivedData( - std::vector* data) { - DCHECK(MessageLoop::current() == message_loop_); - --num_pending_tasks_; - scoped_ptr > scoped_data(data); - if (delegate_) - delegate_->DidReceiveData(handle_, &(data->at(0)), data->size()); -} - -void WebSocketStreamHandleBridgeImpl::DoOnClose() { - DCHECK(MessageLoop::current() == message_loop_); - --num_pending_tasks_; - // 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( - URLRequestContext* request_context) { - g_io_thread = MessageLoop::current(); - g_request_context = request_context; -} - -void BrowserSocketStreamBridge::Cleanup() { - g_io_thread = NULL; - g_request_context = NULL; -} - -namespace webkit_glue { - -/* static */ -WebSocketStreamHandleBridge* WebSocketStreamHandleBridge::Create( - WebKit::WebSocketStreamHandle* handle, - WebSocketStreamHandleDelegate* delegate) { - return new WebSocketStreamHandleBridgeImpl(handle, delegate); -} - -} // namespace webkit_glue +// 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 + +#include "browser_socket_stream_bridge.h" + +#include "base/message_loop.h" +#include "base/ref_counted.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 "webkit/glue/websocketstreamhandle_bridge.h" +#include "webkit/glue/websocketstreamhandle_delegate.h" +#include "third_party/WebKit/WebKit/chromium/public/WebSocketStreamHandle.h" + +using webkit_glue::WebSocketStreamHandleBridge; + +static const int kNoSocketId = 0; + +namespace { + +MessageLoop* g_io_thread; +scoped_refptr 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. + int 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, + NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoConnect, + url)); + if (delegate_) + delegate_->WillOpenStream(handle_, url); +} + +bool WebSocketStreamHandleBridgeImpl::Send( + const std::vector& data) { + DCHECK(g_io_thread); + g_io_thread->PostTask( + FROM_HERE, + NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoSend, + new std::vector(data))); + return true; +} + +void WebSocketStreamHandleBridgeImpl::Close() { + DCHECK(g_io_thread); + g_io_thread->PostTask( + FROM_HERE, + NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoClose)); +} + +void WebSocketStreamHandleBridgeImpl::OnConnected( + net::SocketStream* socket, int max_pending_send_allowed) { + ++num_pending_tasks_; + message_loop_->PostTask( + FROM_HERE, + NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoOnConnected, + max_pending_send_allowed)); +} + +void WebSocketStreamHandleBridgeImpl::OnSentData( + net::SocketStream* socket, int amount_sent) { + ++num_pending_tasks_; + message_loop_->PostTask( + FROM_HERE, + NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoOnSentData, + amount_sent)); +} + +void WebSocketStreamHandleBridgeImpl::OnReceivedData( + net::SocketStream* socket, const char* data, int len) { + ++num_pending_tasks_; + message_loop_->PostTask( + FROM_HERE, + NewRunnableMethod(this, + &WebSocketStreamHandleBridgeImpl::DoOnReceivedData, + new std::vector(data, data + len))); +} + +void WebSocketStreamHandleBridgeImpl::OnClose(net::SocketStream* socket) { + ++num_pending_tasks_; + // Release socket_ on IO thread. + socket_ = NULL; + socket_id_ = kNoSocketId; + message_loop_->PostTask( + FROM_HERE, + NewRunnableMethod(this, &WebSocketStreamHandleBridgeImpl::DoOnClose)); +} + +void WebSocketStreamHandleBridgeImpl::DoConnect(const GURL& url) { + DCHECK(MessageLoop::current() == g_io_thread); + socket_ = net::SocketStreamJob::CreateSocketStreamJob(url, this); + 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_); + --num_pending_tasks_; + if (delegate_) + delegate_->DidOpenStream(handle_, max_pending_send_allowed); +} + +void WebSocketStreamHandleBridgeImpl::DoOnSentData(int amount_sent) { + DCHECK(MessageLoop::current() == message_loop_); + --num_pending_tasks_; + if (delegate_) + delegate_->DidSendData(handle_, amount_sent); +} + +void WebSocketStreamHandleBridgeImpl::DoOnReceivedData( + std::vector* data) { + DCHECK(MessageLoop::current() == message_loop_); + --num_pending_tasks_; + scoped_ptr > scoped_data(data); + if (delegate_) + delegate_->DidReceiveData(handle_, &(data->at(0)), data->size()); +} + +void WebSocketStreamHandleBridgeImpl::DoOnClose() { + DCHECK(MessageLoop::current() == message_loop_); + --num_pending_tasks_; + // 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( + URLRequestContext* request_context) { + g_io_thread = MessageLoop::current(); + g_request_context = request_context; +} + +void BrowserSocketStreamBridge::Cleanup() { + g_io_thread = NULL; + g_request_context = NULL; +} + +namespace webkit_glue { + +/* static */ +WebSocketStreamHandleBridge* WebSocketStreamHandleBridge::Create( + WebKit::WebSocketStreamHandle* handle, + WebSocketStreamHandleDelegate* delegate) { + return new WebSocketStreamHandleBridgeImpl(handle, delegate); +} + +} // namespace webkit_glue diff --git a/libcef/browser_socket_stream_bridge.h b/libcef/browser_socket_stream_bridge.h index 9ae9fd93c..7c343b13d 100644 --- a/libcef/browser_socket_stream_bridge.h +++ b/libcef/browser_socket_stream_bridge.h @@ -1,16 +1,16 @@ -// 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 _BROWSER_SOCKET_STREAM_BRIDGE_H -#define _BROWSER_SOCKET_STREAM_BRIDGE_H - -class URLRequestContext; - -class BrowserSocketStreamBridge { - public: - static void InitializeOnIOThread(URLRequestContext* request_context); - static void Cleanup(); -}; - -#endif // _BROWSER_SOCKET_STREAM_BRIDGE_H +// 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 _BROWSER_SOCKET_STREAM_BRIDGE_H +#define _BROWSER_SOCKET_STREAM_BRIDGE_H + +class URLRequestContext; + +class BrowserSocketStreamBridge { + public: + static void InitializeOnIOThread(URLRequestContext* request_context); + static void Cleanup(); +}; + +#endif // _BROWSER_SOCKET_STREAM_BRIDGE_H diff --git a/libcef/browser_webkit_glue.cc b/libcef/browser_webkit_glue.cc index 6f41cd961..d6dcc4ac9 100644 --- a/libcef/browser_webkit_glue.cc +++ b/libcef/browser_webkit_glue.cc @@ -1,141 +1,141 @@ -// 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 "base/compiler_specific.h" - -#include "third_party/webkit/webcore/config.h" -MSVC_PUSH_WARNING_LEVEL(0); -#include "Cache.h" -#include "TextEncoding.h" -#include "third_party/WebKit/WebKit/chromium/src/WebFrameImpl.h" -MSVC_POP_WARNING(); - -#include "browser_webkit_glue.h" - -#undef LOG -#include "base/logging.h" -#include "base/path_service.h" -#include "base/scoped_ptr.h" -#include "base/string16.h" -#include "base/utf_string_conversions.h" -#include "base/win_util.h" -#include "net/base/mime_util.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "webkit/glue/webkit_glue.h" - -// Generated by GRIT -#include "grit/webkit_resources.h" - -using WebKit::WebFrameImpl; - -namespace webkit_glue { - -bool IsMediaPlayerAvailable() { - return true; -} - -void PrecacheUrl(const char16* url, int url_length) {} - -void AppendToLog(const char* file, int line, const char* msg) { - logging::LogMessage(file, line).stream() << msg; -} - -base::StringPiece GetDataResource(int resource_id) { - return NetResourceProvider(resource_id); -} - -bool GetApplicationDirectory(FilePath* path) { - return PathService::Get(base::DIR_EXE, path); -} - -bool GetExeDirectory(FilePath* path) { - return PathService::Get(base::DIR_EXE, path); -} - -bool IsPluginRunningInRendererProcess() { - return true; -} - -bool GetPluginFinderURL(std::string* plugin_finder_url) { - return false; -} - -bool IsDefaultPluginEnabled() { - return false; -} - -bool IsProtocolSupportedForMedia(const GURL& url) { - if (url.SchemeIsFile() || url.SchemeIs("http") || url.SchemeIs("https")) - return true; - return false; -} - -std::string GetWebKitLocale() { - return "en-US"; -} - -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 CloseIdleConnections() { - // Used in benchmarking, Ignored for CEF. -} - -void SetCacheMode(bool enabled) { - // Used in benchmarking, Ignored for CEF. -} - -void ClearCache() -{ - // Clear the cache by disabling it and then re-enabling it. - WebCore::cache()->setDisabled(true); - WebCore::cache()->setDisabled(false); -} - -WebKit::WebString StdStringToWebString(const std::string& str) { - return WebKit::WebString::fromUTF8(str.data(), str.size()); -} - -std::string WebStringToStdString(const WebKit::WebString& str) { - std::string ret; - if (!str.isNull()) - UTF16ToUTF8(str.data(), str.length(), &ret); - return ret; -} - -std::string GetProductVersion() { - return std::string("Chrome/7.0.517.0"); -} - -bool IsSingleProcess() { - return true; -} - -#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 - -void EnableSpdy(bool enable) { - // Used in benchmarking, Ignored for CEF. -} - -} // namespace webkit_glue +// 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 "base/compiler_specific.h" + +#include "third_party/webkit/webcore/config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "Cache.h" +#include "TextEncoding.h" +#include "third_party/WebKit/WebKit/chromium/src/WebFrameImpl.h" +MSVC_POP_WARNING(); + +#include "browser_webkit_glue.h" + +#undef LOG +#include "base/logging.h" +#include "base/path_service.h" +#include "base/scoped_ptr.h" +#include "base/string16.h" +#include "base/utf_string_conversions.h" +#include "base/win_util.h" +#include "net/base/mime_util.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebString.h" +#include "webkit/glue/webkit_glue.h" + +// Generated by GRIT +#include "grit/webkit_resources.h" + +using WebKit::WebFrameImpl; + +namespace webkit_glue { + +bool IsMediaPlayerAvailable() { + return true; +} + +void PrecacheUrl(const char16* url, int url_length) {} + +void AppendToLog(const char* file, int line, const char* msg) { + logging::LogMessage(file, line).stream() << msg; +} + +base::StringPiece GetDataResource(int resource_id) { + return NetResourceProvider(resource_id); +} + +bool GetApplicationDirectory(FilePath* path) { + return PathService::Get(base::DIR_EXE, path); +} + +bool GetExeDirectory(FilePath* path) { + return PathService::Get(base::DIR_EXE, path); +} + +bool IsPluginRunningInRendererProcess() { + return true; +} + +bool GetPluginFinderURL(std::string* plugin_finder_url) { + return false; +} + +bool IsDefaultPluginEnabled() { + return false; +} + +bool IsProtocolSupportedForMedia(const GURL& url) { + if (url.SchemeIsFile() || url.SchemeIs("http") || url.SchemeIs("https")) + return true; + return false; +} + +std::string GetWebKitLocale() { + return "en-US"; +} + +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 CloseIdleConnections() { + // Used in benchmarking, Ignored for CEF. +} + +void SetCacheMode(bool enabled) { + // Used in benchmarking, Ignored for CEF. +} + +void ClearCache() +{ + // Clear the cache by disabling it and then re-enabling it. + WebCore::cache()->setDisabled(true); + WebCore::cache()->setDisabled(false); +} + +WebKit::WebString StdStringToWebString(const std::string& str) { + return WebKit::WebString::fromUTF8(str.data(), str.size()); +} + +std::string WebStringToStdString(const WebKit::WebString& str) { + std::string ret; + if (!str.isNull()) + UTF16ToUTF8(str.data(), str.length(), &ret); + return ret; +} + +std::string GetProductVersion() { + return std::string("Chrome/7.0.517.0"); +} + +bool IsSingleProcess() { + return true; +} + +#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 + +void EnableSpdy(bool enable) { + // Used in benchmarking, Ignored for CEF. +} + +} // namespace webkit_glue diff --git a/libcef/browser_webkit_glue.h b/libcef/browser_webkit_glue.h index e1e34d77a..2b128647c 100644 --- a/libcef/browser_webkit_glue.h +++ b/libcef/browser_webkit_glue.h @@ -1,46 +1,46 @@ -// 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. - -#if defined(OS_WIN) -#include -#endif -#include - -#include "base/string_piece.h" -#include "v8/include/v8.h" - -namespace WebKit { -class WebFrame; -class WebString; -class WebView; -} - -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(); - -// This is called indirectly by the network layer to access resources. -base::StringPiece NetResourceProvider(int key); - -// Retrieve the V8 context associated with the frame. -v8::Handle GetV8Context(WebKit::WebFrame* frame); - -// Clear all cached data. -void ClearCache(); - -WebKit::WebString StdStringToWebString(const std::string& str); - -std::string WebStringToStdString(const WebKit::WebString& str); - -} // namespace webkit_glue +// 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. + +#if defined(OS_WIN) +#include +#endif +#include + +#include "base/string_piece.h" +#include "v8/include/v8.h" + +namespace WebKit { +class WebFrame; +class WebString; +class WebView; +} + +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(); + +// This is called indirectly by the network layer to access resources. +base::StringPiece NetResourceProvider(int key); + +// Retrieve the V8 context associated with the frame. +v8::Handle GetV8Context(WebKit::WebFrame* frame); + +// Clear all cached data. +void ClearCache(); + +WebKit::WebString StdStringToWebString(const std::string& str); + +std::string WebStringToStdString(const WebKit::WebString& str); + +} // namespace webkit_glue diff --git a/libcef/browser_webkit_glue_win.cc b/libcef/browser_webkit_glue_win.cc index 48c28bdc1..20eeb60ac 100644 --- a/libcef/browser_webkit_glue_win.cc +++ b/libcef/browser_webkit_glue_win.cc @@ -1,310 +1,310 @@ -// 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 -#include -#include - -#include "base/compiler_specific.h" - -#include "third_party/webkit/webcore/config.h" -MSVC_PUSH_WARNING_LEVEL(0); -#include "PlatformContextSkia.h" -MSVC_POP_WARNING(); - -#include "browser_webkit_glue.h" - -#undef LOG -#include "base/logging.h" -#include "base/resource_util.h" -#include "gfx/gdi_util.h" -#include "skia/ext/platform_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSize.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/plugins/plugin_list.h" - -using WebKit::WebRect; -using WebKit::WebSize; -using WebKit::WebView; - -namespace webkit_glue { - -string16 GetLocalizedString(int message_id) { - // Localized resources are provided via webkit_resources.rc and - // webkit_strings_en-US.rc. - const ATLSTRINGRESOURCEIMAGE* image = - AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(), - message_id); - if (!image) { - NOTREACHED(); - return L"No string for this identifier!"; - } - return string16(image->achString, image->nLength); -} - -HCURSOR LoadCursor(int cursor_id) { - return NULL; -} - -base::StringPiece GetRawDataResource(HMODULE module, int resource_id) { - void* data_ptr; - size_t data_size; - return base::GetDataResourceFromModule(module, resource_id, &data_ptr, - &data_size) - ? base::StringPiece(static_cast(data_ptr), data_size) - : base::StringPiece(); -} - -base::StringPiece NetResourceProvider(int key) { - HMODULE hModule = ::GetModuleHandle(L"libcef.dll"); - if(!hModule) - hModule = ::GetModuleHandle(NULL); - return GetRawDataResource(hModule, key); -} - -void GetPlugins(bool refresh, std::vector* plugins) { - NPAPI::PluginList::Singleton()->GetPlugins(refresh, plugins); -} - -bool EnsureFontLoaded(HFONT font) { - return true; -} - -bool DownloadUrl(const std::string& url, HWND caller_window) { - return false; -} - -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, (int) cb, (LPDWORD) &dwTmp,NULL)) { - // Could not write bitmap data to file - NOTREACHED(); - goto end; - } - - ret = TRUE; - -end: - // 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 +// 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 +#include +#include + +#include "base/compiler_specific.h" + +#include "third_party/webkit/webcore/config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "PlatformContextSkia.h" +MSVC_POP_WARNING(); + +#include "browser_webkit_glue.h" + +#undef LOG +#include "base/logging.h" +#include "base/resource_util.h" +#include "gfx/gdi_util.h" +#include "skia/ext/platform_canvas.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" +#include "third_party/WebKit/WebKit/chromium/public/WebSize.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/plugins/plugin_list.h" + +using WebKit::WebRect; +using WebKit::WebSize; +using WebKit::WebView; + +namespace webkit_glue { + +string16 GetLocalizedString(int message_id) { + // Localized resources are provided via webkit_resources.rc and + // webkit_strings_en-US.rc. + const ATLSTRINGRESOURCEIMAGE* image = + AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(), + message_id); + if (!image) { + NOTREACHED(); + return L"No string for this identifier!"; + } + return string16(image->achString, image->nLength); +} + +HCURSOR LoadCursor(int cursor_id) { + return NULL; +} + +base::StringPiece GetRawDataResource(HMODULE module, int resource_id) { + void* data_ptr; + size_t data_size; + return base::GetDataResourceFromModule(module, resource_id, &data_ptr, + &data_size) + ? base::StringPiece(static_cast(data_ptr), data_size) + : base::StringPiece(); +} + +base::StringPiece NetResourceProvider(int key) { + HMODULE hModule = ::GetModuleHandle(L"libcef.dll"); + if(!hModule) + hModule = ::GetModuleHandle(NULL); + return GetRawDataResource(hModule, key); +} + +void GetPlugins(bool refresh, std::vector* plugins) { + NPAPI::PluginList::Singleton()->GetPlugins(refresh, plugins); +} + +bool EnsureFontLoaded(HFONT font) { + return true; +} + +bool DownloadUrl(const std::string& url, HWND caller_window) { + return false; +} + +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, (int) cb, (LPDWORD) &dwTmp,NULL)) { + // Could not write bitmap data to file + NOTREACHED(); + goto end; + } + + ret = TRUE; + +end: + // 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/libcef/browser_webkit_init.h b/libcef/browser_webkit_init.h index f9a1aa71b..47e260c7d 100644 --- a/libcef/browser_webkit_init.h +++ b/libcef/browser_webkit_init.h @@ -1,227 +1,227 @@ -// Copyright (c) 2009 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 _BROWSER_WEBKIT_INIT_H -#define _BROWSER_WEBKIT_INIT_H - -#include "base/file_util.h" -#include "base/path_service.h" -#include "base/scoped_temp_dir.h" -#include "base/stats_counters.h" -#include "base/utf_string_conversions.h" -#include "media/base/media.h" -#include "webkit/appcache/web_application_cache_host_impl.h" -#include "webkit/database/vfs_backend.h" -#include "webkit/extensions/v8/gears_extension.h" -#include "third_party/WebKit/WebKit/chromium/public/WebData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h" -#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h" -#include "third_party/WebKit/WebKit/chromium/public/WebStorageArea.h" -#include "third_party/WebKit/WebKit/chromium/public/WebStorageEventDispatcher.h" -#include "third_party/WebKit/WebKit/chromium/public/WebIDBFactory.h" -#include "third_party/WebKit/WebKit/chromium/public/WebIDBKey.h" -#include "third_party/WebKit/WebKit/chromium/public/WebIDBKeyPath.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSerializedScriptValue.h" -#include "third_party/WebKit/WebKit/chromium/public/WebStorageNamespace.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "webkit/glue/simple_webmimeregistry_impl.h" -#include "webkit/glue/webclipboard_impl.h" -#include "webkit/glue/webfileutilities_impl.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/webkitclient_impl.h" -#include "browser_appcache_system.h" -#include "browser_database_system.h" -#include "browser_file_system.h" -#include "browser_resource_loader_bridge.h" -#include "browser_webblobregistry_impl.h" -#include "browser_webcookiejar_impl.h" - - -class BrowserWebKitInit : public webkit_glue::WebKitClientImpl { - public: - explicit BrowserWebKitInit() { - v8::V8::SetCounterFunction(StatsTable::FindLocation); - - WebKit::initialize(this); - WebKit::setLayoutTestMode(false); - WebKit::WebScriptController::registerExtension( - extensions_v8::GearsExtension::Get()); - WebKit::WebRuntimeFeatures::enableSockets(true); - WebKit::WebRuntimeFeatures::enableApplicationCache(true); - WebKit::WebRuntimeFeatures::enableDatabase(true); - WebKit::WebRuntimeFeatures::enableWebGL(true); - WebKit::WebRuntimeFeatures::enablePushState(true); - WebKit::WebRuntimeFeatures::enableNotifications(true); - WebKit::WebRuntimeFeatures::enableTouch(true); - WebKit::WebRuntimeFeatures::enableIndexedDatabase(true); - WebKit::WebRuntimeFeatures::enableGeolocation(false); - WebKit::WebRuntimeFeatures::enableSpeechInput(true); - WebKit::WebRuntimeFeatures::enableFileSystem(true); - - // TODO(hwennborg): Enable this once the implementation supports it. - WebKit::WebRuntimeFeatures::enableDeviceMotion(false); - WebKit::WebRuntimeFeatures::enableDeviceOrientation(false); - - // 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)); - - // Construct and initialize an appcache system for this scope. - // A new empty temp directory is created to house any cached - // content during the run. Upon exit that directory is deleted. - // If we can't create a tempdir, we'll use in-memory storage. - if (!appcache_dir_.CreateUniqueTempDir()) { - LOG(WARNING) << "Failed to create a temp dir for the appcache, " - "using in-memory storage."; - DCHECK(appcache_dir_.path().empty()); - } - BrowserAppCacheSystem::InitializeOnUIThread(appcache_dir_.path()); - - WebKit::WebDatabase::setObserver(&database_system_); - - blob_registry_ = new BrowserWebBlobRegistryImpl(); - - file_utilities_.set_sandbox_enabled(false); - } - - ~BrowserWebKitInit() { - WebKit::shutdown(); - } - - virtual WebKit::WebMimeRegistry* mimeRegistry() { - return &mime_registry_; - } - - WebKit::WebClipboard* clipboard() { - return &clipboard_; - } - - virtual WebKit::WebFileUtilities* fileUtilities() { - return &file_utilities_; - } - - virtual WebKit::WebSandboxSupport* sandboxSupport() { - return NULL; - } - - virtual WebKit::WebBlobRegistry* blobRegistry() { - return blob_registry_.get(); - } - - virtual WebKit::WebCookieJar* cookieJar() { - return &cookie_jar_; - } - - virtual WebKit::WebFileSystem* fileSystem() { - return &file_system_; - } - - virtual bool sandboxEnabled() { - return true; - } - - virtual WebKit::WebKitClient::FileHandle databaseOpenFile( - const WebKit::WebString& vfs_file_name, int desired_flags) { - return BrowserDatabaseSystem::GetInstance()->OpenFile( - vfs_file_name, desired_flags); - } - - virtual int databaseDeleteFile(const WebKit::WebString& vfs_file_name, - bool sync_dir) { - return BrowserDatabaseSystem::GetInstance()->DeleteFile( - vfs_file_name, sync_dir); - } - - virtual long databaseGetFileAttributes( - const WebKit::WebString& vfs_file_name) { - return BrowserDatabaseSystem::GetInstance()->GetFileAttributes( - vfs_file_name); - } - - virtual long long databaseGetFileSize( - const WebKit::WebString& vfs_file_name) { - return BrowserDatabaseSystem::GetInstance()->GetFileSize(vfs_file_name); - } - - virtual unsigned long long visitedLinkHash(const char* canonicalURL, - size_t length) { - return 0; - } - - virtual bool isLinkVisited(unsigned long long linkHash) { - return false; - } - - virtual WebKit::WebMessagePortChannel* createMessagePortChannel() { - return NULL; - } - - virtual void prefetchHostName(const WebKit::WebString&) { - } - - virtual WebKit::WebData 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::WebKitClientImpl::loadResource(name); - } - - virtual WebKit::WebString defaultLocale() { - return ASCIIToUTF16("en-US"); - } - - virtual WebKit::WebStorageNamespace* createLocalStorageNamespace( - const WebKit::WebString& path, unsigned quota) { - return WebKit::WebStorageNamespace::createLocalStorageNamespace(path, - WebKit::WebStorageNamespace::m_localStorageQuota); - } - - virtual WebKit::WebIDBFactory* idbFactory() { - return WebKit::WebIDBFactory::create(); - } - - virtual void createIDBKeysFromSerializedValuesAndKeyPath( - const WebKit::WebVector& values, - const WebKit::WebString& 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], WebKit::WebIDBKeyPath::create(keyPath)); - } - keys_out.swap(keys); - } - - private: - webkit_glue::SimpleWebMimeRegistryImpl mime_registry_; - webkit_glue::WebClipboardImpl clipboard_; - webkit_glue::WebFileUtilitiesImpl file_utilities_; - ScopedTempDir appcache_dir_; - BrowserAppCacheSystem appcache_system_; - BrowserDatabaseSystem database_system_; - BrowserWebCookieJarImpl cookie_jar_; - scoped_refptr blob_registry_; - BrowserFileSystem file_system_; -}; - -#endif // _BROWSER_WEBKIT_INIT_H +// Copyright (c) 2009 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 _BROWSER_WEBKIT_INIT_H +#define _BROWSER_WEBKIT_INIT_H + +#include "base/file_util.h" +#include "base/path_service.h" +#include "base/scoped_temp_dir.h" +#include "base/stats_counters.h" +#include "base/utf_string_conversions.h" +#include "media/base/media.h" +#include "webkit/appcache/web_application_cache_host_impl.h" +#include "webkit/database/vfs_backend.h" +#include "webkit/extensions/v8/gears_extension.h" +#include "third_party/WebKit/WebKit/chromium/public/WebData.h" +#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h" +#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" +#include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h" +#include "third_party/WebKit/WebKit/chromium/public/WebStorageArea.h" +#include "third_party/WebKit/WebKit/chromium/public/WebStorageEventDispatcher.h" +#include "third_party/WebKit/WebKit/chromium/public/WebIDBFactory.h" +#include "third_party/WebKit/WebKit/chromium/public/WebIDBKey.h" +#include "third_party/WebKit/WebKit/chromium/public/WebIDBKeyPath.h" +#include "third_party/WebKit/WebKit/chromium/public/WebSerializedScriptValue.h" +#include "third_party/WebKit/WebKit/chromium/public/WebStorageNamespace.h" +#include "third_party/WebKit/WebKit/chromium/public/WebString.h" +#include "webkit/glue/simple_webmimeregistry_impl.h" +#include "webkit/glue/webclipboard_impl.h" +#include "webkit/glue/webfileutilities_impl.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/webkitclient_impl.h" +#include "browser_appcache_system.h" +#include "browser_database_system.h" +#include "browser_file_system.h" +#include "browser_resource_loader_bridge.h" +#include "browser_webblobregistry_impl.h" +#include "browser_webcookiejar_impl.h" + + +class BrowserWebKitInit : public webkit_glue::WebKitClientImpl { + public: + explicit BrowserWebKitInit() { + v8::V8::SetCounterFunction(StatsTable::FindLocation); + + WebKit::initialize(this); + WebKit::setLayoutTestMode(false); + WebKit::WebScriptController::registerExtension( + extensions_v8::GearsExtension::Get()); + WebKit::WebRuntimeFeatures::enableSockets(true); + WebKit::WebRuntimeFeatures::enableApplicationCache(true); + WebKit::WebRuntimeFeatures::enableDatabase(true); + WebKit::WebRuntimeFeatures::enableWebGL(true); + WebKit::WebRuntimeFeatures::enablePushState(true); + WebKit::WebRuntimeFeatures::enableNotifications(true); + WebKit::WebRuntimeFeatures::enableTouch(true); + WebKit::WebRuntimeFeatures::enableIndexedDatabase(true); + WebKit::WebRuntimeFeatures::enableGeolocation(false); + WebKit::WebRuntimeFeatures::enableSpeechInput(true); + WebKit::WebRuntimeFeatures::enableFileSystem(true); + + // TODO(hwennborg): Enable this once the implementation supports it. + WebKit::WebRuntimeFeatures::enableDeviceMotion(false); + WebKit::WebRuntimeFeatures::enableDeviceOrientation(false); + + // 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)); + + // Construct and initialize an appcache system for this scope. + // A new empty temp directory is created to house any cached + // content during the run. Upon exit that directory is deleted. + // If we can't create a tempdir, we'll use in-memory storage. + if (!appcache_dir_.CreateUniqueTempDir()) { + LOG(WARNING) << "Failed to create a temp dir for the appcache, " + "using in-memory storage."; + DCHECK(appcache_dir_.path().empty()); + } + BrowserAppCacheSystem::InitializeOnUIThread(appcache_dir_.path()); + + WebKit::WebDatabase::setObserver(&database_system_); + + blob_registry_ = new BrowserWebBlobRegistryImpl(); + + file_utilities_.set_sandbox_enabled(false); + } + + ~BrowserWebKitInit() { + WebKit::shutdown(); + } + + virtual WebKit::WebMimeRegistry* mimeRegistry() { + return &mime_registry_; + } + + WebKit::WebClipboard* clipboard() { + return &clipboard_; + } + + virtual WebKit::WebFileUtilities* fileUtilities() { + return &file_utilities_; + } + + virtual WebKit::WebSandboxSupport* sandboxSupport() { + return NULL; + } + + virtual WebKit::WebBlobRegistry* blobRegistry() { + return blob_registry_.get(); + } + + virtual WebKit::WebCookieJar* cookieJar() { + return &cookie_jar_; + } + + virtual WebKit::WebFileSystem* fileSystem() { + return &file_system_; + } + + virtual bool sandboxEnabled() { + return true; + } + + virtual WebKit::WebKitClient::FileHandle databaseOpenFile( + const WebKit::WebString& vfs_file_name, int desired_flags) { + return BrowserDatabaseSystem::GetInstance()->OpenFile( + vfs_file_name, desired_flags); + } + + virtual int databaseDeleteFile(const WebKit::WebString& vfs_file_name, + bool sync_dir) { + return BrowserDatabaseSystem::GetInstance()->DeleteFile( + vfs_file_name, sync_dir); + } + + virtual long databaseGetFileAttributes( + const WebKit::WebString& vfs_file_name) { + return BrowserDatabaseSystem::GetInstance()->GetFileAttributes( + vfs_file_name); + } + + virtual long long databaseGetFileSize( + const WebKit::WebString& vfs_file_name) { + return BrowserDatabaseSystem::GetInstance()->GetFileSize(vfs_file_name); + } + + virtual unsigned long long visitedLinkHash(const char* canonicalURL, + size_t length) { + return 0; + } + + virtual bool isLinkVisited(unsigned long long linkHash) { + return false; + } + + virtual WebKit::WebMessagePortChannel* createMessagePortChannel() { + return NULL; + } + + virtual void prefetchHostName(const WebKit::WebString&) { + } + + virtual WebKit::WebData 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::WebKitClientImpl::loadResource(name); + } + + virtual WebKit::WebString defaultLocale() { + return ASCIIToUTF16("en-US"); + } + + virtual WebKit::WebStorageNamespace* createLocalStorageNamespace( + const WebKit::WebString& path, unsigned quota) { + return WebKit::WebStorageNamespace::createLocalStorageNamespace(path, + WebKit::WebStorageNamespace::m_localStorageQuota); + } + + virtual WebKit::WebIDBFactory* idbFactory() { + return WebKit::WebIDBFactory::create(); + } + + virtual void createIDBKeysFromSerializedValuesAndKeyPath( + const WebKit::WebVector& values, + const WebKit::WebString& 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], WebKit::WebIDBKeyPath::create(keyPath)); + } + keys_out.swap(keys); + } + + private: + webkit_glue::SimpleWebMimeRegistryImpl mime_registry_; + webkit_glue::WebClipboardImpl clipboard_; + webkit_glue::WebFileUtilitiesImpl file_utilities_; + ScopedTempDir appcache_dir_; + BrowserAppCacheSystem appcache_system_; + BrowserDatabaseSystem database_system_; + BrowserWebCookieJarImpl cookie_jar_; + scoped_refptr blob_registry_; + BrowserFileSystem file_system_; +}; + +#endif // _BROWSER_WEBKIT_INIT_H diff --git a/libcef/browser_webview_delegate.cc b/libcef/browser_webview_delegate.cc index d80871ac6..1079e2703 100644 --- a/libcef/browser_webview_delegate.cc +++ b/libcef/browser_webview_delegate.cc @@ -1,982 +1,982 @@ -// 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 "browser_webview_delegate.h" -#include "browser_appcache_system.h" -#include "browser_impl.h" -#include "browser_navigation_controller.h" -#include "cef_context.h" -#include "request_impl.h" -#include "v8_impl.h" - -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/process_util.h" -#include "base/string_util.h" -#include "base/trace_event.h" -#include "base/utf_string_conversions.h" -#include "gfx/gdi_util.h" -#include "gfx/native_widget_types.h" -#include "gfx/point.h" -#include "media/filters/audio_renderer_impl.h" -#include "net/base/net_errors.h" -#include "third_party/WebKit/WebKit/chromium/public/WebConsoleMessage.h" -#include "third_party/WebKit/WebKit/chromium/public/WebContextMenuData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDataSource.h" -#include "third_party/WebKit/WebKit/chromium/public/WebDragData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFileError.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFileSystemCallbacks.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHistoryItem.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKitClient.h" -#include "third_party/WebKit/WebKit/chromium/public/WebNode.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPopupMenu.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRange.h" -#include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebStorageNamespace.h" -#include "third_party/WebKit/WebKit/chromium/public/WebString.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" -#include "third_party/WebKit/WebKit/chromium/public/WebVector.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/appcache/web_application_cache_host_impl.h" -#include "webkit/glue/glue_serialize.h" -#include "webkit/glue/media/buffered_data_source.h" -#include "webkit/glue/media/media_resource_loader_bridge_factory.h" -#include "webkit/glue/media/simple_data_source.h" -#include "webkit/glue/media/video_renderer_impl.h" -#include "webkit/glue/webdropdata.h" -#include "webkit/glue/plugins/webplugin_impl.h" -#include "webkit/glue/webpreferences.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/webplugin_delegate_impl.h" -#include "webkit/glue/webmediaplayer_impl.h" -#include "webkit/glue/window_open_disposition.h" -#include "browser_webkit_glue.h" - -#if defined(OS_WIN) -// TODO(port): make these files work everywhere. -#include "browser_drag_delegate.h" -#include "browser_drop_delegate.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::WebDragData; -using WebKit::WebDragOperationsMask; -using WebKit::WebEditingAction; -using WebKit::WebFileChooserParams; -using WebKit::WebFileSystem; -using WebKit::WebFileSystemCallbacks; -using WebKit::WebFormElement; -using WebKit::WebFrame; -using WebKit::WebHistoryItem; -using WebKit::WebImage; -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::WebPopupMenu; -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::WebWorker; -using WebKit::WebWorkerClient; -using WebKit::WebKeyboardEvent; - -namespace { - -int next_page_id_ = 1; - -} // namespace - -// WebViewDelegate ----------------------------------------------------------- - -void BrowserWebViewDelegate::SetUserStyleSheetEnabled(bool is_enabled) { - WebPreferences* prefs = _Context->web_preferences(); - prefs->user_style_sheet_enabled = is_enabled; - if (browser_->GetWebView()) - prefs->Apply(browser_->GetWebView()); -} - -void BrowserWebViewDelegate::SetUserStyleSheetLocation(const GURL& location) { - WebPreferences* prefs = _Context->web_preferences(); - prefs->user_style_sheet_enabled = true; - prefs->user_style_sheet_location = location; - if (browser_->GetWebView()) - prefs->Apply(browser_->GetWebView()); -} - -// WebViewClient ------------------------------------------------------------- - -WebView* BrowserWebViewDelegate::createView(WebFrame* creator, - const WebWindowFeatures& features, - const WebString& name) { - CefRefPtr browser = - browser_->UIT_CreatePopupWindow(std::wstring()); - return browser.get() ? browser->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) { - // Enforce quota, ignoring the parameter from WebCore as in Chrome. - return WebKit::WebStorageNamespace::createSessionStorageNamespace( - WebStorageNamespace::m_sessionStorageQuota); -} - -void BrowserWebViewDelegate::didAddMessageToConsole( - const WebConsoleMessage& message, const WebString& source_name, - unsigned source_line) { - std::wstring wmessage = UTF16ToWideHack(message.text); - std::wstring wsource = UTF16ToWideHack(source_name); - - CefHandler::RetVal rv = RV_CONTINUE; - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - rv = handler->HandleConsoleMessage(browser_, wmessage, wsource, - source_line); - } - - if(rv == RV_CONTINUE) { - logging::LogMessage("CONSOLE", 0).stream() << "\"" - << message.text.utf8().data() - << ",\" source: " - << source_name.utf8().data() - << "(" - << source_line - << ")"; - } -} - -void BrowserWebViewDelegate::printPage(WebFrame* frame) { - if (!frame) - frame = browser_->GetWebView() ? browser_->GetWebView()->mainFrame() : NULL; - if (frame) - browser_->UIT_PrintPages(frame); -} - -void BrowserWebViewDelegate::didStartLoading() { - // clear the title so we can tell if it wasn't provided by the page - browser_->UIT_SetTitle(std::wstring()); - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has started - handler->HandleLoadStart(browser_, NULL); - } -} - -void BrowserWebViewDelegate::didStopLoading() { - if(browser_->UIT_GetTitle().empty()) { - // no title was provided by the page, so send a blank string to the client - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler of a page title change - handler->HandleTitleChange(browser_, browser_->UIT_GetTitle()); - } - } - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has ended - handler->HandleLoadEnd(browser_, NULL); - } -} - -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() { - CefHandler::RetVal rv = RV_CONTINUE; - CefRefPtr handler = browser_->GetHandler(); - if (handler.get()) { - WebWidgetHost* host = GetWidgetHost(); - if (host) { - WebKeyboardEvent event = host->GetLastKeyEvent(); - switch (event.type) - { - case WebKeyboardEvent::RawKeyDown: - rv = handler->HandleKeyEvent(browser_, - KEYEVENT_RAWKEYDOWN, event.windowsKeyCode, - event.modifiers, event.isSystemKey?true:false); - break; - case WebKeyboardEvent::KeyUp: - rv = handler->HandleKeyEvent(browser_, - KEYEVENT_KEYUP, event.windowsKeyCode, - event.modifiers, event.isSystemKey?true:false); - break; - case WebKeyboardEvent::Char: - rv = handler->HandleKeyEvent(browser_, - KEYEVENT_CHAR, event.windowsKeyCode, - event.modifiers, event.isSystemKey?true:false); - break; - } - } - } - if (rv == RV_HANDLED) - return true; - - if (edit_command_name_.empty()) - return false; - - WebFrame* frame = browser_->GetWebView() ? - browser_->GetWebView()->focusedFrame() : NULL; - 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) { - std::wstring messageStr = UTF16ToWideHack(message); - CefHandler::RetVal rv = RV_CONTINUE; - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - rv = handler->HandleJSAlert(browser_, browser_->GetCefFrame(frame), - messageStr); - } - if(rv != RV_HANDLED) - ShowJavaScriptAlert(frame, messageStr); -} - -bool BrowserWebViewDelegate::runModalConfirmDialog( - WebFrame* frame, const WebString& message) { - std::wstring messageStr = UTF16ToWideHack(message); - CefHandler::RetVal rv = RV_CONTINUE; - bool retval = false; - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - rv = handler->HandleJSConfirm(browser_, browser_->GetCefFrame(frame), - messageStr, retval); - } - if(rv != RV_HANDLED) - retval = ShowJavaScriptConfirm(frame, messageStr); - return retval; -} - -bool BrowserWebViewDelegate::runModalPromptDialog( - WebFrame* frame, const WebString& message, const WebString& default_value, - WebString* actual_value) { - std::wstring wmessage = UTF16ToWideHack(message); - std::wstring wdefault = UTF16ToWideHack(default_value); - std::wstring wresult; - - if(actual_value) - wresult = UTF16ToWideHack(*actual_value); - - CefHandler::RetVal rv = RV_CONTINUE; - bool retval = false; - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - rv = handler->HandleJSPrompt(browser_, browser_->GetCefFrame(frame), - wmessage, wdefault, retval, wresult); - } - if(rv != RV_HANDLED) - retval = ShowJavaScriptPrompt(frame, wmessage, wdefault, &wresult); - - if(actual_value && !wresult.empty()) - *actual_value = WideToUTF16Hack(wresult); - - return retval; -} - -bool BrowserWebViewDelegate::runModalBeforeUnloadDialog( - WebFrame* frame, const WebString& message) { - return true; // Allow window closure. -} - -void BrowserWebViewDelegate::setStatusText(const WebString& text) { -} - -void BrowserWebViewDelegate::setMouseOverURL(const WebURL& url) { -} - -void BrowserWebViewDelegate::setKeyboardFocusURL(const WebKit::WebURL& url) { -} - -void BrowserWebViewDelegate::setToolTipText( - const WebString& text, WebTextDirection hint) -{ - std::wstring tooltipText(UTF8ToWide(webkit_glue::WebStringToStdString(text))); - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get() && handler->HandleTooltip(browser_, tooltipText) == RV_CONTINUE){ - GetWidgetHost()->SetTooltipText(tooltipText); - } -} - -void BrowserWebViewDelegate::startDragging( - const WebDragData& data, - WebDragOperationsMask mask, - const WebImage& image, - const WebPoint& image_offset) { - // TODO(tc): Drag and drop is disabled in the test shell because we need - // to be able to convert from WebDragData to an IDataObject. - //if (!drag_delegate_) - // drag_delegate_ = new BrowserDragDelegate(shell_->webViewWnd(), - // shell_->webView()); - //const DWORD ok_effect = DROPEFFECT_COPY | DROPEFFECT_LINK | DROPEFFECT_MOVE; - //DWORD effect; - //HRESULT res = DoDragDrop(drop_data.data_object, drag_delegate_.get(), - // ok_effect, &effect); - //DCHECK(DRAGDROP_S_DROP == res || DRAGDROP_S_CANCEL == res); - if (browser_->GetWebView()) - browser_->GetWebView()->dragSourceSystemDragEnded(); -} - -void BrowserWebViewDelegate::focusNext() { - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that it should take a focus - handler->HandleTakeFocus(browser_, false); - } -} - -void BrowserWebViewDelegate::focusPrevious() { - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that it should take a focus - handler->HandleTakeFocus(browser_, true); - } -} - -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; -} - -// WebPluginPageDelegate ----------------------------------------------------- - -WebCookieJar* BrowserWebViewDelegate::GetCookieJar() { - return WebKit::webKitClient()->cookieJar(); -} - -// 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::didFocus() { - if (WebWidgetHost* host = GetWidgetHost()) { - CefRefPtr handler = browser_->GetHandler(); - if (handler.get() && handler->HandleSetFocus(browser_, true) == RV_CONTINUE) - browser_->UIT_SetFocus(host, true); - } -} - -void BrowserWebViewDelegate::didBlur() { - if (WebWidgetHost* host = GetWidgetHost()) - browser_->UIT_SetFocus(host, false); -} - -WebScreenInfo BrowserWebViewDelegate::screenInfo() { - if (WebWidgetHost* host = GetWidgetHost()) - return host->GetScreenInfo(); - - return WebScreenInfo(); -} - -// WebFrameClient ------------------------------------------------------------ - -WebPlugin* BrowserWebViewDelegate::createPlugin( - WebFrame* frame, const WebPluginParams& params) { - bool allow_wildcard = true; - WebPluginInfo info; - std::string actual_mime_type; - if (!NPAPI::PluginList::Singleton()->GetPluginInfo( - params.url, params.mimeType.utf8(), allow_wildcard, &info, - &actual_mime_type)) { - return NULL; - } - - if (actual_mime_type.empty()) - actual_mime_type = params.mimeType.utf8(); - - return new webkit_glue::WebPluginImpl( - frame, params, info.path, actual_mime_type, AsWeakPtr()); -} - -WebMediaPlayer* BrowserWebViewDelegate::createMediaPlayer( - WebFrame* frame, WebMediaPlayerClient* client) { - scoped_refptr factory = - new media::FilterFactoryCollection(); - - // Add the audio renderer factory. - factory->AddFactory(media::AudioRendererImpl::CreateFilterFactory()); - - appcache::WebApplicationCacheHostImpl* appcache_host = - appcache::WebApplicationCacheHostImpl::FromFrame(frame); - - // TODO(hclam): this is the same piece of code as in RenderView, maybe they - // should be grouped together. - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory = - new webkit_glue::MediaResourceLoaderBridgeFactory( - GURL(), // referrer - "null", // frame origin - "null", // main_frame_origin - base::GetCurrentProcId(), - appcache_host ? appcache_host->host_id() : appcache::kNoHostId, - 0); - // A simple data source that keeps all data in memory. - media::FilterFactory* simple_data_source_factory = - webkit_glue::SimpleDataSource::CreateFactory(MessageLoop::current(), - bridge_factory); - // A sophisticated data source that does memory caching. - media::FilterFactory* buffered_data_source_factory = - webkit_glue::BufferedDataSource::CreateFactory(MessageLoop::current(), - bridge_factory); - factory->AddFactory(buffered_data_source_factory); - factory->AddFactory(simple_data_source_factory); - return new webkit_glue::WebMediaPlayerImpl( - client, factory, new webkit_glue::VideoRendererImpl::FactoryFactory(false)); -} - -WebApplicationCacheHost* BrowserWebViewDelegate::createApplicationCacheHost( - WebFrame* frame, WebApplicationCacheHostClient* client) { - return BrowserAppCacheSystem::CreateApplicationCacheHost(client); -} - -void BrowserWebViewDelegate::loadURLExternally( - WebFrame* frame, const WebURLRequest& request, - WebNavigationPolicy policy) { - DCHECK_NE(policy, WebKit::WebNavigationPolicyCurrentTab); - browser_->UIT_CreatePopupWindow(UTF8ToWide(request.url().spec().data())); -} - -WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation( - WebFrame* frame, const WebURLRequest& request, - WebNavigationType type, const WebNode& originating_node, - WebNavigationPolicy default_policy, bool is_redirect) { - CefRefPtr handler = browser_->GetHandler(); - 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(UTF8ToWide(request_url.spec())); - req->SetMethod( - UTF8ToWide(webkit_glue::WebStringToStdString(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); - - // Notify the handler of a browse request - CefHandler::RetVal rv = handler->HandleBeforeBrowse(browser_, - browser_->GetCefFrame(frame), req, (CefHandler::NavType)type, - is_redirect); - if(rv == RV_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()); -} - -void BrowserWebViewDelegate::didStartProvisionalLoad(WebFrame* frame) { - if (!top_loading_frame_) { - top_loading_frame_ = frame; - } - - UpdateAddressBar(frame->view()); -} - -void BrowserWebViewDelegate::didReceiveServerRedirectForProvisionalLoad( - WebFrame* frame) { - UpdateAddressBar(frame->view()); -} - -void BrowserWebViewDelegate::didFailProvisionalLoad( - WebFrame* frame, const WebURLError& error) { - LocationChangeDone(frame); - - // 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; - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // give the handler an opportunity to generate a custom error message - std::wstring error_str; - CefHandler::RetVal rv = handler->HandleLoadError(browser_, - browser_->GetCefFrame(frame), - static_cast(error.reason), - UTF8ToWide(failed_ds->request().url().spec().data()), error_str); - if(rv == RV_HANDLED && !error_str.empty()) - error_text = WideToUTF8(error_str); - } else { - error_text = 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("testshell-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) { - UpdateForCommittedLoad(frame, is_new_navigation); - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has started - handler->HandleLoadStart(browser_, browser_->GetCefFrame(frame)); - } -} - -void BrowserWebViewDelegate::didClearWindowObject(WebFrame* frame) { - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - v8::HandleScope handle_scope; - v8::Handle context = webkit_glue::GetV8Context(frame); - if(context.IsEmpty()) - return; - - v8::Context::Scope scope(context); - - CefRefPtr cframe(browser_->GetCefFrame(frame)); - CefRefPtr object = new CefV8ValueImpl(context->Global()); - handler->HandleJSBinding(browser_, cframe, object); - } -} - -void BrowserWebViewDelegate::didReceiveTitle( - WebFrame* frame, const WebString& title) { - std::wstring wtitle = UTF16ToWideHack(title); - - browser_->UIT_SetTitle(wtitle); - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler of a page title change - handler->HandleTitleChange(browser_, wtitle); - } -} - -void BrowserWebViewDelegate::didFailLoad( - WebFrame* frame, const WebURLError& error) { - LocationChangeDone(frame); -} - -void BrowserWebViewDelegate::didFinishLoad(WebFrame* frame) { - UpdateAddressBar(frame->view()); - LocationChangeDone(frame); - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has ended - handler->HandleLoadEnd(browser_, browser_->GetCefFrame(frame)); - } -} - -void BrowserWebViewDelegate::didChangeLocationWithinPage( - 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::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, - WebFileSystemCallbacks* callbacks) { - if (browser_->file_system_root().empty()) { - // The FileSystem temp directory was not initialized successfully. - callbacks->didFail(WebKit::WebFileErrorSecurity); - } else { - callbacks->didOpenFileSystem( - "CefFileSystem", - webkit_glue::FilePathToWebString(browser_->file_system_root())); - } -} - -// Public methods ------------------------------------------------------------ - -BrowserWebViewDelegate::BrowserWebViewDelegate(CefBrowserImpl* browser) - : policy_delegate_enabled_(false), - policy_delegate_is_permissive_(false), - policy_delegate_should_notify_done_(false), - browser_(browser), - top_loading_frame_(NULL), - page_id_(-1), - last_page_id_updated_(-1), - smart_insert_delete_enabled_(true), -#if defined(OS_WIN) - select_trailing_whitespace_enabled_(true), -#else - select_trailing_whitespace_enabled_(false), -#endif - block_redirects_(false) { -} - -BrowserWebViewDelegate::~BrowserWebViewDelegate() { -} - -void BrowserWebViewDelegate::Reset() { - // Do a little placement new dance... - CefBrowserImpl* browser = browser_; - this->~BrowserWebViewDelegate(); - new (this) BrowserWebViewDelegate(browser); -} - -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::RegisterDragDrop() { -#if defined(OS_WIN) - // TODO(port): add me once drag and drop works. - DCHECK(!drop_delegate_); - drop_delegate_ = new BrowserDropDelegate(browser_->GetWebViewWndHandle(), - browser_->GetWebView()); -#endif -} - -void BrowserWebViewDelegate::RevokeDragDrop() { -#if defined(OS_WIN) - ::RevokeDragDrop(browser_->GetWebViewWndHandle()); -#endif -} - -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 ----------------------------------------------------------- - -void BrowserWebViewDelegate::UpdateAddressBar(WebView* webView) { -} - -void BrowserWebViewDelegate::LocationChangeDone(WebFrame* frame) { - if (frame == top_loading_frame_) - top_loading_frame_ = NULL; -} - -WebWidgetHost* BrowserWebViewDelegate::GetWidgetHost() { - if (this == browser_->GetWebViewDelegate()) - return browser_->GetWebViewHost(); - if (this == browser_->GetPopupDelegate()) - return browser_->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(); - - // 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()); - } - - std::wstring url = UTF8ToWide(entry->GetURL().spec().c_str()); - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler of an address change - handler->HandleAddressChange(browser_, browser_->GetCefFrame(frame), url); - } - - const WebHistoryItem& history_item = frame->currentHistoryItem(); - if (!history_item.isNull()) - entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); - - browser_->UIT_GetNavigationController()->DidNavigateToEntry(entry.release()); - - last_page_id_updated_ = std::max(last_page_id_updated_, page_id_); -} - -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; - - if (!browser_->GetWebView()) - return; - - const WebHistoryItem& history_item = - browser_->GetWebView()->mainFrame()->previousHistoryItem(); - if (history_item.isNull()) - return; - - entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); -} +// 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 "browser_webview_delegate.h" +#include "browser_appcache_system.h" +#include "browser_impl.h" +#include "browser_navigation_controller.h" +#include "cef_context.h" +#include "request_impl.h" +#include "v8_impl.h" + +#include "base/file_util.h" +#include "base/message_loop.h" +#include "base/process_util.h" +#include "base/string_util.h" +#include "base/trace_event.h" +#include "base/utf_string_conversions.h" +#include "gfx/gdi_util.h" +#include "gfx/native_widget_types.h" +#include "gfx/point.h" +#include "media/filters/audio_renderer_impl.h" +#include "net/base/net_errors.h" +#include "third_party/WebKit/WebKit/chromium/public/WebConsoleMessage.h" +#include "third_party/WebKit/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/WebKit/chromium/public/WebCString.h" +#include "third_party/WebKit/WebKit/chromium/public/WebData.h" +#include "third_party/WebKit/WebKit/chromium/public/WebDataSource.h" +#include "third_party/WebKit/WebKit/chromium/public/WebDragData.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFileError.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFileSystemCallbacks.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebHistoryItem.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKitClient.h" +#include "third_party/WebKit/WebKit/chromium/public/WebNode.h" +#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" +#include "third_party/WebKit/WebKit/chromium/public/WebPopupMenu.h" +#include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRange.h" +#include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h" +#include "third_party/WebKit/WebKit/chromium/public/WebStorageNamespace.h" +#include "third_party/WebKit/WebKit/chromium/public/WebString.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURL.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLError.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLResponse.h" +#include "third_party/WebKit/WebKit/chromium/public/WebVector.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" +#include "webkit/appcache/web_application_cache_host_impl.h" +#include "webkit/glue/glue_serialize.h" +#include "webkit/glue/media/buffered_data_source.h" +#include "webkit/glue/media/media_resource_loader_bridge_factory.h" +#include "webkit/glue/media/simple_data_source.h" +#include "webkit/glue/media/video_renderer_impl.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/plugins/webplugin_impl.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/plugins/plugin_list.h" +#include "webkit/glue/plugins/webplugin_delegate_impl.h" +#include "webkit/glue/webmediaplayer_impl.h" +#include "webkit/glue/window_open_disposition.h" +#include "browser_webkit_glue.h" + +#if defined(OS_WIN) +// TODO(port): make these files work everywhere. +#include "browser_drag_delegate.h" +#include "browser_drop_delegate.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::WebDragData; +using WebKit::WebDragOperationsMask; +using WebKit::WebEditingAction; +using WebKit::WebFileChooserParams; +using WebKit::WebFileSystem; +using WebKit::WebFileSystemCallbacks; +using WebKit::WebFormElement; +using WebKit::WebFrame; +using WebKit::WebHistoryItem; +using WebKit::WebImage; +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::WebPopupMenu; +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::WebWorker; +using WebKit::WebWorkerClient; +using WebKit::WebKeyboardEvent; + +namespace { + +int next_page_id_ = 1; + +} // namespace + +// WebViewDelegate ----------------------------------------------------------- + +void BrowserWebViewDelegate::SetUserStyleSheetEnabled(bool is_enabled) { + WebPreferences* prefs = _Context->web_preferences(); + prefs->user_style_sheet_enabled = is_enabled; + if (browser_->GetWebView()) + prefs->Apply(browser_->GetWebView()); +} + +void BrowserWebViewDelegate::SetUserStyleSheetLocation(const GURL& location) { + WebPreferences* prefs = _Context->web_preferences(); + prefs->user_style_sheet_enabled = true; + prefs->user_style_sheet_location = location; + if (browser_->GetWebView()) + prefs->Apply(browser_->GetWebView()); +} + +// WebViewClient ------------------------------------------------------------- + +WebView* BrowserWebViewDelegate::createView(WebFrame* creator, + const WebWindowFeatures& features, + const WebString& name) { + CefRefPtr browser = + browser_->UIT_CreatePopupWindow(std::wstring()); + return browser.get() ? browser->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) { + // Enforce quota, ignoring the parameter from WebCore as in Chrome. + return WebKit::WebStorageNamespace::createSessionStorageNamespace( + WebStorageNamespace::m_sessionStorageQuota); +} + +void BrowserWebViewDelegate::didAddMessageToConsole( + const WebConsoleMessage& message, const WebString& source_name, + unsigned source_line) { + std::wstring wmessage = UTF16ToWideHack(message.text); + std::wstring wsource = UTF16ToWideHack(source_name); + + CefHandler::RetVal rv = RV_CONTINUE; + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + rv = handler->HandleConsoleMessage(browser_, wmessage, wsource, + source_line); + } + + if(rv == RV_CONTINUE) { + logging::LogMessage("CONSOLE", 0).stream() << "\"" + << message.text.utf8().data() + << ",\" source: " + << source_name.utf8().data() + << "(" + << source_line + << ")"; + } +} + +void BrowserWebViewDelegate::printPage(WebFrame* frame) { + if (!frame) + frame = browser_->GetWebView() ? browser_->GetWebView()->mainFrame() : NULL; + if (frame) + browser_->UIT_PrintPages(frame); +} + +void BrowserWebViewDelegate::didStartLoading() { + // clear the title so we can tell if it wasn't provided by the page + browser_->UIT_SetTitle(std::wstring()); + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that loading has started + handler->HandleLoadStart(browser_, NULL); + } +} + +void BrowserWebViewDelegate::didStopLoading() { + if(browser_->UIT_GetTitle().empty()) { + // no title was provided by the page, so send a blank string to the client + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler of a page title change + handler->HandleTitleChange(browser_, browser_->UIT_GetTitle()); + } + } + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that loading has ended + handler->HandleLoadEnd(browser_, NULL); + } +} + +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() { + CefHandler::RetVal rv = RV_CONTINUE; + CefRefPtr handler = browser_->GetHandler(); + if (handler.get()) { + WebWidgetHost* host = GetWidgetHost(); + if (host) { + WebKeyboardEvent event = host->GetLastKeyEvent(); + switch (event.type) + { + case WebKeyboardEvent::RawKeyDown: + rv = handler->HandleKeyEvent(browser_, + KEYEVENT_RAWKEYDOWN, event.windowsKeyCode, + event.modifiers, event.isSystemKey?true:false); + break; + case WebKeyboardEvent::KeyUp: + rv = handler->HandleKeyEvent(browser_, + KEYEVENT_KEYUP, event.windowsKeyCode, + event.modifiers, event.isSystemKey?true:false); + break; + case WebKeyboardEvent::Char: + rv = handler->HandleKeyEvent(browser_, + KEYEVENT_CHAR, event.windowsKeyCode, + event.modifiers, event.isSystemKey?true:false); + break; + } + } + } + if (rv == RV_HANDLED) + return true; + + if (edit_command_name_.empty()) + return false; + + WebFrame* frame = browser_->GetWebView() ? + browser_->GetWebView()->focusedFrame() : NULL; + 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) { + std::wstring messageStr = UTF16ToWideHack(message); + CefHandler::RetVal rv = RV_CONTINUE; + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + rv = handler->HandleJSAlert(browser_, browser_->GetCefFrame(frame), + messageStr); + } + if(rv != RV_HANDLED) + ShowJavaScriptAlert(frame, messageStr); +} + +bool BrowserWebViewDelegate::runModalConfirmDialog( + WebFrame* frame, const WebString& message) { + std::wstring messageStr = UTF16ToWideHack(message); + CefHandler::RetVal rv = RV_CONTINUE; + bool retval = false; + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + rv = handler->HandleJSConfirm(browser_, browser_->GetCefFrame(frame), + messageStr, retval); + } + if(rv != RV_HANDLED) + retval = ShowJavaScriptConfirm(frame, messageStr); + return retval; +} + +bool BrowserWebViewDelegate::runModalPromptDialog( + WebFrame* frame, const WebString& message, const WebString& default_value, + WebString* actual_value) { + std::wstring wmessage = UTF16ToWideHack(message); + std::wstring wdefault = UTF16ToWideHack(default_value); + std::wstring wresult; + + if(actual_value) + wresult = UTF16ToWideHack(*actual_value); + + CefHandler::RetVal rv = RV_CONTINUE; + bool retval = false; + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + rv = handler->HandleJSPrompt(browser_, browser_->GetCefFrame(frame), + wmessage, wdefault, retval, wresult); + } + if(rv != RV_HANDLED) + retval = ShowJavaScriptPrompt(frame, wmessage, wdefault, &wresult); + + if(actual_value && !wresult.empty()) + *actual_value = WideToUTF16Hack(wresult); + + return retval; +} + +bool BrowserWebViewDelegate::runModalBeforeUnloadDialog( + WebFrame* frame, const WebString& message) { + return true; // Allow window closure. +} + +void BrowserWebViewDelegate::setStatusText(const WebString& text) { +} + +void BrowserWebViewDelegate::setMouseOverURL(const WebURL& url) { +} + +void BrowserWebViewDelegate::setKeyboardFocusURL(const WebKit::WebURL& url) { +} + +void BrowserWebViewDelegate::setToolTipText( + const WebString& text, WebTextDirection hint) +{ + std::wstring tooltipText(UTF8ToWide(webkit_glue::WebStringToStdString(text))); + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get() && handler->HandleTooltip(browser_, tooltipText) == RV_CONTINUE){ + GetWidgetHost()->SetTooltipText(tooltipText); + } +} + +void BrowserWebViewDelegate::startDragging( + const WebDragData& data, + WebDragOperationsMask mask, + const WebImage& image, + const WebPoint& image_offset) { + // TODO(tc): Drag and drop is disabled in the test shell because we need + // to be able to convert from WebDragData to an IDataObject. + //if (!drag_delegate_) + // drag_delegate_ = new BrowserDragDelegate(shell_->webViewWnd(), + // shell_->webView()); + //const DWORD ok_effect = DROPEFFECT_COPY | DROPEFFECT_LINK | DROPEFFECT_MOVE; + //DWORD effect; + //HRESULT res = DoDragDrop(drop_data.data_object, drag_delegate_.get(), + // ok_effect, &effect); + //DCHECK(DRAGDROP_S_DROP == res || DRAGDROP_S_CANCEL == res); + if (browser_->GetWebView()) + browser_->GetWebView()->dragSourceSystemDragEnded(); +} + +void BrowserWebViewDelegate::focusNext() { + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that it should take a focus + handler->HandleTakeFocus(browser_, false); + } +} + +void BrowserWebViewDelegate::focusPrevious() { + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that it should take a focus + handler->HandleTakeFocus(browser_, true); + } +} + +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; +} + +// WebPluginPageDelegate ----------------------------------------------------- + +WebCookieJar* BrowserWebViewDelegate::GetCookieJar() { + return WebKit::webKitClient()->cookieJar(); +} + +// 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::didFocus() { + if (WebWidgetHost* host = GetWidgetHost()) { + CefRefPtr handler = browser_->GetHandler(); + if (handler.get() && handler->HandleSetFocus(browser_, true) == RV_CONTINUE) + browser_->UIT_SetFocus(host, true); + } +} + +void BrowserWebViewDelegate::didBlur() { + if (WebWidgetHost* host = GetWidgetHost()) + browser_->UIT_SetFocus(host, false); +} + +WebScreenInfo BrowserWebViewDelegate::screenInfo() { + if (WebWidgetHost* host = GetWidgetHost()) + return host->GetScreenInfo(); + + return WebScreenInfo(); +} + +// WebFrameClient ------------------------------------------------------------ + +WebPlugin* BrowserWebViewDelegate::createPlugin( + WebFrame* frame, const WebPluginParams& params) { + bool allow_wildcard = true; + WebPluginInfo info; + std::string actual_mime_type; + if (!NPAPI::PluginList::Singleton()->GetPluginInfo( + params.url, params.mimeType.utf8(), allow_wildcard, &info, + &actual_mime_type)) { + return NULL; + } + + if (actual_mime_type.empty()) + actual_mime_type = params.mimeType.utf8(); + + return new webkit_glue::WebPluginImpl( + frame, params, info.path, actual_mime_type, AsWeakPtr()); +} + +WebMediaPlayer* BrowserWebViewDelegate::createMediaPlayer( + WebFrame* frame, WebMediaPlayerClient* client) { + scoped_refptr factory = + new media::FilterFactoryCollection(); + + // Add the audio renderer factory. + factory->AddFactory(media::AudioRendererImpl::CreateFilterFactory()); + + appcache::WebApplicationCacheHostImpl* appcache_host = + appcache::WebApplicationCacheHostImpl::FromFrame(frame); + + // TODO(hclam): this is the same piece of code as in RenderView, maybe they + // should be grouped together. + webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory = + new webkit_glue::MediaResourceLoaderBridgeFactory( + GURL(), // referrer + "null", // frame origin + "null", // main_frame_origin + base::GetCurrentProcId(), + appcache_host ? appcache_host->host_id() : appcache::kNoHostId, + 0); + // A simple data source that keeps all data in memory. + media::FilterFactory* simple_data_source_factory = + webkit_glue::SimpleDataSource::CreateFactory(MessageLoop::current(), + bridge_factory); + // A sophisticated data source that does memory caching. + media::FilterFactory* buffered_data_source_factory = + webkit_glue::BufferedDataSource::CreateFactory(MessageLoop::current(), + bridge_factory); + factory->AddFactory(buffered_data_source_factory); + factory->AddFactory(simple_data_source_factory); + return new webkit_glue::WebMediaPlayerImpl( + client, factory, new webkit_glue::VideoRendererImpl::FactoryFactory(false)); +} + +WebApplicationCacheHost* BrowserWebViewDelegate::createApplicationCacheHost( + WebFrame* frame, WebApplicationCacheHostClient* client) { + return BrowserAppCacheSystem::CreateApplicationCacheHost(client); +} + +void BrowserWebViewDelegate::loadURLExternally( + WebFrame* frame, const WebURLRequest& request, + WebNavigationPolicy policy) { + DCHECK_NE(policy, WebKit::WebNavigationPolicyCurrentTab); + browser_->UIT_CreatePopupWindow(UTF8ToWide(request.url().spec().data())); +} + +WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation( + WebFrame* frame, const WebURLRequest& request, + WebNavigationType type, const WebNode& originating_node, + WebNavigationPolicy default_policy, bool is_redirect) { + CefRefPtr handler = browser_->GetHandler(); + 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(UTF8ToWide(request_url.spec())); + req->SetMethod( + UTF8ToWide(webkit_glue::WebStringToStdString(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); + + // Notify the handler of a browse request + CefHandler::RetVal rv = handler->HandleBeforeBrowse(browser_, + browser_->GetCefFrame(frame), req, (CefHandler::NavType)type, + is_redirect); + if(rv == RV_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()); +} + +void BrowserWebViewDelegate::didStartProvisionalLoad(WebFrame* frame) { + if (!top_loading_frame_) { + top_loading_frame_ = frame; + } + + UpdateAddressBar(frame->view()); +} + +void BrowserWebViewDelegate::didReceiveServerRedirectForProvisionalLoad( + WebFrame* frame) { + UpdateAddressBar(frame->view()); +} + +void BrowserWebViewDelegate::didFailProvisionalLoad( + WebFrame* frame, const WebURLError& error) { + LocationChangeDone(frame); + + // 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; + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // give the handler an opportunity to generate a custom error message + std::wstring error_str; + CefHandler::RetVal rv = handler->HandleLoadError(browser_, + browser_->GetCefFrame(frame), + static_cast(error.reason), + UTF8ToWide(failed_ds->request().url().spec().data()), error_str); + if(rv == RV_HANDLED && !error_str.empty()) + error_text = WideToUTF8(error_str); + } else { + error_text = 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("testshell-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) { + UpdateForCommittedLoad(frame, is_new_navigation); + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that loading has started + handler->HandleLoadStart(browser_, browser_->GetCefFrame(frame)); + } +} + +void BrowserWebViewDelegate::didClearWindowObject(WebFrame* frame) { + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + v8::HandleScope handle_scope; + v8::Handle context = webkit_glue::GetV8Context(frame); + if(context.IsEmpty()) + return; + + v8::Context::Scope scope(context); + + CefRefPtr cframe(browser_->GetCefFrame(frame)); + CefRefPtr object = new CefV8ValueImpl(context->Global()); + handler->HandleJSBinding(browser_, cframe, object); + } +} + +void BrowserWebViewDelegate::didReceiveTitle( + WebFrame* frame, const WebString& title) { + std::wstring wtitle = UTF16ToWideHack(title); + + browser_->UIT_SetTitle(wtitle); + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler of a page title change + handler->HandleTitleChange(browser_, wtitle); + } +} + +void BrowserWebViewDelegate::didFailLoad( + WebFrame* frame, const WebURLError& error) { + LocationChangeDone(frame); +} + +void BrowserWebViewDelegate::didFinishLoad(WebFrame* frame) { + UpdateAddressBar(frame->view()); + LocationChangeDone(frame); + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that loading has ended + handler->HandleLoadEnd(browser_, browser_->GetCefFrame(frame)); + } +} + +void BrowserWebViewDelegate::didChangeLocationWithinPage( + 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::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, + WebFileSystemCallbacks* callbacks) { + if (browser_->file_system_root().empty()) { + // The FileSystem temp directory was not initialized successfully. + callbacks->didFail(WebKit::WebFileErrorSecurity); + } else { + callbacks->didOpenFileSystem( + "CefFileSystem", + webkit_glue::FilePathToWebString(browser_->file_system_root())); + } +} + +// Public methods ------------------------------------------------------------ + +BrowserWebViewDelegate::BrowserWebViewDelegate(CefBrowserImpl* browser) + : policy_delegate_enabled_(false), + policy_delegate_is_permissive_(false), + policy_delegate_should_notify_done_(false), + browser_(browser), + top_loading_frame_(NULL), + page_id_(-1), + last_page_id_updated_(-1), + smart_insert_delete_enabled_(true), +#if defined(OS_WIN) + select_trailing_whitespace_enabled_(true), +#else + select_trailing_whitespace_enabled_(false), +#endif + block_redirects_(false) { +} + +BrowserWebViewDelegate::~BrowserWebViewDelegate() { +} + +void BrowserWebViewDelegate::Reset() { + // Do a little placement new dance... + CefBrowserImpl* browser = browser_; + this->~BrowserWebViewDelegate(); + new (this) BrowserWebViewDelegate(browser); +} + +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::RegisterDragDrop() { +#if defined(OS_WIN) + // TODO(port): add me once drag and drop works. + DCHECK(!drop_delegate_); + drop_delegate_ = new BrowserDropDelegate(browser_->GetWebViewWndHandle(), + browser_->GetWebView()); +#endif +} + +void BrowserWebViewDelegate::RevokeDragDrop() { +#if defined(OS_WIN) + ::RevokeDragDrop(browser_->GetWebViewWndHandle()); +#endif +} + +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 ----------------------------------------------------------- + +void BrowserWebViewDelegate::UpdateAddressBar(WebView* webView) { +} + +void BrowserWebViewDelegate::LocationChangeDone(WebFrame* frame) { + if (frame == top_loading_frame_) + top_loading_frame_ = NULL; +} + +WebWidgetHost* BrowserWebViewDelegate::GetWidgetHost() { + if (this == browser_->GetWebViewDelegate()) + return browser_->GetWebViewHost(); + if (this == browser_->GetPopupDelegate()) + return browser_->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(); + + // 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()); + } + + std::wstring url = UTF8ToWide(entry->GetURL().spec().c_str()); + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler of an address change + handler->HandleAddressChange(browser_, browser_->GetCefFrame(frame), url); + } + + const WebHistoryItem& history_item = frame->currentHistoryItem(); + if (!history_item.isNull()) + entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); + + browser_->UIT_GetNavigationController()->DidNavigateToEntry(entry.release()); + + last_page_id_updated_ = std::max(last_page_id_updated_, page_id_); +} + +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; + + if (!browser_->GetWebView()) + return; + + const WebHistoryItem& history_item = + browser_->GetWebView()->mainFrame()->previousHistoryItem(); + if (history_item.isNull()) + return; + + entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); +} diff --git a/libcef/browser_webview_delegate.h b/libcef/browser_webview_delegate.h index 4f643294a..ff1d6f41d 100644 --- a/libcef/browser_webview_delegate.h +++ b/libcef/browser_webview_delegate.h @@ -1,334 +1,334 @@ -// 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 _BROWSER_WEBVIEW_DELEGATE_H -#define _BROWSER_WEBVIEW_DELEGATE_H - -#include "build/build_config.h" - -#include - -#if defined(OS_LINUX) -#include -#endif - -#include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "base/weak_ptr.h" -#include "third_party/WebKit/WebKit/chromium/public/WebContextMenuData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserParams.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFileSystem.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrameClient.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebViewClient.h" -#include "webkit/glue/webcursor.h" -#include "webkit/glue/plugins/webplugin_page_delegate.h" -#if defined(OS_WIN) -#include "browser_drag_delegate.h" -#include "browser_drop_delegate.h" -#endif -#include "browser_navigation_controller.h" - -class CefBrowserImpl; -struct WebPreferences; -class GURL; -class WebWidgetHost; -class FilePath; - -class BrowserWebViewDelegate : public WebKit::WebViewClient, - public WebKit::WebFrameClient, - public webkit_glue::WebPluginPageDelegate, - public base::SupportsWeakPtr { - public: - // WebKit::WebViewClient - virtual WebKit::WebView* createView(WebKit::WebFrame* creator, - const WebKit::WebWindowFeatures& features, - const WebKit::WebString& name); - virtual WebKit::WebWidget* createPopupMenu(WebKit::WebPopupType popup_type); - virtual WebKit::WebWidget* createPopupMenu( - const WebKit::WebPopupMenuInfo& info); - virtual WebKit::WebStorageNamespace* createSessionStorageNamespace( - unsigned quota); - virtual void didAddMessageToConsole( - const WebKit::WebConsoleMessage& message, - const WebKit::WebString& source_name, unsigned source_line); - virtual void printPage(WebKit::WebFrame* frame); - virtual void didStartLoading(); - virtual void didStopLoading(); - virtual bool shouldBeginEditing(const WebKit::WebRange& range); - virtual bool shouldEndEditing(const WebKit::WebRange& range); - virtual bool shouldInsertNode( - const WebKit::WebNode& node, const WebKit::WebRange& range, - WebKit::WebEditingAction action); - virtual bool shouldInsertText( - const WebKit::WebString& text, const WebKit::WebRange& range, - WebKit::WebEditingAction action); - virtual bool shouldChangeSelectedRange( - const WebKit::WebRange& from, const WebKit::WebRange& to, - WebKit::WebTextAffinity affinity, bool still_selecting); - virtual bool shouldDeleteRange(const WebKit::WebRange& range); - virtual bool shouldApplyStyle( - const WebKit::WebString& style, const WebKit::WebRange& range); - virtual bool isSmartInsertDeleteEnabled(); - virtual bool isSelectTrailingWhitespaceEnabled(); - virtual bool handleCurrentKeyboardEvent(); - virtual bool runFileChooser( - const WebKit::WebFileChooserParams& params, - WebKit::WebFileChooserCompletion* chooser_completion); - virtual void runModalAlertDialog( - WebKit::WebFrame* frame, const WebKit::WebString& message); - virtual bool runModalConfirmDialog( - WebKit::WebFrame* frame, const WebKit::WebString& message); - virtual bool runModalPromptDialog( - WebKit::WebFrame* frame, const WebKit::WebString& message, - const WebKit::WebString& default_value, WebKit::WebString* actual_value); - virtual bool runModalBeforeUnloadDialog( - WebKit::WebFrame* frame, const WebKit::WebString& message); - virtual void showContextMenu( - WebKit::WebFrame* frame, const WebKit::WebContextMenuData& data); - virtual void setStatusText(const WebKit::WebString& text); - virtual void setMouseOverURL(const WebKit::WebURL& url); - virtual void setKeyboardFocusURL(const WebKit::WebURL& url); - virtual void setToolTipText( - const WebKit::WebString& text, WebKit::WebTextDirection hint); - virtual void startDragging( - const WebKit::WebDragData& data, - WebKit::WebDragOperationsMask mask, - const WebKit::WebImage& image, - const WebKit::WebPoint& image_offset); - virtual bool acceptsLoadDrops() { return true; } - virtual void focusNext(); - virtual void focusPrevious(); - virtual void navigateBackForwardSoon(int offset); - virtual int historyBackListCount(); - virtual int historyForwardListCount(); - - // WebKit::WebWidgetClient - virtual void didInvalidateRect(const WebKit::WebRect& rect); - virtual void didScrollRect(int dx, int dy, - const WebKit::WebRect& clip_rect); - virtual void scheduleComposite(); - virtual void didFocus(); - virtual void didBlur(); - virtual void didChangeCursor(const WebKit::WebCursorInfo& cursor); - virtual void closeWidgetSoon(); - virtual void show(WebKit::WebNavigationPolicy policy); - virtual void runModal(); - virtual WebKit::WebRect windowRect(); - virtual void setWindowRect(const WebKit::WebRect& rect); - virtual WebKit::WebRect rootWindowRect(); - virtual WebKit::WebRect windowResizerRect(); - virtual WebKit::WebScreenInfo screenInfo(); - - // WebKit::WebFrameClient - virtual WebKit::WebPlugin* createPlugin( - WebKit::WebFrame*, const WebKit::WebPluginParams&); - virtual WebKit::WebMediaPlayer* createMediaPlayer( - WebKit::WebFrame*, WebKit::WebMediaPlayerClient*); - virtual WebKit::WebApplicationCacheHost* createApplicationCacheHost( - WebKit::WebFrame* frame, WebKit::WebApplicationCacheHostClient* client); - virtual void loadURLExternally( - WebKit::WebFrame*, const WebKit::WebURLRequest&, - WebKit::WebNavigationPolicy); - virtual WebKit::WebNavigationPolicy decidePolicyForNavigation( - WebKit::WebFrame*, const WebKit::WebURLRequest&, - WebKit::WebNavigationType, const WebKit::WebNode&, - WebKit::WebNavigationPolicy default_policy, bool isRedirect); - virtual bool canHandleRequest( - WebKit::WebFrame*, const WebKit::WebURLRequest&) { return true; } - virtual WebKit::WebURLError cannotHandleRequestError( - WebKit::WebFrame*, const WebKit::WebURLRequest& request); - virtual WebKit::WebURLError cancelledError( - WebKit::WebFrame*, const WebKit::WebURLRequest& request); - virtual void didCreateDataSource( - WebKit::WebFrame*, WebKit::WebDataSource*); - virtual void didStartProvisionalLoad(WebKit::WebFrame*); - virtual void didReceiveServerRedirectForProvisionalLoad(WebKit::WebFrame*); - virtual void didFailProvisionalLoad( - WebKit::WebFrame*, const WebKit::WebURLError&); - virtual void didCommitProvisionalLoad( - WebKit::WebFrame*, bool is_new_navigation); - virtual void didClearWindowObject(WebKit::WebFrame*); - virtual void didReceiveTitle( - WebKit::WebFrame*, const WebKit::WebString& title); - virtual void didFailLoad( - WebKit::WebFrame*, const WebKit::WebURLError&); - virtual void didFinishLoad(WebKit::WebFrame*); - virtual void didChangeLocationWithinPage( - WebKit::WebFrame*, bool isNewNavigation); - virtual void willSendRequest( - WebKit::WebFrame*, unsigned identifier, WebKit::WebURLRequest&, - const WebKit::WebURLResponse& redirectResponse); - virtual void reportFindInPageMatchCount( - int request_id, int count, bool final_update); - virtual void reportFindInPageSelection( - int request_id, int active_match_ordinal, const WebKit::WebRect& sel); - virtual void openFileSystem( - WebKit::WebFrame* frame, - WebKit::WebFileSystem::Type type, - long long size, - WebKit::WebFileSystemCallbacks* callbacks); - - // webkit_glue::WebPluginPageDelegate - virtual webkit_glue::WebPluginDelegate* CreatePluginDelegate( - const FilePath& file_path, - const std::string& mime_type); - virtual void CreatedPluginWindow( - gfx::PluginWindowHandle handle); - virtual void WillDestroyPluginWindow( - gfx::PluginWindowHandle handle); - virtual void DidMovePlugin( - const webkit_glue::WebPluginGeometry& move); - virtual void DidStartLoadingForPlugin() {} - virtual void DidStopLoadingForPlugin() {} - virtual void ShowModalHTMLDialogForPlugin( - const GURL& url, - const gfx::Size& size, - const std::string& json_arguments, - std::string* json_retval) {} - virtual WebKit::WebCookieJar* GetCookieJar(); - - BrowserWebViewDelegate(CefBrowserImpl* browser); - ~BrowserWebViewDelegate(); - void Reset(); - - void SetSmartInsertDeleteEnabled(bool enabled); - void SetSelectTrailingWhitespaceEnabled(bool enabled); - - // Additional accessors - WebKit::WebFrame* top_loading_frame() { return top_loading_frame_; } -#if defined(OS_WIN) - IDropTarget* drop_delegate() { return drop_delegate_.get(); } - IDropSource* drag_delegate() { return drag_delegate_.get(); } -#endif - - void set_pending_extra_data(BrowserExtraData* extra_data) { - pending_extra_data_.reset(extra_data); - } - - // Methods for modifying WebPreferences - void SetUserStyleSheetEnabled(bool is_enabled); - void SetUserStyleSheetLocation(const GURL& location); - - // Sets the webview as a drop target. - void RegisterDragDrop(); - void RevokeDragDrop(); - - void ResetDragDrop(); - - 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_; } - - protected: - // Called when the URL of the page changes. - void UpdateAddressBar(WebKit::WebView* webView); - - // Default handling of JavaScript messages. - void ShowJavaScriptAlert(WebKit::WebFrame* webframe, - const std::wstring& message); - bool ShowJavaScriptConfirm(WebKit::WebFrame* webframe, - const std::wstring& message); - bool ShowJavaScriptPrompt(WebKit::WebFrame* webframe, - const std::wstring& message, - const std::wstring& default_value, - std::wstring* 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); - - // 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); - - 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_; - - // This is non-NULL IFF a load is in progress. - WebKit::WebFrame* top_loading_frame_; - - // 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_; - scoped_refptr drop_delegate_; -#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_; -#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_; - - DISALLOW_COPY_AND_ASSIGN(BrowserWebViewDelegate); -}; - -#endif // _BROWSER_WEBVIEW_DELEGATE_H +// 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 _BROWSER_WEBVIEW_DELEGATE_H +#define _BROWSER_WEBVIEW_DELEGATE_H + +#include "build/build_config.h" + +#include + +#if defined(OS_LINUX) +#include +#endif + +#include "base/basictypes.h" +#include "base/scoped_ptr.h" +#include "base/weak_ptr.h" +#include "third_party/WebKit/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserParams.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFileSystem.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrameClient.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" +#include "third_party/WebKit/WebKit/chromium/public/WebViewClient.h" +#include "webkit/glue/webcursor.h" +#include "webkit/glue/plugins/webplugin_page_delegate.h" +#if defined(OS_WIN) +#include "browser_drag_delegate.h" +#include "browser_drop_delegate.h" +#endif +#include "browser_navigation_controller.h" + +class CefBrowserImpl; +struct WebPreferences; +class GURL; +class WebWidgetHost; +class FilePath; + +class BrowserWebViewDelegate : public WebKit::WebViewClient, + public WebKit::WebFrameClient, + public webkit_glue::WebPluginPageDelegate, + public base::SupportsWeakPtr { + public: + // WebKit::WebViewClient + virtual WebKit::WebView* createView(WebKit::WebFrame* creator, + const WebKit::WebWindowFeatures& features, + const WebKit::WebString& name); + virtual WebKit::WebWidget* createPopupMenu(WebKit::WebPopupType popup_type); + virtual WebKit::WebWidget* createPopupMenu( + const WebKit::WebPopupMenuInfo& info); + virtual WebKit::WebStorageNamespace* createSessionStorageNamespace( + unsigned quota); + virtual void didAddMessageToConsole( + const WebKit::WebConsoleMessage& message, + const WebKit::WebString& source_name, unsigned source_line); + virtual void printPage(WebKit::WebFrame* frame); + virtual void didStartLoading(); + virtual void didStopLoading(); + virtual bool shouldBeginEditing(const WebKit::WebRange& range); + virtual bool shouldEndEditing(const WebKit::WebRange& range); + virtual bool shouldInsertNode( + const WebKit::WebNode& node, const WebKit::WebRange& range, + WebKit::WebEditingAction action); + virtual bool shouldInsertText( + const WebKit::WebString& text, const WebKit::WebRange& range, + WebKit::WebEditingAction action); + virtual bool shouldChangeSelectedRange( + const WebKit::WebRange& from, const WebKit::WebRange& to, + WebKit::WebTextAffinity affinity, bool still_selecting); + virtual bool shouldDeleteRange(const WebKit::WebRange& range); + virtual bool shouldApplyStyle( + const WebKit::WebString& style, const WebKit::WebRange& range); + virtual bool isSmartInsertDeleteEnabled(); + virtual bool isSelectTrailingWhitespaceEnabled(); + virtual bool handleCurrentKeyboardEvent(); + virtual bool runFileChooser( + const WebKit::WebFileChooserParams& params, + WebKit::WebFileChooserCompletion* chooser_completion); + virtual void runModalAlertDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message); + virtual bool runModalConfirmDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message); + virtual bool runModalPromptDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message, + const WebKit::WebString& default_value, WebKit::WebString* actual_value); + virtual bool runModalBeforeUnloadDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message); + virtual void showContextMenu( + WebKit::WebFrame* frame, const WebKit::WebContextMenuData& data); + virtual void setStatusText(const WebKit::WebString& text); + virtual void setMouseOverURL(const WebKit::WebURL& url); + virtual void setKeyboardFocusURL(const WebKit::WebURL& url); + virtual void setToolTipText( + const WebKit::WebString& text, WebKit::WebTextDirection hint); + virtual void startDragging( + const WebKit::WebDragData& data, + WebKit::WebDragOperationsMask mask, + const WebKit::WebImage& image, + const WebKit::WebPoint& image_offset); + virtual bool acceptsLoadDrops() { return true; } + virtual void focusNext(); + virtual void focusPrevious(); + virtual void navigateBackForwardSoon(int offset); + virtual int historyBackListCount(); + virtual int historyForwardListCount(); + + // WebKit::WebWidgetClient + virtual void didInvalidateRect(const WebKit::WebRect& rect); + virtual void didScrollRect(int dx, int dy, + const WebKit::WebRect& clip_rect); + virtual void scheduleComposite(); + virtual void didFocus(); + virtual void didBlur(); + virtual void didChangeCursor(const WebKit::WebCursorInfo& cursor); + virtual void closeWidgetSoon(); + virtual void show(WebKit::WebNavigationPolicy policy); + virtual void runModal(); + virtual WebKit::WebRect windowRect(); + virtual void setWindowRect(const WebKit::WebRect& rect); + virtual WebKit::WebRect rootWindowRect(); + virtual WebKit::WebRect windowResizerRect(); + virtual WebKit::WebScreenInfo screenInfo(); + + // WebKit::WebFrameClient + virtual WebKit::WebPlugin* createPlugin( + WebKit::WebFrame*, const WebKit::WebPluginParams&); + virtual WebKit::WebMediaPlayer* createMediaPlayer( + WebKit::WebFrame*, WebKit::WebMediaPlayerClient*); + virtual WebKit::WebApplicationCacheHost* createApplicationCacheHost( + WebKit::WebFrame* frame, WebKit::WebApplicationCacheHostClient* client); + virtual void loadURLExternally( + WebKit::WebFrame*, const WebKit::WebURLRequest&, + WebKit::WebNavigationPolicy); + virtual WebKit::WebNavigationPolicy decidePolicyForNavigation( + WebKit::WebFrame*, const WebKit::WebURLRequest&, + WebKit::WebNavigationType, const WebKit::WebNode&, + WebKit::WebNavigationPolicy default_policy, bool isRedirect); + virtual bool canHandleRequest( + WebKit::WebFrame*, const WebKit::WebURLRequest&) { return true; } + virtual WebKit::WebURLError cannotHandleRequestError( + WebKit::WebFrame*, const WebKit::WebURLRequest& request); + virtual WebKit::WebURLError cancelledError( + WebKit::WebFrame*, const WebKit::WebURLRequest& request); + virtual void didCreateDataSource( + WebKit::WebFrame*, WebKit::WebDataSource*); + virtual void didStartProvisionalLoad(WebKit::WebFrame*); + virtual void didReceiveServerRedirectForProvisionalLoad(WebKit::WebFrame*); + virtual void didFailProvisionalLoad( + WebKit::WebFrame*, const WebKit::WebURLError&); + virtual void didCommitProvisionalLoad( + WebKit::WebFrame*, bool is_new_navigation); + virtual void didClearWindowObject(WebKit::WebFrame*); + virtual void didReceiveTitle( + WebKit::WebFrame*, const WebKit::WebString& title); + virtual void didFailLoad( + WebKit::WebFrame*, const WebKit::WebURLError&); + virtual void didFinishLoad(WebKit::WebFrame*); + virtual void didChangeLocationWithinPage( + WebKit::WebFrame*, bool isNewNavigation); + virtual void willSendRequest( + WebKit::WebFrame*, unsigned identifier, WebKit::WebURLRequest&, + const WebKit::WebURLResponse& redirectResponse); + virtual void reportFindInPageMatchCount( + int request_id, int count, bool final_update); + virtual void reportFindInPageSelection( + int request_id, int active_match_ordinal, const WebKit::WebRect& sel); + virtual void openFileSystem( + WebKit::WebFrame* frame, + WebKit::WebFileSystem::Type type, + long long size, + WebKit::WebFileSystemCallbacks* callbacks); + + // webkit_glue::WebPluginPageDelegate + virtual webkit_glue::WebPluginDelegate* CreatePluginDelegate( + const FilePath& file_path, + const std::string& mime_type); + virtual void CreatedPluginWindow( + gfx::PluginWindowHandle handle); + virtual void WillDestroyPluginWindow( + gfx::PluginWindowHandle handle); + virtual void DidMovePlugin( + const webkit_glue::WebPluginGeometry& move); + virtual void DidStartLoadingForPlugin() {} + virtual void DidStopLoadingForPlugin() {} + virtual void ShowModalHTMLDialogForPlugin( + const GURL& url, + const gfx::Size& size, + const std::string& json_arguments, + std::string* json_retval) {} + virtual WebKit::WebCookieJar* GetCookieJar(); + + BrowserWebViewDelegate(CefBrowserImpl* browser); + ~BrowserWebViewDelegate(); + void Reset(); + + void SetSmartInsertDeleteEnabled(bool enabled); + void SetSelectTrailingWhitespaceEnabled(bool enabled); + + // Additional accessors + WebKit::WebFrame* top_loading_frame() { return top_loading_frame_; } +#if defined(OS_WIN) + IDropTarget* drop_delegate() { return drop_delegate_.get(); } + IDropSource* drag_delegate() { return drag_delegate_.get(); } +#endif + + void set_pending_extra_data(BrowserExtraData* extra_data) { + pending_extra_data_.reset(extra_data); + } + + // Methods for modifying WebPreferences + void SetUserStyleSheetEnabled(bool is_enabled); + void SetUserStyleSheetLocation(const GURL& location); + + // Sets the webview as a drop target. + void RegisterDragDrop(); + void RevokeDragDrop(); + + void ResetDragDrop(); + + 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_; } + + protected: + // Called when the URL of the page changes. + void UpdateAddressBar(WebKit::WebView* webView); + + // Default handling of JavaScript messages. + void ShowJavaScriptAlert(WebKit::WebFrame* webframe, + const std::wstring& message); + bool ShowJavaScriptConfirm(WebKit::WebFrame* webframe, + const std::wstring& message); + bool ShowJavaScriptPrompt(WebKit::WebFrame* webframe, + const std::wstring& message, + const std::wstring& default_value, + std::wstring* 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); + + // 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); + + 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_; + + // This is non-NULL IFF a load is in progress. + WebKit::WebFrame* top_loading_frame_; + + // 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_; + scoped_refptr drop_delegate_; +#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_; +#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_; + + DISALLOW_COPY_AND_ASSIGN(BrowserWebViewDelegate); +}; + +#endif // _BROWSER_WEBVIEW_DELEGATE_H diff --git a/libcef/browser_webview_delegate_win.cc b/libcef/browser_webview_delegate_win.cc index ce6fe2f65..ed444b3ce 100644 --- a/libcef/browser_webview_delegate_win.cc +++ b/libcef/browser_webview_delegate_win.cc @@ -1,527 +1,527 @@ -// 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 "browser_webview_delegate.h" -#include "browser_drag_delegate.h" -#include "browser_drop_delegate.h" -#include "browser_navigation_controller.h" -#include "browser_impl.h" -#include "cef_context.h" - -#include -#include -#include - -#include "gfx/point.h" -#include "base/message_loop.h" -#include "base/trace_event.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "gfx/gdi_util.h" -#include "gfx/native_widget_types.h" -#include "net/base/net_errors.h" -#include "third_party/WebKit/WebKit/chromium/public/WebContextMenuData.h" -#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" -#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/webdropdata.h" -#include "webkit/glue/webpreferences.h" -#include "webkit/glue/plugins/webplugin.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/webplugin_delegate_impl.h" -#include "webkit/glue/window_open_disposition.h" - -using WebKit::WebContextMenuData; -using WebKit::WebCursorInfo; -using WebKit::WebFrame; -using WebKit::WebNavigationPolicy; -using WebKit::WebPopupMenuInfo; -using WebKit::WebRect; -using WebKit::WebWidget; - -// WebViewClient -------------------------------------------------------------- - -WebWidget* BrowserWebViewDelegate::createPopupMenu( - const WebPopupMenuInfo& info) { - NOTREACHED(); - return NULL; -} - -// WebWidgetClient ------------------------------------------------------------ - -void BrowserWebViewDelegate::show(WebNavigationPolicy) { - if (WebWidgetHost* host = GetWidgetHost()) { - HWND root = GetAncestor(host->view_handle(), GA_ROOT); - ShowWindow(root, SW_SHOW); - UpdateWindow(root); - } -} - -void BrowserWebViewDelegate::closeWidgetSoon() { - if (this == browser_->GetWebViewDelegate()) { - PostMessage(browser_->GetMainWndHandle(), WM_CLOSE, 0, 0); - } else if (this == browser_->GetPopupDelegate()) { - browser_->UIT_ClosePopupWidget(); - } -} - -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); - host->SetCursor(current_cursor_.GetCursor(hModule)); - } -} - -WebRect BrowserWebViewDelegate::windowRect() { - if (WebWidgetHost* host = GetWidgetHost()) { - RECT rect; - ::GetWindowRect(host->view_handle(), &rect); - return gfx::Rect(rect); - } - return WebRect(); -} - -void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) { - if (this == browser_->GetWebViewDelegate()) { - // ignored - } else if (this == browser_->GetPopupDelegate()) { - MoveWindow(browser_->GetPopupWndHandle(), - rect.x, rect.y, rect.width, rect.height, FALSE); - } -} - -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::runModal() { - WebWidgetHost* host = GetWidgetHost(); - if (!host) - return; - - show(WebKit::WebNavigationPolicyNewWindow); - - CefContext::BrowserList *list; - CefContext::BrowserList::const_iterator i; - - _Context->Lock(); - list = _Context->GetBrowserList(); - i = list->begin(); - for (; i != list->end(); ++i) { - if (i->get()->IsPopup()) - EnableWindow(i->get()->GetMainWndHandle(), FALSE); - } - _Context->Unlock(); - - browser_->UIT_SetIsModal(true); - MessageLoop::current()->Run(); - - _Context->Lock(); - list = _Context->GetBrowserList(); - i = list->begin(); - for (; i != list->end(); ++i) - EnableWindow(i->get()->GetMainWndHandle(), TRUE); - _Context->Unlock(); -} - -// WebPluginPageDelegate ------------------------------------------------------ - -webkit_glue::WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate( - const FilePath& file_path, - const std::string& mime_type) -{ - HWND hwnd = browser_->GetWebViewHost() ? - browser_->GetWebViewHost()->view_handle() : NULL; - if (!hwnd) - return NULL; - - return WebPluginDelegateImpl::Create(file_path, mime_type, hwnd); -} - -void BrowserWebViewDelegate::CreatedPluginWindow( - gfx::PluginWindowHandle handle) { - // ignored -} - -void BrowserWebViewDelegate::WillDestroyPluginWindow( - gfx::PluginWindowHandle handle) { - // ignored -} - -void BrowserWebViewDelegate::DidMovePlugin( - const webkit_glue::WebPluginGeometry& move) { - unsigned long 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); -} - -static void AddMenuItem(CefRefPtr browser, HMENU menu, int index, - CefHandler::MenuId id, const wchar_t* label, - bool enabled, std::list& label_list) -{ - std::wstring actual_label = label; - CefRefPtr handler = browser->GetHandler(); - if(handler.get()) { - // Let the handler change the label if desired - handler->HandleGetMenuLabel(browser, id, 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 = id; - mii.dwTypeData = const_cast(label_list.back().c_str()); - - InsertMenuItem(menu, index, TRUE, &mii); -} - -static void AddMenuSeparator(HMENU menu, int index) -{ - MENUITEMINFO mii; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_FTYPE; - mii.fType = MFT_SEPARATOR; - - InsertMenuItem(menu, index, TRUE, &mii); -} - -void BrowserWebViewDelegate::showContextMenu( - WebFrame* frame, const WebContextMenuData& data) -{ - POINT screen_pt = { data.mousePosition.x, data.mousePosition.y }; - MapWindowPoints(browser_->GetMainWndHandle(), HWND_DESKTOP, - &screen_pt, 1); - - HMENU menu = NULL; - std::list label_list; - - // Enable recursive tasks on the message loop so we can get updates while - // the context menu is being displayed. - bool old_state = MessageLoop::current()->NestableTasksAllowed(); - MessageLoop::current()->SetNestableTasksAllowed(true); - - int edit_flags = data.editFlags; - if(browser_->UIT_CanGoBack()) - edit_flags |= MENU_CAN_GO_BACK; - if(browser_->UIT_CanGoForward()) - edit_flags |= MENU_CAN_GO_FORWARD; - - int 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 handler = browser_->GetHandler(); - if(handler.get()) { - // Gather menu information - CefHandler::MenuInfo menuInfo; - std::wstring linkStr, imageStr, pageStr, frameStr; - std::wstring selectedTextStr, misspelledWordStr, securityInfoStr; - - linkStr = UTF16ToWideHack(data.linkURL.spec().utf16()); - imageStr = UTF16ToWideHack(data.srcURL.spec().utf16()); - pageStr = UTF16ToWideHack(data.pageURL.spec().utf16()); - frameStr = UTF16ToWideHack(data.frameURL.spec().utf16()); - selectedTextStr = UTF16ToWideHack(data.selectedText); - misspelledWordStr = UTF16ToWideHack(data.misspelledWord); - securityInfoStr = UTF16ToWideHack(data.securityInfo.utf16()); - - menuInfo.typeFlags = type_flags; - menuInfo.x = screen_pt.x; - menuInfo.y = screen_pt.y; - menuInfo.linkUrl = linkStr.c_str(); - menuInfo.imageUrl = imageStr.c_str(); - menuInfo.pageUrl = pageStr.c_str(); - menuInfo.frameUrl = frameStr.c_str(); - menuInfo.selectionText = selectedTextStr.c_str(); - menuInfo.misspelledWord = misspelledWordStr.c_str(); - menuInfo.editFlags = edit_flags; - menuInfo.securityInfo = securityInfoStr.c_str(); - - // Notify the handler that a context menu is requested - CefHandler::RetVal rv = handler->HandleBeforeMenu(browser_, menuInfo); - if(rv == RV_HANDLED) - goto end; - } - - // Build the correct default context menu - if (type_flags & MENUTYPE_EDITABLE) { - menu = CreatePopupMenu(); - AddMenuItem(browser_, menu, -1, MENU_ID_UNDO, L"Undo", - !!(edit_flags & MENU_CAN_UNDO), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_REDO, L"Redo", - !!(edit_flags & MENU_CAN_REDO), label_list); - AddMenuSeparator(menu, -1); - AddMenuItem(browser_, menu, -1, MENU_ID_CUT, L"Cut", - !!(edit_flags & MENU_CAN_CUT), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", - !!(edit_flags & MENU_CAN_COPY), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_PASTE, L"Paste", - !!(edit_flags & MENU_CAN_PASTE), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_DELETE, L"Delete", - !!(edit_flags & MENU_CAN_DELETE), label_list); - AddMenuSeparator(menu, -1); - AddMenuItem(browser_, menu, -1, MENU_ID_SELECTALL, L"Select All", - !!(edit_flags & MENU_CAN_SELECT_ALL), label_list); - } else if(type_flags & MENUTYPE_SELECTION) { - menu = CreatePopupMenu(); - AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", - !!(edit_flags & MENU_CAN_COPY), label_list); - } else if(type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) { - menu = CreatePopupMenu(); - AddMenuItem(browser_, menu, -1, MENU_ID_NAV_BACK, L"Back", - !!(edit_flags & MENU_CAN_GO_BACK), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_NAV_FORWARD, L"Forward", - !!(edit_flags & MENU_CAN_GO_FORWARD), label_list); - AddMenuSeparator(menu, -1); - AddMenuItem(browser_, menu, -1, MENU_ID_PRINT, L"Print", - true, label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_VIEWSOURCE, L"View Source", - true, label_list); - } - - if(menu) { - // show the context menu - int selected_id = TrackPopupMenu(menu, - TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_RECURSE, - screen_pt.x, screen_pt.y, 0, browser_->GetMainWndHandle(), NULL); - - if(selected_id != 0) { - // An action was chosen - CefHandler::MenuId menuId = static_cast(selected_id); - bool handled = false; - if(handler.get()) { - // Ask the handler if it wants to handle the action - CefHandler::RetVal rv = handler->HandleMenuAction(browser_, menuId); - handled = (rv == RV_HANDLED); - } - - if(!handled) { - // Execute the action - CefRefPtr frame = browser_->GetFocusedFrame(); - frame->AddRef(); - browser_->UIT_HandleAction(menuId, frame.get()); - } - } - } - - DestroyMenu(menu); - -end: - MessageLoop::current()->SetNestableTasksAllowed(old_state); -} - -// Private methods ------------------------------------------------------------ - -void BrowserWebViewDelegate::ShowJavaScriptAlert(WebFrame* webframe, - const std::wstring& message) -{ - // TODO(cef): Think about what we should be showing as the prompt caption - MessageBox(browser_->GetMainWndHandle(), message.c_str(), - browser_->UIT_GetTitle().c_str(), MB_OK | MB_ICONWARNING); -} - -bool BrowserWebViewDelegate::ShowJavaScriptConfirm(WebFrame* webframe, - const std::wstring& message) -{ - // TODO(cef): Think about what we should be showing as the prompt caption - int rv = MessageBox(browser_->GetMainWndHandle(), message.c_str(), - browser_->UIT_GetTitle().c_str(), - MB_YESNO | MB_ICONQUESTION); - return (rv == IDYES); -} - -bool BrowserWebViewDelegate::ShowJavaScriptPrompt(WebFrame* webframe, - const std::wstring& message, - const std::wstring& default_value, - std::wstring* 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; - - wchar_t filename[MAX_PATH] = L""; - - 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_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; -} - -} - -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_->GetMainWndHandle(), &file_names); - } - else - { - FilePath file_name; - result = RunOpenFileDialog(L"", browser_->GetMainWndHandle(), &file_name); - if (result) - file_names.push_back(file_name); - } - - return result; -} - +// 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 "browser_webview_delegate.h" +#include "browser_drag_delegate.h" +#include "browser_drop_delegate.h" +#include "browser_navigation_controller.h" +#include "browser_impl.h" +#include "cef_context.h" + +#include +#include +#include + +#include "gfx/point.h" +#include "base/message_loop.h" +#include "base/trace_event.h" +#include "base/string_util.h" +#include "base/utf_string_conversions.h" +#include "gfx/gdi_util.h" +#include "gfx/native_widget_types.h" +#include "net/base/net_errors.h" +#include "third_party/WebKit/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" +#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/WebKit/chromium/public/WebRect.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/glue/plugins/webplugin.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/plugins/plugin_list.h" +#include "webkit/glue/plugins/webplugin_delegate_impl.h" +#include "webkit/glue/window_open_disposition.h" + +using WebKit::WebContextMenuData; +using WebKit::WebCursorInfo; +using WebKit::WebFrame; +using WebKit::WebNavigationPolicy; +using WebKit::WebPopupMenuInfo; +using WebKit::WebRect; +using WebKit::WebWidget; + +// WebViewClient -------------------------------------------------------------- + +WebWidget* BrowserWebViewDelegate::createPopupMenu( + const WebPopupMenuInfo& info) { + NOTREACHED(); + return NULL; +} + +// WebWidgetClient ------------------------------------------------------------ + +void BrowserWebViewDelegate::show(WebNavigationPolicy) { + if (WebWidgetHost* host = GetWidgetHost()) { + HWND root = GetAncestor(host->view_handle(), GA_ROOT); + ShowWindow(root, SW_SHOW); + UpdateWindow(root); + } +} + +void BrowserWebViewDelegate::closeWidgetSoon() { + if (this == browser_->GetWebViewDelegate()) { + PostMessage(browser_->GetMainWndHandle(), WM_CLOSE, 0, 0); + } else if (this == browser_->GetPopupDelegate()) { + browser_->UIT_ClosePopupWidget(); + } +} + +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); + host->SetCursor(current_cursor_.GetCursor(hModule)); + } +} + +WebRect BrowserWebViewDelegate::windowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + RECT rect; + ::GetWindowRect(host->view_handle(), &rect); + return gfx::Rect(rect); + } + return WebRect(); +} + +void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) { + if (this == browser_->GetWebViewDelegate()) { + // ignored + } else if (this == browser_->GetPopupDelegate()) { + MoveWindow(browser_->GetPopupWndHandle(), + rect.x, rect.y, rect.width, rect.height, FALSE); + } +} + +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::runModal() { + WebWidgetHost* host = GetWidgetHost(); + if (!host) + return; + + show(WebKit::WebNavigationPolicyNewWindow); + + CefContext::BrowserList *list; + CefContext::BrowserList::const_iterator i; + + _Context->Lock(); + list = _Context->GetBrowserList(); + i = list->begin(); + for (; i != list->end(); ++i) { + if (i->get()->IsPopup()) + EnableWindow(i->get()->GetMainWndHandle(), FALSE); + } + _Context->Unlock(); + + browser_->UIT_SetIsModal(true); + MessageLoop::current()->Run(); + + _Context->Lock(); + list = _Context->GetBrowserList(); + i = list->begin(); + for (; i != list->end(); ++i) + EnableWindow(i->get()->GetMainWndHandle(), TRUE); + _Context->Unlock(); +} + +// WebPluginPageDelegate ------------------------------------------------------ + +webkit_glue::WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate( + const FilePath& file_path, + const std::string& mime_type) +{ + HWND hwnd = browser_->GetWebViewHost() ? + browser_->GetWebViewHost()->view_handle() : NULL; + if (!hwnd) + return NULL; + + return WebPluginDelegateImpl::Create(file_path, mime_type, hwnd); +} + +void BrowserWebViewDelegate::CreatedPluginWindow( + gfx::PluginWindowHandle handle) { + // ignored +} + +void BrowserWebViewDelegate::WillDestroyPluginWindow( + gfx::PluginWindowHandle handle) { + // ignored +} + +void BrowserWebViewDelegate::DidMovePlugin( + const webkit_glue::WebPluginGeometry& move) { + unsigned long 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); +} + +static void AddMenuItem(CefRefPtr browser, HMENU menu, int index, + CefHandler::MenuId id, const wchar_t* label, + bool enabled, std::list& label_list) +{ + std::wstring actual_label = label; + CefRefPtr handler = browser->GetHandler(); + if(handler.get()) { + // Let the handler change the label if desired + handler->HandleGetMenuLabel(browser, id, 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 = id; + mii.dwTypeData = const_cast(label_list.back().c_str()); + + InsertMenuItem(menu, index, TRUE, &mii); +} + +static void AddMenuSeparator(HMENU menu, int index) +{ + MENUITEMINFO mii; + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_FTYPE; + mii.fType = MFT_SEPARATOR; + + InsertMenuItem(menu, index, TRUE, &mii); +} + +void BrowserWebViewDelegate::showContextMenu( + WebFrame* frame, const WebContextMenuData& data) +{ + POINT screen_pt = { data.mousePosition.x, data.mousePosition.y }; + MapWindowPoints(browser_->GetMainWndHandle(), HWND_DESKTOP, + &screen_pt, 1); + + HMENU menu = NULL; + std::list label_list; + + // Enable recursive tasks on the message loop so we can get updates while + // the context menu is being displayed. + bool old_state = MessageLoop::current()->NestableTasksAllowed(); + MessageLoop::current()->SetNestableTasksAllowed(true); + + int edit_flags = data.editFlags; + if(browser_->UIT_CanGoBack()) + edit_flags |= MENU_CAN_GO_BACK; + if(browser_->UIT_CanGoForward()) + edit_flags |= MENU_CAN_GO_FORWARD; + + int 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 handler = browser_->GetHandler(); + if(handler.get()) { + // Gather menu information + CefHandler::MenuInfo menuInfo; + std::wstring linkStr, imageStr, pageStr, frameStr; + std::wstring selectedTextStr, misspelledWordStr, securityInfoStr; + + linkStr = UTF16ToWideHack(data.linkURL.spec().utf16()); + imageStr = UTF16ToWideHack(data.srcURL.spec().utf16()); + pageStr = UTF16ToWideHack(data.pageURL.spec().utf16()); + frameStr = UTF16ToWideHack(data.frameURL.spec().utf16()); + selectedTextStr = UTF16ToWideHack(data.selectedText); + misspelledWordStr = UTF16ToWideHack(data.misspelledWord); + securityInfoStr = UTF16ToWideHack(data.securityInfo.utf16()); + + menuInfo.typeFlags = type_flags; + menuInfo.x = screen_pt.x; + menuInfo.y = screen_pt.y; + menuInfo.linkUrl = linkStr.c_str(); + menuInfo.imageUrl = imageStr.c_str(); + menuInfo.pageUrl = pageStr.c_str(); + menuInfo.frameUrl = frameStr.c_str(); + menuInfo.selectionText = selectedTextStr.c_str(); + menuInfo.misspelledWord = misspelledWordStr.c_str(); + menuInfo.editFlags = edit_flags; + menuInfo.securityInfo = securityInfoStr.c_str(); + + // Notify the handler that a context menu is requested + CefHandler::RetVal rv = handler->HandleBeforeMenu(browser_, menuInfo); + if(rv == RV_HANDLED) + goto end; + } + + // Build the correct default context menu + if (type_flags & MENUTYPE_EDITABLE) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, menu, -1, MENU_ID_UNDO, L"Undo", + !!(edit_flags & MENU_CAN_UNDO), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_REDO, L"Redo", + !!(edit_flags & MENU_CAN_REDO), label_list); + AddMenuSeparator(menu, -1); + AddMenuItem(browser_, menu, -1, MENU_ID_CUT, L"Cut", + !!(edit_flags & MENU_CAN_CUT), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", + !!(edit_flags & MENU_CAN_COPY), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_PASTE, L"Paste", + !!(edit_flags & MENU_CAN_PASTE), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_DELETE, L"Delete", + !!(edit_flags & MENU_CAN_DELETE), label_list); + AddMenuSeparator(menu, -1); + AddMenuItem(browser_, menu, -1, MENU_ID_SELECTALL, L"Select All", + !!(edit_flags & MENU_CAN_SELECT_ALL), label_list); + } else if(type_flags & MENUTYPE_SELECTION) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", + !!(edit_flags & MENU_CAN_COPY), label_list); + } else if(type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, menu, -1, MENU_ID_NAV_BACK, L"Back", + !!(edit_flags & MENU_CAN_GO_BACK), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_NAV_FORWARD, L"Forward", + !!(edit_flags & MENU_CAN_GO_FORWARD), label_list); + AddMenuSeparator(menu, -1); + AddMenuItem(browser_, menu, -1, MENU_ID_PRINT, L"Print", + true, label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_VIEWSOURCE, L"View Source", + true, label_list); + } + + if(menu) { + // show the context menu + int selected_id = TrackPopupMenu(menu, + TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_RECURSE, + screen_pt.x, screen_pt.y, 0, browser_->GetMainWndHandle(), NULL); + + if(selected_id != 0) { + // An action was chosen + CefHandler::MenuId menuId = static_cast(selected_id); + bool handled = false; + if(handler.get()) { + // Ask the handler if it wants to handle the action + CefHandler::RetVal rv = handler->HandleMenuAction(browser_, menuId); + handled = (rv == RV_HANDLED); + } + + if(!handled) { + // Execute the action + CefRefPtr frame = browser_->GetFocusedFrame(); + frame->AddRef(); + browser_->UIT_HandleAction(menuId, frame.get()); + } + } + } + + DestroyMenu(menu); + +end: + MessageLoop::current()->SetNestableTasksAllowed(old_state); +} + +// Private methods ------------------------------------------------------------ + +void BrowserWebViewDelegate::ShowJavaScriptAlert(WebFrame* webframe, + const std::wstring& message) +{ + // TODO(cef): Think about what we should be showing as the prompt caption + MessageBox(browser_->GetMainWndHandle(), message.c_str(), + browser_->UIT_GetTitle().c_str(), MB_OK | MB_ICONWARNING); +} + +bool BrowserWebViewDelegate::ShowJavaScriptConfirm(WebFrame* webframe, + const std::wstring& message) +{ + // TODO(cef): Think about what we should be showing as the prompt caption + int rv = MessageBox(browser_->GetMainWndHandle(), message.c_str(), + browser_->UIT_GetTitle().c_str(), + MB_YESNO | MB_ICONQUESTION); + return (rv == IDYES); +} + +bool BrowserWebViewDelegate::ShowJavaScriptPrompt(WebFrame* webframe, + const std::wstring& message, + const std::wstring& default_value, + std::wstring* 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; + + wchar_t filename[MAX_PATH] = L""; + + 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_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; +} + +} + +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_->GetMainWndHandle(), &file_names); + } + else + { + FilePath file_name; + result = RunOpenFileDialog(L"", browser_->GetMainWndHandle(), &file_name); + if (result) + file_names.push_back(file_name); + } + + return result; +} + diff --git a/libcef/cef_context.cc b/libcef/cef_context.cc index fbf264558..4f00ed052 100644 --- a/libcef/cef_context.cc +++ b/libcef/cef_context.cc @@ -1,324 +1,324 @@ -// 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 "cef_context.h" -#include "browser_impl.h" -#include "browser_webkit_glue.h" -#include "cef_thread.h" -#include "cef_process.h" -#include "../include/cef_nplugin.h" - -#include "base/file_util.h" -#if defined(OS_MACOSX) || defined(OS_WIN) -#include "base/nss_util.h" -#endif -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/webpreferences.h" - -// Global CefContext pointer -CefRefPtr _Context; - -bool CefInitialize(bool multi_threaded_message_loop, - const std::wstring& cache_path) -{ - // Return true if the context is already initialized - if(_Context.get()) - return true; - - // Create the new global context object - _Context = new CefContext(); - // Initialize the global context - return _Context->Initialize(multi_threaded_message_loop, cache_path); -} - -void CefShutdown() -{ - // Verify that the context is already initialized - if(!_Context.get()) - return; - - // Shut down the global context - _Context->Shutdown(); - // Delete the global context object - _Context = NULL; -} - -void CefDoMessageLoopWork() -{ - // Verify that the context is already initialized. - if(!_Context.get() || !_Context->process()) - return; - - if(!_Context->process()->CalledOnValidThread()) - return; - _Context->process()->DoMessageLoopIteration(); -} - -static void UIT_RegisterPlugin(struct CefPluginInfo* plugin_info) -{ - REQUIRE_UIT(); - - NPAPI::PluginVersionInfo info; - - info.path = FilePath(plugin_info->unique_name); - info.product_name = plugin_info->display_name; - info.file_description = plugin_info->description; - info.file_version =plugin_info->version; - - for(size_t i = 0; i < plugin_info->mime_types.size(); ++i) { - if(i > 0) { - info.mime_types += L"|"; - info.file_extensions += L"|"; - info.type_descriptions += L"|"; - } - - info.mime_types += plugin_info->mime_types[i].mime_type; - info.type_descriptions += plugin_info->mime_types[i].description; - - for(size_t j = 0; - j < plugin_info->mime_types[i].file_extensions.size(); ++j) { - if(j > 0) { - info.file_extensions += L","; - } - info.file_extensions += plugin_info->mime_types[i].file_extensions[j]; - } - } - - info.entry_points.np_getentrypoints = plugin_info->np_getentrypoints; - info.entry_points.np_initialize = plugin_info->np_initialize; - info.entry_points.np_shutdown = plugin_info->np_shutdown; - - NPAPI::PluginList::Singleton()->RegisterInternalPlugin(info); - - delete plugin_info; -} - -bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info) -{ - if(!_Context.get()) - return false; - - CefPluginInfo* pPluginInfo = new CefPluginInfo; - *pPluginInfo = plugin_info; - - CefThread::PostTask(CefThread::UI, FROM_HERE, - NewRunnableFunction(UIT_RegisterPlugin, pPluginInfo)); - - return true; -} - -static 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; -} - -bool CefCurrentlyOn(CefThreadId threadId) -{ - int id = GetThreadId(threadId); - if(id < 0) - return false; - - return CefThread::CurrentlyOn(static_cast(id)); -} - -class CefTaskHelper : public base::RefCountedThreadSafe -{ -public: - CefTaskHelper(CefRefPtr task) : task_(task) {} - void Execute(CefThreadId threadId) { task_->Execute(threadId); } -private: - CefRefPtr task_; - DISALLOW_COPY_AND_ASSIGN(CefTaskHelper); -}; - -bool CefPostTask(CefThreadId threadId, CefRefPtr task) -{ - int id = GetThreadId(threadId); - if(id < 0) - return false; - - scoped_refptr helper(new CefTaskHelper(task)); - return CefThread::PostTask(static_cast(id), FROM_HERE, - NewRunnableMethod(helper.get(), &CefTaskHelper::Execute, threadId)); -} - -bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, - long delay_ms) -{ - int id = GetThreadId(threadId); - if(id < 0) - return false; - - scoped_refptr helper(new CefTaskHelper(task)); - return CefThread::PostDelayedTask(static_cast(id), FROM_HERE, - NewRunnableMethod(helper.get(), &CefTaskHelper::Execute, threadId), - delay_ms); -} - - -// CefContext - -CefContext::CefContext() : process_(NULL), webprefs_(NULL) -{ - -} - -CefContext::~CefContext() -{ - // Just in case CefShutdown() isn't called - Shutdown(); -} - -bool CefContext::Initialize(bool multi_threaded_message_loop, - const std::wstring& cache_path) -{ - cache_path_ = cache_path; - - // Initialize web preferences - webprefs_ = new WebPreferences; - *webprefs_ = WebPreferences(); - webprefs_->standard_font_family = L"Times"; - webprefs_->fixed_font_family = L"Courier"; - webprefs_->serif_font_family = L"Times"; - webprefs_->sans_serif_font_family = L"Helvetica"; - // These two fonts 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 defined(OS_MACOSX) - webprefs_->cursive_font_family = L"Apple Chancery"; - webprefs_->fantasy_font_family = L"Papyrus"; -#else - webprefs_->cursive_font_family = L"Comic Sans MS"; - webprefs_->fantasy_font_family = L"Impact"; -#endif - webprefs_->default_encoding = "ISO-8859-1"; - webprefs_->default_font_size = 16; - webprefs_->default_fixed_font_size = 13; - webprefs_->minimum_font_size = 1; - webprefs_->minimum_logical_font_size = 9; - webprefs_->javascript_can_open_windows_automatically = true; - webprefs_->dom_paste_enabled = true; - webprefs_->developer_extras_enabled = true; - webprefs_->site_specific_quirks_enabled = true; - webprefs_->shrinks_standalone_images_to_fit = false; - webprefs_->uses_universal_detector = false; - webprefs_->text_areas_are_resizable = true; - webprefs_->java_enabled = true; - webprefs_->allow_scripts_to_close_windows = false; - webprefs_->xss_auditor_enabled = false; - webprefs_->remote_fonts_enabled = true; - webprefs_->local_storage_enabled = true; - webprefs_->application_cache_enabled = true; - webprefs_->databases_enabled = true; - webprefs_->allow_file_access_from_file_urls = true; - webprefs_->accelerated_2d_canvas_enabled = true; - webprefs_->accelerated_compositing_enabled = true; - -#if defined(OS_MACOSX) || defined(OS_WIN) - // We want to be sure to init NSPR on the main thread. - base::EnsureNSPRInit(); -#endif - - process_ = new CefProcess(multi_threaded_message_loop); - process_->CreateChildThreads(); - - return true; -} - -void CefContext::Shutdown() -{ - // Remove all existing browsers. - //RemoveAllBrowsers(); - - // Deleting the process will destroy the child threads. - process_ = NULL; -} - - -bool CefContext::AddBrowser(CefRefPtr browser) -{ - bool found = false; - - Lock(); - - // 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); - } - - Unlock(); - return !found; -} - -bool CefContext::RemoveBrowser(CefRefPtr browser) -{ - bool deleted = false; - bool empty = false; - - Lock(); - - 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_ = 1; - empty = true; - } - - Unlock(); - - if (empty) { - CefThread::PostTask(CefThread::UI, FROM_HERE, - NewRunnableFunction(webkit_glue::ClearCache)); - } - - return deleted; -} - -CefRefPtr CefContext::GetBrowserByID(int id) -{ - CefRefPtr browser; - Lock(); - - BrowserList::const_iterator it = browserlist_.begin(); - for(; it != browserlist_.end(); ++it) { - if(it->get()->UIT_GetUniqueID() == id) { - browser = it->get(); - break; - } - } - - Unlock(); - - return browser; -} +// 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 "cef_context.h" +#include "browser_impl.h" +#include "browser_webkit_glue.h" +#include "cef_thread.h" +#include "cef_process.h" +#include "../include/cef_nplugin.h" + +#include "base/file_util.h" +#if defined(OS_MACOSX) || defined(OS_WIN) +#include "base/nss_util.h" +#endif +#include "webkit/glue/plugins/plugin_list.h" +#include "webkit/glue/webpreferences.h" + +// Global CefContext pointer +CefRefPtr _Context; + +bool CefInitialize(bool multi_threaded_message_loop, + const std::wstring& cache_path) +{ + // Return true if the context is already initialized + if(_Context.get()) + return true; + + // Create the new global context object + _Context = new CefContext(); + // Initialize the global context + return _Context->Initialize(multi_threaded_message_loop, cache_path); +} + +void CefShutdown() +{ + // Verify that the context is already initialized + if(!_Context.get()) + return; + + // Shut down the global context + _Context->Shutdown(); + // Delete the global context object + _Context = NULL; +} + +void CefDoMessageLoopWork() +{ + // Verify that the context is already initialized. + if(!_Context.get() || !_Context->process()) + return; + + if(!_Context->process()->CalledOnValidThread()) + return; + _Context->process()->DoMessageLoopIteration(); +} + +static void UIT_RegisterPlugin(struct CefPluginInfo* plugin_info) +{ + REQUIRE_UIT(); + + NPAPI::PluginVersionInfo info; + + info.path = FilePath(plugin_info->unique_name); + info.product_name = plugin_info->display_name; + info.file_description = plugin_info->description; + info.file_version =plugin_info->version; + + for(size_t i = 0; i < plugin_info->mime_types.size(); ++i) { + if(i > 0) { + info.mime_types += L"|"; + info.file_extensions += L"|"; + info.type_descriptions += L"|"; + } + + info.mime_types += plugin_info->mime_types[i].mime_type; + info.type_descriptions += plugin_info->mime_types[i].description; + + for(size_t j = 0; + j < plugin_info->mime_types[i].file_extensions.size(); ++j) { + if(j > 0) { + info.file_extensions += L","; + } + info.file_extensions += plugin_info->mime_types[i].file_extensions[j]; + } + } + + info.entry_points.np_getentrypoints = plugin_info->np_getentrypoints; + info.entry_points.np_initialize = plugin_info->np_initialize; + info.entry_points.np_shutdown = plugin_info->np_shutdown; + + NPAPI::PluginList::Singleton()->RegisterInternalPlugin(info); + + delete plugin_info; +} + +bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info) +{ + if(!_Context.get()) + return false; + + CefPluginInfo* pPluginInfo = new CefPluginInfo; + *pPluginInfo = plugin_info; + + CefThread::PostTask(CefThread::UI, FROM_HERE, + NewRunnableFunction(UIT_RegisterPlugin, pPluginInfo)); + + return true; +} + +static 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; +} + +bool CefCurrentlyOn(CefThreadId threadId) +{ + int id = GetThreadId(threadId); + if(id < 0) + return false; + + return CefThread::CurrentlyOn(static_cast(id)); +} + +class CefTaskHelper : public base::RefCountedThreadSafe +{ +public: + CefTaskHelper(CefRefPtr task) : task_(task) {} + void Execute(CefThreadId threadId) { task_->Execute(threadId); } +private: + CefRefPtr task_; + DISALLOW_COPY_AND_ASSIGN(CefTaskHelper); +}; + +bool CefPostTask(CefThreadId threadId, CefRefPtr task) +{ + int id = GetThreadId(threadId); + if(id < 0) + return false; + + scoped_refptr helper(new CefTaskHelper(task)); + return CefThread::PostTask(static_cast(id), FROM_HERE, + NewRunnableMethod(helper.get(), &CefTaskHelper::Execute, threadId)); +} + +bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, + long delay_ms) +{ + int id = GetThreadId(threadId); + if(id < 0) + return false; + + scoped_refptr helper(new CefTaskHelper(task)); + return CefThread::PostDelayedTask(static_cast(id), FROM_HERE, + NewRunnableMethod(helper.get(), &CefTaskHelper::Execute, threadId), + delay_ms); +} + + +// CefContext + +CefContext::CefContext() : process_(NULL), webprefs_(NULL) +{ + +} + +CefContext::~CefContext() +{ + // Just in case CefShutdown() isn't called + Shutdown(); +} + +bool CefContext::Initialize(bool multi_threaded_message_loop, + const std::wstring& cache_path) +{ + cache_path_ = cache_path; + + // Initialize web preferences + webprefs_ = new WebPreferences; + *webprefs_ = WebPreferences(); + webprefs_->standard_font_family = L"Times"; + webprefs_->fixed_font_family = L"Courier"; + webprefs_->serif_font_family = L"Times"; + webprefs_->sans_serif_font_family = L"Helvetica"; + // These two fonts 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 defined(OS_MACOSX) + webprefs_->cursive_font_family = L"Apple Chancery"; + webprefs_->fantasy_font_family = L"Papyrus"; +#else + webprefs_->cursive_font_family = L"Comic Sans MS"; + webprefs_->fantasy_font_family = L"Impact"; +#endif + webprefs_->default_encoding = "ISO-8859-1"; + webprefs_->default_font_size = 16; + webprefs_->default_fixed_font_size = 13; + webprefs_->minimum_font_size = 1; + webprefs_->minimum_logical_font_size = 9; + webprefs_->javascript_can_open_windows_automatically = true; + webprefs_->dom_paste_enabled = true; + webprefs_->developer_extras_enabled = true; + webprefs_->site_specific_quirks_enabled = true; + webprefs_->shrinks_standalone_images_to_fit = false; + webprefs_->uses_universal_detector = false; + webprefs_->text_areas_are_resizable = true; + webprefs_->java_enabled = true; + webprefs_->allow_scripts_to_close_windows = false; + webprefs_->xss_auditor_enabled = false; + webprefs_->remote_fonts_enabled = true; + webprefs_->local_storage_enabled = true; + webprefs_->application_cache_enabled = true; + webprefs_->databases_enabled = true; + webprefs_->allow_file_access_from_file_urls = true; + webprefs_->accelerated_2d_canvas_enabled = true; + webprefs_->accelerated_compositing_enabled = true; + +#if defined(OS_MACOSX) || defined(OS_WIN) + // We want to be sure to init NSPR on the main thread. + base::EnsureNSPRInit(); +#endif + + process_ = new CefProcess(multi_threaded_message_loop); + process_->CreateChildThreads(); + + return true; +} + +void CefContext::Shutdown() +{ + // Remove all existing browsers. + //RemoveAllBrowsers(); + + // Deleting the process will destroy the child threads. + process_ = NULL; +} + + +bool CefContext::AddBrowser(CefRefPtr browser) +{ + bool found = false; + + Lock(); + + // 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); + } + + Unlock(); + return !found; +} + +bool CefContext::RemoveBrowser(CefRefPtr browser) +{ + bool deleted = false; + bool empty = false; + + Lock(); + + 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_ = 1; + empty = true; + } + + Unlock(); + + if (empty) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + NewRunnableFunction(webkit_glue::ClearCache)); + } + + return deleted; +} + +CefRefPtr CefContext::GetBrowserByID(int id) +{ + CefRefPtr browser; + Lock(); + + BrowserList::const_iterator it = browserlist_.begin(); + for(; it != browserlist_.end(); ++it) { + if(it->get()->UIT_GetUniqueID() == id) { + browser = it->get(); + break; + } + } + + Unlock(); + + return browser; +} diff --git a/libcef/cef_context.h b/libcef/cef_context.h index 046f74109..57c116e6b 100644 --- a/libcef/cef_context.h +++ b/libcef/cef_context.h @@ -1,81 +1,81 @@ -// 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_CONTEXT_H -#define _CEF_CONTEXT_H - -#include "../include/cef.h" -#include "browser_request_context.h" -#include "cef_process.h" -#include "cef_thread.h" - -#include "base/at_exit.h" -#include "base/file_path.h" -#include "base/message_loop.h" -#include "base/ref_counted.h" -#include - -class BrowserRequestContext; -class CefBrowserImpl; -struct WebPreferences; - -class CefContext : public CefThreadSafeBase -{ -public: - typedef std::list > BrowserList; - - CefContext(); - ~CefContext(); - - // These methods will be called on the main application thread. - bool Initialize(bool multi_threaded_message_loop, - const std::wstring& cache_path); - void Shutdown(); - - scoped_refptr process() { return process_; } - - bool AddBrowser(CefRefPtr browser); - bool RemoveBrowser(CefRefPtr browser); - CefRefPtr GetBrowserByID(int id); - BrowserList* GetBrowserList() { return &browserlist_; } - - // Retrieve the path at which cache data will be stored on disk. If empty, - // cache data will be stored in-memory. - const std::wstring& cache_path() { return cache_path_; } - - WebPreferences* web_preferences() - { - REQUIRE_UIT(); - return webprefs_; - } - - // The BrowserRequestContext object is managed by CefProcessIOThread. - void set_request_context(BrowserRequestContext* request_context) - { request_context_ = request_context; } - scoped_refptr request_context() - { return request_context_; } - -private: - // Manages the various process threads. - scoped_refptr process_; - - // Initialize the AtExitManager on the main application thread to avoid - // asserts and possible memory leaks. - base::AtExitManager at_exit_manager_; - - std::wstring cache_path_; - WebPreferences* webprefs_; - scoped_refptr request_context_; - - // Map of browsers that currently exist. - BrowserList browserlist_; - - // Used for assigning unique IDs to browser instances. - int next_browser_id_; -}; - -// Global context object pointer -extern CefRefPtr _Context; - -#endif // _CEF_CONTEXT_H +// 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_CONTEXT_H +#define _CEF_CONTEXT_H + +#include "../include/cef.h" +#include "browser_request_context.h" +#include "cef_process.h" +#include "cef_thread.h" + +#include "base/at_exit.h" +#include "base/file_path.h" +#include "base/message_loop.h" +#include "base/ref_counted.h" +#include + +class BrowserRequestContext; +class CefBrowserImpl; +struct WebPreferences; + +class CefContext : public CefThreadSafeBase +{ +public: + typedef std::list > BrowserList; + + CefContext(); + ~CefContext(); + + // These methods will be called on the main application thread. + bool Initialize(bool multi_threaded_message_loop, + const std::wstring& cache_path); + void Shutdown(); + + scoped_refptr process() { return process_; } + + bool AddBrowser(CefRefPtr browser); + bool RemoveBrowser(CefRefPtr browser); + CefRefPtr GetBrowserByID(int id); + BrowserList* GetBrowserList() { return &browserlist_; } + + // Retrieve the path at which cache data will be stored on disk. If empty, + // cache data will be stored in-memory. + const std::wstring& cache_path() { return cache_path_; } + + WebPreferences* web_preferences() + { + REQUIRE_UIT(); + return webprefs_; + } + + // The BrowserRequestContext object is managed by CefProcessIOThread. + void set_request_context(BrowserRequestContext* request_context) + { request_context_ = request_context; } + scoped_refptr request_context() + { return request_context_; } + +private: + // Manages the various process threads. + scoped_refptr process_; + + // Initialize the AtExitManager on the main application thread to avoid + // asserts and possible memory leaks. + base::AtExitManager at_exit_manager_; + + std::wstring cache_path_; + WebPreferences* webprefs_; + scoped_refptr request_context_; + + // Map of browsers that currently exist. + BrowserList browserlist_; + + // Used for assigning unique IDs to browser instances. + int next_browser_id_; +}; + +// Global context object pointer +extern CefRefPtr _Context; + +#endif // _CEF_CONTEXT_H diff --git a/libcef/cef_process.cc b/libcef/cef_process.cc index aa424f63a..a68dbbb61 100644 --- a/libcef/cef_process.cc +++ b/libcef/cef_process.cc @@ -1,128 +1,128 @@ -// 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 "cef_process.h" -#include "cef_process_io_thread.h" -#include "cef_process_sub_thread.h" -#include "cef_process_ui_thread.h" - -#include "base/thread.h" -#include "base/waitable_event.h" - -CefProcess* g_cef_process = NULL; - -// Class used to process events on the current message loop. -class CefMessageLoopForUI : public MessageLoopForUI -{ - typedef MessageLoopForUI inherited; - -public: - CefMessageLoopForUI() - { - } - - // 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(); - pump_->Quit(); - return valueToRet; - } - - void DoMessageLoopIteration() { - Run(NULL); - } - - private: - 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) { - g_cef_process = this; -} - -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(); - } - - g_cef_process = NULL; -} - -void CefProcess::DoMessageLoopIteration() { - DCHECK(CalledOnValidThread() && ui_message_loop_.get() != NULL); - ui_message_loop_->DoMessageLoopIteration(); -} - -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); -} +// 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 "cef_process.h" +#include "cef_process_io_thread.h" +#include "cef_process_sub_thread.h" +#include "cef_process_ui_thread.h" + +#include "base/thread.h" +#include "base/waitable_event.h" + +CefProcess* g_cef_process = NULL; + +// Class used to process events on the current message loop. +class CefMessageLoopForUI : public MessageLoopForUI +{ + typedef MessageLoopForUI inherited; + +public: + CefMessageLoopForUI() + { + } + + // 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(); + pump_->Quit(); + return valueToRet; + } + + void DoMessageLoopIteration() { + Run(NULL); + } + + private: + 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) { + g_cef_process = this; +} + +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(); + } + + g_cef_process = NULL; +} + +void CefProcess::DoMessageLoopIteration() { + DCHECK(CalledOnValidThread() && ui_message_loop_.get() != NULL); + ui_message_loop_->DoMessageLoopIteration(); +} + +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/libcef/cef_process_io_thread.cc b/libcef/cef_process_io_thread.cc index 54da2c92e..b4212d6bb 100644 --- a/libcef/cef_process_io_thread.cc +++ b/libcef/cef_process_io_thread.cc @@ -1,64 +1,64 @@ -// 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 "cef_process_io_thread.h" -#include "cef_context.h" -#include "browser_appcache_system.h" -#include "browser_resource_loader_bridge.h" -#include "browser_socket_stream_bridge.h" -#include "browser_webblobregistry_impl.h" - -#include "build/build_config.h" - -#if defined(OS_WIN) -#include -#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() { -#if defined(OS_WIN) - // Initializes the COM library on the current thread. - CoInitialize(NULL); -#endif - - request_context_ = new BrowserRequestContext(FilePath(_Context->cache_path()), - net::HttpCache::NORMAL, false); - _Context->set_request_context(request_context_); - - BrowserAppCacheSystem::InitializeOnIOThread(request_context_); - BrowserSocketStreamBridge::InitializeOnIOThread(request_context_); - 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(); - - BrowserSocketStreamBridge::Cleanup(); - BrowserWebBlobRegistryImpl::Cleanup(); - - _Context->set_request_context(NULL); - request_context_ = NULL; - -#if defined(OS_WIN) - // Closes the COM library on the current thread. CoInitialize must - // be balanced by a corresponding call to CoUninitialize. - CoUninitialize(); -#endif -} +// 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 "cef_process_io_thread.h" +#include "cef_context.h" +#include "browser_appcache_system.h" +#include "browser_resource_loader_bridge.h" +#include "browser_socket_stream_bridge.h" +#include "browser_webblobregistry_impl.h" + +#include "build/build_config.h" + +#if defined(OS_WIN) +#include +#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() { +#if defined(OS_WIN) + // Initializes the COM library on the current thread. + CoInitialize(NULL); +#endif + + request_context_ = new BrowserRequestContext(FilePath(_Context->cache_path()), + net::HttpCache::NORMAL, false); + _Context->set_request_context(request_context_); + + BrowserAppCacheSystem::InitializeOnIOThread(request_context_); + BrowserSocketStreamBridge::InitializeOnIOThread(request_context_); + 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(); + + BrowserSocketStreamBridge::Cleanup(); + BrowserWebBlobRegistryImpl::Cleanup(); + + _Context->set_request_context(NULL); + request_context_ = NULL; + +#if defined(OS_WIN) + // Closes the COM library on the current thread. CoInitialize must + // be balanced by a corresponding call to CoUninitialize. + CoUninitialize(); +#endif +} diff --git a/libcef/cef_process_sub_thread.cc b/libcef/cef_process_sub_thread.cc index 42e9f4f16..a61a1f2bd 100644 --- a/libcef/cef_process_sub_thread.cc +++ b/libcef/cef_process_sub_thread.cc @@ -1,44 +1,44 @@ -// 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 "cef_process_sub_thread.h" -#include "build/build_config.h" - -#if defined(OS_WIN) -#include -#endif - -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::Init() { -#if defined(OS_WIN) - // Initializes the COM library on the current thread. - CoInitialize(NULL); -#endif -} - -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(); - -#if defined(OS_WIN) - // Closes the COM library on the current thread. CoInitialize must - // be balanced by a corresponding call to CoUninitialize. - CoUninitialize(); -#endif -} +// 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 "cef_process_sub_thread.h" +#include "build/build_config.h" + +#if defined(OS_WIN) +#include +#endif + +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::Init() { +#if defined(OS_WIN) + // Initializes the COM library on the current thread. + CoInitialize(NULL); +#endif +} + +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(); + +#if defined(OS_WIN) + // Closes the COM library on the current thread. CoInitialize must + // be balanced by a corresponding call to CoUninitialize. + CoUninitialize(); +#endif +} diff --git a/libcef/cef_process_ui_thread.cc b/libcef/cef_process_ui_thread.cc index edb7f18dd..969db858e 100644 --- a/libcef/cef_process_ui_thread.cc +++ b/libcef/cef_process_ui_thread.cc @@ -1,178 +1,178 @@ -// 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 "cef_process_ui_thread.h" -#include "browser_impl.h" -#include "browser_resource_loader_bridge.h" -#include "browser_request_context.h" -#include "browser_webkit_glue.h" -#include "browser_webkit_init.h" -#include "cef_context.h" - -#include "base/command_line.h" -#include "base/i18n/icu_util.h" -#include "base/rand_util.h" -#include "base/stats_table.h" -#include "base/string_number_conversions.h" -#include "build/build_config.h" -#include "app/gfx/gl/gl_implementation.h" -#include "net/base/net_module.h" -#if defined(OS_WIN) -#include "net/socket/ssl_client_socket_nss_factory.h" -#endif -#include "webkit/blob/blob_storage_controller.h" -#include "webkit/blob/blob_url_request_job.h" -#include "webkit/extensions/v8/gc_extension.h" -#include "net/url_request/url_request.h" - -#if defined(OS_WIN) -#include -#include -#endif - -static const char* kStatsFilePrefix = "libcef_"; -static int kStatsFileThreads = 20; -static int kStatsFileCounters = 200; - -namespace { - -URLRequestJob* BlobURLRequestJobFactory(URLRequest* request, - const std::string& scheme) { - webkit_blob::BlobStorageController* blob_storage_controller = - static_cast(request->context())-> - blob_storage_controller(); - return new webkit_blob::BlobURLRequestJob( - request, - blob_storage_controller->GetBlobDataFromUrl(request->url()), - NULL); -} - -} // 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() { -#if defined(OS_WIN) - 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); -#endif - -#ifndef _DEBUG - // Only log error messages and above in release build. - logging::SetMinLogLevel(logging::LOG_ERROR); -#endif - - // Initialize the global CommandLine object. - CommandLine::Init(0, NULL); - - // Initialize WebKit. - webkit_init_ = new BrowserWebKitInit(); - - // Initialize WebKit encodings - webkit_glue::InitializeTextEncoding(); - - // Load ICU data tables. - bool ret = icu_util::Initialize(); - if(!ret) { -#if defined(OS_WIN) - MessageBox(NULL, L"Failed to load the required icudt38 library", - L"CEF Initialization Error", MB_ICONERROR | MB_OK); -#endif - return; - } - - // Config the network module so it has access to a limited set of resources. - net::NetModule::SetResourceProvider(webkit_glue::NetResourceProvider); - - // Load and initialize the stats table. Attempt to construct a somewhat - // unique name to isolate separate instances from each other. - statstable_ = new StatsTable( - kStatsFilePrefix + base::Uint64ToString(base::RandUint64()), - kStatsFileThreads, - kStatsFileCounters); - StatsTable::set_current(statstable_); - - // CEF always exposes the GC. - webkit_glue::SetJavaScriptFlags("--expose-gc"); - // Expose GCController to JavaScript. - WebKit::WebScriptController::registerExtension( - extensions_v8::GCExtension::Get()); - -#if defined(OS_WIN) - // Use NSS for SSL on Windows. TODO(wtc): this should eventually be hidden - // inside DefaultClientSocketFactory::CreateSSLClientSocket. - net::ClientSocketFactory::SetSSLClientSocketFactory( - net::SSLClientSocketNSSFactory); -#endif - - gfx::InitializeGLBindings(gfx::kGLImplementationOSMesaGL); - - URLRequest::RegisterProtocolFactory("blob", &BlobURLRequestJobFactory); -} - -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. - StatsTable::set_current(NULL); - delete statstable_; - statstable_ = NULL; - - // Shut down WebKit. - delete webkit_init_; - webkit_init_ = NULL; - -#if defined(OS_WIN) - // Uninitialize COM stuff - OleUninitialize(); - - // Closes the COM library on the current thread. CoInitialize must - // be balanced by a corresponding call to CoUninitialize. - CoUninitialize(); -#endif -} +// 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 "cef_process_ui_thread.h" +#include "browser_impl.h" +#include "browser_resource_loader_bridge.h" +#include "browser_request_context.h" +#include "browser_webkit_glue.h" +#include "browser_webkit_init.h" +#include "cef_context.h" + +#include "base/command_line.h" +#include "base/i18n/icu_util.h" +#include "base/rand_util.h" +#include "base/stats_table.h" +#include "base/string_number_conversions.h" +#include "build/build_config.h" +#include "app/gfx/gl/gl_implementation.h" +#include "net/base/net_module.h" +#if defined(OS_WIN) +#include "net/socket/ssl_client_socket_nss_factory.h" +#endif +#include "webkit/blob/blob_storage_controller.h" +#include "webkit/blob/blob_url_request_job.h" +#include "webkit/extensions/v8/gc_extension.h" +#include "net/url_request/url_request.h" + +#if defined(OS_WIN) +#include +#include +#endif + +static const char* kStatsFilePrefix = "libcef_"; +static int kStatsFileThreads = 20; +static int kStatsFileCounters = 200; + +namespace { + +URLRequestJob* BlobURLRequestJobFactory(URLRequest* request, + const std::string& scheme) { + webkit_blob::BlobStorageController* blob_storage_controller = + static_cast(request->context())-> + blob_storage_controller(); + return new webkit_blob::BlobURLRequestJob( + request, + blob_storage_controller->GetBlobDataFromUrl(request->url()), + NULL); +} + +} // 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() { +#if defined(OS_WIN) + 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); +#endif + +#ifndef _DEBUG + // Only log error messages and above in release build. + logging::SetMinLogLevel(logging::LOG_ERROR); +#endif + + // Initialize the global CommandLine object. + CommandLine::Init(0, NULL); + + // Initialize WebKit. + webkit_init_ = new BrowserWebKitInit(); + + // Initialize WebKit encodings + webkit_glue::InitializeTextEncoding(); + + // Load ICU data tables. + bool ret = icu_util::Initialize(); + if(!ret) { +#if defined(OS_WIN) + MessageBox(NULL, L"Failed to load the required icudt38 library", + L"CEF Initialization Error", MB_ICONERROR | MB_OK); +#endif + return; + } + + // Config the network module so it has access to a limited set of resources. + net::NetModule::SetResourceProvider(webkit_glue::NetResourceProvider); + + // Load and initialize the stats table. Attempt to construct a somewhat + // unique name to isolate separate instances from each other. + statstable_ = new StatsTable( + kStatsFilePrefix + base::Uint64ToString(base::RandUint64()), + kStatsFileThreads, + kStatsFileCounters); + StatsTable::set_current(statstable_); + + // CEF always exposes the GC. + webkit_glue::SetJavaScriptFlags("--expose-gc"); + // Expose GCController to JavaScript. + WebKit::WebScriptController::registerExtension( + extensions_v8::GCExtension::Get()); + +#if defined(OS_WIN) + // Use NSS for SSL on Windows. TODO(wtc): this should eventually be hidden + // inside DefaultClientSocketFactory::CreateSSLClientSocket. + net::ClientSocketFactory::SetSSLClientSocketFactory( + net::SSLClientSocketNSSFactory); +#endif + + gfx::InitializeGLBindings(gfx::kGLImplementationOSMesaGL); + + URLRequest::RegisterProtocolFactory("blob", &BlobURLRequestJobFactory); +} + +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. + StatsTable::set_current(NULL); + delete statstable_; + statstable_ = NULL; + + // Shut down WebKit. + delete webkit_init_; + webkit_init_ = NULL; + +#if defined(OS_WIN) + // Uninitialize COM stuff + OleUninitialize(); + + // Closes the COM library on the current thread. CoInitialize must + // be balanced by a corresponding call to CoUninitialize. + CoUninitialize(); +#endif +} diff --git a/libcef/cef_process_ui_thread.h b/libcef/cef_process_ui_thread.h index e7fd07ac4..ca3957c2d 100644 --- a/libcef/cef_process_ui_thread.h +++ b/libcef/cef_process_ui_thread.h @@ -1,42 +1,42 @@ -// 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_PROCESS_UI_THREAD -#define _CEF_PROCESS_UI_THREAD - -#include "base/basictypes.h" -#include "cef_thread.h" - -class BrowserWebKitInit; -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 CefThread { - public: - explicit CefProcessUIThread(); - CefProcessUIThread(MessageLoop* message_loop); - virtual ~CefProcessUIThread(); - - virtual void Init(); - virtual void CleanUp(); - - private: - StatsTable* statstable_; - - // WebKit implementation class. - BrowserWebKitInit* webkit_init_; - - DISALLOW_COPY_AND_ASSIGN(CefProcessUIThread); -}; - -#endif // _CEF_PROCESS_UI_THREAD +// 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_PROCESS_UI_THREAD +#define _CEF_PROCESS_UI_THREAD + +#include "base/basictypes.h" +#include "cef_thread.h" + +class BrowserWebKitInit; +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 CefThread { + public: + explicit CefProcessUIThread(); + CefProcessUIThread(MessageLoop* message_loop); + virtual ~CefProcessUIThread(); + + virtual void Init(); + virtual void CleanUp(); + + private: + StatsTable* statstable_; + + // WebKit implementation class. + BrowserWebKitInit* webkit_init_; + + DISALLOW_COPY_AND_ASSIGN(CefProcessUIThread); +}; + +#endif // _CEF_PROCESS_UI_THREAD diff --git a/libcef/cef_string.c b/libcef/cef_string.c index 4c048bb7f..c5d39aff0 100644 --- a/libcef/cef_string.c +++ b/libcef/cef_string.c @@ -1,163 +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. - -#include "include/cef_string.h" -#include -#include -#include - -typedef unsigned long dword_t; - -CEF_EXPORT size_t cef_string_length(cef_string_t str) -{ - dword_t* ptr; - - if(!str) - return 0; - - // The string length, in bytes, is placed in a dword_t immediately proceeding - // the string value. - ptr = (dword_t*)str; - ptr--; - - return (size_t)(*ptr / sizeof(wchar_t)); -} - -CEF_EXPORT cef_string_t cef_string_alloc(const wchar_t* str) -{ - if(!str) - return NULL; - - return cef_string_alloc_length(str, wcslen(str)); -} - -CEF_EXPORT cef_string_t cef_string_alloc_length(const wchar_t* str, - size_t len) -{ - dword_t size, *ptr; - wchar_t* newstr; - - // Check that the size can fit in a dword_t. - if(len >= (UINT_MAX - sizeof(wchar_t) - sizeof(dword_t)) / sizeof(wchar_t)) - return NULL; - - // Get the size of the string in bytes. - size = sizeof(wchar_t) * len; - - // Allocate the new buffer including space for the proceeding dword_t size - // value and the terminating nul. - ptr = (dword_t*)malloc(sizeof(dword_t) + size + sizeof(wchar_t)); - if(!ptr) - return NULL; - - // Set the size as the first value in the newly allocated memory and - // increment to the string location. - *ptr = size; - ptr++; - - if(str != NULL) - { - // Copy the string to the buffer. - memcpy(ptr, str, size); - } - else - { - // Initialize the string to zeros. - memset(ptr, 0, size); - } - - newstr = (wchar_t*)ptr; - - // Nul-terminate the string. - newstr[len] = '\0'; - - return (cef_string_t)newstr; -} - -CEF_EXPORT int cef_string_realloc(cef_string_t* oldstr, const wchar_t* newstr) -{ - if(!oldstr) - return 0; - - // Free the old string. - cef_string_free(*oldstr); - - // Copy the new string. - *oldstr = cef_string_alloc(newstr); - - return 1; -} - -CEF_EXPORT int cef_string_realloc_length(cef_string_t* oldstr, - const wchar_t* newstr, - size_t len) -{ - if(!oldstr) - return 0; - - // Check that the size can fit in a dword_t. - if(len >= (UINT_MAX - sizeof(wchar_t) - sizeof(dword_t)) / sizeof(wchar_t)) - return 0; - - if(*oldstr) - { - dword_t newsize, *oldptr, *newptr; - - // Get the new size of the string in bytes. - newsize = sizeof(wchar_t) * len; - - // Adjust the pointer to account for the dword_t immediately proceeding the - // string value. - oldptr = (dword_t*)*oldstr; - oldptr--; - - // Re-allocate the buffer including space for the proceeding dword_t size - // value and the terminating nul. - newptr = (dword_t*)realloc( - oldptr, sizeof(dword_t) + newsize + sizeof(wchar_t)); - if(!newptr) - return 0; - - // Set the size as the first value in the newly allocated memory and - // increment to the string location. - *newptr = newsize; - newptr++; - - // Set the string pointer to the beginning on the string in the newly - // allocated memory. - *oldstr = (cef_string_t)newptr; - - if(newstr) - { - // Copy the new string value. Use of memmove() ensures that any - // overlapping region in the old string will be copied before being - // overwritten. - memmove(*oldstr, newstr, newsize); - - // Nul-terminate the string. - *oldstr[len] = '\0'; - } - } - else - { - // Allocate the string. - *oldstr = cef_string_alloc_length(newstr, len); - } - - return 1; -} - -CEF_EXPORT void cef_string_free(cef_string_t str) -{ - dword_t* ptr; - - if(!str) - return; - - // The size is placed in a dword_t immediately proceeding the string value. - ptr = (dword_t*)str; - ptr--; - - free(ptr); -} +// 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/cef_string.h" +#include +#include +#include + +typedef unsigned long dword_t; + +CEF_EXPORT size_t cef_string_length(cef_string_t str) +{ + dword_t* ptr; + + if(!str) + return 0; + + // The string length, in bytes, is placed in a dword_t immediately proceeding + // the string value. + ptr = (dword_t*)str; + ptr--; + + return (size_t)(*ptr / sizeof(wchar_t)); +} + +CEF_EXPORT cef_string_t cef_string_alloc(const wchar_t* str) +{ + if(!str) + return NULL; + + return cef_string_alloc_length(str, wcslen(str)); +} + +CEF_EXPORT cef_string_t cef_string_alloc_length(const wchar_t* str, + size_t len) +{ + dword_t size, *ptr; + wchar_t* newstr; + + // Check that the size can fit in a dword_t. + if(len >= (UINT_MAX - sizeof(wchar_t) - sizeof(dword_t)) / sizeof(wchar_t)) + return NULL; + + // Get the size of the string in bytes. + size = sizeof(wchar_t) * len; + + // Allocate the new buffer including space for the proceeding dword_t size + // value and the terminating nul. + ptr = (dword_t*)malloc(sizeof(dword_t) + size + sizeof(wchar_t)); + if(!ptr) + return NULL; + + // Set the size as the first value in the newly allocated memory and + // increment to the string location. + *ptr = size; + ptr++; + + if(str != NULL) + { + // Copy the string to the buffer. + memcpy(ptr, str, size); + } + else + { + // Initialize the string to zeros. + memset(ptr, 0, size); + } + + newstr = (wchar_t*)ptr; + + // Nul-terminate the string. + newstr[len] = '\0'; + + return (cef_string_t)newstr; +} + +CEF_EXPORT int cef_string_realloc(cef_string_t* oldstr, const wchar_t* newstr) +{ + if(!oldstr) + return 0; + + // Free the old string. + cef_string_free(*oldstr); + + // Copy the new string. + *oldstr = cef_string_alloc(newstr); + + return 1; +} + +CEF_EXPORT int cef_string_realloc_length(cef_string_t* oldstr, + const wchar_t* newstr, + size_t len) +{ + if(!oldstr) + return 0; + + // Check that the size can fit in a dword_t. + if(len >= (UINT_MAX - sizeof(wchar_t) - sizeof(dword_t)) / sizeof(wchar_t)) + return 0; + + if(*oldstr) + { + dword_t newsize, *oldptr, *newptr; + + // Get the new size of the string in bytes. + newsize = sizeof(wchar_t) * len; + + // Adjust the pointer to account for the dword_t immediately proceeding the + // string value. + oldptr = (dword_t*)*oldstr; + oldptr--; + + // Re-allocate the buffer including space for the proceeding dword_t size + // value and the terminating nul. + newptr = (dword_t*)realloc( + oldptr, sizeof(dword_t) + newsize + sizeof(wchar_t)); + if(!newptr) + return 0; + + // Set the size as the first value in the newly allocated memory and + // increment to the string location. + *newptr = newsize; + newptr++; + + // Set the string pointer to the beginning on the string in the newly + // allocated memory. + *oldstr = (cef_string_t)newptr; + + if(newstr) + { + // Copy the new string value. Use of memmove() ensures that any + // overlapping region in the old string will be copied before being + // overwritten. + memmove(*oldstr, newstr, newsize); + + // Nul-terminate the string. + *oldstr[len] = '\0'; + } + } + else + { + // Allocate the string. + *oldstr = cef_string_alloc_length(newstr, len); + } + + return 1; +} + +CEF_EXPORT void cef_string_free(cef_string_t str) +{ + dword_t* ptr; + + if(!str) + return; + + // The size is placed in a dword_t immediately proceeding the string value. + ptr = (dword_t*)str; + ptr--; + + free(ptr); +} diff --git a/libcef/cef_string_list.cc b/libcef/cef_string_list.cc index e3ff17477..acd4c78fe 100644 --- a/libcef/cef_string_list.cc +++ b/libcef/cef_string_list.cc @@ -1,55 +1,55 @@ -// 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/cef_string_list.h" -#include "base/logging.h" -#include - - -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 = (StringList*)list; - return impl->size(); -} - -CEF_EXPORT cef_string_t cef_string_list_value(cef_string_list_t list, int index) -{ - DCHECK(list); - StringList* impl = (StringList*)list; - DCHECK(index >= 0 && index < (int)impl->size()); - if(index < 0 || index >= (int)impl->size()) - return NULL; - return cef_string_alloc((*impl)[index].c_str()); -} - -CEF_EXPORT void cef_string_list_append(cef_string_list_t list, const wchar_t* value) -{ - DCHECK(list); - StringList* impl = (StringList*)list; - std::wstring valstr; - if(value) - valstr = value; - impl->push_back(valstr); -} - -CEF_EXPORT void cef_string_list_clear(cef_string_list_t list) -{ - DCHECK(list); - StringList* impl = (StringList*)list; - impl->clear(); -} - -CEF_EXPORT void cef_string_list_free(cef_string_list_t list) -{ - DCHECK(list); - delete (StringList*)list; -} +// 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/cef_string_list.h" +#include "base/logging.h" +#include + + +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 = (StringList*)list; + return impl->size(); +} + +CEF_EXPORT cef_string_t cef_string_list_value(cef_string_list_t list, int index) +{ + DCHECK(list); + StringList* impl = (StringList*)list; + DCHECK(index >= 0 && index < (int)impl->size()); + if(index < 0 || index >= (int)impl->size()) + return NULL; + return cef_string_alloc((*impl)[index].c_str()); +} + +CEF_EXPORT void cef_string_list_append(cef_string_list_t list, const wchar_t* value) +{ + DCHECK(list); + StringList* impl = (StringList*)list; + std::wstring valstr; + if(value) + valstr = value; + impl->push_back(valstr); +} + +CEF_EXPORT void cef_string_list_clear(cef_string_list_t list) +{ + DCHECK(list); + StringList* impl = (StringList*)list; + impl->clear(); +} + +CEF_EXPORT void cef_string_list_free(cef_string_list_t list) +{ + DCHECK(list); + delete (StringList*)list; +} diff --git a/libcef/cef_string_map.cc b/libcef/cef_string_map.cc index 44ccdc980..244a2393c 100644 --- a/libcef/cef_string_map.cc +++ b/libcef/cef_string_map.cc @@ -1,92 +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/cef_string_map.h" -#include "base/logging.h" -#include - - -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 = (StringMap*)map; - return impl->size(); -} - -CEF_EXPORT cef_string_t cef_string_map_find(cef_string_map_t map, - const wchar_t* key) -{ - DCHECK(map); - StringMap* impl = (StringMap*)map; - std::wstring keystr; - if(key) - keystr = key; - StringMap::const_iterator it = impl->find(keystr); - if(it == impl->end()) - return NULL; - return cef_string_alloc(it->second.c_str()); -} - -CEF_EXPORT cef_string_t cef_string_map_key(cef_string_map_t map, int index) -{ - DCHECK(map); - StringMap* impl = (StringMap*)map; - DCHECK(index >= 0 && index < (int)impl->size()); - if(index < 0 || index >= (int)impl->size()) - return NULL; - StringMap::const_iterator it = impl->begin(); - for(int ct = 0; it != impl->end(); ++it, ct++) { - if(ct == index) - return cef_string_alloc(it->first.c_str()); - } - return NULL; -} - -CEF_EXPORT cef_string_t cef_string_map_value(cef_string_map_t map, int index) -{ - DCHECK(map); - StringMap* impl = (StringMap*)map; - DCHECK(index >= 0 && index < (int)impl->size()); - if(index < 0 || index >= (int)impl->size()) - return NULL; - StringMap::const_iterator it = impl->begin(); - for(int ct = 0; it != impl->end(); ++it, ct++) { - if(ct == index) - return cef_string_alloc(it->second.c_str()); - } - return NULL; -} - -CEF_EXPORT void cef_string_map_append(cef_string_map_t map, const wchar_t* key, - const wchar_t* value) -{ - DCHECK(map); - StringMap* impl = (StringMap*)map; - std::wstring keystr, valstr; - if(key) - keystr = key; - if(value) - valstr = value; - impl->insert(std::pair(keystr, valstr)); -} - -CEF_EXPORT void cef_string_map_clear(cef_string_map_t map) -{ - DCHECK(map); - StringMap* impl = (StringMap*)map; - impl->clear(); -} - -CEF_EXPORT void cef_string_map_free(cef_string_map_t map) -{ - DCHECK(map); - delete (StringMap*)map; -} +// 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/cef_string_map.h" +#include "base/logging.h" +#include + + +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 = (StringMap*)map; + return impl->size(); +} + +CEF_EXPORT cef_string_t cef_string_map_find(cef_string_map_t map, + const wchar_t* key) +{ + DCHECK(map); + StringMap* impl = (StringMap*)map; + std::wstring keystr; + if(key) + keystr = key; + StringMap::const_iterator it = impl->find(keystr); + if(it == impl->end()) + return NULL; + return cef_string_alloc(it->second.c_str()); +} + +CEF_EXPORT cef_string_t cef_string_map_key(cef_string_map_t map, int index) +{ + DCHECK(map); + StringMap* impl = (StringMap*)map; + DCHECK(index >= 0 && index < (int)impl->size()); + if(index < 0 || index >= (int)impl->size()) + return NULL; + StringMap::const_iterator it = impl->begin(); + for(int ct = 0; it != impl->end(); ++it, ct++) { + if(ct == index) + return cef_string_alloc(it->first.c_str()); + } + return NULL; +} + +CEF_EXPORT cef_string_t cef_string_map_value(cef_string_map_t map, int index) +{ + DCHECK(map); + StringMap* impl = (StringMap*)map; + DCHECK(index >= 0 && index < (int)impl->size()); + if(index < 0 || index >= (int)impl->size()) + return NULL; + StringMap::const_iterator it = impl->begin(); + for(int ct = 0; it != impl->end(); ++it, ct++) { + if(ct == index) + return cef_string_alloc(it->second.c_str()); + } + return NULL; +} + +CEF_EXPORT void cef_string_map_append(cef_string_map_t map, const wchar_t* key, + const wchar_t* value) +{ + DCHECK(map); + StringMap* impl = (StringMap*)map; + std::wstring keystr, valstr; + if(key) + keystr = key; + if(value) + valstr = value; + impl->insert(std::pair(keystr, valstr)); +} + +CEF_EXPORT void cef_string_map_clear(cef_string_map_t map) +{ + DCHECK(map); + StringMap* impl = (StringMap*)map; + impl->clear(); +} + +CEF_EXPORT void cef_string_map_free(cef_string_map_t map) +{ + DCHECK(map); + delete (StringMap*)map; +} diff --git a/libcef/cef_thread.h b/libcef/cef_thread.h index eed4ff1ed..488e427ff 100644 --- a/libcef/cef_thread.h +++ b/libcef/cef_thread.h @@ -1,185 +1,185 @@ -// 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_THREAD_H -#define _CEF_THREAD_H - -#include "base/lock.h" -#include "base/task.h" -#include "base/thread.h" - -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 if 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, - Task* task); - static bool PostDelayedTask(ID identifier, - const tracked_objects::Location& from_here, - Task* task, - int64 delay_ms); - static bool PostNonNestableTask(ID identifier, - const tracked_objects::Location& from_here, - Task* task); - static bool PostNonNestableDelayedTask( - ID identifier, - const tracked_objects::Location& from_here, - Task* task, - int64 delay_ms); - - template - static bool DeleteSoon(ID identifier, - const tracked_objects::Location& from_here, - T* object) { - return PostNonNestableTask( - identifier, from_here, new DeleteTask(object)); - } - - template - static bool ReleaseSoon(ID identifier, - const tracked_objects::Location& from_here, - T* object) { - return PostNonNestableTask( - identifier, from_here, new ReleaseTask(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 { }; - - private: - // Common initialization code for the constructors. - void Initialize(); - - static bool PostTaskHelper( - ID identifier, - const tracked_objects::Location& from_here, - Task* 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 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]; -}; - -#define REQUIRE_UIT() DCHECK(CefThread::CurrentlyOn(CefThread::UI)) -#define REQUIRE_IOT() DCHECK(CefThread::CurrentlyOn(CefThread::IO)) - -#endif // _CEF_THREAD_H +// 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_THREAD_H +#define _CEF_THREAD_H + +#include "base/lock.h" +#include "base/task.h" +#include "base/thread.h" + +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 if 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, + Task* task); + static bool PostDelayedTask(ID identifier, + const tracked_objects::Location& from_here, + Task* task, + int64 delay_ms); + static bool PostNonNestableTask(ID identifier, + const tracked_objects::Location& from_here, + Task* task); + static bool PostNonNestableDelayedTask( + ID identifier, + const tracked_objects::Location& from_here, + Task* task, + int64 delay_ms); + + template + static bool DeleteSoon(ID identifier, + const tracked_objects::Location& from_here, + T* object) { + return PostNonNestableTask( + identifier, from_here, new DeleteTask(object)); + } + + template + static bool ReleaseSoon(ID identifier, + const tracked_objects::Location& from_here, + T* object) { + return PostNonNestableTask( + identifier, from_here, new ReleaseTask(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 { }; + + private: + // Common initialization code for the constructors. + void Initialize(); + + static bool PostTaskHelper( + ID identifier, + const tracked_objects::Location& from_here, + Task* 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 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]; +}; + +#define REQUIRE_UIT() DCHECK(CefThread::CurrentlyOn(CefThread::UI)) +#define REQUIRE_IOT() DCHECK(CefThread::CurrentlyOn(CefThread::IO)) + +#endif // _CEF_THREAD_H diff --git a/libcef/printing/print_settings.cc b/libcef/printing/print_settings.cc index 85b5d270b..2f4a8021a 100644 --- a/libcef/printing/print_settings.cc +++ b/libcef/printing/print_settings.cc @@ -1,265 +1,265 @@ -// 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 "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(base::LINKER_INITIALIZED); - -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 std::wstring& new_device_name, - bool print_selection_only, - bool print_to_file) { - DCHECK(hdc); - printer_name_ = 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 - +// 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 "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(base::LINKER_INITIALIZED); + +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 std::wstring& new_device_name, + bool print_selection_only, + bool print_to_file) { + DCHECK(hdc); + printer_name_ = 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/libcef/printing/print_settings.h b/libcef/printing/print_settings.h index c36e27f9b..fa495dde6 100644 --- a/libcef/printing/print_settings.h +++ b/libcef/printing/print_settings.h @@ -1,178 +1,178 @@ -// 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 _PRINTING_PRINT_SETTINGS_H -#define _PRINTING_PRINT_SETTINGS_H - -#include "include/cef_types.h" - -#include "gfx/rect.h" -#include "printing/page_range.h" -#include "printing/page_setup.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 std::wstring& 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 std::wstring& printer_name() const { return printer_name_; } - void set_device_name(const std::wstring& device_name) { - device_name_ = device_name; - } - const std::wstring& 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. - std::wstring printer_name_; - - // Printer device name as opened by the OS. - std::wstring 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 // _PRINTING_PRINT_SETTINGS_H - +// 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 _PRINTING_PRINT_SETTINGS_H +#define _PRINTING_PRINT_SETTINGS_H + +#include "include/cef_types.h" + +#include "gfx/rect.h" +#include "printing/page_range.h" +#include "printing/page_setup.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 std::wstring& 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 std::wstring& printer_name() const { return printer_name_; } + void set_device_name(const std::wstring& device_name) { + device_name_ = device_name; + } + const std::wstring& 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. + std::wstring printer_name_; + + // Printer device name as opened by the OS. + std::wstring 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 // _PRINTING_PRINT_SETTINGS_H + diff --git a/libcef/printing/win_printing_context.cc b/libcef/printing/win_printing_context.cc index 367c8299f..7fa40ff30 100644 --- a/libcef/printing/win_printing_context.cc +++ b/libcef/printing/win_printing_context.cc @@ -1,599 +1,599 @@ -// 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 "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/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(abs(settings_.page_measurements.page_length), - 10.0 * settings_.desired_dpi, - static_cast(kHundrethsMMPerInch)) + 0.5); - dev_mode.dmPaperWidth = static_cast( - ConvertUnitDouble(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(std::wstring(printername), false); - } - return FAILED; -} - -PrintingContext::Result PrintingContext::InitWithSettings( - const PrintSettings& settings) { - DCHECK(!in_print_job_); - settings_ = settings; - - return Init(settings_.device_name().c_str(), true); -} - -PrintingContext::Result PrintingContext::Init(const std::wstring& device_name, - bool adjust_dev_mode) { - HANDLE printer; - if (!OpenPrinter(const_cast(device_name.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 std::wstring& 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) }; - di.lpszDocName = document_name.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 std::wstring& new_device_name, - const PRINTPAGERANGE* ranges, - int number_ranges, - bool selection_only, - bool to_file) { - skia::PlatformDevice::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 std::wstring& 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 std::wstring& printer_name, - const DEVMODE* dev_mode) { - hdc_ = CreateDC(L"WINSPOOL", printer_name.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, - dialog_options.lpPageRanges, - dialog_options.nPageRanges, - 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 - +// 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 "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/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(abs(settings_.page_measurements.page_length), + 10.0 * settings_.desired_dpi, + static_cast(kHundrethsMMPerInch)) + 0.5); + dev_mode.dmPaperWidth = static_cast( + ConvertUnitDouble(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(std::wstring(printername), false); + } + return FAILED; +} + +PrintingContext::Result PrintingContext::InitWithSettings( + const PrintSettings& settings) { + DCHECK(!in_print_job_); + settings_ = settings; + + return Init(settings_.device_name().c_str(), true); +} + +PrintingContext::Result PrintingContext::Init(const std::wstring& device_name, + bool adjust_dev_mode) { + HANDLE printer; + if (!OpenPrinter(const_cast(device_name.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 std::wstring& 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) }; + di.lpszDocName = document_name.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 std::wstring& new_device_name, + const PRINTPAGERANGE* ranges, + int number_ranges, + bool selection_only, + bool to_file) { + skia::PlatformDevice::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 std::wstring& 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 std::wstring& printer_name, + const DEVMODE* dev_mode) { + hdc_ = CreateDC(L"WINSPOOL", printer_name.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, + dialog_options.lpPageRanges, + dialog_options.nPageRanges, + 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/libcef/printing/win_printing_context.h b/libcef/printing/win_printing_context.h index a58529d2b..79d5f5423 100644 --- a/libcef/printing/win_printing_context.h +++ b/libcef/printing/win_printing_context.h @@ -1,151 +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 _PRINTING_WIN_PRINTING_CONTEXT_H -#define _PRINTING_WIN_PRINTING_CONTEXT_H - -#include "print_settings.h" - -#include -#include -#include - -#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 std::wstring& 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 std::wstring& 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 std::wstring& device_name, - bool adjust_dev_mode); - - // Allocates the HDC for a specific DEVMODE. - bool AllocateContext(const std::wstring& 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 std::wstring& 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 // _PRINTING_WIN_PRINTING_CONTEXT_H +// 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 _PRINTING_WIN_PRINTING_CONTEXT_H +#define _PRINTING_WIN_PRINTING_CONTEXT_H + +#include "print_settings.h" + +#include +#include +#include + +#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 std::wstring& 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 std::wstring& 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 std::wstring& device_name, + bool adjust_dev_mode); + + // Allocates the HDC for a specific DEVMODE. + bool AllocateContext(const std::wstring& 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 std::wstring& 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 // _PRINTING_WIN_PRINTING_CONTEXT_H diff --git a/libcef/request_impl.cc b/libcef/request_impl.cc index bb48537d9..7eeea485c 100644 --- a/libcef/request_impl.cc +++ b/libcef/request_impl.cc @@ -1,524 +1,524 @@ -// 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 "request_impl.h" -#include "browser_webkit_glue.h" - -#include "base/logging.h" -#include "base/utf_string_conversions.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_util.h" -#include "net/url_request/url_request.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPHeaderVisitor.h" - -using net::HttpResponseHeaders; - - -CefRefPtr CefRequest::CreateRequest() -{ - CefRefPtr request(new CefRequestImpl()); - return request; -} - -CefRequestImpl::CefRequestImpl() -{ -} - -std::wstring CefRequestImpl::GetURL() -{ - Lock(); - std::wstring url = url_; - Unlock(); - return url; -} - -void CefRequestImpl::SetURL(const std::wstring& url) -{ - Lock(); - url_ = url; - Unlock(); -} - -std::wstring CefRequestImpl::GetMethod() -{ - Lock(); - std::wstring method = method_; - Unlock(); - return method; -} - -void CefRequestImpl::SetMethod(const std::wstring& method) -{ - Lock(); - method_ = method; - Unlock(); -} - -CefRefPtr CefRequestImpl::GetPostData() -{ - Lock(); - CefRefPtr postData = postdata_; - Unlock(); - return postData; -} - -void CefRequestImpl::SetPostData(CefRefPtr postData) -{ - Lock(); - postdata_ = postData; - Unlock(); -} - -void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap) -{ - Lock(); - headerMap = headermap_; - Unlock(); -} - -void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap) -{ - Lock(); - headermap_ = headerMap; - Unlock(); -} - -void CefRequestImpl::Set(const std::wstring& url, - const std::wstring& method, - CefRefPtr postData, - const HeaderMap& headerMap) -{ - Lock(); - url_ = url; - method_ = method; - postdata_ = postData; - headermap_ = headerMap; - Unlock(); -} - -void CefRequestImpl::Set(URLRequest* request) -{ - SetURL(UTF8ToWide(request->url().spec())); - SetMethod(UTF8ToWide(request->method())); - - // Transfer request headers - HeaderMap headerMap; - GetHeaderMap(request->extra_request_headers(), headerMap); - headerMap.insert( - std::make_pair(L"Referrer", UTF8ToWide(request->referrer()))); - SetHeaderMap(headerMap); - - // Transfer post data, if any - net::UploadData* data = request->get_upload(); - if (data) { - CefRefPtr postdata(CefPostData::CreatePostData()); - static_cast(postdata.get())->Set(*data); - SetPostData(postdata); - } -} - - -void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers, HeaderMap& map) -{ - net::HttpRequestHeaders::Iterator it(headers); - do { - map[UTF8ToWide(it.name())] = UTF8ToWide(it.value()); - } while (it.GetNext()); -} - -void CefRequestImpl::GetHeaderMap(const WebKit::WebURLRequest& request, - HeaderMap& map) -{ - class CefHTTPHeaderVisitor : public WebKit::WebHTTPHeaderVisitor { - public: - CefHTTPHeaderVisitor(HeaderMap* map) : map_(map) {} - - virtual void visitHeader(const WebKit::WebString& name, - const WebKit::WebString& value) { - map_->insert( - std::make_pair( - UTF8ToWide(webkit_glue::WebStringToStdString(name)), - UTF8ToWide(webkit_glue::WebStringToStdString(value)))); - } - - private: - HeaderMap* map_; - }; - - CefHTTPHeaderVisitor visitor(&map); - request.visitHTTPHeaderFields(&visitor); -} - -void CefRequestImpl::SetHeaderMap(const HeaderMap& map, - WebKit::WebURLRequest& request) -{ - HeaderMap::const_iterator it = map.begin(); - for(; it != map.end(); ++it) { - request.setHTTPHeaderField( - webkit_glue::StdStringToWebString(WideToUTF8(it->first.c_str())), - webkit_glue::StdStringToWebString(WideToUTF8(it->second.c_str()))); - } -} - -std::string CefRequestImpl::GenerateHeaders(const HeaderMap& map) -{ - std::string headers; - - for(HeaderMap::const_iterator header = map.begin(); - header != map.end(); - ++header) { - const std::wstring& key = header->first; - const std::wstring& value = header->second; - - if(!key.empty()) { - // Delimit with "\r\n". - if(!headers.empty()) - headers += "\r\n"; - - headers += WideToUTF8(key) + ": " + WideToUTF8(value); - } - } - - return headers; -} - -void CefRequestImpl::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(UTF8ToWide(name), UTF8ToWide(value))); -} - -CefRefPtr CefPostData::CreatePostData() -{ - CefRefPtr postdata(new CefPostDataImpl()); - return postdata; -} - -CefPostDataImpl::CefPostDataImpl() -{ -} - -size_t CefPostDataImpl::GetElementCount() -{ - Lock(); - size_t ct = elements_.size(); - Unlock(); - return ct; -} - -void CefPostDataImpl::GetElements(ElementVector& elements) -{ - Lock(); - elements = elements_; - Unlock(); -} - -bool CefPostDataImpl::RemoveElement(CefRefPtr element) -{ - bool deleted = false; - - Lock(); - - ElementVector::iterator it = elements_.begin(); - for(; it != elements_.end(); ++it) { - if(it->get() == element.get()) { - elements_.erase(it); - deleted = true; - break; - } - } - - Unlock(); - - return deleted; -} - -bool CefPostDataImpl::AddElement(CefRefPtr element) -{ - bool found = false; - - Lock(); - - // 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); - - Unlock(); - return !found; -} - -void CefPostDataImpl::RemoveElements() -{ - Lock(); - elements_.clear(); - Unlock(); -} - -void CefPostDataImpl::Set(net::UploadData& data) -{ - Lock(); - - 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); - } - - Unlock(); -} - -void CefPostDataImpl::Get(net::UploadData& data) -{ - Lock(); - - 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); - - Unlock(); -} - -void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data) -{ - Lock(); - - 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); - } - } - - Unlock(); -} - -void CefPostDataImpl::Get(WebKit::WebHTTPBody& data) -{ - Lock(); - - 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(); - } - } - - Unlock(); -} - -CefRefPtr CefPostDataElement::CreatePostDataElement() -{ - CefRefPtr element(new CefPostDataElementImpl()); - return element; -} - -CefPostDataElementImpl::CefPostDataElementImpl() -{ - type_ = PDE_TYPE_EMPTY; -} - -CefPostDataElementImpl::~CefPostDataElementImpl() -{ - SetToEmpty(); -} - -void CefPostDataElementImpl::SetToEmpty() -{ - Lock(); - if(type_ == PDE_TYPE_BYTES) - free(data_.bytes.bytes); - else if(type_ == PDE_TYPE_FILE) - free(data_.filename); - type_ = PDE_TYPE_EMPTY; - Unlock(); -} - -void CefPostDataElementImpl::SetToFile(const std::wstring& fileName) -{ - Lock(); - // Clear any data currently in the element - SetToEmpty(); - - // Assign the new file name - size_t size = fileName.size(); - wchar_t* data = static_cast(malloc((size + 1) * sizeof(wchar_t))); - DCHECK(data != NULL); - if(data == NULL) - return; - - memcpy(static_cast(data), static_cast(fileName.c_str()), - size * sizeof(wchar_t)); - data[size] = 0; - - // Assign the new data - type_ = PDE_TYPE_FILE; - data_.filename = data; - Unlock(); -} - -void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes) -{ - Lock(); - // 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; - Unlock(); -} - -CefPostDataElement::Type CefPostDataElementImpl::GetType() -{ - Lock(); - CefPostDataElement::Type type = type_; - Unlock(); - return type; -} - -std::wstring CefPostDataElementImpl::GetFile() -{ - Lock(); - DCHECK(type_ == PDE_TYPE_FILE); - std::wstring filename; - if(type_ == PDE_TYPE_FILE) - filename = data_.filename; - Unlock(); - return filename; -} - -size_t CefPostDataElementImpl::GetBytesCount() -{ - Lock(); - DCHECK(type_ == PDE_TYPE_BYTES); - size_t size = 0; - if(type_ == PDE_TYPE_BYTES) - size = data_.bytes.size; - Unlock(); - return size; -} - -size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes) -{ - Lock(); - DCHECK(type_ == PDE_TYPE_BYTES); - size_t rv = 0; - if(type_ == PDE_TYPE_BYTES) { - rv = (size < data_.bytes.size ? size : data_.bytes.size); - memcpy(bytes, data_.bytes.bytes, rv); - } - Unlock(); - return rv; -} - -void CefPostDataElementImpl::Set(const net::UploadData::Element& element) -{ - Lock(); - - 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(); - } - - Unlock(); -} - -void CefPostDataElementImpl::Get(net::UploadData::Element& element) -{ - Lock(); - - if(type_ == PDE_TYPE_BYTES) { - element.SetToBytes(static_cast(data_.bytes.bytes), data_.bytes.size); - } else if(type_ == PDE_TYPE_FILE) { - element.SetToFilePath(FilePath(data_.filename)); - } else { - NOTREACHED(); - } - - Unlock(); -} - -void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element) -{ - Lock(); - - 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(UTF8ToWide(webkit_glue::WebStringToStdString(element.filePath))); - } else { - NOTREACHED(); - } - - Unlock(); -} - -void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element) -{ - Lock(); - - 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( - webkit_glue::StdStringToWebString(WideToUTF8(data_.filename))); - } else { - NOTREACHED(); - } - - Unlock(); -} +// 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 "request_impl.h" +#include "browser_webkit_glue.h" + +#include "base/logging.h" +#include "base/utf_string_conversions.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_util.h" +#include "net/url_request/url_request.h" +#include "third_party/WebKit/WebKit/chromium/public/WebHTTPHeaderVisitor.h" + +using net::HttpResponseHeaders; + + +CefRefPtr CefRequest::CreateRequest() +{ + CefRefPtr request(new CefRequestImpl()); + return request; +} + +CefRequestImpl::CefRequestImpl() +{ +} + +std::wstring CefRequestImpl::GetURL() +{ + Lock(); + std::wstring url = url_; + Unlock(); + return url; +} + +void CefRequestImpl::SetURL(const std::wstring& url) +{ + Lock(); + url_ = url; + Unlock(); +} + +std::wstring CefRequestImpl::GetMethod() +{ + Lock(); + std::wstring method = method_; + Unlock(); + return method; +} + +void CefRequestImpl::SetMethod(const std::wstring& method) +{ + Lock(); + method_ = method; + Unlock(); +} + +CefRefPtr CefRequestImpl::GetPostData() +{ + Lock(); + CefRefPtr postData = postdata_; + Unlock(); + return postData; +} + +void CefRequestImpl::SetPostData(CefRefPtr postData) +{ + Lock(); + postdata_ = postData; + Unlock(); +} + +void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap) +{ + Lock(); + headerMap = headermap_; + Unlock(); +} + +void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap) +{ + Lock(); + headermap_ = headerMap; + Unlock(); +} + +void CefRequestImpl::Set(const std::wstring& url, + const std::wstring& method, + CefRefPtr postData, + const HeaderMap& headerMap) +{ + Lock(); + url_ = url; + method_ = method; + postdata_ = postData; + headermap_ = headerMap; + Unlock(); +} + +void CefRequestImpl::Set(URLRequest* request) +{ + SetURL(UTF8ToWide(request->url().spec())); + SetMethod(UTF8ToWide(request->method())); + + // Transfer request headers + HeaderMap headerMap; + GetHeaderMap(request->extra_request_headers(), headerMap); + headerMap.insert( + std::make_pair(L"Referrer", UTF8ToWide(request->referrer()))); + SetHeaderMap(headerMap); + + // Transfer post data, if any + net::UploadData* data = request->get_upload(); + if (data) { + CefRefPtr postdata(CefPostData::CreatePostData()); + static_cast(postdata.get())->Set(*data); + SetPostData(postdata); + } +} + + +void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers, HeaderMap& map) +{ + net::HttpRequestHeaders::Iterator it(headers); + do { + map[UTF8ToWide(it.name())] = UTF8ToWide(it.value()); + } while (it.GetNext()); +} + +void CefRequestImpl::GetHeaderMap(const WebKit::WebURLRequest& request, + HeaderMap& map) +{ + class CefHTTPHeaderVisitor : public WebKit::WebHTTPHeaderVisitor { + public: + CefHTTPHeaderVisitor(HeaderMap* map) : map_(map) {} + + virtual void visitHeader(const WebKit::WebString& name, + const WebKit::WebString& value) { + map_->insert( + std::make_pair( + UTF8ToWide(webkit_glue::WebStringToStdString(name)), + UTF8ToWide(webkit_glue::WebStringToStdString(value)))); + } + + private: + HeaderMap* map_; + }; + + CefHTTPHeaderVisitor visitor(&map); + request.visitHTTPHeaderFields(&visitor); +} + +void CefRequestImpl::SetHeaderMap(const HeaderMap& map, + WebKit::WebURLRequest& request) +{ + HeaderMap::const_iterator it = map.begin(); + for(; it != map.end(); ++it) { + request.setHTTPHeaderField( + webkit_glue::StdStringToWebString(WideToUTF8(it->first.c_str())), + webkit_glue::StdStringToWebString(WideToUTF8(it->second.c_str()))); + } +} + +std::string CefRequestImpl::GenerateHeaders(const HeaderMap& map) +{ + std::string headers; + + for(HeaderMap::const_iterator header = map.begin(); + header != map.end(); + ++header) { + const std::wstring& key = header->first; + const std::wstring& value = header->second; + + if(!key.empty()) { + // Delimit with "\r\n". + if(!headers.empty()) + headers += "\r\n"; + + headers += WideToUTF8(key) + ": " + WideToUTF8(value); + } + } + + return headers; +} + +void CefRequestImpl::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(UTF8ToWide(name), UTF8ToWide(value))); +} + +CefRefPtr CefPostData::CreatePostData() +{ + CefRefPtr postdata(new CefPostDataImpl()); + return postdata; +} + +CefPostDataImpl::CefPostDataImpl() +{ +} + +size_t CefPostDataImpl::GetElementCount() +{ + Lock(); + size_t ct = elements_.size(); + Unlock(); + return ct; +} + +void CefPostDataImpl::GetElements(ElementVector& elements) +{ + Lock(); + elements = elements_; + Unlock(); +} + +bool CefPostDataImpl::RemoveElement(CefRefPtr element) +{ + bool deleted = false; + + Lock(); + + ElementVector::iterator it = elements_.begin(); + for(; it != elements_.end(); ++it) { + if(it->get() == element.get()) { + elements_.erase(it); + deleted = true; + break; + } + } + + Unlock(); + + return deleted; +} + +bool CefPostDataImpl::AddElement(CefRefPtr element) +{ + bool found = false; + + Lock(); + + // 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); + + Unlock(); + return !found; +} + +void CefPostDataImpl::RemoveElements() +{ + Lock(); + elements_.clear(); + Unlock(); +} + +void CefPostDataImpl::Set(net::UploadData& data) +{ + Lock(); + + 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); + } + + Unlock(); +} + +void CefPostDataImpl::Get(net::UploadData& data) +{ + Lock(); + + 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); + + Unlock(); +} + +void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data) +{ + Lock(); + + 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); + } + } + + Unlock(); +} + +void CefPostDataImpl::Get(WebKit::WebHTTPBody& data) +{ + Lock(); + + 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(); + } + } + + Unlock(); +} + +CefRefPtr CefPostDataElement::CreatePostDataElement() +{ + CefRefPtr element(new CefPostDataElementImpl()); + return element; +} + +CefPostDataElementImpl::CefPostDataElementImpl() +{ + type_ = PDE_TYPE_EMPTY; +} + +CefPostDataElementImpl::~CefPostDataElementImpl() +{ + SetToEmpty(); +} + +void CefPostDataElementImpl::SetToEmpty() +{ + Lock(); + if(type_ == PDE_TYPE_BYTES) + free(data_.bytes.bytes); + else if(type_ == PDE_TYPE_FILE) + free(data_.filename); + type_ = PDE_TYPE_EMPTY; + Unlock(); +} + +void CefPostDataElementImpl::SetToFile(const std::wstring& fileName) +{ + Lock(); + // Clear any data currently in the element + SetToEmpty(); + + // Assign the new file name + size_t size = fileName.size(); + wchar_t* data = static_cast(malloc((size + 1) * sizeof(wchar_t))); + DCHECK(data != NULL); + if(data == NULL) + return; + + memcpy(static_cast(data), static_cast(fileName.c_str()), + size * sizeof(wchar_t)); + data[size] = 0; + + // Assign the new data + type_ = PDE_TYPE_FILE; + data_.filename = data; + Unlock(); +} + +void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes) +{ + Lock(); + // 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; + Unlock(); +} + +CefPostDataElement::Type CefPostDataElementImpl::GetType() +{ + Lock(); + CefPostDataElement::Type type = type_; + Unlock(); + return type; +} + +std::wstring CefPostDataElementImpl::GetFile() +{ + Lock(); + DCHECK(type_ == PDE_TYPE_FILE); + std::wstring filename; + if(type_ == PDE_TYPE_FILE) + filename = data_.filename; + Unlock(); + return filename; +} + +size_t CefPostDataElementImpl::GetBytesCount() +{ + Lock(); + DCHECK(type_ == PDE_TYPE_BYTES); + size_t size = 0; + if(type_ == PDE_TYPE_BYTES) + size = data_.bytes.size; + Unlock(); + return size; +} + +size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes) +{ + Lock(); + DCHECK(type_ == PDE_TYPE_BYTES); + size_t rv = 0; + if(type_ == PDE_TYPE_BYTES) { + rv = (size < data_.bytes.size ? size : data_.bytes.size); + memcpy(bytes, data_.bytes.bytes, rv); + } + Unlock(); + return rv; +} + +void CefPostDataElementImpl::Set(const net::UploadData::Element& element) +{ + Lock(); + + 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(); + } + + Unlock(); +} + +void CefPostDataElementImpl::Get(net::UploadData::Element& element) +{ + Lock(); + + if(type_ == PDE_TYPE_BYTES) { + element.SetToBytes(static_cast(data_.bytes.bytes), data_.bytes.size); + } else if(type_ == PDE_TYPE_FILE) { + element.SetToFilePath(FilePath(data_.filename)); + } else { + NOTREACHED(); + } + + Unlock(); +} + +void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element) +{ + Lock(); + + 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(UTF8ToWide(webkit_glue::WebStringToStdString(element.filePath))); + } else { + NOTREACHED(); + } + + Unlock(); +} + +void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element) +{ + Lock(); + + 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( + webkit_glue::StdStringToWebString(WideToUTF8(data_.filename))); + } else { + NOTREACHED(); + } + + Unlock(); +} diff --git a/libcef/request_impl.h b/libcef/request_impl.h index 2ec4b823f..83dd55fa6 100644 --- a/libcef/request_impl.h +++ b/libcef/request_impl.h @@ -1,110 +1,110 @@ -// 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 _REQUEST_IMPL_H -#define _REQUEST_IMPL_H - -#include "../include/cef.h" -#include "net/base/upload_data.h" -#include "net/http/http_request_headers.h" -#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" -#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" - -class URLRequest; - -// Implementation of CefRequest -class CefRequestImpl : public CefThreadSafeBase -{ -public: - CefRequestImpl(); - ~CefRequestImpl() {} - - virtual std::wstring GetURL(); - virtual void SetURL(const std::wstring& url); - virtual std::wstring GetMethod(); - virtual void SetMethod(const std::wstring& method); - virtual CefRefPtr GetPostData(); - virtual void SetPostData(CefRefPtr postData); - virtual void GetHeaderMap(HeaderMap& headerMap); - virtual void SetHeaderMap(const HeaderMap& headerMap); - virtual void Set(const std::wstring& url, - const std::wstring& method, - CefRefPtr postData, - const HeaderMap& headerMap); - - void Set(URLRequest* 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); - - static std::string GenerateHeaders(const HeaderMap& map); - static void ParseHeaders(const std::string& header_str, HeaderMap& map); - -protected: - std::wstring url_; - std::wstring method_; - CefRefPtr postdata_; - HeaderMap headermap_; -}; - -// Implementation of CefPostData -class CefPostDataImpl : public CefThreadSafeBase -{ -public: - CefPostDataImpl(); - ~CefPostDataImpl() {} - - virtual size_t GetElementCount(); - virtual void GetElements(ElementVector& elements); - virtual bool RemoveElement(CefRefPtr element); - virtual bool AddElement(CefRefPtr element); - 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_; -}; - -// Implementation of CefPostDataElement -class CefPostDataElementImpl : public CefThreadSafeBase -{ -public: - CefPostDataElementImpl(); - ~CefPostDataElementImpl(); - - virtual void SetToEmpty(); - virtual void SetToFile(const std::wstring& fileName); - virtual void SetToBytes(size_t size, const void* bytes); - virtual Type GetType(); - virtual std::wstring GetFile(); - virtual size_t GetBytesCount(); - virtual size_t GetBytes(size_t size, void* bytes); - - 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; - wchar_t* filename; - } data_; -}; - -#endif // _REQUEST_IMPL_H +// 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 _REQUEST_IMPL_H +#define _REQUEST_IMPL_H + +#include "../include/cef.h" +#include "net/base/upload_data.h" +#include "net/http/http_request_headers.h" +#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h" +#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h" + +class URLRequest; + +// Implementation of CefRequest +class CefRequestImpl : public CefThreadSafeBase +{ +public: + CefRequestImpl(); + ~CefRequestImpl() {} + + virtual std::wstring GetURL(); + virtual void SetURL(const std::wstring& url); + virtual std::wstring GetMethod(); + virtual void SetMethod(const std::wstring& method); + virtual CefRefPtr GetPostData(); + virtual void SetPostData(CefRefPtr postData); + virtual void GetHeaderMap(HeaderMap& headerMap); + virtual void SetHeaderMap(const HeaderMap& headerMap); + virtual void Set(const std::wstring& url, + const std::wstring& method, + CefRefPtr postData, + const HeaderMap& headerMap); + + void Set(URLRequest* 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); + + static std::string GenerateHeaders(const HeaderMap& map); + static void ParseHeaders(const std::string& header_str, HeaderMap& map); + +protected: + std::wstring url_; + std::wstring method_; + CefRefPtr postdata_; + HeaderMap headermap_; +}; + +// Implementation of CefPostData +class CefPostDataImpl : public CefThreadSafeBase +{ +public: + CefPostDataImpl(); + ~CefPostDataImpl() {} + + virtual size_t GetElementCount(); + virtual void GetElements(ElementVector& elements); + virtual bool RemoveElement(CefRefPtr element); + virtual bool AddElement(CefRefPtr element); + 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_; +}; + +// Implementation of CefPostDataElement +class CefPostDataElementImpl : public CefThreadSafeBase +{ +public: + CefPostDataElementImpl(); + ~CefPostDataElementImpl(); + + virtual void SetToEmpty(); + virtual void SetToFile(const std::wstring& fileName); + virtual void SetToBytes(size_t size, const void* bytes); + virtual Type GetType(); + virtual std::wstring GetFile(); + virtual size_t GetBytesCount(); + virtual size_t GetBytes(size_t size, void* bytes); + + 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; + wchar_t* filename; + } data_; +}; + +#endif // _REQUEST_IMPL_H diff --git a/libcef/scheme_impl.cc b/libcef/scheme_impl.cc index 6af4f7a2a..c6c2a15aa 100644 --- a/libcef/scheme_impl.cc +++ b/libcef/scheme_impl.cc @@ -1,417 +1,417 @@ -// Copyright (c) 2009 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 "base/lazy_instance.h" -#include "base/logging.h" -#include "base/message_loop.h" -#include "base/utf_string_conversions.h" -#include "googleurl/src/url_util.h" -#include "net/base/completion_callback.h" -#include "net/base/io_buffer.h" -#include "net/base/upload_data.h" -#include "net/http/http_util.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_filter.h" -#include "net/url_request/url_request_job.h" - -#include "include/cef.h" -#include "tracker.h" -#include "cef_context.h" -#include "request_impl.h" - -#include - - -// Memory manager. - -base::LazyInstance g_scheme_tracker(base::LINKER_INITIALIZED); - -class TrackBase : public CefTrackObject -{ -public: - TrackBase(CefBase* base) { base_ = base; } - -protected: - CefRefPtr base_; -}; - -static void TrackAdd(CefTrackObject* object) -{ - g_scheme_tracker.Pointer()->Add(object); -} - -static void TrackDelete(CefTrackObject* object) -{ - g_scheme_tracker.Pointer()->Delete(object); -} - - -// URLRequestJob implementation. - -class CefUrlRequestJob : public URLRequestJob { -public: - CefUrlRequestJob(URLRequest* request, CefRefPtr handler) - : URLRequestJob(request), - url_(request->url()), - handler_(handler), - response_length_(0), - remaining_bytes_(0) { } - - virtual ~CefUrlRequestJob(){} - - virtual void Start() - { - handler_->Cancel(); - // Continue asynchronously. - DCHECK(!async_resolver_); - async_resolver_ = new AsyncResolver(this); - CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( - async_resolver_.get(), &AsyncResolver::Resolve, url_)); - return; - } - - virtual void Kill() - { - if (async_resolver_) { - async_resolver_->Cancel(); - async_resolver_ = NULL; - } - - URLRequestJob::Kill(); - } - - virtual bool ReadRawData(net::IOBuffer* dest, int dest_size, int *bytes_read) - { - DCHECK_NE(dest_size, 0); - DCHECK(bytes_read); - - // When remaining_bytes_>=0, it means the handler knows the content size - // before hand. We continue to read until - if (remaining_bytes_>=0) { - if (remaining_bytes_ < dest_size) - dest_size = static_cast(remaining_bytes_); - - // If we should copy zero bytes because |remaining_bytes_| is zero, short - // circuit here. - if (!dest_size) { - *bytes_read = 0; - return true; - } - - // remaining_bytes > 0 - bool rv = handler_->ReadResponse(dest->data(), dest_size, bytes_read); - remaining_bytes_ -= *bytes_read; - if (!rv) { - // handler indicated no further data to read - *bytes_read = 0; - } - return true; - } else { - // The handler returns -1 for GetResponseLength, this means the handler - // doesn't know the content size before hand. We do basically the same - // thing, except for checking the return value for handler_->ReadResponse, - // which is an indicator for no further data to be read. - bool rv = handler_->ReadResponse(dest->data(), dest_size, bytes_read); - if (!rv) - // handler indicated no further data to read - *bytes_read = 0; - return true; - } - } - - virtual bool IsRedirectResponse(GURL* location, int* http_status_code) - { - return false; - } - - virtual bool GetContentEncodings( - std::vector* encoding_types) - { - DCHECK(encoding_types->empty()); - - return !encoding_types->empty(); - } - - virtual bool GetMimeType(std::string* mime_type) const - { - DCHECK(request_); - // call handler to get mime type - *mime_type = mime_type_; - return true; - } - - virtual void SetExtraRequestHeaders(const std::string& headers) - { - } - - CefRefPtr handler_; - std::string mime_type_; - int response_length_; - -protected: - GURL url_; - -private: - void DidResolve(const GURL& url) - { - async_resolver_ = NULL; - - // We may have been orphaned... - if (!request_) - return; - - remaining_bytes_ = response_length_; - if (remaining_bytes_>0) - set_expected_content_size(remaining_bytes_); - NotifyHeadersComplete(); - } - - int64 remaining_bytes_; - std::string m_response; - - class AsyncResolver : - public base::RefCountedThreadSafe { - public: - explicit AsyncResolver(CefUrlRequestJob* owner) - : owner_(owner), owner_loop_(MessageLoop::current()) { - } - - void Resolve(const GURL& url) { - AutoLock locked(lock_); - if (!owner_ || !owner_loop_) - return; - - ////////////////////////////////////////////////////////////////////////// - // safe to perform long operation here - CefRefPtr req(CefRequest::CreateRequest()); - - // populate the request data - static_cast(req.get())->Set(owner_->request()); - - owner_->handler_->Cancel(); - std::wstring mime_type; - int response_length = 0; - // handler should complete content generation in ProcessRequest - bool res = owner_->handler_->ProcessRequest(req, mime_type, - &response_length); - if (res) { - owner_->mime_type_ = WideToUTF8(mime_type); - owner_->response_length_ = response_length; - } - ////////////////////////////////////////////////////////////////////////// - if (owner_loop_) { - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &AsyncResolver::ReturnResults, url)); - } - } - - void Cancel() { - owner_->handler_->Cancel(); - - AutoLock locked(lock_); - owner_ = NULL; - owner_loop_ = NULL; - } - - private: - void ReturnResults(const GURL& url) { - if (owner_) - owner_->DidResolve(url); - } - - CefUrlRequestJob* owner_; - - Lock lock_; - MessageLoop* owner_loop_; - }; - - friend class AsyncResolver; - scoped_refptr async_resolver_; - - DISALLOW_COPY_AND_ASSIGN(CefUrlRequestJob); -}; - - -// URLRequestFilter clone that manages the CefSchemeHandlerFactory pointers. - -class CefUrlRequestFilter { -public: - // scheme,hostname -> ProtocolFactory - typedef std::map, - CefSchemeHandlerFactory*> HandlerMap; - - // Singleton instance for use. - static CefUrlRequestFilter* GetInstance() - { - if (!shared_instance_) - shared_instance_ = new CefUrlRequestFilter; - return shared_instance_; - } - - static URLRequestJob* Factory(URLRequest* request, - const std::string& scheme) - { - // Returning null here just means that the built-in handler will be used. - return GetInstance()->FindRequestHandler(request, scheme); - } - - void AddHostnameHandler(const std::string& scheme, - const std::string& hostname, - CefSchemeHandlerFactory* factory) - { - handler_map_[make_pair(scheme, hostname)] = factory; - - // Register with the ProtocolFactory. - URLRequest::RegisterProtocolFactory(scheme, - &CefUrlRequestFilter::Factory); - } - - void RemoveHostnameHandler(const std::string& scheme, - const std::string& hostname) - { - HandlerMap::iterator iter = - handler_map_.find(make_pair(scheme, hostname)); - DCHECK(iter != handler_map_.end()); - - handler_map_.erase(iter); - } - - // Clear all the existing URL handlers and unregister with the - // ProtocolFactory. Resets the hit count. - void ClearHandlers() - { - // 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) { - URLRequest::RegisterProtocolFactory(*scheme, NULL); - } - - handler_map_.clear(); - hit_count_ = 0; - } - - CefSchemeHandlerFactory* FindRequestHandlerFactory(URLRequest* request, - const std::string& scheme) - { - CefSchemeHandlerFactory* factory = NULL; - if (request->url().is_valid()) { - // Check for a map with a hostname first. - const std::string& hostname = request->url().host(); - - HandlerMap::iterator i = handler_map_.find(make_pair(scheme, hostname)); - if (i != handler_map_.end()) - factory = i->second; - } - - if (!factory) { - // Check for a map with no specified hostname. - HandlerMap::iterator i = - handler_map_.find(make_pair(scheme, std::string())); - if (i != handler_map_.end()) - factory = i->second; - } - - return factory; - } - - // Returns the number of times a handler was used to service a request. - int hit_count() const { return hit_count_; } - -protected: - CefUrlRequestFilter() : hit_count_(0) { } - - // Helper method that looks up the request in the handler_map_. - URLRequestJob* FindRequestHandler(URLRequest* request, - const std::string& scheme) - { - URLRequestJob* job = NULL; - CefSchemeHandlerFactory* factory = - FindRequestHandlerFactory(request, scheme); - if (factory) { - CefRefPtr handler = factory->Create(); - if (handler.get()) - job = new CefUrlRequestJob(request, handler); - } - - if (job) { - DLOG(INFO) << "URLRequestFilter hit for " << request->url().spec(); - hit_count_++; - } - return job; - } - - // Maps hostnames to factories. Hostnames take priority over URLs. - HandlerMap handler_map_; - - int hit_count_; - -private: - // Singleton instance. - static CefUrlRequestFilter* shared_instance_; - - DISALLOW_EVIL_CONSTRUCTORS(CefUrlRequestFilter); -}; - -CefUrlRequestFilter* CefUrlRequestFilter::shared_instance_ = NULL; - - -class SchemeRequestJobWrapper : public CefThreadSafeBase { -public: - SchemeRequestJobWrapper(const std::string& scheme_name, - const std::string& host_name, - CefSchemeHandlerFactory* factory) - : factory_(factory), scheme_name_(scheme_name), host_name_(host_name) - { - // The reference will be released when the application exits. - TrackAdd(new TrackBase(factory)); - } - - void RegisterScheme() - { - // Register the scheme as a standard scheme if it isn't already. - url_parse::Component scheme(0, scheme_name_.length()); - if (!url_util::IsStandard(scheme_name_.c_str(), scheme)) - url_util::AddStandardScheme(scheme_name_.c_str()); - - // we need to store the pointer of this handler because - // we can't pass it as a parameter to the factory method - CefUrlRequestFilter::GetInstance()->AddHostnameHandler( - scheme_name_, host_name_, factory_); - } - - static bool ImplementsThreadSafeReferenceCounting() { return true; } - -private: - CefSchemeHandlerFactory* factory_; - std::string scheme_name_; - std::string host_name_; -}; - -bool CefRegisterScheme(const std::wstring& scheme_name, - const std::wstring& host_name, - CefRefPtr factory) -{ - // Verify that the context is already initialized - if(!_Context.get()) - return false; - - // Use a smart pointer for the wrapper object because - // RunnableMethodTraits::RetainCallee() (originating from NewRunnableMethod) - // will call AddRef() and Release() on the object in debug mode, resulting in - // the object being deleted if it doesn't already have a reference. - CefRefPtr wrapper( - new SchemeRequestJobWrapper(WideToUTF8(scheme_name), - WideToUTF8(host_name), factory)); - - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(wrapper.get(), - &SchemeRequestJobWrapper::RegisterScheme)); - - return true; -} +// Copyright (c) 2009 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 "base/lazy_instance.h" +#include "base/logging.h" +#include "base/message_loop.h" +#include "base/utf_string_conversions.h" +#include "googleurl/src/url_util.h" +#include "net/base/completion_callback.h" +#include "net/base/io_buffer.h" +#include "net/base/upload_data.h" +#include "net/http/http_util.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_filter.h" +#include "net/url_request/url_request_job.h" + +#include "include/cef.h" +#include "tracker.h" +#include "cef_context.h" +#include "request_impl.h" + +#include + + +// Memory manager. + +base::LazyInstance g_scheme_tracker(base::LINKER_INITIALIZED); + +class TrackBase : public CefTrackObject +{ +public: + TrackBase(CefBase* base) { base_ = base; } + +protected: + CefRefPtr base_; +}; + +static void TrackAdd(CefTrackObject* object) +{ + g_scheme_tracker.Pointer()->Add(object); +} + +static void TrackDelete(CefTrackObject* object) +{ + g_scheme_tracker.Pointer()->Delete(object); +} + + +// URLRequestJob implementation. + +class CefUrlRequestJob : public URLRequestJob { +public: + CefUrlRequestJob(URLRequest* request, CefRefPtr handler) + : URLRequestJob(request), + url_(request->url()), + handler_(handler), + response_length_(0), + remaining_bytes_(0) { } + + virtual ~CefUrlRequestJob(){} + + virtual void Start() + { + handler_->Cancel(); + // Continue asynchronously. + DCHECK(!async_resolver_); + async_resolver_ = new AsyncResolver(this); + CefThread::PostTask(CefThread::IO, FROM_HERE, NewRunnableMethod( + async_resolver_.get(), &AsyncResolver::Resolve, url_)); + return; + } + + virtual void Kill() + { + if (async_resolver_) { + async_resolver_->Cancel(); + async_resolver_ = NULL; + } + + URLRequestJob::Kill(); + } + + virtual bool ReadRawData(net::IOBuffer* dest, int dest_size, int *bytes_read) + { + DCHECK_NE(dest_size, 0); + DCHECK(bytes_read); + + // When remaining_bytes_>=0, it means the handler knows the content size + // before hand. We continue to read until + if (remaining_bytes_>=0) { + if (remaining_bytes_ < dest_size) + dest_size = static_cast(remaining_bytes_); + + // If we should copy zero bytes because |remaining_bytes_| is zero, short + // circuit here. + if (!dest_size) { + *bytes_read = 0; + return true; + } + + // remaining_bytes > 0 + bool rv = handler_->ReadResponse(dest->data(), dest_size, bytes_read); + remaining_bytes_ -= *bytes_read; + if (!rv) { + // handler indicated no further data to read + *bytes_read = 0; + } + return true; + } else { + // The handler returns -1 for GetResponseLength, this means the handler + // doesn't know the content size before hand. We do basically the same + // thing, except for checking the return value for handler_->ReadResponse, + // which is an indicator for no further data to be read. + bool rv = handler_->ReadResponse(dest->data(), dest_size, bytes_read); + if (!rv) + // handler indicated no further data to read + *bytes_read = 0; + return true; + } + } + + virtual bool IsRedirectResponse(GURL* location, int* http_status_code) + { + return false; + } + + virtual bool GetContentEncodings( + std::vector* encoding_types) + { + DCHECK(encoding_types->empty()); + + return !encoding_types->empty(); + } + + virtual bool GetMimeType(std::string* mime_type) const + { + DCHECK(request_); + // call handler to get mime type + *mime_type = mime_type_; + return true; + } + + virtual void SetExtraRequestHeaders(const std::string& headers) + { + } + + CefRefPtr handler_; + std::string mime_type_; + int response_length_; + +protected: + GURL url_; + +private: + void DidResolve(const GURL& url) + { + async_resolver_ = NULL; + + // We may have been orphaned... + if (!request_) + return; + + remaining_bytes_ = response_length_; + if (remaining_bytes_>0) + set_expected_content_size(remaining_bytes_); + NotifyHeadersComplete(); + } + + int64 remaining_bytes_; + std::string m_response; + + class AsyncResolver : + public base::RefCountedThreadSafe { + public: + explicit AsyncResolver(CefUrlRequestJob* owner) + : owner_(owner), owner_loop_(MessageLoop::current()) { + } + + void Resolve(const GURL& url) { + AutoLock locked(lock_); + if (!owner_ || !owner_loop_) + return; + + ////////////////////////////////////////////////////////////////////////// + // safe to perform long operation here + CefRefPtr req(CefRequest::CreateRequest()); + + // populate the request data + static_cast(req.get())->Set(owner_->request()); + + owner_->handler_->Cancel(); + std::wstring mime_type; + int response_length = 0; + // handler should complete content generation in ProcessRequest + bool res = owner_->handler_->ProcessRequest(req, mime_type, + &response_length); + if (res) { + owner_->mime_type_ = WideToUTF8(mime_type); + owner_->response_length_ = response_length; + } + ////////////////////////////////////////////////////////////////////////// + if (owner_loop_) { + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &AsyncResolver::ReturnResults, url)); + } + } + + void Cancel() { + owner_->handler_->Cancel(); + + AutoLock locked(lock_); + owner_ = NULL; + owner_loop_ = NULL; + } + + private: + void ReturnResults(const GURL& url) { + if (owner_) + owner_->DidResolve(url); + } + + CefUrlRequestJob* owner_; + + Lock lock_; + MessageLoop* owner_loop_; + }; + + friend class AsyncResolver; + scoped_refptr async_resolver_; + + DISALLOW_COPY_AND_ASSIGN(CefUrlRequestJob); +}; + + +// URLRequestFilter clone that manages the CefSchemeHandlerFactory pointers. + +class CefUrlRequestFilter { +public: + // scheme,hostname -> ProtocolFactory + typedef std::map, + CefSchemeHandlerFactory*> HandlerMap; + + // Singleton instance for use. + static CefUrlRequestFilter* GetInstance() + { + if (!shared_instance_) + shared_instance_ = new CefUrlRequestFilter; + return shared_instance_; + } + + static URLRequestJob* Factory(URLRequest* request, + const std::string& scheme) + { + // Returning null here just means that the built-in handler will be used. + return GetInstance()->FindRequestHandler(request, scheme); + } + + void AddHostnameHandler(const std::string& scheme, + const std::string& hostname, + CefSchemeHandlerFactory* factory) + { + handler_map_[make_pair(scheme, hostname)] = factory; + + // Register with the ProtocolFactory. + URLRequest::RegisterProtocolFactory(scheme, + &CefUrlRequestFilter::Factory); + } + + void RemoveHostnameHandler(const std::string& scheme, + const std::string& hostname) + { + HandlerMap::iterator iter = + handler_map_.find(make_pair(scheme, hostname)); + DCHECK(iter != handler_map_.end()); + + handler_map_.erase(iter); + } + + // Clear all the existing URL handlers and unregister with the + // ProtocolFactory. Resets the hit count. + void ClearHandlers() + { + // 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) { + URLRequest::RegisterProtocolFactory(*scheme, NULL); + } + + handler_map_.clear(); + hit_count_ = 0; + } + + CefSchemeHandlerFactory* FindRequestHandlerFactory(URLRequest* request, + const std::string& scheme) + { + CefSchemeHandlerFactory* factory = NULL; + if (request->url().is_valid()) { + // Check for a map with a hostname first. + const std::string& hostname = request->url().host(); + + HandlerMap::iterator i = handler_map_.find(make_pair(scheme, hostname)); + if (i != handler_map_.end()) + factory = i->second; + } + + if (!factory) { + // Check for a map with no specified hostname. + HandlerMap::iterator i = + handler_map_.find(make_pair(scheme, std::string())); + if (i != handler_map_.end()) + factory = i->second; + } + + return factory; + } + + // Returns the number of times a handler was used to service a request. + int hit_count() const { return hit_count_; } + +protected: + CefUrlRequestFilter() : hit_count_(0) { } + + // Helper method that looks up the request in the handler_map_. + URLRequestJob* FindRequestHandler(URLRequest* request, + const std::string& scheme) + { + URLRequestJob* job = NULL; + CefSchemeHandlerFactory* factory = + FindRequestHandlerFactory(request, scheme); + if (factory) { + CefRefPtr handler = factory->Create(); + if (handler.get()) + job = new CefUrlRequestJob(request, handler); + } + + if (job) { + DLOG(INFO) << "URLRequestFilter hit for " << request->url().spec(); + hit_count_++; + } + return job; + } + + // Maps hostnames to factories. Hostnames take priority over URLs. + HandlerMap handler_map_; + + int hit_count_; + +private: + // Singleton instance. + static CefUrlRequestFilter* shared_instance_; + + DISALLOW_EVIL_CONSTRUCTORS(CefUrlRequestFilter); +}; + +CefUrlRequestFilter* CefUrlRequestFilter::shared_instance_ = NULL; + + +class SchemeRequestJobWrapper : public CefThreadSafeBase { +public: + SchemeRequestJobWrapper(const std::string& scheme_name, + const std::string& host_name, + CefSchemeHandlerFactory* factory) + : factory_(factory), scheme_name_(scheme_name), host_name_(host_name) + { + // The reference will be released when the application exits. + TrackAdd(new TrackBase(factory)); + } + + void RegisterScheme() + { + // Register the scheme as a standard scheme if it isn't already. + url_parse::Component scheme(0, scheme_name_.length()); + if (!url_util::IsStandard(scheme_name_.c_str(), scheme)) + url_util::AddStandardScheme(scheme_name_.c_str()); + + // we need to store the pointer of this handler because + // we can't pass it as a parameter to the factory method + CefUrlRequestFilter::GetInstance()->AddHostnameHandler( + scheme_name_, host_name_, factory_); + } + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + +private: + CefSchemeHandlerFactory* factory_; + std::string scheme_name_; + std::string host_name_; +}; + +bool CefRegisterScheme(const std::wstring& scheme_name, + const std::wstring& host_name, + CefRefPtr factory) +{ + // Verify that the context is already initialized + if(!_Context.get()) + return false; + + // Use a smart pointer for the wrapper object because + // RunnableMethodTraits::RetainCallee() (originating from NewRunnableMethod) + // will call AddRef() and Release() on the object in debug mode, resulting in + // the object being deleted if it doesn't already have a reference. + CefRefPtr wrapper( + new SchemeRequestJobWrapper(WideToUTF8(scheme_name), + WideToUTF8(host_name), factory)); + + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(wrapper.get(), + &SchemeRequestJobWrapper::RegisterScheme)); + + return true; +} diff --git a/libcef/stream_impl.cc b/libcef/stream_impl.cc index d98f7fd6b..c5da5d12a 100644 --- a/libcef/stream_impl.cc +++ b/libcef/stream_impl.cc @@ -1,356 +1,356 @@ -// 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 "stream_impl.h" - -#include "base/logging.h" - - -// Static functions - -CefRefPtr CefStreamReader::CreateForFile( - const std::wstring& fileName) -{ - CefRefPtr reader; - FILE *f = _wfopen(fileName.c_str(), L"rb"); - if(f) - reader = new CefFileReader(f, true); - return reader; -} - -CefRefPtr CefStreamReader::CreateForData(void* data, - size_t size) -{ - DCHECK(data != NULL); - DCHECK(size > 0); - 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 std::wstring& fileName) -{ - DCHECK(!fileName.empty()); - CefRefPtr writer; - FILE* file = _wfopen(fileName.c_str(), L"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) - : file_(file), close_(close) -{ -} - -CefFileReader::~CefFileReader() -{ - Lock(); - if(close_) - fclose(file_); - Unlock(); -} - -size_t CefFileReader::Read(void* ptr, size_t size, size_t n) -{ - Lock(); - size_t rv = fread(ptr, size, n, file_); - Unlock(); - return rv; -} - -int CefFileReader::Seek(long offset, int whence) -{ - Lock(); - int rv = fseek(file_, offset, whence); - Unlock(); - return rv; -} - -long CefFileReader::Tell() -{ - Lock(); - long rv = ftell(file_); - Unlock(); - return rv; -} - -int CefFileReader::Eof() -{ - Lock(); - int rv = feof(file_); - Unlock(); - return rv; -} - - -// CefFileWriter - -CefFileWriter::CefFileWriter(FILE* file, bool close) - : file_(file), close_(close) -{ -} - -CefFileWriter::~CefFileWriter() -{ - Lock(); - if(close_) - fclose(file_); - Unlock(); -} - -size_t CefFileWriter::Write(const void* ptr, size_t size, size_t n) -{ - Lock(); - size_t rv = (size_t)fwrite(ptr, size, n, file_); - Unlock(); - return rv; -} - -int CefFileWriter::Seek(long offset, int whence) -{ - Lock(); - int rv = fseek(file_, offset, whence); - Unlock(); - return rv; -} - -long CefFileWriter::Tell() -{ - Lock(); - long rv = ftell(file_); - Unlock(); - return rv; -} - -int CefFileWriter::Flush() -{ - Lock(); - int rv = fflush(file_); - Unlock(); - return rv; -} - - -// CefBytesReader - -CefBytesReader::CefBytesReader(void* data, long 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) -{ - Lock(); - size_t s = (datasize_ - offset_) / size; - size_t ret = (n < s ? n : s); - memcpy(ptr, ((char*)data_) + offset_, ret * size); - offset_ += ret * size; - Unlock(); - return ret; -} - -int CefBytesReader::Seek(long offset, int whence) -{ - int rv = -1L; - Lock(); - switch(whence) { - case SEEK_CUR: - if(offset_ + offset > datasize_) { - break; - } - offset_ += offset; - rv = 0; - break; - case SEEK_END: - if(offset > (int)datasize_) { - break; - } - offset_ = datasize_ - offset; - rv = 0; - break; - case SEEK_SET: - if(offset > (int)datasize_) { - break; - } - offset_ = offset; - rv = 0; - break; - } - Unlock(); - - return rv; -} - -long CefBytesReader::Tell() -{ - Lock(); - long rv = offset_; - Unlock(); - return rv; -} - -int CefBytesReader::Eof() -{ - Lock(); - int rv = (offset_ >= datasize_); - Unlock(); - return rv; -} - -void CefBytesReader::SetData(void* data, long datasize, bool copy) -{ - Lock(); - if(copy_) - free(data_); - - copy_ = copy; - offset_ = 0; - datasize_ = datasize; - - if(copy) { - data_ = malloc(datasize); - DCHECK(data_ != NULL); - if(data_) - memcpy(data_, data, datasize); - } else { - data_ = data; - } - Unlock(); -} - - -// CefBytesWriter - -CefBytesWriter::CefBytesWriter(size_t grow) - : grow_(grow), offset_(0), datasize_(grow) -{ - DCHECK(grow > 0); - data_ = malloc(grow); - DCHECK(data_ != NULL); -} - -CefBytesWriter::~CefBytesWriter() -{ - Lock(); - if(data_) - free(data_); - Unlock(); -} - -size_t CefBytesWriter::Write(const void* ptr, size_t size, size_t n) -{ - Lock(); - size_t rv; - if(offset_ + size * n >= datasize_ && Grow(size * n) == 0) { - rv = 0; - } else { - memcpy(((char*)data_) + offset_, ptr, size * n); - offset_ += size * n; - rv = n; - } - Unlock(); - return rv; -} - -int CefBytesWriter::Seek(long offset, int whence) -{ - int rv = -1L; - Lock(); - switch(whence) { - case SEEK_CUR: - if(offset_ + offset > datasize_) { - break; - } - offset_ += offset; - rv = offset_; - break; - case SEEK_END: - if(offset > (int)datasize_) { - break; - } - offset_ = datasize_ - offset; - rv = offset_; - case SEEK_SET: - if(offset > (int)datasize_) { - break; - } - offset_ = offset; - rv = offset_; - break; - } - Unlock(); - - return rv; -} - -long CefBytesWriter::Tell() -{ - Lock(); - long rv = offset_; - Unlock(); - return rv; -} - -int CefBytesWriter::Flush() -{ - return 0; -} - -std::string CefBytesWriter::GetDataString() -{ - Lock(); - std::string str((char*)data_, offset_); - Unlock(); - return str; -} - -size_t CefBytesWriter::Grow(size_t size) -{ - Lock(); - size_t rv; - size_t s = (size > grow_ ? size : grow_); - void* tmp = realloc(data_, datasize_ + s); - DCHECK(tmp != NULL); - if(tmp) { - data_ = tmp; - datasize_ += s; - rv = datasize_; - } else { - rv = 0; - } - Unlock(); - return rv; -} +// 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 "stream_impl.h" + +#include "base/logging.h" + + +// Static functions + +CefRefPtr CefStreamReader::CreateForFile( + const std::wstring& fileName) +{ + CefRefPtr reader; + FILE *f = _wfopen(fileName.c_str(), L"rb"); + if(f) + reader = new CefFileReader(f, true); + return reader; +} + +CefRefPtr CefStreamReader::CreateForData(void* data, + size_t size) +{ + DCHECK(data != NULL); + DCHECK(size > 0); + 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 std::wstring& fileName) +{ + DCHECK(!fileName.empty()); + CefRefPtr writer; + FILE* file = _wfopen(fileName.c_str(), L"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) + : file_(file), close_(close) +{ +} + +CefFileReader::~CefFileReader() +{ + Lock(); + if(close_) + fclose(file_); + Unlock(); +} + +size_t CefFileReader::Read(void* ptr, size_t size, size_t n) +{ + Lock(); + size_t rv = fread(ptr, size, n, file_); + Unlock(); + return rv; +} + +int CefFileReader::Seek(long offset, int whence) +{ + Lock(); + int rv = fseek(file_, offset, whence); + Unlock(); + return rv; +} + +long CefFileReader::Tell() +{ + Lock(); + long rv = ftell(file_); + Unlock(); + return rv; +} + +int CefFileReader::Eof() +{ + Lock(); + int rv = feof(file_); + Unlock(); + return rv; +} + + +// CefFileWriter + +CefFileWriter::CefFileWriter(FILE* file, bool close) + : file_(file), close_(close) +{ +} + +CefFileWriter::~CefFileWriter() +{ + Lock(); + if(close_) + fclose(file_); + Unlock(); +} + +size_t CefFileWriter::Write(const void* ptr, size_t size, size_t n) +{ + Lock(); + size_t rv = (size_t)fwrite(ptr, size, n, file_); + Unlock(); + return rv; +} + +int CefFileWriter::Seek(long offset, int whence) +{ + Lock(); + int rv = fseek(file_, offset, whence); + Unlock(); + return rv; +} + +long CefFileWriter::Tell() +{ + Lock(); + long rv = ftell(file_); + Unlock(); + return rv; +} + +int CefFileWriter::Flush() +{ + Lock(); + int rv = fflush(file_); + Unlock(); + return rv; +} + + +// CefBytesReader + +CefBytesReader::CefBytesReader(void* data, long 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) +{ + Lock(); + size_t s = (datasize_ - offset_) / size; + size_t ret = (n < s ? n : s); + memcpy(ptr, ((char*)data_) + offset_, ret * size); + offset_ += ret * size; + Unlock(); + return ret; +} + +int CefBytesReader::Seek(long offset, int whence) +{ + int rv = -1L; + Lock(); + switch(whence) { + case SEEK_CUR: + if(offset_ + offset > datasize_) { + break; + } + offset_ += offset; + rv = 0; + break; + case SEEK_END: + if(offset > (int)datasize_) { + break; + } + offset_ = datasize_ - offset; + rv = 0; + break; + case SEEK_SET: + if(offset > (int)datasize_) { + break; + } + offset_ = offset; + rv = 0; + break; + } + Unlock(); + + return rv; +} + +long CefBytesReader::Tell() +{ + Lock(); + long rv = offset_; + Unlock(); + return rv; +} + +int CefBytesReader::Eof() +{ + Lock(); + int rv = (offset_ >= datasize_); + Unlock(); + return rv; +} + +void CefBytesReader::SetData(void* data, long datasize, bool copy) +{ + Lock(); + if(copy_) + free(data_); + + copy_ = copy; + offset_ = 0; + datasize_ = datasize; + + if(copy) { + data_ = malloc(datasize); + DCHECK(data_ != NULL); + if(data_) + memcpy(data_, data, datasize); + } else { + data_ = data; + } + Unlock(); +} + + +// CefBytesWriter + +CefBytesWriter::CefBytesWriter(size_t grow) + : grow_(grow), offset_(0), datasize_(grow) +{ + DCHECK(grow > 0); + data_ = malloc(grow); + DCHECK(data_ != NULL); +} + +CefBytesWriter::~CefBytesWriter() +{ + Lock(); + if(data_) + free(data_); + Unlock(); +} + +size_t CefBytesWriter::Write(const void* ptr, size_t size, size_t n) +{ + Lock(); + size_t rv; + if(offset_ + size * n >= datasize_ && Grow(size * n) == 0) { + rv = 0; + } else { + memcpy(((char*)data_) + offset_, ptr, size * n); + offset_ += size * n; + rv = n; + } + Unlock(); + return rv; +} + +int CefBytesWriter::Seek(long offset, int whence) +{ + int rv = -1L; + Lock(); + switch(whence) { + case SEEK_CUR: + if(offset_ + offset > datasize_) { + break; + } + offset_ += offset; + rv = offset_; + break; + case SEEK_END: + if(offset > (int)datasize_) { + break; + } + offset_ = datasize_ - offset; + rv = offset_; + case SEEK_SET: + if(offset > (int)datasize_) { + break; + } + offset_ = offset; + rv = offset_; + break; + } + Unlock(); + + return rv; +} + +long CefBytesWriter::Tell() +{ + Lock(); + long rv = offset_; + Unlock(); + return rv; +} + +int CefBytesWriter::Flush() +{ + return 0; +} + +std::string CefBytesWriter::GetDataString() +{ + Lock(); + std::string str((char*)data_, offset_); + Unlock(); + return str; +} + +size_t CefBytesWriter::Grow(size_t size) +{ + Lock(); + size_t rv; + size_t s = (size > grow_ ? size : grow_); + void* tmp = realloc(data_, datasize_ + s); + DCHECK(tmp != NULL); + if(tmp) { + data_ = tmp; + datasize_ += s; + rv = datasize_; + } else { + rv = 0; + } + Unlock(); + return rv; +} diff --git a/libcef/stream_impl.h b/libcef/stream_impl.h index 9fd095606..b4fcb41be 100644 --- a/libcef/stream_impl.h +++ b/libcef/stream_impl.h @@ -1,149 +1,149 @@ -// 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 _STREAM_IMPL_H -#define _STREAM_IMPL_H - -#include "../include/cef.h" -#include - -// Implementation of CefStreamReader for files. -class CefFileReader : public CefThreadSafeBase -{ -public: - CefFileReader(FILE* file, bool close); - virtual ~CefFileReader(); - - virtual size_t Read(void* ptr, size_t size, size_t n); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Eof(); - -protected: - bool close_; - FILE *file_; -}; - -// Implementation of CefStreamWriter for files. -class CefFileWriter : public CefThreadSafeBase -{ -public: - CefFileWriter(FILE* file, bool close); - virtual ~CefFileWriter(); - - virtual size_t Write(const void* ptr, size_t size, size_t n); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Flush(); - -protected: - FILE *file_; - bool close_; -}; - -// Implementation of CefStreamReader for byte buffers. -class CefBytesReader : public CefThreadSafeBase -{ -public: - CefBytesReader(void* data, long datasize, bool copy); - virtual ~CefBytesReader(); - - virtual size_t Read(void* ptr, size_t size, size_t n); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Eof(); - - void SetData(void* data, long datasize, bool copy); - - void* GetData() { return data_; } - size_t GetDataSize() { return offset_; } - -protected: - void* data_; - size_t datasize_; - bool copy_; - size_t offset_; -}; - -// Implementation of CefStreamWriter for byte buffers. -class CefBytesWriter : public CefThreadSafeBase -{ -public: - CefBytesWriter(size_t grow); - virtual ~CefBytesWriter(); - - virtual size_t Write(const void* ptr, size_t size, size_t n); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Flush(); - - void* GetData() { return data_; } - size_t GetDataSize() { return offset_; } - std::string GetDataString(); - -protected: - size_t Grow(size_t size); - -protected: - size_t grow_; - void* data_; - size_t datasize_; - size_t offset_; -}; - -// Implementation of CefStreamReader for handlers. -class CefHandlerReader : public CefThreadSafeBase -{ -public: - CefHandlerReader(CefRefPtr handler) : handler_(handler) {} - - virtual size_t Read(void* ptr, size_t size, size_t n) - { - return handler_->Read(ptr, size, n); - } - virtual int Seek(long offset, int whence) - { - return handler_->Seek(offset, whence); - } - virtual long Tell() - { - return handler_->Tell(); - } - virtual int Eof() - { - return handler_->Eof(); - } - -protected: - CefRefPtr handler_; -}; - -// Implementation of CefStreamWriter for handlers. -class CefHandlerWriter : public CefThreadSafeBase -{ -public: - CefHandlerWriter(CefRefPtr handler) : handler_(handler) {} - - virtual size_t Write(const void* ptr, size_t size, size_t n) - { - return handler_->Write(ptr, size, n); - } - virtual int Seek(long offset, int whence) - { - return handler_->Seek(offset, whence); - } - virtual long Tell() - { - return handler_->Tell(); - } - virtual int Flush() - { - return handler_->Flush(); - } - -protected: - CefRefPtr handler_; -}; - -#endif // _STREAM_IMPL_H +// 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 _STREAM_IMPL_H +#define _STREAM_IMPL_H + +#include "../include/cef.h" +#include + +// Implementation of CefStreamReader for files. +class CefFileReader : public CefThreadSafeBase +{ +public: + CefFileReader(FILE* file, bool close); + virtual ~CefFileReader(); + + virtual size_t Read(void* ptr, size_t size, size_t n); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Eof(); + +protected: + bool close_; + FILE *file_; +}; + +// Implementation of CefStreamWriter for files. +class CefFileWriter : public CefThreadSafeBase +{ +public: + CefFileWriter(FILE* file, bool close); + virtual ~CefFileWriter(); + + virtual size_t Write(const void* ptr, size_t size, size_t n); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Flush(); + +protected: + FILE *file_; + bool close_; +}; + +// Implementation of CefStreamReader for byte buffers. +class CefBytesReader : public CefThreadSafeBase +{ +public: + CefBytesReader(void* data, long datasize, bool copy); + virtual ~CefBytesReader(); + + virtual size_t Read(void* ptr, size_t size, size_t n); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Eof(); + + void SetData(void* data, long datasize, bool copy); + + void* GetData() { return data_; } + size_t GetDataSize() { return offset_; } + +protected: + void* data_; + size_t datasize_; + bool copy_; + size_t offset_; +}; + +// Implementation of CefStreamWriter for byte buffers. +class CefBytesWriter : public CefThreadSafeBase +{ +public: + CefBytesWriter(size_t grow); + virtual ~CefBytesWriter(); + + virtual size_t Write(const void* ptr, size_t size, size_t n); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Flush(); + + void* GetData() { return data_; } + size_t GetDataSize() { return offset_; } + std::string GetDataString(); + +protected: + size_t Grow(size_t size); + +protected: + size_t grow_; + void* data_; + size_t datasize_; + size_t offset_; +}; + +// Implementation of CefStreamReader for handlers. +class CefHandlerReader : public CefThreadSafeBase +{ +public: + CefHandlerReader(CefRefPtr handler) : handler_(handler) {} + + virtual size_t Read(void* ptr, size_t size, size_t n) + { + return handler_->Read(ptr, size, n); + } + virtual int Seek(long offset, int whence) + { + return handler_->Seek(offset, whence); + } + virtual long Tell() + { + return handler_->Tell(); + } + virtual int Eof() + { + return handler_->Eof(); + } + +protected: + CefRefPtr handler_; +}; + +// Implementation of CefStreamWriter for handlers. +class CefHandlerWriter : public CefThreadSafeBase +{ +public: + CefHandlerWriter(CefRefPtr handler) : handler_(handler) {} + + virtual size_t Write(const void* ptr, size_t size, size_t n) + { + return handler_->Write(ptr, size, n); + } + virtual int Seek(long offset, int whence) + { + return handler_->Seek(offset, whence); + } + virtual long Tell() + { + return handler_->Tell(); + } + virtual int Flush() + { + return handler_->Flush(); + } + +protected: + CefRefPtr handler_; +}; + +#endif // _STREAM_IMPL_H diff --git a/libcef/tracker.h b/libcef/tracker.h index 5e0aa8df2..b7e536ad9 100644 --- a/libcef/tracker.h +++ b/libcef/tracker.h @@ -1,136 +1,136 @@ -// 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 _TRACKER_H -#define _TRACKER_H - -#include "include/cef.h" - -// Class extended by objects that must be tracked. After creating a tracked -// object you should add it to the appropriate track manager. -class CefTrackObject -{ -public: - CefTrackObject() - { - track_next_ = NULL; - track_prev_ = NULL; - } - virtual ~CefTrackObject() - { - } - - // Returns true if the object is currently being tracked. - bool IsTracked() { return (track_prev_ || track_next_); } - -private: - CefTrackObject* GetTrackPrev() { return track_prev_; } - void SetTrackPrev(CefTrackObject* base) { track_prev_ = base; } - CefTrackObject* GetTrackNext() { return track_next_; } - void SetTrackNext(CefTrackObject* base) { track_next_ = base; } - - // Insert a new object into the tracking list before this object. - void InsertTrackPrev(CefTrackObject* 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(CefTrackObject* 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: - CefTrackObject* track_next_; - CefTrackObject* 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(base::LINKER_INITIALIZED); -class CefTrackManager : public CefThreadSafeBase -{ -public: - CefTrackManager() : object_count_(0) {} - virtual ~CefTrackManager() - { - DeleteAll(); - } - - // Add an object to be tracked by this manager. - void Add(CefTrackObject* object) - { - Lock(); - if(!object->IsTracked()) { - tracker_.InsertTrackNext(object); - ++object_count_; - } - Unlock(); - } - - // Delete an object tracked by this manager. - bool Delete(CefTrackObject* 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(); - CefTrackObject* 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. - long GetCount() { return object_count_; } - -private: - CefTrackObject tracker_; - long object_count_; -}; - -#endif // _TRACKER_H +// 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 _TRACKER_H +#define _TRACKER_H + +#include "include/cef.h" + +// Class extended by objects that must be tracked. After creating a tracked +// object you should add it to the appropriate track manager. +class CefTrackObject +{ +public: + CefTrackObject() + { + track_next_ = NULL; + track_prev_ = NULL; + } + virtual ~CefTrackObject() + { + } + + // Returns true if the object is currently being tracked. + bool IsTracked() { return (track_prev_ || track_next_); } + +private: + CefTrackObject* GetTrackPrev() { return track_prev_; } + void SetTrackPrev(CefTrackObject* base) { track_prev_ = base; } + CefTrackObject* GetTrackNext() { return track_next_; } + void SetTrackNext(CefTrackObject* base) { track_next_ = base; } + + // Insert a new object into the tracking list before this object. + void InsertTrackPrev(CefTrackObject* 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(CefTrackObject* 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: + CefTrackObject* track_next_; + CefTrackObject* 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(base::LINKER_INITIALIZED); +class CefTrackManager : public CefThreadSafeBase +{ +public: + CefTrackManager() : object_count_(0) {} + virtual ~CefTrackManager() + { + DeleteAll(); + } + + // Add an object to be tracked by this manager. + void Add(CefTrackObject* object) + { + Lock(); + if(!object->IsTracked()) { + tracker_.InsertTrackNext(object); + ++object_count_; + } + Unlock(); + } + + // Delete an object tracked by this manager. + bool Delete(CefTrackObject* 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(); + CefTrackObject* 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. + long GetCount() { return object_count_; } + +private: + CefTrackObject tracker_; + long object_count_; +}; + +#endif // _TRACKER_H diff --git a/libcef/v8_impl.cc b/libcef/v8_impl.cc index 5d8b42237..621f4d2d1 100644 --- a/libcef/v8_impl.cc +++ b/libcef/v8_impl.cc @@ -1,690 +1,690 @@ -// 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 "v8_impl.h" -#include "cef_context.h" -#include "tracker.h" -#include "base/lazy_instance.h" -#include "base/utf_string_conversions.h" -#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" -#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" - -// Memory manager. - -base::LazyInstance g_v8_tracker(base::LINKER_INITIALIZED); - -class TrackBase : public CefTrackObject -{ -public: - TrackBase(CefBase* base) { base_ = base; } - -protected: - CefRefPtr base_; -}; - -class TrackString : public CefTrackObject -{ -public: - TrackString(const std::string& str) : string_(str) {} - const char* GetString() { return string_.c_str(); } - -private: - std::string string_; -}; - - -static void TrackAdd(CefTrackObject* object) -{ - g_v8_tracker.Pointer()->Add(object); -} - -static void TrackDelete(CefTrackObject* object) -{ - g_v8_tracker.Pointer()->Delete(object); -} - -// Callback for weak persistent reference destruction. -static void TrackDestructor(v8::Persistent object, - void* parameter) -{ - if(parameter) - TrackDelete(static_cast(parameter)); - object.Dispose(); - object.Clear(); -} - - -// Convert a wide string to a V8 string. -static v8::Handle GetV8String(const std::wstring& str) -{ - return v8::String::New( - reinterpret_cast(str.c_str()), str.length()); -} - -// Convert a V8 string to a wide string. -static std::wstring GetWString(v8::Handle str) -{ - uint16_t* buf = new uint16_t[str->Length()+1]; - str->Write(buf); - std::wstring value = reinterpret_cast(buf); - delete [] buf; - return value; -} - - -// V8 function callback -static 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])); - - std::wstring func_name = - GetWString(v8::Handle::Cast(args.Callee()->GetName())); - CefRefPtr object = new CefV8ValueImpl(args.This()); - CefRefPtr retval; - std::wstring exception; - v8::Handle value = v8::Null(); - - if(handler->Execute(func_name, object, params, retval, exception)) { - if(!exception.empty()) - value = v8::ThrowException(GetV8String(exception)); - else { - CefV8ValueImpl* rv = static_cast(retval.get()); - if(rv) - value = rv->GetValue(); - } - } - - return value; -} - - -// 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) - { - // The reference will be released when the application exits. - TrackAdd(new TrackBase(handler)); - } - - virtual v8::Handle GetNativeFunction( - v8::Handle name) - { - return v8::FunctionTemplate::New(FunctionCallbackImpl, - v8::External::New(handler_)); - } - - void UIT_RegisterExtension() - { - WebKit::WebScriptController::registerExtension(this); - } - - void AddRef() {} - void Release() {} - - static bool ImplementsThreadSafeReferenceCounting() { return true; } - -private: - CefV8Handler* handler_; -}; - -bool CefRegisterExtension(const std::wstring& extension_name, - const std::wstring& javascript_code, - CefRefPtr handler) -{ - // Verify that the context is already initialized - if(!_Context.get()) - return false; - - if(!handler.get()) - return false; - - TrackString* name = new TrackString(WideToUTF8(extension_name)); - TrackAdd(name); - TrackString* code = new TrackString(WideToUTF8(javascript_code)); - TrackAdd(name); - - ExtensionWrapper* wrapper = new ExtensionWrapper(name->GetString(), - code->GetString(), handler.get()); - - CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(wrapper, - &ExtensionWrapper::UIT_RegisterExtension)); - return true; -} - - -// CefV8Value - -// static -CefRefPtr CefV8Value::CreateUndefined() -{ - v8::HandleScope handle_scope; - return new CefV8ValueImpl(v8::Undefined()); -} - -// static -CefRefPtr CefV8Value::CreateNull() -{ - v8::HandleScope handle_scope; - return new CefV8ValueImpl(v8::Null()); -} - -// static -CefRefPtr CefV8Value::CreateBool(bool value) -{ - v8::HandleScope handle_scope; - return new CefV8ValueImpl(v8::Boolean::New(value)); -} - -// static -CefRefPtr CefV8Value::CreateInt(int value) -{ - v8::HandleScope handle_scope; - return new CefV8ValueImpl(v8::Int32::New(value)); -} - -// static -CefRefPtr CefV8Value::CreateDouble(double value) -{ - v8::HandleScope handle_scope; - return new CefV8ValueImpl(v8::Number::New(value)); -} - -// static -CefRefPtr CefV8Value::CreateString(const std::wstring& value) -{ - v8::HandleScope handle_scope; - return new CefV8ValueImpl(GetV8String(value)); -} - -// static -CefRefPtr CefV8Value::CreateObject(CefRefPtr user_data) -{ - v8::HandleScope handle_scope; - CefV8ValueImpl* impl = new CefV8ValueImpl(); - - // Create the new V8 object. - v8::Local obj = v8::Object::New(); - - TrackBase *tracker = NULL; - if(user_data.get()) { - // Attach the user data to the V8 object. - v8::Local data = v8::External::Wrap(user_data.get()); - obj->Set(v8::String::New("Cef::UserData"), data); - - // Provide a tracker object that will cause the user data reference to be - // released when the V8 object is destroyed. - tracker = new TrackBase(user_data); - } - - // Attach to the CefV8ValueImpl. - impl->Attach(obj, tracker); - return impl; -} - -// static -CefRefPtr CefV8Value::CreateArray() -{ - v8::HandleScope handle_scope; - return new CefV8ValueImpl(v8::Array::New()); -} - -// static -CefRefPtr CefV8Value::CreateFunction(const std::wstring& name, - CefRefPtr handler) -{ - v8::HandleScope handle_scope; - CefV8ValueImpl* impl = new CefV8ValueImpl(); - - // Create a new V8 function template with one internal field. - 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(); - func->SetName(GetV8String(name)); - - // Attach the handler instance to the V8 object. - func->Set(v8::String::New("Cef::Handler"), data); - - // Attach to the CefV8ValueImpl and provide a tracker object that will cause - // the handler reference to be released when the V8 object is destroyed. - impl->Attach(func, new TrackBase(handler)); - return impl; -} - - -// CefV8ValueImpl - -CefV8ValueImpl::CefV8ValueImpl() - : tracker_(NULL) -{ -} - -CefV8ValueImpl::CefV8ValueImpl(v8::Handle value, - CefTrackObject* tracker) -{ - Attach(value, tracker); -} - -CefV8ValueImpl::~CefV8ValueImpl() -{ - Detach(); -} - -bool CefV8ValueImpl::Attach(v8::Handle value, - CefTrackObject* tracker) -{ - bool rv = false; - Lock(); - if(v8_value_.IsEmpty()) { - v8_value_ = v8::Persistent::New(value); - tracker_ = tracker; - rv = true; - } - Unlock(); - return rv; -} - -void CefV8ValueImpl::Detach() -{ - Lock(); - if(tracker_) - TrackAdd(tracker_); - v8_value_.MakeWeak(tracker_, TrackDestructor); - tracker_ = NULL; - Unlock(); -} - -v8::Handle CefV8ValueImpl::GetValue() -{ - v8::HandleScope handle_scope; - v8::Handle rv; - Lock(); - rv = v8_value_; - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsReservedKey(const std::wstring& key) -{ - return (key.find(L"Cef::") == 0 || key.find(L"v8::") == 0); -} - -bool CefV8ValueImpl::IsUndefined() -{ - Lock(); - bool rv = v8_value_->IsUndefined(); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsNull() -{ - Lock(); - bool rv = v8_value_->IsNull(); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsBool() -{ - Lock(); - bool rv = (v8_value_->IsBoolean() || v8_value_->IsTrue() - || v8_value_->IsFalse()); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsInt() -{ - Lock(); - bool rv = v8_value_->IsInt32(); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsDouble() -{ - Lock(); - bool rv = (v8_value_->IsNumber() || v8_value_->IsDate()); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsString() -{ - Lock(); - bool rv = v8_value_->IsString(); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsObject() -{ - Lock(); - bool rv = v8_value_->IsObject(); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsArray() -{ - Lock(); - bool rv = v8_value_->IsArray(); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::IsFunction() -{ - Lock(); - bool rv = v8_value_->IsFunction(); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::GetBoolValue() -{ - bool rv = false; - Lock(); - if(v8_value_->IsTrue()) - rv = true; - else if(v8_value_->IsFalse()) - rv = false; - else { - v8::HandleScope handle_scope; - v8::Local val = v8_value_->ToBoolean(); - rv = val->Value(); - } - Unlock(); - return rv; -} - -int CefV8ValueImpl::GetIntValue() -{ - int rv = 0; - Lock(); - v8::HandleScope handle_scope; - v8::Local val = v8_value_->ToInt32(); - rv = val->Value(); - Unlock(); - return rv; -} - -double CefV8ValueImpl::GetDoubleValue() -{ - double rv = 0.; - Lock(); - v8::HandleScope handle_scope; - v8::Local val = v8_value_->ToNumber(); - rv = val->Value(); - Unlock(); - return rv; -} - -std::wstring CefV8ValueImpl::GetStringValue() -{ - std::wstring rv; - Lock(); - v8::HandleScope handle_scope; - rv = GetWString(v8_value_->ToString()); - Unlock(); - return rv; -} - -bool CefV8ValueImpl::HasValue(const std::wstring& key) -{ - if(IsReservedKey(key)) - return false; - - bool rv = false; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = obj->Has(GetV8String(key)); - } - Unlock(); - return rv; -} - -bool CefV8ValueImpl::HasValue(int index) -{ - bool rv = false; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = obj->Has(index); - } - Unlock(); - return rv; -} - -bool CefV8ValueImpl::DeleteValue(const std::wstring& key) -{ - if(IsReservedKey(key)) - return false; - - bool rv = false; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = obj->Delete(GetV8String(key)); - } - Unlock(); - return rv; -} - -bool CefV8ValueImpl::DeleteValue(int index) -{ - bool rv = false; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = obj->Delete(index); - } - Unlock(); - return rv; -} - -CefRefPtr CefV8ValueImpl::GetValue(const std::wstring& key) -{ - if(IsReservedKey(key)) - return false; - - CefRefPtr rv; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = new CefV8ValueImpl(obj->Get(GetV8String(key))); - } - Unlock(); - return rv; -} - -CefRefPtr CefV8ValueImpl::GetValue(int index) -{ - CefRefPtr rv; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = new CefV8ValueImpl(obj->Get(v8::Number::New(index))); - } - Unlock(); - return rv; -} - -bool CefV8ValueImpl::SetValue(const std::wstring& key, - CefRefPtr value) -{ - if(IsReservedKey(key)) - return false; - - bool rv = false; - Lock(); - if(v8_value_->IsObject()) { - CefV8ValueImpl *impl = static_cast(value.get()); - if(impl) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = obj->Set(GetV8String(key), impl->GetValue()); - } - } - Unlock(); - return rv; -} - -bool CefV8ValueImpl::SetValue(int index, CefRefPtr value) -{ - bool rv = false; - Lock(); - if(v8_value_->IsObject()) { - CefV8ValueImpl *impl = static_cast(value.get()); - if(impl) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - rv = obj->Set(v8::Number::New(index), impl->GetValue()); - } - } - Unlock(); - return rv; -} - -bool CefV8ValueImpl::GetKeys(std::vector& keys) -{ - bool rv = false; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - v8::Local arr_keys = obj->GetPropertyNames(); - uint32_t len = arr_keys->Length(); - for(uint32_t i = 0; i < len; ++i) { - v8::Local value = arr_keys->Get(v8::Integer::New(i)); - std::wstring str = GetWString(value->ToString()); - if(!IsReservedKey(str)) - keys.push_back(str); - } - rv = true; - } - Unlock(); - return rv; -} - -CefRefPtr CefV8ValueImpl::GetUserData() -{ - CefRefPtr rv; - Lock(); - if(v8_value_->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - v8::Local key = v8::String::New("Cef::UserData"); - if(obj->Has(key)) - rv = static_cast(v8::External::Unwrap(obj->Get(key))); - } - Unlock(); - return rv; -} - -int CefV8ValueImpl::GetArrayLength() -{ - int rv = 0; - Lock(); - if(v8_value_->IsArray()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - v8::Local arr = v8::Local::Cast(obj); - rv = arr->Length(); - } - Unlock(); - return rv; -} - -std::wstring CefV8ValueImpl::GetFunctionName() -{ - std::wstring rv; - Lock(); - if(v8_value_->IsFunction()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - v8::Local func = v8::Local::Cast(obj); - rv = GetWString(v8::Handle::Cast(func->GetName())); - } - Unlock(); - return rv; -} - -CefRefPtr CefV8ValueImpl::GetFunctionHandler() -{ - CefRefPtr rv; - Lock(); - if(v8_value_->IsFunction()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - v8::Local key = v8::String::New("Cef::Handler"); - if(obj->Has(key)) - rv = static_cast(v8::External::Unwrap(obj->Get(key))); - } - Unlock(); - return rv; -} - -bool CefV8ValueImpl::ExecuteFunction(CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) -{ - bool rv = false; - Lock(); - if(v8_value_->IsFunction() && object.get() && object->IsObject()) { - v8::HandleScope handle_scope; - v8::Local obj = v8_value_->ToObject(); - v8::Local func = v8::Local::Cast(obj); - - CefV8ValueImpl* recv_impl = static_cast(object.get()); - v8::Handle recv = - v8::Handle::Cast(recv_impl->GetValue()); - - 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())->GetValue(); - } - } - - v8::TryCatch try_catch; - v8::Local func_rv = func->Call(recv, argc, argv); - if (try_catch.HasCaught()) - exception = GetWString(try_catch.Message()->Get()); - else - retval = new CefV8ValueImpl(func_rv); - - rv = true; - } - Unlock(); - return rv; -} +// 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 "v8_impl.h" +#include "cef_context.h" +#include "tracker.h" +#include "base/lazy_instance.h" +#include "base/utf_string_conversions.h" +#include "third_party/WebKit/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" + +// Memory manager. + +base::LazyInstance g_v8_tracker(base::LINKER_INITIALIZED); + +class TrackBase : public CefTrackObject +{ +public: + TrackBase(CefBase* base) { base_ = base; } + +protected: + CefRefPtr base_; +}; + +class TrackString : public CefTrackObject +{ +public: + TrackString(const std::string& str) : string_(str) {} + const char* GetString() { return string_.c_str(); } + +private: + std::string string_; +}; + + +static void TrackAdd(CefTrackObject* object) +{ + g_v8_tracker.Pointer()->Add(object); +} + +static void TrackDelete(CefTrackObject* object) +{ + g_v8_tracker.Pointer()->Delete(object); +} + +// Callback for weak persistent reference destruction. +static void TrackDestructor(v8::Persistent object, + void* parameter) +{ + if(parameter) + TrackDelete(static_cast(parameter)); + object.Dispose(); + object.Clear(); +} + + +// Convert a wide string to a V8 string. +static v8::Handle GetV8String(const std::wstring& str) +{ + return v8::String::New( + reinterpret_cast(str.c_str()), str.length()); +} + +// Convert a V8 string to a wide string. +static std::wstring GetWString(v8::Handle str) +{ + uint16_t* buf = new uint16_t[str->Length()+1]; + str->Write(buf); + std::wstring value = reinterpret_cast(buf); + delete [] buf; + return value; +} + + +// V8 function callback +static 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])); + + std::wstring func_name = + GetWString(v8::Handle::Cast(args.Callee()->GetName())); + CefRefPtr object = new CefV8ValueImpl(args.This()); + CefRefPtr retval; + std::wstring exception; + v8::Handle value = v8::Null(); + + if(handler->Execute(func_name, object, params, retval, exception)) { + if(!exception.empty()) + value = v8::ThrowException(GetV8String(exception)); + else { + CefV8ValueImpl* rv = static_cast(retval.get()); + if(rv) + value = rv->GetValue(); + } + } + + return value; +} + + +// 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) + { + // The reference will be released when the application exits. + TrackAdd(new TrackBase(handler)); + } + + virtual v8::Handle GetNativeFunction( + v8::Handle name) + { + return v8::FunctionTemplate::New(FunctionCallbackImpl, + v8::External::New(handler_)); + } + + void UIT_RegisterExtension() + { + WebKit::WebScriptController::registerExtension(this); + } + + void AddRef() {} + void Release() {} + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + +private: + CefV8Handler* handler_; +}; + +bool CefRegisterExtension(const std::wstring& extension_name, + const std::wstring& javascript_code, + CefRefPtr handler) +{ + // Verify that the context is already initialized + if(!_Context.get()) + return false; + + if(!handler.get()) + return false; + + TrackString* name = new TrackString(WideToUTF8(extension_name)); + TrackAdd(name); + TrackString* code = new TrackString(WideToUTF8(javascript_code)); + TrackAdd(name); + + ExtensionWrapper* wrapper = new ExtensionWrapper(name->GetString(), + code->GetString(), handler.get()); + + CefThread::PostTask(CefThread::UI, FROM_HERE, NewRunnableMethod(wrapper, + &ExtensionWrapper::UIT_RegisterExtension)); + return true; +} + + +// CefV8Value + +// static +CefRefPtr CefV8Value::CreateUndefined() +{ + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Undefined()); +} + +// static +CefRefPtr CefV8Value::CreateNull() +{ + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Null()); +} + +// static +CefRefPtr CefV8Value::CreateBool(bool value) +{ + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Boolean::New(value)); +} + +// static +CefRefPtr CefV8Value::CreateInt(int value) +{ + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Int32::New(value)); +} + +// static +CefRefPtr CefV8Value::CreateDouble(double value) +{ + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Number::New(value)); +} + +// static +CefRefPtr CefV8Value::CreateString(const std::wstring& value) +{ + v8::HandleScope handle_scope; + return new CefV8ValueImpl(GetV8String(value)); +} + +// static +CefRefPtr CefV8Value::CreateObject(CefRefPtr user_data) +{ + v8::HandleScope handle_scope; + CefV8ValueImpl* impl = new CefV8ValueImpl(); + + // Create the new V8 object. + v8::Local obj = v8::Object::New(); + + TrackBase *tracker = NULL; + if(user_data.get()) { + // Attach the user data to the V8 object. + v8::Local data = v8::External::Wrap(user_data.get()); + obj->Set(v8::String::New("Cef::UserData"), data); + + // Provide a tracker object that will cause the user data reference to be + // released when the V8 object is destroyed. + tracker = new TrackBase(user_data); + } + + // Attach to the CefV8ValueImpl. + impl->Attach(obj, tracker); + return impl; +} + +// static +CefRefPtr CefV8Value::CreateArray() +{ + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Array::New()); +} + +// static +CefRefPtr CefV8Value::CreateFunction(const std::wstring& name, + CefRefPtr handler) +{ + v8::HandleScope handle_scope; + CefV8ValueImpl* impl = new CefV8ValueImpl(); + + // Create a new V8 function template with one internal field. + 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(); + func->SetName(GetV8String(name)); + + // Attach the handler instance to the V8 object. + func->Set(v8::String::New("Cef::Handler"), data); + + // Attach to the CefV8ValueImpl and provide a tracker object that will cause + // the handler reference to be released when the V8 object is destroyed. + impl->Attach(func, new TrackBase(handler)); + return impl; +} + + +// CefV8ValueImpl + +CefV8ValueImpl::CefV8ValueImpl() + : tracker_(NULL) +{ +} + +CefV8ValueImpl::CefV8ValueImpl(v8::Handle value, + CefTrackObject* tracker) +{ + Attach(value, tracker); +} + +CefV8ValueImpl::~CefV8ValueImpl() +{ + Detach(); +} + +bool CefV8ValueImpl::Attach(v8::Handle value, + CefTrackObject* tracker) +{ + bool rv = false; + Lock(); + if(v8_value_.IsEmpty()) { + v8_value_ = v8::Persistent::New(value); + tracker_ = tracker; + rv = true; + } + Unlock(); + return rv; +} + +void CefV8ValueImpl::Detach() +{ + Lock(); + if(tracker_) + TrackAdd(tracker_); + v8_value_.MakeWeak(tracker_, TrackDestructor); + tracker_ = NULL; + Unlock(); +} + +v8::Handle CefV8ValueImpl::GetValue() +{ + v8::HandleScope handle_scope; + v8::Handle rv; + Lock(); + rv = v8_value_; + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsReservedKey(const std::wstring& key) +{ + return (key.find(L"Cef::") == 0 || key.find(L"v8::") == 0); +} + +bool CefV8ValueImpl::IsUndefined() +{ + Lock(); + bool rv = v8_value_->IsUndefined(); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsNull() +{ + Lock(); + bool rv = v8_value_->IsNull(); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsBool() +{ + Lock(); + bool rv = (v8_value_->IsBoolean() || v8_value_->IsTrue() + || v8_value_->IsFalse()); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsInt() +{ + Lock(); + bool rv = v8_value_->IsInt32(); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsDouble() +{ + Lock(); + bool rv = (v8_value_->IsNumber() || v8_value_->IsDate()); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsString() +{ + Lock(); + bool rv = v8_value_->IsString(); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsObject() +{ + Lock(); + bool rv = v8_value_->IsObject(); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsArray() +{ + Lock(); + bool rv = v8_value_->IsArray(); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::IsFunction() +{ + Lock(); + bool rv = v8_value_->IsFunction(); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::GetBoolValue() +{ + bool rv = false; + Lock(); + if(v8_value_->IsTrue()) + rv = true; + else if(v8_value_->IsFalse()) + rv = false; + else { + v8::HandleScope handle_scope; + v8::Local val = v8_value_->ToBoolean(); + rv = val->Value(); + } + Unlock(); + return rv; +} + +int CefV8ValueImpl::GetIntValue() +{ + int rv = 0; + Lock(); + v8::HandleScope handle_scope; + v8::Local val = v8_value_->ToInt32(); + rv = val->Value(); + Unlock(); + return rv; +} + +double CefV8ValueImpl::GetDoubleValue() +{ + double rv = 0.; + Lock(); + v8::HandleScope handle_scope; + v8::Local val = v8_value_->ToNumber(); + rv = val->Value(); + Unlock(); + return rv; +} + +std::wstring CefV8ValueImpl::GetStringValue() +{ + std::wstring rv; + Lock(); + v8::HandleScope handle_scope; + rv = GetWString(v8_value_->ToString()); + Unlock(); + return rv; +} + +bool CefV8ValueImpl::HasValue(const std::wstring& key) +{ + if(IsReservedKey(key)) + return false; + + bool rv = false; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = obj->Has(GetV8String(key)); + } + Unlock(); + return rv; +} + +bool CefV8ValueImpl::HasValue(int index) +{ + bool rv = false; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = obj->Has(index); + } + Unlock(); + return rv; +} + +bool CefV8ValueImpl::DeleteValue(const std::wstring& key) +{ + if(IsReservedKey(key)) + return false; + + bool rv = false; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = obj->Delete(GetV8String(key)); + } + Unlock(); + return rv; +} + +bool CefV8ValueImpl::DeleteValue(int index) +{ + bool rv = false; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = obj->Delete(index); + } + Unlock(); + return rv; +} + +CefRefPtr CefV8ValueImpl::GetValue(const std::wstring& key) +{ + if(IsReservedKey(key)) + return false; + + CefRefPtr rv; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = new CefV8ValueImpl(obj->Get(GetV8String(key))); + } + Unlock(); + return rv; +} + +CefRefPtr CefV8ValueImpl::GetValue(int index) +{ + CefRefPtr rv; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = new CefV8ValueImpl(obj->Get(v8::Number::New(index))); + } + Unlock(); + return rv; +} + +bool CefV8ValueImpl::SetValue(const std::wstring& key, + CefRefPtr value) +{ + if(IsReservedKey(key)) + return false; + + bool rv = false; + Lock(); + if(v8_value_->IsObject()) { + CefV8ValueImpl *impl = static_cast(value.get()); + if(impl) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = obj->Set(GetV8String(key), impl->GetValue()); + } + } + Unlock(); + return rv; +} + +bool CefV8ValueImpl::SetValue(int index, CefRefPtr value) +{ + bool rv = false; + Lock(); + if(v8_value_->IsObject()) { + CefV8ValueImpl *impl = static_cast(value.get()); + if(impl) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + rv = obj->Set(v8::Number::New(index), impl->GetValue()); + } + } + Unlock(); + return rv; +} + +bool CefV8ValueImpl::GetKeys(std::vector& keys) +{ + bool rv = false; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + v8::Local arr_keys = obj->GetPropertyNames(); + uint32_t len = arr_keys->Length(); + for(uint32_t i = 0; i < len; ++i) { + v8::Local value = arr_keys->Get(v8::Integer::New(i)); + std::wstring str = GetWString(value->ToString()); + if(!IsReservedKey(str)) + keys.push_back(str); + } + rv = true; + } + Unlock(); + return rv; +} + +CefRefPtr CefV8ValueImpl::GetUserData() +{ + CefRefPtr rv; + Lock(); + if(v8_value_->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + v8::Local key = v8::String::New("Cef::UserData"); + if(obj->Has(key)) + rv = static_cast(v8::External::Unwrap(obj->Get(key))); + } + Unlock(); + return rv; +} + +int CefV8ValueImpl::GetArrayLength() +{ + int rv = 0; + Lock(); + if(v8_value_->IsArray()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + v8::Local arr = v8::Local::Cast(obj); + rv = arr->Length(); + } + Unlock(); + return rv; +} + +std::wstring CefV8ValueImpl::GetFunctionName() +{ + std::wstring rv; + Lock(); + if(v8_value_->IsFunction()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + v8::Local func = v8::Local::Cast(obj); + rv = GetWString(v8::Handle::Cast(func->GetName())); + } + Unlock(); + return rv; +} + +CefRefPtr CefV8ValueImpl::GetFunctionHandler() +{ + CefRefPtr rv; + Lock(); + if(v8_value_->IsFunction()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + v8::Local key = v8::String::New("Cef::Handler"); + if(obj->Has(key)) + rv = static_cast(v8::External::Unwrap(obj->Get(key))); + } + Unlock(); + return rv; +} + +bool CefV8ValueImpl::ExecuteFunction(CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) +{ + bool rv = false; + Lock(); + if(v8_value_->IsFunction() && object.get() && object->IsObject()) { + v8::HandleScope handle_scope; + v8::Local obj = v8_value_->ToObject(); + v8::Local func = v8::Local::Cast(obj); + + CefV8ValueImpl* recv_impl = static_cast(object.get()); + v8::Handle recv = + v8::Handle::Cast(recv_impl->GetValue()); + + 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())->GetValue(); + } + } + + v8::TryCatch try_catch; + v8::Local func_rv = func->Call(recv, argc, argv); + if (try_catch.HasCaught()) + exception = GetWString(try_catch.Message()->Get()); + else + retval = new CefV8ValueImpl(func_rv); + + rv = true; + } + Unlock(); + return rv; +} diff --git a/libcef/v8_impl.h b/libcef/v8_impl.h index 971623df3..10e934003 100644 --- a/libcef/v8_impl.h +++ b/libcef/v8_impl.h @@ -1,61 +1,61 @@ -// 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 _V8_IMPL_H -#define _V8_IMPL_H - -#include "include/cef.h" -#include "v8/include/v8.h" - -class CefTrackObject; - -class CefV8ValueImpl : public CefThreadSafeBase -{ -public: - CefV8ValueImpl(); - CefV8ValueImpl(v8::Handle value, CefTrackObject* tracker = NULL); - virtual ~CefV8ValueImpl(); - - bool Attach(v8::Handle value, CefTrackObject* tracker = NULL); - void Detach(); - v8::Handle GetValue(); - bool IsReservedKey(const std::wstring& key); - - virtual bool IsUndefined(); - virtual bool IsNull(); - virtual bool IsBool(); - virtual bool IsInt(); - virtual bool IsDouble(); - virtual bool IsString(); - virtual bool IsObject(); - virtual bool IsArray(); - virtual bool IsFunction(); - virtual bool GetBoolValue(); - virtual int GetIntValue(); - virtual double GetDoubleValue(); - virtual std::wstring GetStringValue(); - virtual bool HasValue(const std::wstring& key); - virtual bool HasValue(int index); - virtual bool DeleteValue(const std::wstring& key); - virtual bool DeleteValue(int index); - virtual CefRefPtr GetValue(const std::wstring& key); - virtual CefRefPtr GetValue(int index); - virtual bool SetValue(const std::wstring& key, CefRefPtr value); - virtual bool SetValue(int index, CefRefPtr value); - virtual bool GetKeys(std::vector& keys); - virtual CefRefPtr GetUserData(); - virtual int GetArrayLength(); - virtual std::wstring GetFunctionName(); - virtual CefRefPtr GetFunctionHandler(); - virtual bool ExecuteFunction(CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception); - -protected: - v8::Persistent v8_value_; - CefTrackObject* tracker_; -}; - -#endif //_V8_IMPL_H +// 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 _V8_IMPL_H +#define _V8_IMPL_H + +#include "include/cef.h" +#include "v8/include/v8.h" + +class CefTrackObject; + +class CefV8ValueImpl : public CefThreadSafeBase +{ +public: + CefV8ValueImpl(); + CefV8ValueImpl(v8::Handle value, CefTrackObject* tracker = NULL); + virtual ~CefV8ValueImpl(); + + bool Attach(v8::Handle value, CefTrackObject* tracker = NULL); + void Detach(); + v8::Handle GetValue(); + bool IsReservedKey(const std::wstring& key); + + virtual bool IsUndefined(); + virtual bool IsNull(); + virtual bool IsBool(); + virtual bool IsInt(); + virtual bool IsDouble(); + virtual bool IsString(); + virtual bool IsObject(); + virtual bool IsArray(); + virtual bool IsFunction(); + virtual bool GetBoolValue(); + virtual int GetIntValue(); + virtual double GetDoubleValue(); + virtual std::wstring GetStringValue(); + virtual bool HasValue(const std::wstring& key); + virtual bool HasValue(int index); + virtual bool DeleteValue(const std::wstring& key); + virtual bool DeleteValue(int index); + virtual CefRefPtr GetValue(const std::wstring& key); + virtual CefRefPtr GetValue(int index); + virtual bool SetValue(const std::wstring& key, CefRefPtr value); + virtual bool SetValue(int index, CefRefPtr value); + virtual bool GetKeys(std::vector& keys); + virtual CefRefPtr GetUserData(); + virtual int GetArrayLength(); + virtual std::wstring GetFunctionName(); + virtual CefRefPtr GetFunctionHandler(); + virtual bool ExecuteFunction(CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception); + +protected: + v8::Persistent v8_value_; + CefTrackObject* tracker_; +}; + +#endif //_V8_IMPL_H diff --git a/libcef/webview_host.cc b/libcef/webview_host.cc index 892d0d7bd..94b45d26f 100644 --- a/libcef/webview_host.cc +++ b/libcef/webview_host.cc @@ -1,54 +1,54 @@ -// 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 "webview_host.h" -#include "browser_webview_delegate.h" - -#include "gfx/rect.h" -#include "gfx/size.h" -#include "base/win_util.h" -#include "third_party/WebKit/WebKit/chromium/public/WebView.h" -#include "webkit/glue/webpreferences.h" - -using namespace WebKit; - -static const wchar_t kWindowClassName[] = L"WebViewHost"; - -/*static*/ -WebViewHost* WebViewHost::Create(HWND parent_view, - BrowserWebViewDelegate* delegate, - WebDevToolsAgentClient* dev_tools_client, - const WebPreferences& prefs) { - WebViewHost* host = new WebViewHost(); - - 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); - win_util::SetWindowUserData(host->view_, host); - - host->webwidget_ = WebView::create(delegate, dev_tools_client); - prefs.Apply(host->webview()); - host->webview()->initializeMainFrame(delegate); - - return host; -} - -WebView* WebViewHost::webview() const { - return static_cast(webwidget_); -} - +// 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 "webview_host.h" +#include "browser_webview_delegate.h" + +#include "gfx/rect.h" +#include "gfx/size.h" +#include "base/win_util.h" +#include "third_party/WebKit/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webpreferences.h" + +using namespace WebKit; + +static const wchar_t kWindowClassName[] = L"WebViewHost"; + +/*static*/ +WebViewHost* WebViewHost::Create(HWND parent_view, + BrowserWebViewDelegate* delegate, + WebDevToolsAgentClient* dev_tools_client, + const WebPreferences& prefs) { + WebViewHost* host = new WebViewHost(); + + 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); + win_util::SetWindowUserData(host->view_, host); + + host->webwidget_ = WebView::create(delegate, dev_tools_client); + prefs.Apply(host->webview()); + host->webview()->initializeMainFrame(delegate); + + return host; +} + +WebView* WebViewHost::webview() const { + return static_cast(webwidget_); +} + diff --git a/libcef/webview_host.h b/libcef/webview_host.h index 148ed11f9..7b39fb7c8 100644 --- a/libcef/webview_host.h +++ b/libcef/webview_host.h @@ -1,42 +1,42 @@ -// 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 _WEBVIEW_HOST_H -#define _WEBVIEW_HOST_H - -#include "base/basictypes.h" -#include "gfx/rect.h" -#include "gfx/native_widget_types.h" -#include "webwidget_host.h" - -struct WebPreferences; -class BrowserWebViewDelegate; - -namespace WebKit { -class WebDevToolsAgentClient; -class WebView; -} - -// This class is a simple ViewHandle-based host for a WebView -class WebViewHost : public WebWidgetHost { - public: - // The new instance is deleted once the associated ViewHandle 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_window, - BrowserWebViewDelegate* delegate, - WebKit::WebDevToolsAgentClient* devtools_client, - const WebPreferences& prefs); - - WebKit::WebView* webview() const; - - protected: -#if defined(OS_WIN) - virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam) { - return false; - } -#endif -}; - -#endif // _WEBVIEW_HOST_H +// 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 _WEBVIEW_HOST_H +#define _WEBVIEW_HOST_H + +#include "base/basictypes.h" +#include "gfx/rect.h" +#include "gfx/native_widget_types.h" +#include "webwidget_host.h" + +struct WebPreferences; +class BrowserWebViewDelegate; + +namespace WebKit { +class WebDevToolsAgentClient; +class WebView; +} + +// This class is a simple ViewHandle-based host for a WebView +class WebViewHost : public WebWidgetHost { + public: + // The new instance is deleted once the associated ViewHandle 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_window, + BrowserWebViewDelegate* delegate, + WebKit::WebDevToolsAgentClient* devtools_client, + const WebPreferences& prefs); + + WebKit::WebView* webview() const; + + protected: +#if defined(OS_WIN) + virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam) { + return false; + } +#endif +}; + +#endif // _WEBVIEW_HOST_H diff --git a/libcef/webwidget_host.cc b/libcef/webwidget_host.cc index dd4083277..cc265fa8e 100644 --- a/libcef/webwidget_host.cc +++ b/libcef/webwidget_host.cc @@ -1,457 +1,457 @@ -// 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 "webwidget_host.h" - -#include "gfx/rect.h" -#include "base/logging.h" -#include "base/win_util.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" -#include "third_party/WebKit/WebKit/chromium/public/WebPopupMenu.h" -#include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h" -#include "third_party/WebKit/WebKit/chromium/public/WebSize.h" -#include "third_party/WebKit/WebKit/chromium/public/win/WebInputEventFactory.h" -#include "third_party/WebKit/WebKit/chromium/public/win/WebScreenInfoFactory.h" - -#include - -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"; - -/*static*/ -WebWidgetHost* WebWidgetHost::Create(HWND parent_view, - WebWidgetClient* client) { - WebWidgetHost* host = new WebWidgetHost(); - - 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); - - win_util::SetWindowUserData(host->view_, host); - - host->webwidget_ = WebPopupMenu::create(client); - - return host; -} - -/*static*/ -static WebWidgetHost* FromWindow(HWND view) { - return reinterpret_cast(win_util::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: { - RECT rect; - if (GetUpdateRect(hwnd, &rect, FALSE)) { - host->UpdatePaintRect(gfx::Rect(rect)); - } - 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); - break; - - case WM_MOUSEWHEEL: - host->WheelEvent(wparam, lparam); - break; - - case WM_CAPTURECHANGED: - case WM_CANCELMODE: - host->CaptureLostEvent(); - break; - - // TODO(darin): add WM_SYSKEY{DOWN/UP} to capture ALT key actions - case WM_KEYDOWN: - case WM_KEYUP: - case WM_SYSKEYDOWN: - case WM_SYSKEYUP: - case WM_CHAR: - case WM_SYSCHAR: - host->KeyEvent(message, wparam, lparam); - break; - - case WM_SETFOCUS: - host->SetFocus(true); - break; - - case WM_KILLFOCUS: - host->SetFocus(false); - break; - - case WM_NOTIFY: - host->OnNotify(0, (NMHDR*)lparam); - break; - } - } - - 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. - if (damaged_rect.Intersects(scroll_rect_)) { - paint_rect_ = paint_rect_.Union(scroll_rect_); - ResetScrollRect(); - } - paint_rect_ = paint_rect_.Union(damaged_rect); - - RECT r = damaged_rect.ToRECT(); - InvalidateRect(view_, &r, FALSE); -} - -void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) { - if (dx != 0 && dy != 0) { - // We only support uni-directional scroll - DidScrollRect(0, dy, clip_rect); - dy = 0; - } - - // If we already have a pending scroll operation or if this scroll operation - // intersects the existing paint region, then just failover to invalidating. - if (!scroll_rect_.IsEmpty() || paint_rect_.Intersects(clip_rect)) { - paint_rect_ = paint_rect_.Union(scroll_rect_); - ResetScrollRect(); - paint_rect_ = paint_rect_.Union(clip_rect); - } - - // We will perform scrolling lazily, when requested to actually paint. - scroll_rect_ = clip_rect; - scroll_dx_ = dx; - scroll_dy_ = dy; - - RECT r = clip_rect.ToRECT(); - InvalidateRect(view_, &r, FALSE); -} - -void WebWidgetHost::ScheduleComposite() { - if (!webwidget_) - return; - WebSize size = webwidget_->size(); - gfx::Rect rect(0, 0, size.width, size.height); - RECT r = rect.ToRECT(); - InvalidateRect(view_, &r, FALSE); -} - -void WebWidgetHost::SetCursor(HCURSOR cursor) { - SetClassLong(view_, GCL_HCURSOR, - static_cast(reinterpret_cast(cursor))); - ::SetCursor(cursor); -} - -void WebWidgetHost::DiscardBackingStore() { - canvas_.reset(); -} - -WebWidgetHost::WebWidgetHost() - : view_(NULL), - webwidget_(NULL), - track_mouse_leave_(false), - scroll_dx_(0), - scroll_dy_(0), - tooltip_view_(NULL), - tooltip_showing_(false) { - set_painting(false); -} - -WebWidgetHost::~WebWidgetHost() { - win_util::SetWindowUserData(view_, 0); - - TrackMouseLeave(false); - ResetTooltip(); -} - -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::UpdatePaintRect(const gfx::Rect& rect) { - paint_rect_ = paint_rect_.Union(rect); -} - -void WebWidgetHost::Paint() { - RECT r; - GetClientRect(view_, &r); - gfx::Rect client_rect(r); - - // Allocate a canvas if necessary - if (!canvas_.get()) { - ResetScrollRect(); - paint_rect_ = client_rect; - canvas_.reset(new skia::PlatformCanvas( - paint_rect_.width(), paint_rect_.height(), true)); - } - - // This may result in more invalidation - webwidget_->layout(); - - // Scroll the canvas if necessary - scroll_rect_ = client_rect.Intersect(scroll_rect_); - if (!scroll_rect_.IsEmpty()) { - HDC hdc = canvas_->getTopPlatformDevice().getBitmapDC(); - - RECT damaged_rect, r = scroll_rect_.ToRECT(); - ScrollDC(hdc, scroll_dx_, scroll_dy_, NULL, &r, NULL, &damaged_rect); - - PaintRect(gfx::Rect(damaged_rect)); - } - ResetScrollRect(); - - // 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) { - 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); - } - } - DCHECK(paint_rect_.IsEmpty()); - - // Paint to the screen - PAINTSTRUCT ps; - BeginPaint(view_, &ps); - canvas_->getTopPlatformDevice().drawToHDC(ps.hdc, - ps.rcPaint.left, - ps.rcPaint.top, - &ps.rcPaint); - EndPaint(view_, &ps); - - // Draw children - UpdateWindow(view_); -} - -WebScreenInfo WebWidgetHost::GetScreenInfo() { - return WebScreenInfoFactory::screenInfo(view_); -} - -void WebWidgetHost::Resize(LPARAM lparam) { - // Force an entire re-paint. TODO(darin): Maybe reuse this memory buffer. - DiscardBackingStore(); - - webwidget_->resize(WebSize(LOWORD(lparam), HIWORD(lparam))); - EnsureTooltip(); -} - -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: - SetCapture(view_); - // 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. - ::SetFocus(view_); - break; - case WebInputEvent::MouseUp: - 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 std::wstring& new_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() { - UINT message = TTM_NEWTOOLRECT; - - TOOLINFO ti; - ti.cbSize = sizeof(ti); - ti.hwnd = view_handle(); - 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_handle(), NULL, - NULL, NULL); - ti.uFlags = TTF_SUBCLASS; - ti.lpszText = LPSTR_TEXTCALLBACK; - } - - GetClientRect(view_handle(), &ti.rect); - SendMessage(tooltip_view_, message, NULL, reinterpret_cast(&ti)); -} - -void WebWidgetHost::ResetTooltip() { - if (::IsWindow(tooltip_view_)) - ::DestroyWindow(tooltip_view_); - tooltip_view_ = NULL; -} - -void WebWidgetHost::TrackMouseLeave(bool track) { - 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::ResetScrollRect() { - scroll_rect_ = gfx::Rect(); - scroll_dx_ = 0; - scroll_dy_ = 0; -} - -void WebWidgetHost::PaintRect(const gfx::Rect& rect) { -#ifndef NDEBUG - DCHECK(!painting_); -#endif - DCHECK(canvas_.get()); - - set_painting(true); - webwidget_->paint(canvas_.get(), rect); - set_painting(false); -} +// 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 "webwidget_host.h" + +#include "gfx/rect.h" +#include "base/logging.h" +#include "base/win_util.h" +#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/WebKit/chromium/public/WebPopupMenu.h" +#include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h" +#include "third_party/WebKit/WebKit/chromium/public/WebSize.h" +#include "third_party/WebKit/WebKit/chromium/public/win/WebInputEventFactory.h" +#include "third_party/WebKit/WebKit/chromium/public/win/WebScreenInfoFactory.h" + +#include + +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"; + +/*static*/ +WebWidgetHost* WebWidgetHost::Create(HWND parent_view, + WebWidgetClient* client) { + WebWidgetHost* host = new WebWidgetHost(); + + 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); + + win_util::SetWindowUserData(host->view_, host); + + host->webwidget_ = WebPopupMenu::create(client); + + return host; +} + +/*static*/ +static WebWidgetHost* FromWindow(HWND view) { + return reinterpret_cast(win_util::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: { + RECT rect; + if (GetUpdateRect(hwnd, &rect, FALSE)) { + host->UpdatePaintRect(gfx::Rect(rect)); + } + 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); + break; + + case WM_MOUSEWHEEL: + host->WheelEvent(wparam, lparam); + break; + + case WM_CAPTURECHANGED: + case WM_CANCELMODE: + host->CaptureLostEvent(); + break; + + // TODO(darin): add WM_SYSKEY{DOWN/UP} to capture ALT key actions + case WM_KEYDOWN: + case WM_KEYUP: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + case WM_CHAR: + case WM_SYSCHAR: + host->KeyEvent(message, wparam, lparam); + break; + + case WM_SETFOCUS: + host->SetFocus(true); + break; + + case WM_KILLFOCUS: + host->SetFocus(false); + break; + + case WM_NOTIFY: + host->OnNotify(0, (NMHDR*)lparam); + break; + } + } + + 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. + if (damaged_rect.Intersects(scroll_rect_)) { + paint_rect_ = paint_rect_.Union(scroll_rect_); + ResetScrollRect(); + } + paint_rect_ = paint_rect_.Union(damaged_rect); + + RECT r = damaged_rect.ToRECT(); + InvalidateRect(view_, &r, FALSE); +} + +void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) { + if (dx != 0 && dy != 0) { + // We only support uni-directional scroll + DidScrollRect(0, dy, clip_rect); + dy = 0; + } + + // If we already have a pending scroll operation or if this scroll operation + // intersects the existing paint region, then just failover to invalidating. + if (!scroll_rect_.IsEmpty() || paint_rect_.Intersects(clip_rect)) { + paint_rect_ = paint_rect_.Union(scroll_rect_); + ResetScrollRect(); + paint_rect_ = paint_rect_.Union(clip_rect); + } + + // We will perform scrolling lazily, when requested to actually paint. + scroll_rect_ = clip_rect; + scroll_dx_ = dx; + scroll_dy_ = dy; + + RECT r = clip_rect.ToRECT(); + InvalidateRect(view_, &r, FALSE); +} + +void WebWidgetHost::ScheduleComposite() { + if (!webwidget_) + return; + WebSize size = webwidget_->size(); + gfx::Rect rect(0, 0, size.width, size.height); + RECT r = rect.ToRECT(); + InvalidateRect(view_, &r, FALSE); +} + +void WebWidgetHost::SetCursor(HCURSOR cursor) { + SetClassLong(view_, GCL_HCURSOR, + static_cast(reinterpret_cast(cursor))); + ::SetCursor(cursor); +} + +void WebWidgetHost::DiscardBackingStore() { + canvas_.reset(); +} + +WebWidgetHost::WebWidgetHost() + : view_(NULL), + webwidget_(NULL), + track_mouse_leave_(false), + scroll_dx_(0), + scroll_dy_(0), + tooltip_view_(NULL), + tooltip_showing_(false) { + set_painting(false); +} + +WebWidgetHost::~WebWidgetHost() { + win_util::SetWindowUserData(view_, 0); + + TrackMouseLeave(false); + ResetTooltip(); +} + +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::UpdatePaintRect(const gfx::Rect& rect) { + paint_rect_ = paint_rect_.Union(rect); +} + +void WebWidgetHost::Paint() { + RECT r; + GetClientRect(view_, &r); + gfx::Rect client_rect(r); + + // Allocate a canvas if necessary + if (!canvas_.get()) { + ResetScrollRect(); + paint_rect_ = client_rect; + canvas_.reset(new skia::PlatformCanvas( + paint_rect_.width(), paint_rect_.height(), true)); + } + + // This may result in more invalidation + webwidget_->layout(); + + // Scroll the canvas if necessary + scroll_rect_ = client_rect.Intersect(scroll_rect_); + if (!scroll_rect_.IsEmpty()) { + HDC hdc = canvas_->getTopPlatformDevice().getBitmapDC(); + + RECT damaged_rect, r = scroll_rect_.ToRECT(); + ScrollDC(hdc, scroll_dx_, scroll_dy_, NULL, &r, NULL, &damaged_rect); + + PaintRect(gfx::Rect(damaged_rect)); + } + ResetScrollRect(); + + // 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) { + 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); + } + } + DCHECK(paint_rect_.IsEmpty()); + + // Paint to the screen + PAINTSTRUCT ps; + BeginPaint(view_, &ps); + canvas_->getTopPlatformDevice().drawToHDC(ps.hdc, + ps.rcPaint.left, + ps.rcPaint.top, + &ps.rcPaint); + EndPaint(view_, &ps); + + // Draw children + UpdateWindow(view_); +} + +WebScreenInfo WebWidgetHost::GetScreenInfo() { + return WebScreenInfoFactory::screenInfo(view_); +} + +void WebWidgetHost::Resize(LPARAM lparam) { + // Force an entire re-paint. TODO(darin): Maybe reuse this memory buffer. + DiscardBackingStore(); + + webwidget_->resize(WebSize(LOWORD(lparam), HIWORD(lparam))); + EnsureTooltip(); +} + +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: + SetCapture(view_); + // 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. + ::SetFocus(view_); + break; + case WebInputEvent::MouseUp: + 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 std::wstring& new_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() { + UINT message = TTM_NEWTOOLRECT; + + TOOLINFO ti; + ti.cbSize = sizeof(ti); + ti.hwnd = view_handle(); + 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_handle(), NULL, + NULL, NULL); + ti.uFlags = TTF_SUBCLASS; + ti.lpszText = LPSTR_TEXTCALLBACK; + } + + GetClientRect(view_handle(), &ti.rect); + SendMessage(tooltip_view_, message, NULL, reinterpret_cast(&ti)); +} + +void WebWidgetHost::ResetTooltip() { + if (::IsWindow(tooltip_view_)) + ::DestroyWindow(tooltip_view_); + tooltip_view_ = NULL; +} + +void WebWidgetHost::TrackMouseLeave(bool track) { + 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::ResetScrollRect() { + scroll_rect_ = gfx::Rect(); + scroll_dx_ = 0; + scroll_dy_ = 0; +} + +void WebWidgetHost::PaintRect(const gfx::Rect& rect) { +#ifndef NDEBUG + DCHECK(!painting_); +#endif + DCHECK(canvas_.get()); + + set_painting(true); + webwidget_->paint(canvas_.get(), rect); + set_painting(false); +} diff --git a/libcef/webwidget_host.h b/libcef/webwidget_host.h index 74482df22..3d1e4f550 100644 --- a/libcef/webwidget_host.h +++ b/libcef/webwidget_host.h @@ -1,144 +1,144 @@ -// 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 _WEBWIDGET_HOST_H -#define _WEBWIDGET_HOST_H - -#include "base/basictypes.h" -#include "gfx/rect.h" -#include "base/scoped_ptr.h" -#include "gfx/native_widget_types.h" -#include "skia/ext/platform_canvas.h" -#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" - -namespace gfx { -class Size; -} - -namespace WebKit { -class WebWidget; -class WebWidgetClient; -class WebKeyboardEvent; -struct WebScreenInfo; -} - -// This class is a simple ViewHandle-based host for a WebWidget -class WebWidgetHost { - public: - // The new instance is deleted once the associated ViewHandle 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); - -#if defined(OS_MACOSX) - static void HandleEvent(gfx::NativeView view, NSEvent *event); -#endif - - 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); - void ScheduleComposite(); -#if defined(OS_WIN) - void SetCursor(HCURSOR cursor); -#endif - - void DiscardBackingStore(); - // Allow clients to update the paint rect. For example, if we get a gdk - // expose or WM_PAINT event, we need to update the paint rect. - void UpdatePaintRect(const gfx::Rect& rect); - void Paint(); - - 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 std::wstring& tooltip_text); - - protected: - WebWidgetHost(); - ~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); - void MouseEvent(UINT message, WPARAM wparam, LPARAM lparam); - void WheelEvent(WPARAM wparam, LPARAM lparam); - 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); -#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); - void MouseEvent(NSEvent *); - void WheelEvent(NSEvent *); - void KeyEvent(NSEvent *); - void SetFocus(bool enable); - protected: -#elif defined(OS_LINUX) - 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 CreateWindow(gfx::NativeView parent_view, - WebWidgetHost* host); - void WindowDestroyed(); - void Resize(const gfx::Size& size); -#endif - - void TrackMouseLeave(bool enable); - void ResetScrollRect(); - void set_painting(bool value) { -#ifndef NDEBUG - painting_ = value; -#endif - } - - void EnsureTooltip(); - void ResetTooltip(); - - gfx::NativeView view_; - WebKit::WebWidget* webwidget_; - scoped_ptr canvas_; - - // specifies the portion of the webwidget that needs painting - gfx::Rect paint_rect_; - - // specifies the portion of the webwidget that needs scrolling - gfx::Rect scroll_rect_; - int scroll_dx_; - int scroll_dy_; - - bool track_mouse_leave_; - - WebKit::WebKeyboardEvent last_key_event_; - - gfx::NativeView tooltip_view_; - std::wstring tooltip_text_; - bool tooltip_showing_; - -#ifndef NDEBUG - bool painting_; -#endif -}; - -#endif // _WEBWIDGET_HOST_H +// 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 _WEBWIDGET_HOST_H +#define _WEBWIDGET_HOST_H + +#include "base/basictypes.h" +#include "gfx/rect.h" +#include "base/scoped_ptr.h" +#include "gfx/native_widget_types.h" +#include "skia/ext/platform_canvas.h" +#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" + +namespace gfx { +class Size; +} + +namespace WebKit { +class WebWidget; +class WebWidgetClient; +class WebKeyboardEvent; +struct WebScreenInfo; +} + +// This class is a simple ViewHandle-based host for a WebWidget +class WebWidgetHost { + public: + // The new instance is deleted once the associated ViewHandle 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); + +#if defined(OS_MACOSX) + static void HandleEvent(gfx::NativeView view, NSEvent *event); +#endif + + 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); + void ScheduleComposite(); +#if defined(OS_WIN) + void SetCursor(HCURSOR cursor); +#endif + + void DiscardBackingStore(); + // Allow clients to update the paint rect. For example, if we get a gdk + // expose or WM_PAINT event, we need to update the paint rect. + void UpdatePaintRect(const gfx::Rect& rect); + void Paint(); + + 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 std::wstring& tooltip_text); + + protected: + WebWidgetHost(); + ~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); + void MouseEvent(UINT message, WPARAM wparam, LPARAM lparam); + void WheelEvent(WPARAM wparam, LPARAM lparam); + 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); +#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); + void MouseEvent(NSEvent *); + void WheelEvent(NSEvent *); + void KeyEvent(NSEvent *); + void SetFocus(bool enable); + protected: +#elif defined(OS_LINUX) + 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 CreateWindow(gfx::NativeView parent_view, + WebWidgetHost* host); + void WindowDestroyed(); + void Resize(const gfx::Size& size); +#endif + + void TrackMouseLeave(bool enable); + void ResetScrollRect(); + void set_painting(bool value) { +#ifndef NDEBUG + painting_ = value; +#endif + } + + void EnsureTooltip(); + void ResetTooltip(); + + gfx::NativeView view_; + WebKit::WebWidget* webwidget_; + scoped_ptr canvas_; + + // specifies the portion of the webwidget that needs painting + gfx::Rect paint_rect_; + + // specifies the portion of the webwidget that needs scrolling + gfx::Rect scroll_rect_; + int scroll_dx_; + int scroll_dy_; + + bool track_mouse_leave_; + + WebKit::WebKeyboardEvent last_key_event_; + + gfx::NativeView tooltip_view_; + std::wstring tooltip_text_; + bool tooltip_showing_; + +#ifndef NDEBUG + bool painting_; +#endif +}; + +#endif // _WEBWIDGET_HOST_H diff --git a/libcef_dll/cef_logging.h b/libcef_dll/cef_logging.h index 52ef4bb7c..9fcbd50cc 100644 --- a/libcef_dll/cef_logging.h +++ b/libcef_dll/cef_logging.h @@ -1,10 +1,10 @@ -// 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. - -#ifdef BUILDING_CEF_SHARED -#include "base/logging.h" -#else -#include -#define DCHECK(condition) assert(condition) -#endif +// 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. + +#ifdef BUILDING_CEF_SHARED +#include "base/logging.h" +#else +#include +#define DCHECK(condition) assert(condition) +#endif diff --git a/libcef_dll/cpptoc/base_cpptoc.h b/libcef_dll/cpptoc/base_cpptoc.h index aaf42bb29..76aa7c4d6 100644 --- a/libcef_dll/cpptoc/base_cpptoc.h +++ b/libcef_dll/cpptoc/base_cpptoc.h @@ -1,143 +1,143 @@ -// 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 _BASE_CPPTOC_H -#define _BASE_CPPTOC_H - -#include "include/cef.h" -#include "include/cef_capi.h" -#include "libcef_dll/cef_logging.h" - - -// CefCppToC implementation for CefBase. -class CefBaseCppToC : public CefThreadSafeBase -{ -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) - { - // 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) - { - // 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) - { - // 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_; - }; - - 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. - virtual int AddRef() - { - UnderlyingAddRef(); - return CefThreadSafeBase::AddRef(); - } - virtual int Release() - { - UnderlyingRelease(); - return CefThreadSafeBase::Release(); - } - - // 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: - Struct struct_; - CefBase* class_; -}; - -#endif // _BASE_CPPTOC_H +// 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 _BASE_CPPTOC_H +#define _BASE_CPPTOC_H + +#include "include/cef.h" +#include "include/cef_capi.h" +#include "libcef_dll/cef_logging.h" + + +// CefCppToC implementation for CefBase. +class CefBaseCppToC : public CefThreadSafeBase +{ +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) + { + // 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) + { + // 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) + { + // 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_; + }; + + 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. + virtual int AddRef() + { + UnderlyingAddRef(); + return CefThreadSafeBase::AddRef(); + } + virtual int Release() + { + UnderlyingRelease(); + return CefThreadSafeBase::Release(); + } + + // 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: + Struct struct_; + CefBase* class_; +}; + +#endif // _BASE_CPPTOC_H diff --git a/libcef_dll/cpptoc/browser_cpptoc.cc b/libcef_dll/cpptoc/browser_cpptoc.cc index a2a85d400..a3281c760 100644 --- a/libcef_dll/cpptoc/browser_cpptoc.cc +++ b/libcef_dll/cpptoc/browser_cpptoc.cc @@ -1,284 +1,284 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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/handler_ctocpp.h" - - -// GLOBAL FUNCTIONS - Body may be edited by hand. - -CEF_EXPORT int cef_browser_create(cef_window_info_t* windowInfo, int popup, - struct _cef_handler_t* handler, const wchar_t* url) -{ - DCHECK(windowInfo); - - CefRefPtr handlerPtr; - std::wstring urlStr; - CefWindowInfo wi = *windowInfo; - - if(handler) - handlerPtr = CefHandlerCToCpp::Wrap(handler); - if(url) - urlStr = url; - - return CefBrowser::CreateBrowser(wi, popup?true:false, handlerPtr, urlStr); -} - -CEF_EXPORT cef_browser_t* cef_browser_create_sync(cef_window_info_t* windowInfo, - int popup, struct _cef_handler_t* handler, const wchar_t* url) -{ - DCHECK(windowInfo); - - CefRefPtr handlerPtr; - std::wstring urlStr; - CefWindowInfo wi = *windowInfo; - - if(handler) - handlerPtr = CefHandlerCToCpp::Wrap(handler); - if(url) - urlStr = url; - - CefRefPtr browserPtr( - CefBrowser::CreateBrowserSync(wi, popup?true:false, handlerPtr, urlStr)); - if(browserPtr.get()) - return CefBrowserCppToC::Wrap(browserPtr); - return NULL; -} - - -// MEMBER FUNCTIONS - Body may be edited by hand. - -int CEF_CALLBACK browser_can_go_back(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefBrowserCppToC::Get(self)->CanGoBack(); -} - -void CEF_CALLBACK browser_go_back(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefBrowserCppToC::Get(self)->GoBack(); -} - -int CEF_CALLBACK browser_can_go_forward(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefBrowserCppToC::Get(self)->CanGoForward(); -} - -void CEF_CALLBACK browser_go_forward(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefBrowserCppToC::Get(self)->GoForward(); -} - -void CEF_CALLBACK browser_reload(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefBrowserCppToC::Get(self)->Reload(); -} - -void CEF_CALLBACK browser_reload_ignore_cache(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefBrowserCppToC::Get(self)->ReloadIgnoreCache(); -} - -void CEF_CALLBACK browser_stop_load(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefBrowserCppToC::Get(self)->StopLoad(); -} - -void CEF_CALLBACK browser_set_focus(struct _cef_browser_t* self, int enable) -{ - DCHECK(self); - if(!self) - return; - - CefBrowserCppToC::Get(self)->SetFocus(enable ? true : false); -} - -cef_window_handle_t CEF_CALLBACK browser_get_window_handle( - struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - return CefBrowserCppToC::Get(self)->GetWindowHandle(); -} - -int CEF_CALLBACK browser_is_popup(struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefBrowserCppToC::Get(self)->IsPopup(); -} - -struct _cef_handler_t* CEF_CALLBACK browser_get_handler( - struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - CefRefPtr browserPtr = CefBrowserCppToC::Get(self); - CefRefPtr handlerPtr = browserPtr->GetHandler(); - if(handlerPtr.get()) - return CefHandlerCToCpp::Unwrap(handlerPtr); - - return NULL; -} - -struct _cef_frame_t* CEF_CALLBACK browser_get_main_frame( - struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - CefRefPtr browserPtr = CefBrowserCppToC::Get(self); - CefRefPtr framePtr = browserPtr->GetMainFrame(); - if(framePtr.get()) - return CefFrameCppToC::Wrap(framePtr); - return NULL; -} - -struct _cef_frame_t* CEF_CALLBACK browser_get_focused_frame( - struct _cef_browser_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - CefRefPtr browserPtr = CefBrowserCppToC::Get(self); - CefRefPtr framePtr = browserPtr->GetFocusedFrame(); - if(framePtr.get()) - return CefFrameCppToC::Wrap(framePtr); - return NULL; -} - -struct _cef_frame_t* CEF_CALLBACK browser_get_frame(struct _cef_browser_t* self, - const wchar_t* name) -{ - DCHECK(self); - if(!self) - return NULL; - - std::wstring nameStr; - if(name) - nameStr = name; - if(nameStr.empty()) - return NULL; - - CefRefPtr browserPtr = CefBrowserCppToC::Get(self); - CefRefPtr framePtr = browserPtr->GetFrame(nameStr); - if(framePtr.get()) - return CefFrameCppToC::Wrap(framePtr); - return NULL; -} - -void CEF_CALLBACK browser_get_frame_names(struct _cef_browser_t* self, - cef_string_list_t names) -{ - DCHECK(self); - DCHECK(names); - if(!self || !names) - return; - - CefRefPtr browserPtr = CefBrowserCppToC::Get(self); - std::vector stringList; - browserPtr->GetFrameNames(stringList); - size_t size = stringList.size(); - for(size_t i = 0; i < size; ++i) - cef_string_list_append(names, stringList[i].c_str()); -} - -void CEF_CALLBACK browser_find(struct _cef_browser_t* self, int identifier, - const wchar_t* searchText, int forward, int matchCase, int findNext) -{ - DCHECK(self); - if(!self) - return; - - std::wstring searchTextStr; - if(searchText) - searchTextStr = searchText; - - CefBrowserCppToC::Get(self)->Find(identifier, searchTextStr, - forward?true:false, matchCase?true:false, findNext?true:false); -} - -void CEF_CALLBACK browser_stop_finding(struct _cef_browser_t* self, - int clearSelection) -{ - DCHECK(self); - if(!self) - return; - - CefBrowserCppToC::Get(self)->StopFinding(clearSelection?true:false); -} - - -// CONSTRUCTOR - Do not edit by hand. - -CefBrowserCppToC::CefBrowserCppToC(CefBrowser* cls) - : CefCppToC(cls) -{ - 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_.is_popup = browser_is_popup; - struct_.struct_.get_handler = browser_get_handler; - 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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/handler_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT int cef_browser_create(cef_window_info_t* windowInfo, int popup, + struct _cef_handler_t* handler, const wchar_t* url) +{ + DCHECK(windowInfo); + + CefRefPtr handlerPtr; + std::wstring urlStr; + CefWindowInfo wi = *windowInfo; + + if(handler) + handlerPtr = CefHandlerCToCpp::Wrap(handler); + if(url) + urlStr = url; + + return CefBrowser::CreateBrowser(wi, popup?true:false, handlerPtr, urlStr); +} + +CEF_EXPORT cef_browser_t* cef_browser_create_sync(cef_window_info_t* windowInfo, + int popup, struct _cef_handler_t* handler, const wchar_t* url) +{ + DCHECK(windowInfo); + + CefRefPtr handlerPtr; + std::wstring urlStr; + CefWindowInfo wi = *windowInfo; + + if(handler) + handlerPtr = CefHandlerCToCpp::Wrap(handler); + if(url) + urlStr = url; + + CefRefPtr browserPtr( + CefBrowser::CreateBrowserSync(wi, popup?true:false, handlerPtr, urlStr)); + if(browserPtr.get()) + return CefBrowserCppToC::Wrap(browserPtr); + return NULL; +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK browser_can_go_back(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefBrowserCppToC::Get(self)->CanGoBack(); +} + +void CEF_CALLBACK browser_go_back(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefBrowserCppToC::Get(self)->GoBack(); +} + +int CEF_CALLBACK browser_can_go_forward(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefBrowserCppToC::Get(self)->CanGoForward(); +} + +void CEF_CALLBACK browser_go_forward(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefBrowserCppToC::Get(self)->GoForward(); +} + +void CEF_CALLBACK browser_reload(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefBrowserCppToC::Get(self)->Reload(); +} + +void CEF_CALLBACK browser_reload_ignore_cache(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefBrowserCppToC::Get(self)->ReloadIgnoreCache(); +} + +void CEF_CALLBACK browser_stop_load(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefBrowserCppToC::Get(self)->StopLoad(); +} + +void CEF_CALLBACK browser_set_focus(struct _cef_browser_t* self, int enable) +{ + DCHECK(self); + if(!self) + return; + + CefBrowserCppToC::Get(self)->SetFocus(enable ? true : false); +} + +cef_window_handle_t CEF_CALLBACK browser_get_window_handle( + struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + return CefBrowserCppToC::Get(self)->GetWindowHandle(); +} + +int CEF_CALLBACK browser_is_popup(struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefBrowserCppToC::Get(self)->IsPopup(); +} + +struct _cef_handler_t* CEF_CALLBACK browser_get_handler( + struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + CefRefPtr browserPtr = CefBrowserCppToC::Get(self); + CefRefPtr handlerPtr = browserPtr->GetHandler(); + if(handlerPtr.get()) + return CefHandlerCToCpp::Unwrap(handlerPtr); + + return NULL; +} + +struct _cef_frame_t* CEF_CALLBACK browser_get_main_frame( + struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + CefRefPtr browserPtr = CefBrowserCppToC::Get(self); + CefRefPtr framePtr = browserPtr->GetMainFrame(); + if(framePtr.get()) + return CefFrameCppToC::Wrap(framePtr); + return NULL; +} + +struct _cef_frame_t* CEF_CALLBACK browser_get_focused_frame( + struct _cef_browser_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + CefRefPtr browserPtr = CefBrowserCppToC::Get(self); + CefRefPtr framePtr = browserPtr->GetFocusedFrame(); + if(framePtr.get()) + return CefFrameCppToC::Wrap(framePtr); + return NULL; +} + +struct _cef_frame_t* CEF_CALLBACK browser_get_frame(struct _cef_browser_t* self, + const wchar_t* name) +{ + DCHECK(self); + if(!self) + return NULL; + + std::wstring nameStr; + if(name) + nameStr = name; + if(nameStr.empty()) + return NULL; + + CefRefPtr browserPtr = CefBrowserCppToC::Get(self); + CefRefPtr framePtr = browserPtr->GetFrame(nameStr); + if(framePtr.get()) + return CefFrameCppToC::Wrap(framePtr); + return NULL; +} + +void CEF_CALLBACK browser_get_frame_names(struct _cef_browser_t* self, + cef_string_list_t names) +{ + DCHECK(self); + DCHECK(names); + if(!self || !names) + return; + + CefRefPtr browserPtr = CefBrowserCppToC::Get(self); + std::vector stringList; + browserPtr->GetFrameNames(stringList); + size_t size = stringList.size(); + for(size_t i = 0; i < size; ++i) + cef_string_list_append(names, stringList[i].c_str()); +} + +void CEF_CALLBACK browser_find(struct _cef_browser_t* self, int identifier, + const wchar_t* searchText, int forward, int matchCase, int findNext) +{ + DCHECK(self); + if(!self) + return; + + std::wstring searchTextStr; + if(searchText) + searchTextStr = searchText; + + CefBrowserCppToC::Get(self)->Find(identifier, searchTextStr, + forward?true:false, matchCase?true:false, findNext?true:false); +} + +void CEF_CALLBACK browser_stop_finding(struct _cef_browser_t* self, + int clearSelection) +{ + DCHECK(self); + if(!self) + return; + + CefBrowserCppToC::Get(self)->StopFinding(clearSelection?true:false); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefBrowserCppToC::CefBrowserCppToC(CefBrowser* cls) + : CefCppToC(cls) +{ + 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_.is_popup = browser_is_popup; + struct_.struct_.get_handler = browser_get_handler; + 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/browser_cpptoc.h b/libcef_dll/cpptoc/browser_cpptoc.h index 7ab2f6a69..e0cc26db9 100644 --- a/libcef_dll/cpptoc/browser_cpptoc.h +++ b/libcef_dll/cpptoc/browser_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _BROWSER_CPPTOC_H -#define _BROWSER_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefBrowserCppToC(CefBrowser* cls); - virtual ~CefBrowserCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _BROWSER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _BROWSER_CPPTOC_H +#define _BROWSER_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefBrowserCppToC(CefBrowser* cls); + virtual ~CefBrowserCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _BROWSER_CPPTOC_H + diff --git a/libcef_dll/cpptoc/cpptoc.h b/libcef_dll/cpptoc/cpptoc.h index f8f11171c..536645ea9 100644 --- a/libcef_dll/cpptoc/cpptoc.h +++ b/libcef_dll/cpptoc/cpptoc.h @@ -1,160 +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 _CPPTOC_H -#define _CPPTOC_H - -#include "include/cef.h" -#include "include/cef_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 CefThreadSafeBase -{ -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(StructName* s) - { - // Cast our structure to the wrapper structure type. - ClassName::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) - { - // 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) - { - // Cast our structure to the wrapper structure type. - ClassName::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 - { - StructName struct_; - CefCppToC* class_; - }; - - 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; - -#ifdef _DEBUG - CefAtomicIncrement(&DebugObjCt); -#endif - } - virtual ~CefCppToC() - { -#ifdef _DEBUG - 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. - virtual int AddRef() - { - UnderlyingAddRef(); - return CefThreadSafeBase::AddRef(); - } - virtual int Release() - { - UnderlyingRelease(); - return CefThreadSafeBase::Release(); - } - - // Increment/decrement reference counts on only the underlying class. - int UnderlyingAddRef() { return class_->AddRef(); } - int UnderlyingRelease() { return class_->Release(); } - int UnderlyingGetRefCt() { return class_->GetRefCt(); } - -#ifdef _DEBUG - // Simple tracking of allocated objects. - static long DebugObjCt; -#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: - Struct struct_; - BaseName* class_; -}; - -#endif // _CPPTOC_H +// 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 _CPPTOC_H +#define _CPPTOC_H + +#include "include/cef.h" +#include "include/cef_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 CefThreadSafeBase +{ +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(StructName* s) + { + // Cast our structure to the wrapper structure type. + ClassName::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) + { + // 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) + { + // Cast our structure to the wrapper structure type. + ClassName::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 + { + StructName struct_; + CefCppToC* class_; + }; + + 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; + +#ifdef _DEBUG + CefAtomicIncrement(&DebugObjCt); +#endif + } + virtual ~CefCppToC() + { +#ifdef _DEBUG + 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. + virtual int AddRef() + { + UnderlyingAddRef(); + return CefThreadSafeBase::AddRef(); + } + virtual int Release() + { + UnderlyingRelease(); + return CefThreadSafeBase::Release(); + } + + // Increment/decrement reference counts on only the underlying class. + int UnderlyingAddRef() { return class_->AddRef(); } + int UnderlyingRelease() { return class_->Release(); } + int UnderlyingGetRefCt() { return class_->GetRefCt(); } + +#ifdef _DEBUG + // Simple tracking of allocated objects. + static long DebugObjCt; +#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: + Struct struct_; + BaseName* class_; +}; + +#endif // _CPPTOC_H diff --git a/libcef_dll/cpptoc/frame_cpptoc.cc b/libcef_dll/cpptoc/frame_cpptoc.cc index a04b9dbd1..ad20abbb3 100644 --- a/libcef_dll/cpptoc/frame_cpptoc.cc +++ b/libcef_dll/cpptoc/frame_cpptoc.cc @@ -1,270 +1,270 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing function -// implementations. See the translator.README.txt file in the tools directory -// for more information. -// - -#include "libcef_dll/cpptoc/frame_cpptoc.h" -#include "libcef_dll/cpptoc/request_cpptoc.h" -#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" - - -// MEMBER FUNCTIONS - Body may be edited by hand. - -void CEF_CALLBACK frame_undo(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->Undo(); -} - -void CEF_CALLBACK frame_redo(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->Redo(); -} - -void CEF_CALLBACK frame_cut(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->Cut(); -} - -void CEF_CALLBACK frame_copy(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->Copy(); -} - -void CEF_CALLBACK frame_paste(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->Paste(); -} - -void CEF_CALLBACK frame_del(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->Delete(); -} - -void CEF_CALLBACK frame_select_all(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->SelectAll(); -} - -void CEF_CALLBACK frame_print(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->Print(); -} - -void CEF_CALLBACK frame_view_source(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefFrameCppToC::Get(self)->ViewSource(); -} - -cef_string_t CEF_CALLBACK frame_get_source(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - std::wstring sourceStr = CefFrameCppToC::Get(self)->GetSource(); - if(!sourceStr.empty()) - return cef_string_alloc(sourceStr.c_str()); - return NULL; -} - -cef_string_t CEF_CALLBACK frame_get_text(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - std::wstring textStr = CefFrameCppToC::Get(self)->GetText(); - if(!textStr.empty()) - return cef_string_alloc(textStr.c_str()); - return NULL; -} - -void CEF_CALLBACK frame_load_request(struct _cef_frame_t* self, - struct _cef_request_t* request) -{ - DCHECK(self); - DCHECK(request); - if(!self || !request) - return; - - CefRefPtr requestPtr = CefRequestCppToC::Unwrap(request); - CefFrameCppToC::Get(self)->LoadRequest(requestPtr); -} - -void CEF_CALLBACK frame_load_url(struct _cef_frame_t* self, const wchar_t* url) -{ - DCHECK(self); - if(!self) - return; - - std::wstring urlStr; - if(url) - urlStr = url; - CefFrameCppToC::Get(self)->LoadURL(urlStr); -} - -void CEF_CALLBACK frame_load_string(struct _cef_frame_t* self, - const wchar_t* string, const wchar_t* url) -{ - DCHECK(self); - if(!self) - return; - - std::wstring stringStr, urlStr; - if(string) - stringStr = string; - if(url) - urlStr = url; - CefFrameCppToC::Get(self)->LoadString(stringStr, urlStr); -} - -void CEF_CALLBACK frame_load_stream(struct _cef_frame_t* self, - struct _cef_stream_reader_t* stream, const wchar_t* url) -{ - DCHECK(self); - DCHECK(stream); - if(!self || !stream) - return; - - CefRefPtr streamPtr = CefStreamReaderCppToC::Unwrap(stream); - std::wstring urlStr; - if(url) - urlStr = url; - - CefFrameCppToC::Get(self)->LoadStream(streamPtr, urlStr); -} - -void CEF_CALLBACK frame_execute_java_script(struct _cef_frame_t* self, - const wchar_t* jsCode, const wchar_t* scriptUrl, int startLine) -{ - DCHECK(self); - if(!self) - return; - - std::wstring jsCodeStr, scriptUrlStr; - if(jsCode) - jsCodeStr = jsCode; - if(scriptUrl) - scriptUrlStr = scriptUrl; - - CefFrameCppToC::Get(self)->ExecuteJavaScript(jsCodeStr, scriptUrlStr, - startLine); -} - -int CEF_CALLBACK frame_is_main(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefFrameCppToC::Get(self)->IsMain(); -} - -int CEF_CALLBACK frame_is_focused(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefFrameCppToC::Get(self)->IsFocused(); -} - -cef_string_t CEF_CALLBACK frame_get_name(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - std::wstring nameStr = CefFrameCppToC::Get(self)->GetName(); - if(!nameStr.empty()) - return cef_string_alloc(nameStr.c_str()); - return NULL; -} - -cef_string_t CEF_CALLBACK frame_get_url(struct _cef_frame_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - std::wstring urlStr = CefFrameCppToC::Get(self)->GetURL(); - if(!urlStr.empty()) - return cef_string_alloc(urlStr.c_str()); - return NULL; -} - - -// 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_url = frame_get_url; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK frame_undo(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->Undo(); +} + +void CEF_CALLBACK frame_redo(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->Redo(); +} + +void CEF_CALLBACK frame_cut(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->Cut(); +} + +void CEF_CALLBACK frame_copy(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->Copy(); +} + +void CEF_CALLBACK frame_paste(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->Paste(); +} + +void CEF_CALLBACK frame_del(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->Delete(); +} + +void CEF_CALLBACK frame_select_all(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->SelectAll(); +} + +void CEF_CALLBACK frame_print(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->Print(); +} + +void CEF_CALLBACK frame_view_source(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefFrameCppToC::Get(self)->ViewSource(); +} + +cef_string_t CEF_CALLBACK frame_get_source(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + std::wstring sourceStr = CefFrameCppToC::Get(self)->GetSource(); + if(!sourceStr.empty()) + return cef_string_alloc(sourceStr.c_str()); + return NULL; +} + +cef_string_t CEF_CALLBACK frame_get_text(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + std::wstring textStr = CefFrameCppToC::Get(self)->GetText(); + if(!textStr.empty()) + return cef_string_alloc(textStr.c_str()); + return NULL; +} + +void CEF_CALLBACK frame_load_request(struct _cef_frame_t* self, + struct _cef_request_t* request) +{ + DCHECK(self); + DCHECK(request); + if(!self || !request) + return; + + CefRefPtr requestPtr = CefRequestCppToC::Unwrap(request); + CefFrameCppToC::Get(self)->LoadRequest(requestPtr); +} + +void CEF_CALLBACK frame_load_url(struct _cef_frame_t* self, const wchar_t* url) +{ + DCHECK(self); + if(!self) + return; + + std::wstring urlStr; + if(url) + urlStr = url; + CefFrameCppToC::Get(self)->LoadURL(urlStr); +} + +void CEF_CALLBACK frame_load_string(struct _cef_frame_t* self, + const wchar_t* string, const wchar_t* url) +{ + DCHECK(self); + if(!self) + return; + + std::wstring stringStr, urlStr; + if(string) + stringStr = string; + if(url) + urlStr = url; + CefFrameCppToC::Get(self)->LoadString(stringStr, urlStr); +} + +void CEF_CALLBACK frame_load_stream(struct _cef_frame_t* self, + struct _cef_stream_reader_t* stream, const wchar_t* url) +{ + DCHECK(self); + DCHECK(stream); + if(!self || !stream) + return; + + CefRefPtr streamPtr = CefStreamReaderCppToC::Unwrap(stream); + std::wstring urlStr; + if(url) + urlStr = url; + + CefFrameCppToC::Get(self)->LoadStream(streamPtr, urlStr); +} + +void CEF_CALLBACK frame_execute_java_script(struct _cef_frame_t* self, + const wchar_t* jsCode, const wchar_t* scriptUrl, int startLine) +{ + DCHECK(self); + if(!self) + return; + + std::wstring jsCodeStr, scriptUrlStr; + if(jsCode) + jsCodeStr = jsCode; + if(scriptUrl) + scriptUrlStr = scriptUrl; + + CefFrameCppToC::Get(self)->ExecuteJavaScript(jsCodeStr, scriptUrlStr, + startLine); +} + +int CEF_CALLBACK frame_is_main(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefFrameCppToC::Get(self)->IsMain(); +} + +int CEF_CALLBACK frame_is_focused(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefFrameCppToC::Get(self)->IsFocused(); +} + +cef_string_t CEF_CALLBACK frame_get_name(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + std::wstring nameStr = CefFrameCppToC::Get(self)->GetName(); + if(!nameStr.empty()) + return cef_string_alloc(nameStr.c_str()); + return NULL; +} + +cef_string_t CEF_CALLBACK frame_get_url(struct _cef_frame_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + std::wstring urlStr = CefFrameCppToC::Get(self)->GetURL(); + if(!urlStr.empty()) + return cef_string_alloc(urlStr.c_str()); + return NULL; +} + + +// 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_url = frame_get_url; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/frame_cpptoc.h b/libcef_dll/cpptoc/frame_cpptoc.h index 292aa785a..095ed8e67 100644 --- a/libcef_dll/cpptoc/frame_cpptoc.h +++ b/libcef_dll/cpptoc/frame_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _FRAME_CPPTOC_H -#define _FRAME_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefFrameCppToC(CefFrame* cls); - virtual ~CefFrameCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _FRAME_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _FRAME_CPPTOC_H +#define _FRAME_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefFrameCppToC(CefFrame* cls); + virtual ~CefFrameCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _FRAME_CPPTOC_H + diff --git a/libcef_dll/cpptoc/handler_cpptoc.cc b/libcef_dll/cpptoc/handler_cpptoc.cc index a2af92001..b3b25c01d 100644 --- a/libcef_dll/cpptoc/handler_cpptoc.cc +++ b/libcef_dll/cpptoc/handler_cpptoc.cc @@ -1,585 +1,585 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing function -// implementations. See the translator.README.txt file in the tools directory -// for more information. -// - -#include "libcef_dll/cpptoc/handler_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/v8value_ctocpp.h" -#include "libcef_dll/transfer_util.h" - - -// MEMBER FUNCTIONS - Body may be edited by hand. - -enum cef_retval_t CEF_CALLBACK handler_handle_before_created( - struct _cef_handler_t* self, cef_browser_t* parentBrowser, - cef_window_info_t* windowInfo, int popup, struct _cef_handler_t** handler, - cef_string_t* url) -{ - DCHECK(self); - DCHECK(windowInfo); - DCHECK(handler && *handler); - DCHECK(url); - if(!self || !windowInfo || !handler || !*handler || !url) - return RV_CONTINUE; - - CefWindowInfo wndInfo(*windowInfo); - - // |newHandler| will start off pointing to the current handler. - CefRefPtr handlerPtr = CefHandlerCppToC::Unwrap(*handler); - CefHandler* origHandler = handlerPtr.get(); - - // |parentBrowser| will be NULL if this is a top-level browser window. - CefRefPtr browserPtr; - if(parentBrowser) - browserPtr = CefBrowserCToCpp::Wrap(parentBrowser); - - std::wstring urlStr; - if(*url) - urlStr = *url; - - enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleBeforeCreated( - browserPtr, wndInfo, popup?true:false, handlerPtr, urlStr); - - transfer_string_contents(urlStr, url); - - if(handlerPtr.get() != origHandler) { - // The handler has been changed. - *handler = CefHandlerCppToC::Wrap(handlerPtr); - } - - // WindowInfo may or may not have changed. - *windowInfo = wndInfo; -#ifdef WIN32 - // The m_windowName must be duplicated since it's a cef_string_t - if(windowInfo->m_windowName) - windowInfo->m_windowName = cef_string_alloc(windowInfo->m_windowName); -#endif - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_after_created( - struct _cef_handler_t* self, cef_browser_t* browser) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleAfterCreated( - CefBrowserCToCpp::Wrap(browser)); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_address_change( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - const wchar_t* url) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - if(!self || !browser || !frame) - return RV_CONTINUE; - - std::wstring urlStr; - if(url) - urlStr = url; - - return CefHandlerCppToC::Get(self)->HandleAddressChange( - CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), urlStr); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_title_change( - struct _cef_handler_t* self, cef_browser_t* browser, const wchar_t* title) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - std::wstring titleStr; - if(title) - titleStr = title; - - return CefHandlerCppToC::Get(self)->HandleTitleChange( - CefBrowserCToCpp::Wrap(browser), titleStr); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_before_browse( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - struct _cef_request_t* request, enum cef_handler_navtype_t navType, - int isRedirect) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - DCHECK(request); - if(!self || !browser || !request || !frame) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleBeforeBrowse( - CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), - CefRequestCToCpp::Wrap(request), navType, (isRedirect ? true : false)); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_load_start( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - CefRefPtr framePtr; - if(frame) - framePtr = CefFrameCToCpp::Wrap(frame); - - return CefHandlerCppToC::Get(self)->HandleLoadStart( - CefBrowserCToCpp::Wrap(browser), framePtr); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_load_end( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - CefRefPtr framePtr; - if(frame) - framePtr = CefFrameCToCpp::Wrap(frame); - - return CefHandlerCppToC::Get(self)->HandleLoadEnd( - CefBrowserCToCpp::Wrap(browser), framePtr); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_load_error( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - enum cef_handler_errorcode_t errorCode, const wchar_t* failedUrl, - cef_string_t* errorText) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - DCHECK(errorText); - if(!self || !browser || !errorText || !frame) - return RV_CONTINUE; - - std::wstring failedUrlStr, errorTextStr; - - if(failedUrl) - failedUrlStr = failedUrl; - if(*errorText) - errorTextStr = *errorText; - - enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleLoadError( - CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), errorCode, - failedUrlStr, errorTextStr); - - transfer_string_contents(errorTextStr, errorText); - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_before_resource_load( - struct _cef_handler_t* self, cef_browser_t* browser, - struct _cef_request_t* request, cef_string_t* redirectUrl, - struct _cef_stream_reader_t** resourceStream, cef_string_t* mimeType, - int loadFlags) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(redirectUrl); - DCHECK(resourceStream); - DCHECK(mimeType); - if(!self || !browser || !redirectUrl || !resourceStream || !mimeType) - return RV_CONTINUE; - - std::wstring redirectUrlStr, mimeTypeStr; - CefRefPtr streamPtr; - - if(*redirectUrl) - redirectUrlStr = *redirectUrl; - if(*mimeType) - mimeTypeStr = *mimeType; - - enum cef_retval_t rv = CefHandlerCppToC::Get(self)-> - HandleBeforeResourceLoad(CefBrowserCToCpp::Wrap(browser), - CefRequestCToCpp::Wrap(request), redirectUrlStr, streamPtr, mimeTypeStr, - loadFlags); - - transfer_string_contents(redirectUrlStr, redirectUrl); - transfer_string_contents(mimeTypeStr, mimeType); - - if(streamPtr.get()) - *resourceStream = CefStreamReaderCToCpp::Unwrap(streamPtr); - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_before_menu( - struct _cef_handler_t* self, cef_browser_t* browser, - const cef_handler_menuinfo_t* menuInfo) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(menuInfo); - if(!self || !browser || !menuInfo) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleBeforeMenu( - CefBrowserCToCpp::Wrap(browser), *menuInfo); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_get_menu_label( - struct _cef_handler_t* self, cef_browser_t* browser, - enum cef_handler_menuid_t menuId, cef_string_t* label) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(label); - if(!self || !browser || !label) - return RV_CONTINUE; - - std::wstring labelStr; - if(*label) - labelStr = *label; - - enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleGetMenuLabel( - CefBrowserCToCpp::Wrap(browser), menuId, labelStr); - - transfer_string_contents(labelStr, label); - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_menu_action( - struct _cef_handler_t* self, cef_browser_t* browser, - enum cef_handler_menuid_t menuId) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleMenuAction( - CefBrowserCToCpp::Wrap(browser), menuId); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_print_options( - struct _cef_handler_t* self, cef_browser_t* browser, - struct _cef_print_options_t* printOptions) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(printOptions); - if(!self || !browser || !printOptions) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandlePrintOptions(CefBrowserCToCpp::Wrap(browser), *printOptions); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_print_header_footer( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - cef_print_info_t* printInfo, const wchar_t* url, const wchar_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) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - DCHECK(printInfo); - DCHECK(topLeft && topCenter && topRight); - DCHECK(bottomLeft && bottomCenter && bottomRight); - if(!self || !browser || !frame || !printInfo || !topLeft || !topCenter - || !topRight || !bottomLeft || !bottomCenter || !bottomRight) - return RV_CONTINUE; - - std::wstring urlStr, titleStr; - std::wstring topLeftStr, topCenterStr, topRightStr; - std::wstring bottomLeftStr, bottomCenterStr, bottomRightStr; - CefPrintInfo info = *printInfo; - - if(url) - urlStr = url; - if(title) - titleStr = title; - if(*topLeft) - topLeftStr = *topLeft; - if(*topCenter) - topCenterStr = *topCenter; - if(*topRight) - topRightStr = *topRight; - if(*bottomLeft) - bottomLeftStr = *bottomLeft; - if(*bottomCenter) - bottomCenterStr = *bottomCenter; - if(*bottomRight) - bottomRightStr = *bottomRight; - - enum cef_retval_t rv = CefHandlerCppToC::Get(self)-> - HandlePrintHeaderFooter(CefBrowserCToCpp::Wrap(browser), - CefFrameCToCpp::Wrap(frame), info, urlStr, titleStr, currentPage, - maxPages, topLeftStr, topCenterStr, topRightStr, bottomLeftStr, - bottomCenterStr, bottomRightStr); - - transfer_string_contents(topLeftStr, topLeft); - transfer_string_contents(topCenterStr, topCenter); - transfer_string_contents(topRightStr, topRight); - transfer_string_contents(bottomLeftStr, bottomLeft); - transfer_string_contents(bottomCenterStr, bottomCenter); - transfer_string_contents(bottomRightStr, bottomRight); - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_jsalert( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - const wchar_t* message) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - if(!self || !browser || !frame) - return RV_CONTINUE; - - std::wstring messageStr; - if(message) - messageStr = message; - - return CefHandlerCppToC::Get(self)->HandleJSAlert( - CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), messageStr); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_jsconfirm( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - const wchar_t* message, int* retval) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - DCHECK(retval); - if(!self || !browser || !retval || !frame) - return RV_CONTINUE; - - std::wstring messageStr; - if(message) - messageStr = message; - - bool ret = false; - enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleJSConfirm( - CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), messageStr, - ret); - *retval = (ret ? 1 : 0); - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_jsprompt( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - const wchar_t* message, const wchar_t* defaultValue, int* retval, - cef_string_t* result) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - DCHECK(retval); - DCHECK(result); - if(!self || !browser || !frame || !retval || !result) - return RV_CONTINUE; - - std::wstring messageStr, defaultValueStr, resultStr; - - if(message) - messageStr = message; - if(defaultValue) - defaultValueStr = defaultValue; - if(*result) - resultStr = *result; - - bool ret = false; - enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleJSPrompt( - CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), messageStr, - defaultValueStr, ret, resultStr); - *retval = (ret ? 1 : 0); - - transfer_string_contents(resultStr, result); - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_jsbinding( - struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, - struct _cef_v8value_t* object) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(frame); - DCHECK(object); - if(!self || !browser || !frame || !object) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleJSBinding( - CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), - CefV8ValueCToCpp::Wrap(object)); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_before_window_close( - struct _cef_handler_t* self, cef_browser_t* browser) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleBeforeWindowClose( - CefBrowserCToCpp::Wrap(browser)); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_take_focus( - struct _cef_handler_t* self, cef_browser_t* browser, int reverse) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleTakeFocus( - CefBrowserCToCpp::Wrap(browser), (reverse ? true : false)); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_set_focus( - struct _cef_handler_t* self, cef_browser_t* browser, int isWidget) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleSetFocus( - CefBrowserCToCpp::Wrap(browser), isWidget?true:false); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_key_event( - struct _cef_handler_t* self, cef_browser_t* browser, - enum cef_handler_keyevent_type_t type, int code, int modifiers, - int isSystemKey) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - return CefHandlerCppToC::Get(self)->HandleKeyEvent( - CefBrowserCToCpp::Wrap(browser), type, code, - modifiers, isSystemKey?true:false); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_tooltip( - struct _cef_handler_t* self, cef_browser_t* browser, cef_string_t* text) -{ - DCHECK(self); - DCHECK(browser); - DCHECK(text); - if(!self || !browser || !text) - return RV_CONTINUE; - - std::wstring textStr; - if(*text) - textStr = *text; - - enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleTooltip( - CefBrowserCToCpp::Wrap(browser), textStr); - - transfer_string_contents(textStr, text); - - return rv; -} - -enum cef_retval_t CEF_CALLBACK handler_handle_console_message( - struct _cef_handler_t* self, cef_browser_t* browser, const wchar_t* message, - const wchar_t* source, int line) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - std::wstring messageStr, sourceStr; - if(message) - messageStr = message; - if(source) - sourceStr = source; - - return CefHandlerCppToC::Get(self)->HandleConsoleMessage( - CefBrowserCToCpp::Wrap(browser), messageStr, sourceStr, line); -} - -enum cef_retval_t CEF_CALLBACK handler_handle_find_result( - struct _cef_handler_t* self, cef_browser_t* browser, int identifier, - int count, const cef_rect_t* selectionRect, int activeMatchOrdinal, - int finalUpdate) -{ - DCHECK(self); - DCHECK(browser); - if(!self || !browser) - return RV_CONTINUE; - - CefRect rect(*selectionRect); - return CefHandlerCppToC::Get(self)->HandleFindResult( - CefBrowserCToCpp::Wrap(browser), identifier, count, rect, - activeMatchOrdinal, finalUpdate?true:false); -} - - -// CONSTRUCTOR - Do not edit by hand. - -CefHandlerCppToC::CefHandlerCppToC(CefHandler* cls) - : CefCppToC(cls) -{ - struct_.struct_.handle_before_created = handler_handle_before_created; - struct_.struct_.handle_after_created = handler_handle_after_created; - struct_.struct_.handle_address_change = handler_handle_address_change; - struct_.struct_.handle_title_change = handler_handle_title_change; - struct_.struct_.handle_before_browse = handler_handle_before_browse; - struct_.struct_.handle_load_start = handler_handle_load_start; - struct_.struct_.handle_load_end = handler_handle_load_end; - struct_.struct_.handle_load_error = handler_handle_load_error; - struct_.struct_.handle_before_resource_load = - handler_handle_before_resource_load; - struct_.struct_.handle_before_menu = handler_handle_before_menu; - struct_.struct_.handle_get_menu_label = handler_handle_get_menu_label; - struct_.struct_.handle_menu_action = handler_handle_menu_action; - struct_.struct_.handle_print_options = handler_handle_print_options; - struct_.struct_.handle_print_header_footer = - handler_handle_print_header_footer; - struct_.struct_.handle_jsalert = handler_handle_jsalert; - struct_.struct_.handle_jsconfirm = handler_handle_jsconfirm; - struct_.struct_.handle_jsprompt = handler_handle_jsprompt; - struct_.struct_.handle_jsbinding = handler_handle_jsbinding; - struct_.struct_.handle_before_window_close = - handler_handle_before_window_close; - struct_.struct_.handle_take_focus = handler_handle_take_focus; - struct_.struct_.handle_set_focus = handler_handle_set_focus; - struct_.struct_.handle_key_event = handler_handle_key_event; - struct_.struct_.handle_tooltip = handler_handle_tooltip; - struct_.struct_.handle_console_message = handler_handle_console_message; - struct_.struct_.handle_find_result = handler_handle_find_result; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/handler_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/v8value_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +enum cef_retval_t CEF_CALLBACK handler_handle_before_created( + struct _cef_handler_t* self, cef_browser_t* parentBrowser, + cef_window_info_t* windowInfo, int popup, struct _cef_handler_t** handler, + cef_string_t* url) +{ + DCHECK(self); + DCHECK(windowInfo); + DCHECK(handler && *handler); + DCHECK(url); + if(!self || !windowInfo || !handler || !*handler || !url) + return RV_CONTINUE; + + CefWindowInfo wndInfo(*windowInfo); + + // |newHandler| will start off pointing to the current handler. + CefRefPtr handlerPtr = CefHandlerCppToC::Unwrap(*handler); + CefHandler* origHandler = handlerPtr.get(); + + // |parentBrowser| will be NULL if this is a top-level browser window. + CefRefPtr browserPtr; + if(parentBrowser) + browserPtr = CefBrowserCToCpp::Wrap(parentBrowser); + + std::wstring urlStr; + if(*url) + urlStr = *url; + + enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleBeforeCreated( + browserPtr, wndInfo, popup?true:false, handlerPtr, urlStr); + + transfer_string_contents(urlStr, url); + + if(handlerPtr.get() != origHandler) { + // The handler has been changed. + *handler = CefHandlerCppToC::Wrap(handlerPtr); + } + + // WindowInfo may or may not have changed. + *windowInfo = wndInfo; +#ifdef WIN32 + // The m_windowName must be duplicated since it's a cef_string_t + if(windowInfo->m_windowName) + windowInfo->m_windowName = cef_string_alloc(windowInfo->m_windowName); +#endif + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_after_created( + struct _cef_handler_t* self, cef_browser_t* browser) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleAfterCreated( + CefBrowserCToCpp::Wrap(browser)); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_address_change( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + const wchar_t* url) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + if(!self || !browser || !frame) + return RV_CONTINUE; + + std::wstring urlStr; + if(url) + urlStr = url; + + return CefHandlerCppToC::Get(self)->HandleAddressChange( + CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), urlStr); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_title_change( + struct _cef_handler_t* self, cef_browser_t* browser, const wchar_t* title) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + std::wstring titleStr; + if(title) + titleStr = title; + + return CefHandlerCppToC::Get(self)->HandleTitleChange( + CefBrowserCToCpp::Wrap(browser), titleStr); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_before_browse( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + struct _cef_request_t* request, enum cef_handler_navtype_t navType, + int isRedirect) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + DCHECK(request); + if(!self || !browser || !request || !frame) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleBeforeBrowse( + CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), + CefRequestCToCpp::Wrap(request), navType, (isRedirect ? true : false)); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_load_start( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + CefRefPtr framePtr; + if(frame) + framePtr = CefFrameCToCpp::Wrap(frame); + + return CefHandlerCppToC::Get(self)->HandleLoadStart( + CefBrowserCToCpp::Wrap(browser), framePtr); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_load_end( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + CefRefPtr framePtr; + if(frame) + framePtr = CefFrameCToCpp::Wrap(frame); + + return CefHandlerCppToC::Get(self)->HandleLoadEnd( + CefBrowserCToCpp::Wrap(browser), framePtr); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_load_error( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + enum cef_handler_errorcode_t errorCode, const wchar_t* failedUrl, + cef_string_t* errorText) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + DCHECK(errorText); + if(!self || !browser || !errorText || !frame) + return RV_CONTINUE; + + std::wstring failedUrlStr, errorTextStr; + + if(failedUrl) + failedUrlStr = failedUrl; + if(*errorText) + errorTextStr = *errorText; + + enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleLoadError( + CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), errorCode, + failedUrlStr, errorTextStr); + + transfer_string_contents(errorTextStr, errorText); + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_before_resource_load( + struct _cef_handler_t* self, cef_browser_t* browser, + struct _cef_request_t* request, cef_string_t* redirectUrl, + struct _cef_stream_reader_t** resourceStream, cef_string_t* mimeType, + int loadFlags) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(redirectUrl); + DCHECK(resourceStream); + DCHECK(mimeType); + if(!self || !browser || !redirectUrl || !resourceStream || !mimeType) + return RV_CONTINUE; + + std::wstring redirectUrlStr, mimeTypeStr; + CefRefPtr streamPtr; + + if(*redirectUrl) + redirectUrlStr = *redirectUrl; + if(*mimeType) + mimeTypeStr = *mimeType; + + enum cef_retval_t rv = CefHandlerCppToC::Get(self)-> + HandleBeforeResourceLoad(CefBrowserCToCpp::Wrap(browser), + CefRequestCToCpp::Wrap(request), redirectUrlStr, streamPtr, mimeTypeStr, + loadFlags); + + transfer_string_contents(redirectUrlStr, redirectUrl); + transfer_string_contents(mimeTypeStr, mimeType); + + if(streamPtr.get()) + *resourceStream = CefStreamReaderCToCpp::Unwrap(streamPtr); + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_before_menu( + struct _cef_handler_t* self, cef_browser_t* browser, + const cef_handler_menuinfo_t* menuInfo) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(menuInfo); + if(!self || !browser || !menuInfo) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleBeforeMenu( + CefBrowserCToCpp::Wrap(browser), *menuInfo); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_get_menu_label( + struct _cef_handler_t* self, cef_browser_t* browser, + enum cef_handler_menuid_t menuId, cef_string_t* label) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(label); + if(!self || !browser || !label) + return RV_CONTINUE; + + std::wstring labelStr; + if(*label) + labelStr = *label; + + enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleGetMenuLabel( + CefBrowserCToCpp::Wrap(browser), menuId, labelStr); + + transfer_string_contents(labelStr, label); + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_menu_action( + struct _cef_handler_t* self, cef_browser_t* browser, + enum cef_handler_menuid_t menuId) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleMenuAction( + CefBrowserCToCpp::Wrap(browser), menuId); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_print_options( + struct _cef_handler_t* self, cef_browser_t* browser, + struct _cef_print_options_t* printOptions) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(printOptions); + if(!self || !browser || !printOptions) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandlePrintOptions(CefBrowserCToCpp::Wrap(browser), *printOptions); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_print_header_footer( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + cef_print_info_t* printInfo, const wchar_t* url, const wchar_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) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + DCHECK(printInfo); + DCHECK(topLeft && topCenter && topRight); + DCHECK(bottomLeft && bottomCenter && bottomRight); + if(!self || !browser || !frame || !printInfo || !topLeft || !topCenter + || !topRight || !bottomLeft || !bottomCenter || !bottomRight) + return RV_CONTINUE; + + std::wstring urlStr, titleStr; + std::wstring topLeftStr, topCenterStr, topRightStr; + std::wstring bottomLeftStr, bottomCenterStr, bottomRightStr; + CefPrintInfo info = *printInfo; + + if(url) + urlStr = url; + if(title) + titleStr = title; + if(*topLeft) + topLeftStr = *topLeft; + if(*topCenter) + topCenterStr = *topCenter; + if(*topRight) + topRightStr = *topRight; + if(*bottomLeft) + bottomLeftStr = *bottomLeft; + if(*bottomCenter) + bottomCenterStr = *bottomCenter; + if(*bottomRight) + bottomRightStr = *bottomRight; + + enum cef_retval_t rv = CefHandlerCppToC::Get(self)-> + HandlePrintHeaderFooter(CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), info, urlStr, titleStr, currentPage, + maxPages, topLeftStr, topCenterStr, topRightStr, bottomLeftStr, + bottomCenterStr, bottomRightStr); + + transfer_string_contents(topLeftStr, topLeft); + transfer_string_contents(topCenterStr, topCenter); + transfer_string_contents(topRightStr, topRight); + transfer_string_contents(bottomLeftStr, bottomLeft); + transfer_string_contents(bottomCenterStr, bottomCenter); + transfer_string_contents(bottomRightStr, bottomRight); + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_jsalert( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + const wchar_t* message) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + if(!self || !browser || !frame) + return RV_CONTINUE; + + std::wstring messageStr; + if(message) + messageStr = message; + + return CefHandlerCppToC::Get(self)->HandleJSAlert( + CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), messageStr); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_jsconfirm( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + const wchar_t* message, int* retval) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + DCHECK(retval); + if(!self || !browser || !retval || !frame) + return RV_CONTINUE; + + std::wstring messageStr; + if(message) + messageStr = message; + + bool ret = false; + enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleJSConfirm( + CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), messageStr, + ret); + *retval = (ret ? 1 : 0); + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_jsprompt( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + const wchar_t* message, const wchar_t* defaultValue, int* retval, + cef_string_t* result) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + DCHECK(retval); + DCHECK(result); + if(!self || !browser || !frame || !retval || !result) + return RV_CONTINUE; + + std::wstring messageStr, defaultValueStr, resultStr; + + if(message) + messageStr = message; + if(defaultValue) + defaultValueStr = defaultValue; + if(*result) + resultStr = *result; + + bool ret = false; + enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleJSPrompt( + CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), messageStr, + defaultValueStr, ret, resultStr); + *retval = (ret ? 1 : 0); + + transfer_string_contents(resultStr, result); + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_jsbinding( + struct _cef_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, + struct _cef_v8value_t* object) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(frame); + DCHECK(object); + if(!self || !browser || !frame || !object) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleJSBinding( + CefBrowserCToCpp::Wrap(browser), CefFrameCToCpp::Wrap(frame), + CefV8ValueCToCpp::Wrap(object)); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_before_window_close( + struct _cef_handler_t* self, cef_browser_t* browser) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleBeforeWindowClose( + CefBrowserCToCpp::Wrap(browser)); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_take_focus( + struct _cef_handler_t* self, cef_browser_t* browser, int reverse) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleTakeFocus( + CefBrowserCToCpp::Wrap(browser), (reverse ? true : false)); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_set_focus( + struct _cef_handler_t* self, cef_browser_t* browser, int isWidget) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleSetFocus( + CefBrowserCToCpp::Wrap(browser), isWidget?true:false); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_key_event( + struct _cef_handler_t* self, cef_browser_t* browser, + enum cef_handler_keyevent_type_t type, int code, int modifiers, + int isSystemKey) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + return CefHandlerCppToC::Get(self)->HandleKeyEvent( + CefBrowserCToCpp::Wrap(browser), type, code, + modifiers, isSystemKey?true:false); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_tooltip( + struct _cef_handler_t* self, cef_browser_t* browser, cef_string_t* text) +{ + DCHECK(self); + DCHECK(browser); + DCHECK(text); + if(!self || !browser || !text) + return RV_CONTINUE; + + std::wstring textStr; + if(*text) + textStr = *text; + + enum cef_retval_t rv = CefHandlerCppToC::Get(self)->HandleTooltip( + CefBrowserCToCpp::Wrap(browser), textStr); + + transfer_string_contents(textStr, text); + + return rv; +} + +enum cef_retval_t CEF_CALLBACK handler_handle_console_message( + struct _cef_handler_t* self, cef_browser_t* browser, const wchar_t* message, + const wchar_t* source, int line) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + std::wstring messageStr, sourceStr; + if(message) + messageStr = message; + if(source) + sourceStr = source; + + return CefHandlerCppToC::Get(self)->HandleConsoleMessage( + CefBrowserCToCpp::Wrap(browser), messageStr, sourceStr, line); +} + +enum cef_retval_t CEF_CALLBACK handler_handle_find_result( + struct _cef_handler_t* self, cef_browser_t* browser, int identifier, + int count, const cef_rect_t* selectionRect, int activeMatchOrdinal, + int finalUpdate) +{ + DCHECK(self); + DCHECK(browser); + if(!self || !browser) + return RV_CONTINUE; + + CefRect rect(*selectionRect); + return CefHandlerCppToC::Get(self)->HandleFindResult( + CefBrowserCToCpp::Wrap(browser), identifier, count, rect, + activeMatchOrdinal, finalUpdate?true:false); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefHandlerCppToC::CefHandlerCppToC(CefHandler* cls) + : CefCppToC(cls) +{ + struct_.struct_.handle_before_created = handler_handle_before_created; + struct_.struct_.handle_after_created = handler_handle_after_created; + struct_.struct_.handle_address_change = handler_handle_address_change; + struct_.struct_.handle_title_change = handler_handle_title_change; + struct_.struct_.handle_before_browse = handler_handle_before_browse; + struct_.struct_.handle_load_start = handler_handle_load_start; + struct_.struct_.handle_load_end = handler_handle_load_end; + struct_.struct_.handle_load_error = handler_handle_load_error; + struct_.struct_.handle_before_resource_load = + handler_handle_before_resource_load; + struct_.struct_.handle_before_menu = handler_handle_before_menu; + struct_.struct_.handle_get_menu_label = handler_handle_get_menu_label; + struct_.struct_.handle_menu_action = handler_handle_menu_action; + struct_.struct_.handle_print_options = handler_handle_print_options; + struct_.struct_.handle_print_header_footer = + handler_handle_print_header_footer; + struct_.struct_.handle_jsalert = handler_handle_jsalert; + struct_.struct_.handle_jsconfirm = handler_handle_jsconfirm; + struct_.struct_.handle_jsprompt = handler_handle_jsprompt; + struct_.struct_.handle_jsbinding = handler_handle_jsbinding; + struct_.struct_.handle_before_window_close = + handler_handle_before_window_close; + struct_.struct_.handle_take_focus = handler_handle_take_focus; + struct_.struct_.handle_set_focus = handler_handle_set_focus; + struct_.struct_.handle_key_event = handler_handle_key_event; + struct_.struct_.handle_tooltip = handler_handle_tooltip; + struct_.struct_.handle_console_message = handler_handle_console_message; + struct_.struct_.handle_find_result = handler_handle_find_result; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/handler_cpptoc.h b/libcef_dll/cpptoc/handler_cpptoc.h index 36ab18a00..1638f8e70 100644 --- a/libcef_dll/cpptoc/handler_cpptoc.h +++ b/libcef_dll/cpptoc/handler_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _HANDLER_CPPTOC_H -#define _HANDLER_CPPTOC_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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 CefHandlerCppToC - : public CefCppToC -{ -public: - CefHandlerCppToC(CefHandler* cls); - virtual ~CefHandlerCppToC() {} -}; - -#endif // USING_CEF_SHARED -#endif // _HANDLER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _HANDLER_CPPTOC_H +#define _HANDLER_CPPTOC_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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 CefHandlerCppToC + : public CefCppToC +{ +public: + CefHandlerCppToC(CefHandler* cls); + virtual ~CefHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // _HANDLER_CPPTOC_H + diff --git a/libcef_dll/cpptoc/post_data_cpptoc.cc b/libcef_dll/cpptoc/post_data_cpptoc.cc index 0504b64f2..2650ba58c 100644 --- a/libcef_dll/cpptoc/post_data_cpptoc.cc +++ b/libcef_dll/cpptoc/post_data_cpptoc.cc @@ -1,106 +1,106 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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() -{ - CefRefPtr impl = CefPostData::CreatePostData(); - if(impl.get()) - return CefPostDataCppToC::Wrap(impl); - return NULL; -} - - -// MEMBER FUNCTIONS - Body may be edited by hand. - -size_t CEF_CALLBACK post_data_get_element_count(struct _cef_post_data_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefPostDataCppToC::Get(self)->GetElementCount(); -} - -struct _cef_post_data_element_t* CEF_CALLBACK post_data_get_elements( - struct _cef_post_data_t* self, int elementIndex) -{ - DCHECK(self); - if(!self) - return NULL; - - CefPostData::ElementVector elements; - CefPostDataCppToC::Get(self)->GetElements(elements); - - if(elementIndex < 0 || elementIndex >= (int)elements.size()) - return NULL; - - return CefPostDataElementCppToC::Wrap(elements[elementIndex]); -} - -int CEF_CALLBACK post_data_remove_element(struct _cef_post_data_t* self, - struct _cef_post_data_element_t* element) -{ - DCHECK(self); - DCHECK(element); - if(!self || !element) - return 0; - - CefRefPtr selfElementPtr = - CefPostDataElementCppToC::Unwrap(element); - return CefPostDataCppToC::Get(self)->RemoveElement(selfElementPtr); -} - -int CEF_CALLBACK post_data_add_element(struct _cef_post_data_t* self, - struct _cef_post_data_element_t* element) -{ - DCHECK(self); - DCHECK(element); - if(!self || !element) - return 0; - - CefRefPtr selfElementPtr = - CefPostDataElementCppToC::Unwrap(element); - return CefPostDataCppToC::Get(self)->AddElement(selfElementPtr); -} - -void CEF_CALLBACK post_data_remove_elements(struct _cef_post_data_t* self) -{ - DCHECK(self); - if(!self) - return; - - 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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() +{ + CefRefPtr impl = CefPostData::CreatePostData(); + if(impl.get()) + return CefPostDataCppToC::Wrap(impl); + return NULL; +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +size_t CEF_CALLBACK post_data_get_element_count(struct _cef_post_data_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefPostDataCppToC::Get(self)->GetElementCount(); +} + +struct _cef_post_data_element_t* CEF_CALLBACK post_data_get_elements( + struct _cef_post_data_t* self, int elementIndex) +{ + DCHECK(self); + if(!self) + return NULL; + + CefPostData::ElementVector elements; + CefPostDataCppToC::Get(self)->GetElements(elements); + + if(elementIndex < 0 || elementIndex >= (int)elements.size()) + return NULL; + + return CefPostDataElementCppToC::Wrap(elements[elementIndex]); +} + +int CEF_CALLBACK post_data_remove_element(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element) +{ + DCHECK(self); + DCHECK(element); + if(!self || !element) + return 0; + + CefRefPtr selfElementPtr = + CefPostDataElementCppToC::Unwrap(element); + return CefPostDataCppToC::Get(self)->RemoveElement(selfElementPtr); +} + +int CEF_CALLBACK post_data_add_element(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element) +{ + DCHECK(self); + DCHECK(element); + if(!self || !element) + return 0; + + CefRefPtr selfElementPtr = + CefPostDataElementCppToC::Unwrap(element); + return CefPostDataCppToC::Get(self)->AddElement(selfElementPtr); +} + +void CEF_CALLBACK post_data_remove_elements(struct _cef_post_data_t* self) +{ + DCHECK(self); + if(!self) + return; + + 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/post_data_cpptoc.h b/libcef_dll/cpptoc/post_data_cpptoc.h index 36454f4eb..ed72580f7 100644 --- a/libcef_dll/cpptoc/post_data_cpptoc.h +++ b/libcef_dll/cpptoc/post_data_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _POSTDATA_CPPTOC_H -#define _POSTDATA_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefPostDataCppToC(CefPostData* cls); - virtual ~CefPostDataCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _POSTDATA_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _POSTDATA_CPPTOC_H +#define _POSTDATA_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefPostDataCppToC(CefPostData* cls); + virtual ~CefPostDataCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _POSTDATA_CPPTOC_H + diff --git a/libcef_dll/cpptoc/post_data_element_cpptoc.cc b/libcef_dll/cpptoc/post_data_element_cpptoc.cc index 46d81fafb..66efc329f 100644 --- a/libcef_dll/cpptoc/post_data_element_cpptoc.cc +++ b/libcef_dll/cpptoc/post_data_element_cpptoc.cc @@ -1,128 +1,128 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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() -{ - CefRefPtr impl = - CefPostDataElement::CreatePostDataElement(); - if(impl.get()) - return CefPostDataElementCppToC::Wrap(impl); - return NULL; -} - - -// MEMBER FUNCTIONS - Body may be edited by hand. - -void CEF_CALLBACK post_data_element_set_to_empty( - struct _cef_post_data_element_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefPostDataElementCppToC::Get(self)->SetToEmpty(); -} - -void CEF_CALLBACK post_data_element_set_to_file( - struct _cef_post_data_element_t* self, const wchar_t* fileName) -{ - DCHECK(self); - if(!self) - return; - - std::wstring fileNameStr; - if(fileName) - fileNameStr = fileName; - - CefPostDataElementCppToC::Get(self)->SetToFile(fileNameStr); -} - -void CEF_CALLBACK post_data_element_set_to_bytes( - struct _cef_post_data_element_t* self, size_t size, const void* bytes) -{ - DCHECK(self); - if(!self) - return; - - 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) -{ - DCHECK(self); - if(!self) - return PDE_TYPE_EMPTY; - - return CefPostDataElementCppToC::Get(self)->GetType(); -} - -cef_string_t CEF_CALLBACK post_data_element_get_file( - struct _cef_post_data_element_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - std::wstring fileNameStr = - CefPostDataElementCppToC::Get(self)->GetFile(); - if(!fileNameStr.empty()) - return cef_string_alloc(fileNameStr.c_str()); - return NULL; -} - -size_t CEF_CALLBACK post_data_element_get_bytes_count( - struct _cef_post_data_element_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefPostDataElementCppToC::Get(self)->GetBytesCount(); -} - -size_t CEF_CALLBACK post_data_element_get_bytes( - struct _cef_post_data_element_t* self, size_t size, void* bytes) -{ - DCHECK(self); - if(!self) - return 0; - - return CefPostDataElementCppToC::Get(self)->GetBytes(size, bytes); -} - - -// 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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() +{ + CefRefPtr impl = + CefPostDataElement::CreatePostDataElement(); + if(impl.get()) + return CefPostDataElementCppToC::Wrap(impl); + return NULL; +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK post_data_element_set_to_empty( + struct _cef_post_data_element_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefPostDataElementCppToC::Get(self)->SetToEmpty(); +} + +void CEF_CALLBACK post_data_element_set_to_file( + struct _cef_post_data_element_t* self, const wchar_t* fileName) +{ + DCHECK(self); + if(!self) + return; + + std::wstring fileNameStr; + if(fileName) + fileNameStr = fileName; + + CefPostDataElementCppToC::Get(self)->SetToFile(fileNameStr); +} + +void CEF_CALLBACK post_data_element_set_to_bytes( + struct _cef_post_data_element_t* self, size_t size, const void* bytes) +{ + DCHECK(self); + if(!self) + return; + + 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) +{ + DCHECK(self); + if(!self) + return PDE_TYPE_EMPTY; + + return CefPostDataElementCppToC::Get(self)->GetType(); +} + +cef_string_t CEF_CALLBACK post_data_element_get_file( + struct _cef_post_data_element_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + std::wstring fileNameStr = + CefPostDataElementCppToC::Get(self)->GetFile(); + if(!fileNameStr.empty()) + return cef_string_alloc(fileNameStr.c_str()); + return NULL; +} + +size_t CEF_CALLBACK post_data_element_get_bytes_count( + struct _cef_post_data_element_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefPostDataElementCppToC::Get(self)->GetBytesCount(); +} + +size_t CEF_CALLBACK post_data_element_get_bytes( + struct _cef_post_data_element_t* self, size_t size, void* bytes) +{ + DCHECK(self); + if(!self) + return 0; + + return CefPostDataElementCppToC::Get(self)->GetBytes(size, bytes); +} + + +// 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/post_data_element_cpptoc.h b/libcef_dll/cpptoc/post_data_element_cpptoc.h index df7eaa022..0da1a2706 100644 --- a/libcef_dll/cpptoc/post_data_element_cpptoc.h +++ b/libcef_dll/cpptoc/post_data_element_cpptoc.h @@ -1,35 +1,35 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _POSTDATAELEMENT_CPPTOC_H -#define _POSTDATAELEMENT_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefPostDataElementCppToC(CefPostDataElement* cls); - virtual ~CefPostDataElementCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _POSTDATAELEMENT_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _POSTDATAELEMENT_CPPTOC_H +#define _POSTDATAELEMENT_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefPostDataElementCppToC(CefPostDataElement* cls); + virtual ~CefPostDataElementCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _POSTDATAELEMENT_CPPTOC_H + diff --git a/libcef_dll/cpptoc/read_handler_cpptoc.cc b/libcef_dll/cpptoc/read_handler_cpptoc.cc index ac71ed08b..ea9a5a123 100644 --- a/libcef_dll/cpptoc/read_handler_cpptoc.cc +++ b/libcef_dll/cpptoc/read_handler_cpptoc.cc @@ -1,72 +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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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) -{ - DCHECK(self); - if(!self) - return 0; - - return CefReadHandlerCppToC::Get(self)->Read(ptr, size, n); -} - -int CEF_CALLBACK read_handler_seek(struct _cef_read_handler_t* self, - long offset, int whence) -{ - DCHECK(self); - if(!self) - return 0; - - return CefReadHandlerCppToC::Get(self)->Seek(offset, whence); -} - -long CEF_CALLBACK read_handler_tell(struct _cef_read_handler_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefReadHandlerCppToC::Get(self)->Tell(); -} - -int CEF_CALLBACK read_handler_eof(struct _cef_read_handler_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefReadHandlerCppToC::Get(self)->Eof(); -} - - -// 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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) +{ + DCHECK(self); + if(!self) + return 0; + + return CefReadHandlerCppToC::Get(self)->Read(ptr, size, n); +} + +int CEF_CALLBACK read_handler_seek(struct _cef_read_handler_t* self, + long offset, int whence) +{ + DCHECK(self); + if(!self) + return 0; + + return CefReadHandlerCppToC::Get(self)->Seek(offset, whence); +} + +long CEF_CALLBACK read_handler_tell(struct _cef_read_handler_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefReadHandlerCppToC::Get(self)->Tell(); +} + +int CEF_CALLBACK read_handler_eof(struct _cef_read_handler_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefReadHandlerCppToC::Get(self)->Eof(); +} + + +// 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/read_handler_cpptoc.h b/libcef_dll/cpptoc/read_handler_cpptoc.h index 2b0183497..dba1ffd5c 100644 --- a/libcef_dll/cpptoc/read_handler_cpptoc.h +++ b/libcef_dll/cpptoc/read_handler_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _READHANDLER_CPPTOC_H -#define _READHANDLER_CPPTOC_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefReadHandlerCppToC(CefReadHandler* cls); - virtual ~CefReadHandlerCppToC() {} -}; - -#endif // USING_CEF_SHARED -#endif // _READHANDLER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _READHANDLER_CPPTOC_H +#define _READHANDLER_CPPTOC_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefReadHandlerCppToC(CefReadHandler* cls); + virtual ~CefReadHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // _READHANDLER_CPPTOC_H + diff --git a/libcef_dll/cpptoc/request_cpptoc.cc b/libcef_dll/cpptoc/request_cpptoc.cc index 4c08c267a..355469497 100644 --- a/libcef_dll/cpptoc/request_cpptoc.cc +++ b/libcef_dll/cpptoc/request_cpptoc.cc @@ -1,180 +1,180 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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() -{ - CefRefPtr impl = CefRequest::CreateRequest(); - if(impl.get()) - return CefRequestCppToC::Wrap(impl); - return NULL; -} - - -// MEMBER FUNCTIONS - Body may be edited by hand. - -cef_string_t CEF_CALLBACK request_get_url(struct _cef_request_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - std::wstring urlStr = CefRequestCppToC::Get(self)->GetURL(); - if(!urlStr.empty()) - return cef_string_alloc(urlStr.c_str()); - return NULL; -} - -void CEF_CALLBACK request_set_url(struct _cef_request_t* self, - const wchar_t* url) -{ - DCHECK(self); - if(!self) - return; - - std::wstring urlStr; - if(url) - urlStr = url; - CefRequestCppToC::Get(self)->SetURL(urlStr); -} - -cef_string_t CEF_CALLBACK request_get_method(struct _cef_request_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - std::wstring methodStr = CefRequestCppToC::Get(self)->GetMethod(); - if(!methodStr.empty()) - return cef_string_alloc(methodStr.c_str()); - return NULL; -} - -void CEF_CALLBACK request_set_method(struct _cef_request_t* self, - const wchar_t* method) -{ - DCHECK(self); - if(!self) - return; - - std::wstring methodStr; - if(method) - methodStr = method; - CefRequestCppToC::Get(self)->SetMethod(methodStr); -} - -struct _cef_post_data_t* CEF_CALLBACK request_get_post_data( - struct _cef_request_t* self) -{ - DCHECK(self); - if(!self) - return NULL; - - CefRefPtr postDataPtr = - CefRequestCppToC::Get(self)->GetPostData(); - if(!postDataPtr.get()) - return NULL; - - return CefPostDataCppToC::Wrap(postDataPtr); -} - -void CEF_CALLBACK request_set_post_data(struct _cef_request_t* self, - struct _cef_post_data_t* postData) -{ - DCHECK(self); - if(!self) - return; - - CefRefPtr postDataPtr; - if(postData) - postDataPtr = CefPostDataCppToC::Unwrap(postData); - - CefRequestCppToC::Get(self)->SetPostData(postDataPtr); -} - -void CEF_CALLBACK request_get_header_map(struct _cef_request_t* self, - cef_string_map_t headerMap) -{ - DCHECK(self); - if(!self) - return; - - CefRequest::HeaderMap map; - CefRequestCppToC::Get(self)->GetHeaderMap(map); - transfer_string_map_contents(map, headerMap); -} - -void CEF_CALLBACK request_set_header_map(struct _cef_request_t* self, - cef_string_map_t headerMap) -{ - DCHECK(self); - if(!self) - return; - - CefRequest::HeaderMap map; - if(headerMap) - transfer_string_map_contents(headerMap, map); - - CefRequestCppToC::Get(self)->SetHeaderMap(map); -} - -void CEF_CALLBACK request_set(struct _cef_request_t* self, const wchar_t* url, - const wchar_t* method, struct _cef_post_data_t* postData, - cef_string_map_t headerMap) -{ - DCHECK(self); - if(!self) - return; - - std::wstring urlStr, methodStr; - CefRefPtr postDataPtr; - CefRequest::HeaderMap map; - - if(url) - urlStr = url; - if(method) - methodStr = method; - if(postData) - postDataPtr = CefPostDataCppToC::Unwrap(postData); - if(headerMap) - transfer_string_map_contents(headerMap, map); - - CefRequestCppToC::Get(self)->Set(urlStr, methodStr, postDataPtr, map); -} - - -// 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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() +{ + CefRefPtr impl = CefRequest::CreateRequest(); + if(impl.get()) + return CefRequestCppToC::Wrap(impl); + return NULL; +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_string_t CEF_CALLBACK request_get_url(struct _cef_request_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + std::wstring urlStr = CefRequestCppToC::Get(self)->GetURL(); + if(!urlStr.empty()) + return cef_string_alloc(urlStr.c_str()); + return NULL; +} + +void CEF_CALLBACK request_set_url(struct _cef_request_t* self, + const wchar_t* url) +{ + DCHECK(self); + if(!self) + return; + + std::wstring urlStr; + if(url) + urlStr = url; + CefRequestCppToC::Get(self)->SetURL(urlStr); +} + +cef_string_t CEF_CALLBACK request_get_method(struct _cef_request_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + std::wstring methodStr = CefRequestCppToC::Get(self)->GetMethod(); + if(!methodStr.empty()) + return cef_string_alloc(methodStr.c_str()); + return NULL; +} + +void CEF_CALLBACK request_set_method(struct _cef_request_t* self, + const wchar_t* method) +{ + DCHECK(self); + if(!self) + return; + + std::wstring methodStr; + if(method) + methodStr = method; + CefRequestCppToC::Get(self)->SetMethod(methodStr); +} + +struct _cef_post_data_t* CEF_CALLBACK request_get_post_data( + struct _cef_request_t* self) +{ + DCHECK(self); + if(!self) + return NULL; + + CefRefPtr postDataPtr = + CefRequestCppToC::Get(self)->GetPostData(); + if(!postDataPtr.get()) + return NULL; + + return CefPostDataCppToC::Wrap(postDataPtr); +} + +void CEF_CALLBACK request_set_post_data(struct _cef_request_t* self, + struct _cef_post_data_t* postData) +{ + DCHECK(self); + if(!self) + return; + + CefRefPtr postDataPtr; + if(postData) + postDataPtr = CefPostDataCppToC::Unwrap(postData); + + CefRequestCppToC::Get(self)->SetPostData(postDataPtr); +} + +void CEF_CALLBACK request_get_header_map(struct _cef_request_t* self, + cef_string_map_t headerMap) +{ + DCHECK(self); + if(!self) + return; + + CefRequest::HeaderMap map; + CefRequestCppToC::Get(self)->GetHeaderMap(map); + transfer_string_map_contents(map, headerMap); +} + +void CEF_CALLBACK request_set_header_map(struct _cef_request_t* self, + cef_string_map_t headerMap) +{ + DCHECK(self); + if(!self) + return; + + CefRequest::HeaderMap map; + if(headerMap) + transfer_string_map_contents(headerMap, map); + + CefRequestCppToC::Get(self)->SetHeaderMap(map); +} + +void CEF_CALLBACK request_set(struct _cef_request_t* self, const wchar_t* url, + const wchar_t* method, struct _cef_post_data_t* postData, + cef_string_map_t headerMap) +{ + DCHECK(self); + if(!self) + return; + + std::wstring urlStr, methodStr; + CefRefPtr postDataPtr; + CefRequest::HeaderMap map; + + if(url) + urlStr = url; + if(method) + methodStr = method; + if(postData) + postDataPtr = CefPostDataCppToC::Unwrap(postData); + if(headerMap) + transfer_string_map_contents(headerMap, map); + + CefRequestCppToC::Get(self)->Set(urlStr, methodStr, postDataPtr, map); +} + + +// 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/request_cpptoc.h b/libcef_dll/cpptoc/request_cpptoc.h index 81813c9fd..15688dc3b 100644 --- a/libcef_dll/cpptoc/request_cpptoc.h +++ b/libcef_dll/cpptoc/request_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _REQUEST_CPPTOC_H -#define _REQUEST_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefRequestCppToC(CefRequest* cls); - virtual ~CefRequestCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _REQUEST_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _REQUEST_CPPTOC_H +#define _REQUEST_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefRequestCppToC(CefRequest* cls); + virtual ~CefRequestCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _REQUEST_CPPTOC_H + diff --git a/libcef_dll/cpptoc/scheme_handler_cpptoc.cc b/libcef_dll/cpptoc/scheme_handler_cpptoc.cc index 9364fbfdd..bb665a186 100644 --- a/libcef_dll/cpptoc/scheme_handler_cpptoc.cc +++ b/libcef_dll/cpptoc/scheme_handler_cpptoc.cc @@ -1,84 +1,84 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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/transfer_util.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_string_t* mime_type, int* response_length) -{ - DCHECK(self); - DCHECK(request); - DCHECK(mime_type); - DCHECK(response_length); - if(!self || !request || !mime_type || !response_length) - return 0; - - std::wstring mimeTypeStr; - if(*mime_type) - mimeTypeStr = *mime_type; - - bool rv = CefSchemeHandlerCppToC::Get(self)->ProcessRequest( - CefRequestCToCpp::Wrap(request), mimeTypeStr, response_length); - - transfer_string_contents(mimeTypeStr, mime_type); - - return rv?1:0; -} - -void CEF_CALLBACK scheme_handler_cancel(struct _cef_scheme_handler_t* self) -{ - DCHECK(self); - if(!self) - return; - - CefSchemeHandlerCppToC::Get(self)->Cancel(); -} - -int CEF_CALLBACK scheme_handler_read_response( - struct _cef_scheme_handler_t* self, void* data_out, int bytes_to_read, - int* bytes_read) -{ - DCHECK(self); - DCHECK(data_out); - DCHECK(bytes_read); - if(!self || !data_out || !bytes_read) - return 0; - - bool rv = CefSchemeHandlerCppToC::Get(self)->ReadResponse( - data_out, bytes_to_read, bytes_read); - - return rv?1:0; -} - - -// CONSTRUCTOR - Do not edit by hand. - -CefSchemeHandlerCppToC::CefSchemeHandlerCppToC(CefSchemeHandler* cls) - : CefCppToC( - cls) -{ - struct_.struct_.process_request = scheme_handler_process_request; - struct_.struct_.cancel = scheme_handler_cancel; - struct_.struct_.read_response = scheme_handler_read_response; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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/transfer_util.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_string_t* mime_type, int* response_length) +{ + DCHECK(self); + DCHECK(request); + DCHECK(mime_type); + DCHECK(response_length); + if(!self || !request || !mime_type || !response_length) + return 0; + + std::wstring mimeTypeStr; + if(*mime_type) + mimeTypeStr = *mime_type; + + bool rv = CefSchemeHandlerCppToC::Get(self)->ProcessRequest( + CefRequestCToCpp::Wrap(request), mimeTypeStr, response_length); + + transfer_string_contents(mimeTypeStr, mime_type); + + return rv?1:0; +} + +void CEF_CALLBACK scheme_handler_cancel(struct _cef_scheme_handler_t* self) +{ + DCHECK(self); + if(!self) + return; + + CefSchemeHandlerCppToC::Get(self)->Cancel(); +} + +int CEF_CALLBACK scheme_handler_read_response( + struct _cef_scheme_handler_t* self, void* data_out, int bytes_to_read, + int* bytes_read) +{ + DCHECK(self); + DCHECK(data_out); + DCHECK(bytes_read); + if(!self || !data_out || !bytes_read) + return 0; + + bool rv = CefSchemeHandlerCppToC::Get(self)->ReadResponse( + data_out, bytes_to_read, bytes_read); + + return rv?1:0; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefSchemeHandlerCppToC::CefSchemeHandlerCppToC(CefSchemeHandler* cls) + : CefCppToC( + cls) +{ + struct_.struct_.process_request = scheme_handler_process_request; + struct_.struct_.cancel = scheme_handler_cancel; + struct_.struct_.read_response = scheme_handler_read_response; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/scheme_handler_cpptoc.h b/libcef_dll/cpptoc/scheme_handler_cpptoc.h index a43685b44..0e1cc55c2 100644 --- a/libcef_dll/cpptoc/scheme_handler_cpptoc.h +++ b/libcef_dll/cpptoc/scheme_handler_cpptoc.h @@ -1,35 +1,35 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _SCHEMEHANDLER_CPPTOC_H -#define _SCHEMEHANDLER_CPPTOC_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefSchemeHandlerCppToC(CefSchemeHandler* cls); - virtual ~CefSchemeHandlerCppToC() {} -}; - -#endif // USING_CEF_SHARED -#endif // _SCHEMEHANDLER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _SCHEMEHANDLER_CPPTOC_H +#define _SCHEMEHANDLER_CPPTOC_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefSchemeHandlerCppToC(CefSchemeHandler* cls); + virtual ~CefSchemeHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // _SCHEMEHANDLER_CPPTOC_H + diff --git a/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc index 79bb7142b..fc461c6c4 100644 --- a/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc +++ b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc @@ -1,43 +1,43 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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" - - -// 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) -{ - CefRefPtr rv = - CefSchemeHandlerFactoryCppToC::Get(self)->Create(); - - return CefSchemeHandlerCppToC::Wrap(rv); -} - - -// CONSTRUCTOR - Do not edit by hand. - -CefSchemeHandlerFactoryCppToC::CefSchemeHandlerFactoryCppToC( - CefSchemeHandlerFactory* cls) - : CefCppToC(cls) -{ - struct_.struct_.create = scheme_handler_factory_create; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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" + + +// 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) +{ + CefRefPtr rv = + CefSchemeHandlerFactoryCppToC::Get(self)->Create(); + + return CefSchemeHandlerCppToC::Wrap(rv); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefSchemeHandlerFactoryCppToC::CefSchemeHandlerFactoryCppToC( + CefSchemeHandlerFactory* cls) + : CefCppToC(cls) +{ + struct_.struct_.create = scheme_handler_factory_create; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h index 7f5038151..e444f0606 100644 --- a/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h +++ b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h @@ -1,35 +1,35 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _SCHEMEHANDLERFACTORY_CPPTOC_H -#define _SCHEMEHANDLERFACTORY_CPPTOC_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefSchemeHandlerFactoryCppToC(CefSchemeHandlerFactory* cls); - virtual ~CefSchemeHandlerFactoryCppToC() {} -}; - -#endif // USING_CEF_SHARED -#endif // _SCHEMEHANDLERFACTORY_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _SCHEMEHANDLERFACTORY_CPPTOC_H +#define _SCHEMEHANDLERFACTORY_CPPTOC_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefSchemeHandlerFactoryCppToC(CefSchemeHandlerFactory* cls); + virtual ~CefSchemeHandlerFactoryCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // _SCHEMEHANDLERFACTORY_CPPTOC_H + diff --git a/libcef_dll/cpptoc/stream_reader_cpptoc.cc b/libcef_dll/cpptoc/stream_reader_cpptoc.cc index d5cea16ce..814170878 100644 --- a/libcef_dll/cpptoc/stream_reader_cpptoc.cc +++ b/libcef_dll/cpptoc/stream_reader_cpptoc.cc @@ -1,108 +1,108 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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 wchar_t* fileName) -{ - std::wstring filenamestr; - if(fileName) - filenamestr = fileName; - CefRefPtr impl = CefStreamReader::CreateForFile(filenamestr); - if(impl.get()) - return CefStreamReaderCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_data(void* data, - size_t size) -{ - CefRefPtr impl = CefStreamReader::CreateForData(data, size); - if(impl.get()) - return CefStreamReaderCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_handler( - cef_read_handler_t* handler) -{ - CefRefPtr impl = - CefStreamReader::CreateForHandler(CefReadHandlerCToCpp::Wrap(handler)); - if(impl.get()) - return CefStreamReaderCppToC::Wrap(impl); - return NULL; -} - - -// 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) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamReaderCppToC::Get(self)->Read(ptr, size, n); -} - -int CEF_CALLBACK stream_reader_seek(struct _cef_stream_reader_t* self, - long offset, int whence) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamReaderCppToC::Get(self)->Seek(offset, whence); -} - -long CEF_CALLBACK stream_reader_tell(struct _cef_stream_reader_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamReaderCppToC::Get(self)->Tell(); -} - -int CEF_CALLBACK stream_reader_eof(struct _cef_stream_reader_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamReaderCppToC::Get(self)->Eof(); -} - - -// 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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 wchar_t* fileName) +{ + std::wstring filenamestr; + if(fileName) + filenamestr = fileName; + CefRefPtr impl = CefStreamReader::CreateForFile(filenamestr); + if(impl.get()) + return CefStreamReaderCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_data(void* data, + size_t size) +{ + CefRefPtr impl = CefStreamReader::CreateForData(data, size); + if(impl.get()) + return CefStreamReaderCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_handler( + cef_read_handler_t* handler) +{ + CefRefPtr impl = + CefStreamReader::CreateForHandler(CefReadHandlerCToCpp::Wrap(handler)); + if(impl.get()) + return CefStreamReaderCppToC::Wrap(impl); + return NULL; +} + + +// 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) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamReaderCppToC::Get(self)->Read(ptr, size, n); +} + +int CEF_CALLBACK stream_reader_seek(struct _cef_stream_reader_t* self, + long offset, int whence) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamReaderCppToC::Get(self)->Seek(offset, whence); +} + +long CEF_CALLBACK stream_reader_tell(struct _cef_stream_reader_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamReaderCppToC::Get(self)->Tell(); +} + +int CEF_CALLBACK stream_reader_eof(struct _cef_stream_reader_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamReaderCppToC::Get(self)->Eof(); +} + + +// 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/stream_reader_cpptoc.h b/libcef_dll/cpptoc/stream_reader_cpptoc.h index 0ba7df7a0..7e0d5c69f 100644 --- a/libcef_dll/cpptoc/stream_reader_cpptoc.h +++ b/libcef_dll/cpptoc/stream_reader_cpptoc.h @@ -1,35 +1,35 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _STREAMREADER_CPPTOC_H -#define _STREAMREADER_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefStreamReaderCppToC(CefStreamReader* cls); - virtual ~CefStreamReaderCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _STREAMREADER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _STREAMREADER_CPPTOC_H +#define _STREAMREADER_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefStreamReaderCppToC(CefStreamReader* cls); + virtual ~CefStreamReaderCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _STREAMREADER_CPPTOC_H + diff --git a/libcef_dll/cpptoc/stream_writer_cpptoc.cc b/libcef_dll/cpptoc/stream_writer_cpptoc.cc index 66d4406e9..b7b27c0b2 100644 --- a/libcef_dll/cpptoc/stream_writer_cpptoc.cc +++ b/libcef_dll/cpptoc/stream_writer_cpptoc.cc @@ -1,105 +1,105 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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 wchar_t* fileName) -{ - DCHECK(fileName); - if(!fileName) - return NULL; - - std::wstring fileNameStr = fileName; - CefRefPtr impl = CefStreamWriter::CreateForFile(fileName); - if(impl.get()) - return CefStreamWriterCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_handler( - cef_write_handler_t* handler) -{ - DCHECK(handler); - if(!handler) - return NULL; - - CefRefPtr impl = - CefStreamWriter::CreateForHandler(CefWriteHandlerCToCpp::Wrap(handler)); - if(impl.get()) - return CefStreamWriterCppToC::Wrap(impl); - return NULL; -} - - -// 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) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamWriterCppToC::Get(self)->Write(ptr, size, n); -} - -int CEF_CALLBACK stream_writer_seek(struct _cef_stream_writer_t* self, - long offset, int whence) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamWriterCppToC::Get(self)->Seek(offset, whence); -} - -long CEF_CALLBACK stream_writer_tell(struct _cef_stream_writer_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamWriterCppToC::Get(self)->Tell(); -} - -int CEF_CALLBACK stream_writer_flush(struct _cef_stream_writer_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefStreamWriterCppToC::Get(self)->Flush(); -} - - -// 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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 wchar_t* fileName) +{ + DCHECK(fileName); + if(!fileName) + return NULL; + + std::wstring fileNameStr = fileName; + CefRefPtr impl = CefStreamWriter::CreateForFile(fileName); + if(impl.get()) + return CefStreamWriterCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_handler( + cef_write_handler_t* handler) +{ + DCHECK(handler); + if(!handler) + return NULL; + + CefRefPtr impl = + CefStreamWriter::CreateForHandler(CefWriteHandlerCToCpp::Wrap(handler)); + if(impl.get()) + return CefStreamWriterCppToC::Wrap(impl); + return NULL; +} + + +// 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) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamWriterCppToC::Get(self)->Write(ptr, size, n); +} + +int CEF_CALLBACK stream_writer_seek(struct _cef_stream_writer_t* self, + long offset, int whence) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamWriterCppToC::Get(self)->Seek(offset, whence); +} + +long CEF_CALLBACK stream_writer_tell(struct _cef_stream_writer_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamWriterCppToC::Get(self)->Tell(); +} + +int CEF_CALLBACK stream_writer_flush(struct _cef_stream_writer_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefStreamWriterCppToC::Get(self)->Flush(); +} + + +// 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/stream_writer_cpptoc.h b/libcef_dll/cpptoc/stream_writer_cpptoc.h index a58fa3b1a..719f4c4e2 100644 --- a/libcef_dll/cpptoc/stream_writer_cpptoc.h +++ b/libcef_dll/cpptoc/stream_writer_cpptoc.h @@ -1,35 +1,35 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _STREAMWRITER_CPPTOC_H -#define _STREAMWRITER_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefStreamWriterCppToC(CefStreamWriter* cls); - virtual ~CefStreamWriterCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _STREAMWRITER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _STREAMWRITER_CPPTOC_H +#define _STREAMWRITER_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefStreamWriterCppToC(CefStreamWriter* cls); + virtual ~CefStreamWriterCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _STREAMWRITER_CPPTOC_H + diff --git a/libcef_dll/cpptoc/task_cpptoc.cc b/libcef_dll/cpptoc/task_cpptoc.cc index c8dd5ba31..212a08bcc 100644 --- a/libcef_dll/cpptoc/task_cpptoc.cc +++ b/libcef_dll/cpptoc/task_cpptoc.cc @@ -1,40 +1,40 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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) -{ - DCHECK(self); - if(!self) - return; - - CefTaskCppToC::Get(self)->Execute(threadId); -} - - -// CONSTRUCTOR - Do not edit by hand. - -CefTaskCppToC::CefTaskCppToC(CefTask* cls) - : CefCppToC(cls) -{ - struct_.struct_.execute = task_execute; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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) +{ + DCHECK(self); + if(!self) + return; + + CefTaskCppToC::Get(self)->Execute(threadId); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefTaskCppToC::CefTaskCppToC(CefTask* cls) + : CefCppToC(cls) +{ + struct_.struct_.execute = task_execute; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/task_cpptoc.h b/libcef_dll/cpptoc/task_cpptoc.h index 40a42decc..2515be799 100644 --- a/libcef_dll/cpptoc/task_cpptoc.h +++ b/libcef_dll/cpptoc/task_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _TASK_CPPTOC_H -#define _TASK_CPPTOC_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefTaskCppToC(CefTask* cls); - virtual ~CefTaskCppToC() {} -}; - -#endif // USING_CEF_SHARED -#endif // _TASK_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _TASK_CPPTOC_H +#define _TASK_CPPTOC_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefTaskCppToC(CefTask* cls); + virtual ~CefTaskCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // _TASK_CPPTOC_H + diff --git a/libcef_dll/cpptoc/v8handler_cpptoc.cc b/libcef_dll/cpptoc/v8handler_cpptoc.cc index db7179be5..a0bf62e23 100644 --- a/libcef_dll/cpptoc/v8handler_cpptoc.cc +++ b/libcef_dll/cpptoc/v8handler_cpptoc.cc @@ -1,68 +1,68 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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 wchar_t* name, struct _cef_v8value_t* object, size_t argumentCount, - struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, - cef_string_t* exception) -{ - DCHECK(self); - if(!self) - return RV_CONTINUE; - - CefRefPtr objectPtr; - if(object) - objectPtr = CefV8ValueCToCpp::Wrap(object); - - std::wstring nameStr; - if(name) - nameStr = name; - - CefV8ValueList list; - for(size_t i = 0; i < argumentCount; ++i) { - list.push_back(CefV8ValueCToCpp::Wrap(arguments[i])); - } - - CefRefPtr retValPtr; - std::wstring exceptionStr; - bool rv = CefV8HandlerCppToC::Get(self)->Execute(nameStr, objectPtr, - list, retValPtr, exceptionStr); - if(rv) { - if(!exceptionStr.empty() && exception) - *exception = cef_string_alloc(exceptionStr.c_str()); - if(retValPtr.get() && retval) - *retval = CefV8ValueCToCpp::Unwrap(retValPtr); - } - - return rv; -} - - -// CONSTRUCTOR - Do not edit by hand. - -CefV8HandlerCppToC::CefV8HandlerCppToC(CefV8Handler* cls) - : CefCppToC(cls) -{ - struct_.struct_.execute = v8handler_execute; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = - 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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 wchar_t* name, struct _cef_v8value_t* object, size_t argumentCount, + struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, + cef_string_t* exception) +{ + DCHECK(self); + if(!self) + return RV_CONTINUE; + + CefRefPtr objectPtr; + if(object) + objectPtr = CefV8ValueCToCpp::Wrap(object); + + std::wstring nameStr; + if(name) + nameStr = name; + + CefV8ValueList list; + for(size_t i = 0; i < argumentCount; ++i) { + list.push_back(CefV8ValueCToCpp::Wrap(arguments[i])); + } + + CefRefPtr retValPtr; + std::wstring exceptionStr; + bool rv = CefV8HandlerCppToC::Get(self)->Execute(nameStr, objectPtr, + list, retValPtr, exceptionStr); + if(rv) { + if(!exceptionStr.empty() && exception) + *exception = cef_string_alloc(exceptionStr.c_str()); + if(retValPtr.get() && retval) + *retval = CefV8ValueCToCpp::Unwrap(retValPtr); + } + + return rv; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8HandlerCppToC::CefV8HandlerCppToC(CefV8Handler* cls) + : CefCppToC(cls) +{ + struct_.struct_.execute = v8handler_execute; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/cpptoc/v8handler_cpptoc.h b/libcef_dll/cpptoc/v8handler_cpptoc.h index 29ee6233f..b9327cf68 100644 --- a/libcef_dll/cpptoc/v8handler_cpptoc.h +++ b/libcef_dll/cpptoc/v8handler_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _V8HANDLER_CPPTOC_H -#define _V8HANDLER_CPPTOC_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefV8HandlerCppToC(CefV8Handler* cls); - virtual ~CefV8HandlerCppToC() {} -}; - -#endif // USING_CEF_SHARED -#endif // _V8HANDLER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _V8HANDLER_CPPTOC_H +#define _V8HANDLER_CPPTOC_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefV8HandlerCppToC(CefV8Handler* cls); + virtual ~CefV8HandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // _V8HANDLER_CPPTOC_H + diff --git a/libcef_dll/cpptoc/v8value_cpptoc.cc b/libcef_dll/cpptoc/v8value_cpptoc.cc index 6afec1a1e..f3fbf1f2c 100644 --- a/libcef_dll/cpptoc/v8value_cpptoc.cc +++ b/libcef_dll/cpptoc/v8value_cpptoc.cc @@ -1,462 +1,462 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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/base_ctocpp.h" -#include "libcef_dll/ctocpp/v8handler_ctocpp.h" - - -// GLOBAL FUNCTIONS - Body may be edited by hand. - -CEF_EXPORT cef_v8value_t* cef_v8value_create_undefined() -{ - CefRefPtr impl = CefV8Value::CreateUndefined(); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_null() -{ - CefRefPtr impl = CefV8Value::CreateNull(); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_bool(int value) -{ - CefRefPtr impl = CefV8Value::CreateBool(value?true:false); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_int(int value) -{ - CefRefPtr impl = CefV8Value::CreateInt(value); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_double(double value) -{ - CefRefPtr impl = CefV8Value::CreateDouble(value); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_string(const wchar_t* value) -{ - std::wstring valueStr; - if(value) - valueStr = value; - - CefRefPtr impl = CefV8Value::CreateString(valueStr); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_object(cef_base_t* user_data) -{ - CefRefPtr basePtr; - if(user_data) - basePtr = CefBaseCToCpp::Wrap(user_data); - - CefRefPtr impl = CefV8Value::CreateObject(basePtr); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_array() -{ - CefRefPtr impl = CefV8Value::CreateArray(); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - -CEF_EXPORT cef_v8value_t* cef_v8value_create_function(const wchar_t* name, - cef_v8handler_t* handler) -{ - std::wstring nameStr; - if(name) - nameStr = name; - CefRefPtr handlerPtr; - if(handler) - handlerPtr = CefV8HandlerCToCpp::Wrap(handler); - - CefRefPtr impl = CefV8Value::CreateFunction(nameStr, handlerPtr); - if(impl.get()) - return CefV8ValueCppToC::Wrap(impl); - return NULL; -} - - -// MEMBER FUNCTIONS - Body may be edited by hand. - -int CEF_CALLBACK v8value_is_undefined(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsUndefined(); -} - -int CEF_CALLBACK v8value_is_null(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsNull(); -} - -int CEF_CALLBACK v8value_is_bool(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsBool(); -} - -int CEF_CALLBACK v8value_is_int(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsInt(); -} - -int CEF_CALLBACK v8value_is_double(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsDouble(); -} - -int CEF_CALLBACK v8value_is_string(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsString(); -} - -int CEF_CALLBACK v8value_is_object(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsObject(); -} - -int CEF_CALLBACK v8value_is_array(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsArray(); -} - -int CEF_CALLBACK v8value_is_function(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->IsFunction(); -} - -int CEF_CALLBACK v8value_get_bool_value(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->GetBoolValue(); -} - -int CEF_CALLBACK v8value_get_int_value(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->GetIntValue(); -} - -double CEF_CALLBACK v8value_get_double_value(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->GetDoubleValue(); -} - -cef_string_t CEF_CALLBACK v8value_get_string_value(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - std::wstring valueStr = CefV8ValueCppToC::Get(self)->GetStringValue(); - if(!valueStr.empty()) - return cef_string_alloc(valueStr.c_str()); - return NULL; -} - -int CEF_CALLBACK v8value_has_value_bykey(struct _cef_v8value_t* self, - const wchar_t* key) -{ - DCHECK(self); - if(!self) - return 0; - - std::wstring keyStr; - if(key) - keyStr = key; - - return CefV8ValueCppToC::Get(self)->HasValue(keyStr); -} - -int CEF_CALLBACK v8value_has_value_byindex(struct _cef_v8value_t* self, - int index) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->HasValue(index); -} - -int CEF_CALLBACK v8value_delete_value_bykey(struct _cef_v8value_t* self, - const wchar_t* key) -{ - DCHECK(self); - if(!self) - return 0; - - std::wstring keyStr; - if(key) - keyStr = key; - - return CefV8ValueCppToC::Get(self)->DeleteValue(keyStr); -} - -int CEF_CALLBACK v8value_delete_value_byindex(struct _cef_v8value_t* self, - int index) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->DeleteValue(index); -} - -struct _cef_v8value_t* CEF_CALLBACK v8value_get_value_bykey( - struct _cef_v8value_t* self, const wchar_t* key) -{ - DCHECK(self); - if(!self) - return 0; - - std::wstring keyStr; - if(key) - keyStr = key; - - CefRefPtr valuePtr = - CefV8ValueCppToC::Get(self)->GetValue(keyStr); - return CefV8ValueCppToC::Wrap(valuePtr); -} - -struct _cef_v8value_t* CEF_CALLBACK v8value_get_value_byindex( - struct _cef_v8value_t* self, int index) -{ - DCHECK(self); - if(!self) - return 0; - - CefRefPtr valuePtr = - CefV8ValueCppToC::Get(self)->GetValue(index); - return CefV8ValueCppToC::Wrap(valuePtr); -} - -int CEF_CALLBACK v8value_set_value_bykey(struct _cef_v8value_t* self, - const wchar_t* key, struct _cef_v8value_t* value) -{ - DCHECK(self); - if(!self) - return 0; - - std::wstring keyStr; - if(key) - keyStr = key; - - CefRefPtr valuePtr = CefV8ValueCppToC::Unwrap(value); - return CefV8ValueCppToC::Get(self)->SetValue(keyStr, valuePtr); -} - -int CEF_CALLBACK v8value_set_value_byindex(struct _cef_v8value_t* self, - int index, struct _cef_v8value_t* value) -{ - DCHECK(self); - if(!self) - return 0; - - CefRefPtr valuePtr = CefV8ValueCppToC::Unwrap(value); - return CefV8ValueCppToC::Get(self)->SetValue(index, valuePtr); -} - -int CEF_CALLBACK v8value_get_keys(struct _cef_v8value_t* self, - cef_string_list_t keys) -{ - DCHECK(self); - if(!self) - return 0; - - std::vector keysList; - CefV8ValueCppToC::Get(self)->GetKeys(keysList); - size_t size = keysList.size(); - for(size_t i = 0; i < size; ++i) - cef_string_list_append(keys, keysList[i].c_str()); - return size; -} - -cef_base_t* CEF_CALLBACK v8value_get_user_data(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - CefRefPtr base = CefV8ValueCppToC::Get(self)->GetUserData(); - if(base.get()) - return CefBaseCToCpp::Unwrap(base); - return NULL; -} - -int CEF_CALLBACK v8value_get_array_length(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefV8ValueCppToC::Get(self)->GetArrayLength(); -} - -cef_string_t CEF_CALLBACK v8value_get_function_name(struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - std::wstring functionNameStr = - CefV8ValueCppToC::Get(self)->GetFunctionName(); - if(!functionNameStr.empty()) - return cef_string_alloc(functionNameStr.c_str()); - return NULL; -} - -cef_v8handler_t* CEF_CALLBACK v8value_get_function_handler( - struct _cef_v8value_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - CefRefPtr handlerPtr = - CefV8ValueCppToC::Get(self)->GetFunctionHandler(); - if(handlerPtr.get()) - return CefV8HandlerCToCpp::Unwrap(handlerPtr); - return NULL; -} - -int CEF_CALLBACK v8value_execute_function(struct _cef_v8value_t* self, - struct _cef_v8value_t* object, size_t argumentCount, - struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, - cef_string_t* exception) -{ - DCHECK(self); - DCHECK(object); - if(!self || !object) - return 0; - - CefRefPtr objectPtr = CefV8ValueCppToC::Unwrap(object); - CefV8ValueList argsList; - for(size_t i = 0; i < argumentCount; i++) { - argsList.push_back(CefV8ValueCppToC::Unwrap(arguments[i])); - } - CefRefPtr retvalPtr; - std::wstring exceptionStr; - - bool rv = CefV8ValueCppToC::Get(self)->ExecuteFunction(objectPtr, - argsList, retvalPtr, exceptionStr); - if(retvalPtr.get() && retval) - *retval = CefV8ValueCppToC::Wrap(retvalPtr); - if(!exceptionStr.empty() && exception) - *exception = cef_string_alloc(exceptionStr.c_str()); - - return rv; -} - - -// 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_double = v8value_is_double; - 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_.get_bool_value = v8value_get_bool_value; - struct_.struct_.get_int_value = v8value_get_int_value; - struct_.struct_.get_double_value = v8value_get_double_value; - struct_.struct_.get_string_value = v8value_get_string_value; - 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_.get_keys = v8value_get_keys; - struct_.struct_.get_user_data = v8value_get_user_data; - 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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/base_ctocpp.h" +#include "libcef_dll/ctocpp/v8handler_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_v8value_t* cef_v8value_create_undefined() +{ + CefRefPtr impl = CefV8Value::CreateUndefined(); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_null() +{ + CefRefPtr impl = CefV8Value::CreateNull(); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_bool(int value) +{ + CefRefPtr impl = CefV8Value::CreateBool(value?true:false); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_int(int value) +{ + CefRefPtr impl = CefV8Value::CreateInt(value); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_double(double value) +{ + CefRefPtr impl = CefV8Value::CreateDouble(value); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_string(const wchar_t* value) +{ + std::wstring valueStr; + if(value) + valueStr = value; + + CefRefPtr impl = CefV8Value::CreateString(valueStr); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_object(cef_base_t* user_data) +{ + CefRefPtr basePtr; + if(user_data) + basePtr = CefBaseCToCpp::Wrap(user_data); + + CefRefPtr impl = CefV8Value::CreateObject(basePtr); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_array() +{ + CefRefPtr impl = CefV8Value::CreateArray(); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_function(const wchar_t* name, + cef_v8handler_t* handler) +{ + std::wstring nameStr; + if(name) + nameStr = name; + CefRefPtr handlerPtr; + if(handler) + handlerPtr = CefV8HandlerCToCpp::Wrap(handler); + + CefRefPtr impl = CefV8Value::CreateFunction(nameStr, handlerPtr); + if(impl.get()) + return CefV8ValueCppToC::Wrap(impl); + return NULL; +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK v8value_is_undefined(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsUndefined(); +} + +int CEF_CALLBACK v8value_is_null(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsNull(); +} + +int CEF_CALLBACK v8value_is_bool(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsBool(); +} + +int CEF_CALLBACK v8value_is_int(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsInt(); +} + +int CEF_CALLBACK v8value_is_double(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsDouble(); +} + +int CEF_CALLBACK v8value_is_string(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsString(); +} + +int CEF_CALLBACK v8value_is_object(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsObject(); +} + +int CEF_CALLBACK v8value_is_array(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsArray(); +} + +int CEF_CALLBACK v8value_is_function(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->IsFunction(); +} + +int CEF_CALLBACK v8value_get_bool_value(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->GetBoolValue(); +} + +int CEF_CALLBACK v8value_get_int_value(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->GetIntValue(); +} + +double CEF_CALLBACK v8value_get_double_value(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->GetDoubleValue(); +} + +cef_string_t CEF_CALLBACK v8value_get_string_value(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + std::wstring valueStr = CefV8ValueCppToC::Get(self)->GetStringValue(); + if(!valueStr.empty()) + return cef_string_alloc(valueStr.c_str()); + return NULL; +} + +int CEF_CALLBACK v8value_has_value_bykey(struct _cef_v8value_t* self, + const wchar_t* key) +{ + DCHECK(self); + if(!self) + return 0; + + std::wstring keyStr; + if(key) + keyStr = key; + + return CefV8ValueCppToC::Get(self)->HasValue(keyStr); +} + +int CEF_CALLBACK v8value_has_value_byindex(struct _cef_v8value_t* self, + int index) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->HasValue(index); +} + +int CEF_CALLBACK v8value_delete_value_bykey(struct _cef_v8value_t* self, + const wchar_t* key) +{ + DCHECK(self); + if(!self) + return 0; + + std::wstring keyStr; + if(key) + keyStr = key; + + return CefV8ValueCppToC::Get(self)->DeleteValue(keyStr); +} + +int CEF_CALLBACK v8value_delete_value_byindex(struct _cef_v8value_t* self, + int index) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->DeleteValue(index); +} + +struct _cef_v8value_t* CEF_CALLBACK v8value_get_value_bykey( + struct _cef_v8value_t* self, const wchar_t* key) +{ + DCHECK(self); + if(!self) + return 0; + + std::wstring keyStr; + if(key) + keyStr = key; + + CefRefPtr valuePtr = + CefV8ValueCppToC::Get(self)->GetValue(keyStr); + return CefV8ValueCppToC::Wrap(valuePtr); +} + +struct _cef_v8value_t* CEF_CALLBACK v8value_get_value_byindex( + struct _cef_v8value_t* self, int index) +{ + DCHECK(self); + if(!self) + return 0; + + CefRefPtr valuePtr = + CefV8ValueCppToC::Get(self)->GetValue(index); + return CefV8ValueCppToC::Wrap(valuePtr); +} + +int CEF_CALLBACK v8value_set_value_bykey(struct _cef_v8value_t* self, + const wchar_t* key, struct _cef_v8value_t* value) +{ + DCHECK(self); + if(!self) + return 0; + + std::wstring keyStr; + if(key) + keyStr = key; + + CefRefPtr valuePtr = CefV8ValueCppToC::Unwrap(value); + return CefV8ValueCppToC::Get(self)->SetValue(keyStr, valuePtr); +} + +int CEF_CALLBACK v8value_set_value_byindex(struct _cef_v8value_t* self, + int index, struct _cef_v8value_t* value) +{ + DCHECK(self); + if(!self) + return 0; + + CefRefPtr valuePtr = CefV8ValueCppToC::Unwrap(value); + return CefV8ValueCppToC::Get(self)->SetValue(index, valuePtr); +} + +int CEF_CALLBACK v8value_get_keys(struct _cef_v8value_t* self, + cef_string_list_t keys) +{ + DCHECK(self); + if(!self) + return 0; + + std::vector keysList; + CefV8ValueCppToC::Get(self)->GetKeys(keysList); + size_t size = keysList.size(); + for(size_t i = 0; i < size; ++i) + cef_string_list_append(keys, keysList[i].c_str()); + return size; +} + +cef_base_t* CEF_CALLBACK v8value_get_user_data(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + CefRefPtr base = CefV8ValueCppToC::Get(self)->GetUserData(); + if(base.get()) + return CefBaseCToCpp::Unwrap(base); + return NULL; +} + +int CEF_CALLBACK v8value_get_array_length(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefV8ValueCppToC::Get(self)->GetArrayLength(); +} + +cef_string_t CEF_CALLBACK v8value_get_function_name(struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + std::wstring functionNameStr = + CefV8ValueCppToC::Get(self)->GetFunctionName(); + if(!functionNameStr.empty()) + return cef_string_alloc(functionNameStr.c_str()); + return NULL; +} + +cef_v8handler_t* CEF_CALLBACK v8value_get_function_handler( + struct _cef_v8value_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + CefRefPtr handlerPtr = + CefV8ValueCppToC::Get(self)->GetFunctionHandler(); + if(handlerPtr.get()) + return CefV8HandlerCToCpp::Unwrap(handlerPtr); + return NULL; +} + +int CEF_CALLBACK v8value_execute_function(struct _cef_v8value_t* self, + struct _cef_v8value_t* object, size_t argumentCount, + struct _cef_v8value_t* const* arguments, struct _cef_v8value_t** retval, + cef_string_t* exception) +{ + DCHECK(self); + DCHECK(object); + if(!self || !object) + return 0; + + CefRefPtr objectPtr = CefV8ValueCppToC::Unwrap(object); + CefV8ValueList argsList; + for(size_t i = 0; i < argumentCount; i++) { + argsList.push_back(CefV8ValueCppToC::Unwrap(arguments[i])); + } + CefRefPtr retvalPtr; + std::wstring exceptionStr; + + bool rv = CefV8ValueCppToC::Get(self)->ExecuteFunction(objectPtr, + argsList, retvalPtr, exceptionStr); + if(retvalPtr.get() && retval) + *retval = CefV8ValueCppToC::Wrap(retvalPtr); + if(!exceptionStr.empty() && exception) + *exception = cef_string_alloc(exceptionStr.c_str()); + + return rv; +} + + +// 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_double = v8value_is_double; + 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_.get_bool_value = v8value_get_bool_value; + struct_.struct_.get_int_value = v8value_get_int_value; + struct_.struct_.get_double_value = v8value_get_double_value; + struct_.struct_.get_string_value = v8value_get_string_value; + 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_.get_keys = v8value_get_keys; + struct_.struct_.get_user_data = v8value_get_user_data; + 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8value_cpptoc.h b/libcef_dll/cpptoc/v8value_cpptoc.h index 483b57979..1b08dd705 100644 --- a/libcef_dll/cpptoc/v8value_cpptoc.h +++ b/libcef_dll/cpptoc/v8value_cpptoc.h @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _V8VALUE_CPPTOC_H -#define _V8VALUE_CPPTOC_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefV8ValueCppToC(CefV8Value* cls); - virtual ~CefV8ValueCppToC() {} -}; - -#endif // BUILDING_CEF_SHARED -#endif // _V8VALUE_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _V8VALUE_CPPTOC_H +#define _V8VALUE_CPPTOC_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefV8ValueCppToC(CefV8Value* cls); + virtual ~CefV8ValueCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // _V8VALUE_CPPTOC_H + diff --git a/libcef_dll/cpptoc/write_handler_cpptoc.cc b/libcef_dll/cpptoc/write_handler_cpptoc.cc index 60dcac05e..0e09b9ad9 100644 --- a/libcef_dll/cpptoc/write_handler_cpptoc.cc +++ b/libcef_dll/cpptoc/write_handler_cpptoc.cc @@ -1,73 +1,73 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing 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) -{ - DCHECK(self); - if(!self) - return 0; - - return CefWriteHandlerCppToC::Get(self)->Write(ptr, size, n); -} - -int CEF_CALLBACK write_handler_seek(struct _cef_write_handler_t* self, - long offset, int whence) -{ - DCHECK(self); - if(!self) - return 0; - - return CefWriteHandlerCppToC::Get(self)->Seek(offset, whence); -} - -long CEF_CALLBACK write_handler_tell(struct _cef_write_handler_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefWriteHandlerCppToC::Get(self)->Tell(); -} - -int CEF_CALLBACK write_handler_flush(struct _cef_write_handler_t* self) -{ - DCHECK(self); - if(!self) - return 0; - - return CefWriteHandlerCppToC::Get(self)->Flush(); -} - - -// 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; -} - -#ifdef _DEBUG -long CefCppToC::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing 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) +{ + DCHECK(self); + if(!self) + return 0; + + return CefWriteHandlerCppToC::Get(self)->Write(ptr, size, n); +} + +int CEF_CALLBACK write_handler_seek(struct _cef_write_handler_t* self, + long offset, int whence) +{ + DCHECK(self); + if(!self) + return 0; + + return CefWriteHandlerCppToC::Get(self)->Seek(offset, whence); +} + +long CEF_CALLBACK write_handler_tell(struct _cef_write_handler_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefWriteHandlerCppToC::Get(self)->Tell(); +} + +int CEF_CALLBACK write_handler_flush(struct _cef_write_handler_t* self) +{ + DCHECK(self); + if(!self) + return 0; + + return CefWriteHandlerCppToC::Get(self)->Flush(); +} + + +// 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; +} + +#ifdef _DEBUG +long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/write_handler_cpptoc.h b/libcef_dll/cpptoc/write_handler_cpptoc.h index 55e9184a1..7c3a89a68 100644 --- a/libcef_dll/cpptoc/write_handler_cpptoc.h +++ b/libcef_dll/cpptoc/write_handler_cpptoc.h @@ -1,35 +1,35 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// 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 _WRITEHANDLER_CPPTOC_H -#define _WRITEHANDLER_CPPTOC_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefWriteHandlerCppToC(CefWriteHandler* cls); - virtual ~CefWriteHandlerCppToC() {} -}; - -#endif // USING_CEF_SHARED -#endif // _WRITEHANDLER_CPPTOC_H - +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 _WRITEHANDLER_CPPTOC_H +#define _WRITEHANDLER_CPPTOC_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefWriteHandlerCppToC(CefWriteHandler* cls); + virtual ~CefWriteHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // _WRITEHANDLER_CPPTOC_H + diff --git a/libcef_dll/ctocpp/base_ctocpp.h b/libcef_dll/ctocpp/base_ctocpp.h index da758d606..8abd0f42f 100644 --- a/libcef_dll/ctocpp/base_ctocpp.h +++ b/libcef_dll/ctocpp/base_ctocpp.h @@ -1,95 +1,95 @@ -// 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 _BASE_CTOCPP_H -#define _BASE_CTOCPP_H - -#include "include/cef.h" -#include "include/cef_capi.h" -#include "libcef_dll/cef_logging.h" - - -// CefCToCpp implementation for CefBase. -class CefBaseCToCpp : public CefThreadSafeBase -{ -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) - { - // 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) - { - // 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(); - } - - 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. - virtual int AddRef() - { - UnderlyingAddRef(); - return CefThreadSafeBase::AddRef(); - } - virtual int Release() - { - UnderlyingRelease(); - return CefThreadSafeBase::Release(); - } - - // 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: - cef_base_t* struct_; -}; - - -#endif // _BASE_CTOCPP_H +// 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 _BASE_CTOCPP_H +#define _BASE_CTOCPP_H + +#include "include/cef.h" +#include "include/cef_capi.h" +#include "libcef_dll/cef_logging.h" + + +// CefCToCpp implementation for CefBase. +class CefBaseCToCpp : public CefThreadSafeBase +{ +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) + { + // 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) + { + // 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(); + } + + 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. + virtual int AddRef() + { + UnderlyingAddRef(); + return CefThreadSafeBase::AddRef(); + } + virtual int Release() + { + UnderlyingRelease(); + return CefThreadSafeBase::Release(); + } + + // 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: + cef_base_t* struct_; +}; + + +#endif // _BASE_CTOCPP_H diff --git a/libcef_dll/ctocpp/browser_ctocpp.cc b/libcef_dll/ctocpp/browser_ctocpp.cc index 8ee07e2bf..8b61c3947 100644 --- a/libcef_dll/ctocpp/browser_ctocpp.cc +++ b/libcef_dll/ctocpp/browser_ctocpp.cc @@ -1,209 +1,209 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method implementations. See the translator.README.txt file in the -// tools directory for more information. -// - -#include "libcef_dll/cpptoc/handler_cpptoc.h" -#include "libcef_dll/ctocpp/browser_ctocpp.h" -#include "libcef_dll/ctocpp/frame_ctocpp.h" - - -// STATIC METHODS - Body may be edited by hand. - -bool CefBrowser::CreateBrowser(CefWindowInfo& windowInfo, bool popup, - CefRefPtr handler, const std::wstring& url) -{ - return cef_browser_create(&windowInfo, popup, CefHandlerCppToC::Wrap(handler), - url.c_str())?true:false; -} - -CefRefPtr CefBrowser::CreateBrowserSync(CefWindowInfo& windowInfo, - bool popup, CefRefPtr handler, const std::wstring& url) -{ - cef_browser_t* impl = cef_browser_create_sync(&windowInfo, popup, - CefHandlerCppToC::Wrap(handler), url.c_str()); - if(impl) - return CefBrowserCToCpp::Wrap(impl); - return NULL; -} - - -// VIRTUAL METHODS - Body may be edited by hand. - -bool CefBrowserCToCpp::CanGoBack() -{ - if(CEF_MEMBER_MISSING(struct_, can_go_back)) - return false; - - return struct_->can_go_back(struct_) ? true : false; -} - -void CefBrowserCToCpp::GoBack() -{ - if(CEF_MEMBER_MISSING(struct_, go_back)) - return; - - struct_->go_back(struct_); -} - -bool CefBrowserCToCpp::CanGoForward() -{ - if(CEF_MEMBER_MISSING(struct_, can_go_forward)) - return false; - - return struct_->can_go_forward(struct_)?true:false; -} - -void CefBrowserCToCpp::GoForward() -{ - if(CEF_MEMBER_MISSING(struct_, go_forward)) - return; - - struct_->go_forward(struct_); -} - -void CefBrowserCToCpp::Reload() -{ - if(CEF_MEMBER_MISSING(struct_, reload)) - return; - - struct_->reload(struct_); -} - -void CefBrowserCToCpp::ReloadIgnoreCache() -{ - if(CEF_MEMBER_MISSING(struct_, reload)) - return; - - struct_->reload_ignore_cache(struct_); -} - -void CefBrowserCToCpp::StopLoad() -{ - if(CEF_MEMBER_MISSING(struct_, stop_load)) - return; - - struct_->stop_load(struct_); -} - -void CefBrowserCToCpp::SetFocus(bool enable) -{ - if(CEF_MEMBER_MISSING(struct_, set_focus)) - return; - - struct_->set_focus(struct_, enable); -} - -CefWindowHandle CefBrowserCToCpp::GetWindowHandle() -{ - if(CEF_MEMBER_MISSING(struct_, get_window_handle)) - return 0; - - return struct_->get_window_handle(struct_); -} - -bool CefBrowserCToCpp::IsPopup() -{ - if(CEF_MEMBER_MISSING(struct_, is_popup)) - return false; - - return struct_->is_popup(struct_)?true:false; -} - -CefRefPtr CefBrowserCToCpp::GetHandler() -{ - if(CEF_MEMBER_MISSING(struct_, get_handler)) - return NULL; - - cef_handler_t* handlerStruct = struct_->get_handler(struct_); - if(handlerStruct) - return CefHandlerCppToC::Unwrap(handlerStruct); - - return NULL; -} - -CefRefPtr CefBrowserCToCpp::GetMainFrame() -{ - if(CEF_MEMBER_MISSING(struct_, get_main_frame)) - return NULL; - - cef_frame_t* frameStruct = struct_->get_main_frame(struct_); - if(frameStruct) - return CefFrameCToCpp::Wrap(frameStruct); - - return NULL; -} - -CefRefPtr CefBrowserCToCpp::GetFocusedFrame() -{ - if(CEF_MEMBER_MISSING(struct_, get_main_frame)) - return NULL; - - cef_frame_t* frameStruct = struct_->get_focused_frame(struct_); - if(frameStruct) - return CefFrameCToCpp::Wrap(frameStruct); - - return NULL; -} - -CefRefPtr CefBrowserCToCpp::GetFrame(const std::wstring& name) -{ - if(CEF_MEMBER_MISSING(struct_, get_main_frame)) - return NULL; - - cef_frame_t* frameStruct = struct_->get_frame(struct_, name.c_str()); - if(frameStruct) - return CefFrameCToCpp::Wrap(frameStruct); - - return NULL; -} - -void CefBrowserCToCpp::GetFrameNames(std::vector& names) -{ - if(CEF_MEMBER_MISSING(struct_, get_frame_names)) - return; - - cef_string_list_t list = cef_string_list_alloc(); - struct_->get_frame_names(struct_, list); - - cef_string_t str; - int size = cef_string_list_size(list); - for(int i = 0; i < size; ++i) { - str = cef_string_list_value(list, i); - names.push_back(str); - cef_string_free(str); - } - - cef_string_list_free(list); -} - -void CefBrowserCToCpp::Find(int identifier, const std::wstring& searchText, - bool forward, bool matchCase, bool findNext) -{ - if(CEF_MEMBER_MISSING(struct_, find)) - return; - - struct_->find(struct_, identifier, searchText.c_str(), forward, - matchCase, findNext); -} - -void CefBrowserCToCpp::StopFinding(bool clearSelection) -{ - if(CEF_MEMBER_MISSING(struct_, stop_finding)) - return; - - struct_->stop_finding(struct_, clearSelection); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method implementations. See the translator.README.txt file in the +// tools directory for more information. +// + +#include "libcef_dll/cpptoc/handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +bool CefBrowser::CreateBrowser(CefWindowInfo& windowInfo, bool popup, + CefRefPtr handler, const std::wstring& url) +{ + return cef_browser_create(&windowInfo, popup, CefHandlerCppToC::Wrap(handler), + url.c_str())?true:false; +} + +CefRefPtr CefBrowser::CreateBrowserSync(CefWindowInfo& windowInfo, + bool popup, CefRefPtr handler, const std::wstring& url) +{ + cef_browser_t* impl = cef_browser_create_sync(&windowInfo, popup, + CefHandlerCppToC::Wrap(handler), url.c_str()); + if(impl) + return CefBrowserCToCpp::Wrap(impl); + return NULL; +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefBrowserCToCpp::CanGoBack() +{ + if(CEF_MEMBER_MISSING(struct_, can_go_back)) + return false; + + return struct_->can_go_back(struct_) ? true : false; +} + +void CefBrowserCToCpp::GoBack() +{ + if(CEF_MEMBER_MISSING(struct_, go_back)) + return; + + struct_->go_back(struct_); +} + +bool CefBrowserCToCpp::CanGoForward() +{ + if(CEF_MEMBER_MISSING(struct_, can_go_forward)) + return false; + + return struct_->can_go_forward(struct_)?true:false; +} + +void CefBrowserCToCpp::GoForward() +{ + if(CEF_MEMBER_MISSING(struct_, go_forward)) + return; + + struct_->go_forward(struct_); +} + +void CefBrowserCToCpp::Reload() +{ + if(CEF_MEMBER_MISSING(struct_, reload)) + return; + + struct_->reload(struct_); +} + +void CefBrowserCToCpp::ReloadIgnoreCache() +{ + if(CEF_MEMBER_MISSING(struct_, reload)) + return; + + struct_->reload_ignore_cache(struct_); +} + +void CefBrowserCToCpp::StopLoad() +{ + if(CEF_MEMBER_MISSING(struct_, stop_load)) + return; + + struct_->stop_load(struct_); +} + +void CefBrowserCToCpp::SetFocus(bool enable) +{ + if(CEF_MEMBER_MISSING(struct_, set_focus)) + return; + + struct_->set_focus(struct_, enable); +} + +CefWindowHandle CefBrowserCToCpp::GetWindowHandle() +{ + if(CEF_MEMBER_MISSING(struct_, get_window_handle)) + return 0; + + return struct_->get_window_handle(struct_); +} + +bool CefBrowserCToCpp::IsPopup() +{ + if(CEF_MEMBER_MISSING(struct_, is_popup)) + return false; + + return struct_->is_popup(struct_)?true:false; +} + +CefRefPtr CefBrowserCToCpp::GetHandler() +{ + if(CEF_MEMBER_MISSING(struct_, get_handler)) + return NULL; + + cef_handler_t* handlerStruct = struct_->get_handler(struct_); + if(handlerStruct) + return CefHandlerCppToC::Unwrap(handlerStruct); + + return NULL; +} + +CefRefPtr CefBrowserCToCpp::GetMainFrame() +{ + if(CEF_MEMBER_MISSING(struct_, get_main_frame)) + return NULL; + + cef_frame_t* frameStruct = struct_->get_main_frame(struct_); + if(frameStruct) + return CefFrameCToCpp::Wrap(frameStruct); + + return NULL; +} + +CefRefPtr CefBrowserCToCpp::GetFocusedFrame() +{ + if(CEF_MEMBER_MISSING(struct_, get_main_frame)) + return NULL; + + cef_frame_t* frameStruct = struct_->get_focused_frame(struct_); + if(frameStruct) + return CefFrameCToCpp::Wrap(frameStruct); + + return NULL; +} + +CefRefPtr CefBrowserCToCpp::GetFrame(const std::wstring& name) +{ + if(CEF_MEMBER_MISSING(struct_, get_main_frame)) + return NULL; + + cef_frame_t* frameStruct = struct_->get_frame(struct_, name.c_str()); + if(frameStruct) + return CefFrameCToCpp::Wrap(frameStruct); + + return NULL; +} + +void CefBrowserCToCpp::GetFrameNames(std::vector& names) +{ + if(CEF_MEMBER_MISSING(struct_, get_frame_names)) + return; + + cef_string_list_t list = cef_string_list_alloc(); + struct_->get_frame_names(struct_, list); + + cef_string_t str; + int size = cef_string_list_size(list); + for(int i = 0; i < size; ++i) { + str = cef_string_list_value(list, i); + names.push_back(str); + cef_string_free(str); + } + + cef_string_list_free(list); +} + +void CefBrowserCToCpp::Find(int identifier, const std::wstring& searchText, + bool forward, bool matchCase, bool findNext) +{ + if(CEF_MEMBER_MISSING(struct_, find)) + return; + + struct_->find(struct_, identifier, searchText.c_str(), forward, + matchCase, findNext); +} + +void CefBrowserCToCpp::StopFinding(bool clearSelection) +{ + if(CEF_MEMBER_MISSING(struct_, stop_finding)) + return; + + struct_->stop_finding(struct_, clearSelection); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/browser_ctocpp.h b/libcef_dll/ctocpp/browser_ctocpp.h index f0c324a46..c5c800529 100644 --- a/libcef_dll/ctocpp/browser_ctocpp.h +++ b/libcef_dll/ctocpp/browser_ctocpp.h @@ -1,56 +1,56 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _BROWSER_CTOCPP_H -#define _BROWSER_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefBrowserCToCpp(cef_browser_t* str) - : CefCToCpp(str) {} - virtual ~CefBrowserCToCpp() {} - - // CefBrowser methods - virtual bool CanGoBack(); - virtual void GoBack(); - virtual bool CanGoForward(); - virtual void GoForward(); - virtual void Reload(); - virtual void ReloadIgnoreCache(); - virtual void StopLoad(); - virtual void SetFocus(bool enable); - virtual CefWindowHandle GetWindowHandle(); - virtual bool IsPopup(); - virtual CefRefPtr GetHandler(); - virtual CefRefPtr GetMainFrame(); - virtual CefRefPtr GetFocusedFrame(); - virtual CefRefPtr GetFrame(const std::wstring& name); - virtual void GetFrameNames(std::vector& names); - virtual void Find(int identifier, const std::wstring& searchText, - bool forward, bool matchCase, bool findNext); - virtual void StopFinding(bool clearSelection); -}; - -#endif // USING_CEF_SHARED -#endif // _BROWSER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _BROWSER_CTOCPP_H +#define _BROWSER_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefBrowserCToCpp(cef_browser_t* str) + : CefCToCpp(str) {} + virtual ~CefBrowserCToCpp() {} + + // CefBrowser methods + virtual bool CanGoBack(); + virtual void GoBack(); + virtual bool CanGoForward(); + virtual void GoForward(); + virtual void Reload(); + virtual void ReloadIgnoreCache(); + virtual void StopLoad(); + virtual void SetFocus(bool enable); + virtual CefWindowHandle GetWindowHandle(); + virtual bool IsPopup(); + virtual CefRefPtr GetHandler(); + virtual CefRefPtr GetMainFrame(); + virtual CefRefPtr GetFocusedFrame(); + virtual CefRefPtr GetFrame(const std::wstring& name); + virtual void GetFrameNames(std::vector& names); + virtual void Find(int identifier, const std::wstring& searchText, + bool forward, bool matchCase, bool findNext); + virtual void StopFinding(bool clearSelection); +}; + +#endif // USING_CEF_SHARED +#endif // _BROWSER_CTOCPP_H + diff --git a/libcef_dll/ctocpp/ctocpp.h b/libcef_dll/ctocpp/ctocpp.h index 376035b35..bd4360f04 100644 --- a/libcef_dll/ctocpp/ctocpp.h +++ b/libcef_dll/ctocpp/ctocpp.h @@ -1,111 +1,111 @@ -// 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 _CTOCPP_H -#define _CTOCPP_H - -#include "include/cef.h" -#include "include/cef_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 CefThreadSafeBase -{ -public: - // Use this method to create a wrapper class instance for a structure - // received from the other side. - static CefRefPtr Wrap(StructName* s) - { - // 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) - { - // 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(); - } - - CefCToCpp(StructName* str) - : struct_(str) - { - DCHECK(str); - -#ifdef _DEBUG - CefAtomicIncrement(&DebugObjCt); -#endif - } - virtual ~CefCToCpp() - { -#ifdef _DEBUG - 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. - virtual int AddRef() - { - UnderlyingAddRef(); - return CefThreadSafeBase::AddRef(); - } - virtual int Release() - { - UnderlyingRelease(); - return CefThreadSafeBase::Release(); - } - - // 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); - } - -#ifdef _DEBUG - // Simple tracking of allocated objects. - static long DebugObjCt; -#endif - -protected: - StructName* struct_; -}; - -#endif // _CTOCPP_H +// 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 _CTOCPP_H +#define _CTOCPP_H + +#include "include/cef.h" +#include "include/cef_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 CefThreadSafeBase +{ +public: + // Use this method to create a wrapper class instance for a structure + // received from the other side. + static CefRefPtr Wrap(StructName* s) + { + // 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) + { + // 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(); + } + + CefCToCpp(StructName* str) + : struct_(str) + { + DCHECK(str); + +#ifdef _DEBUG + CefAtomicIncrement(&DebugObjCt); +#endif + } + virtual ~CefCToCpp() + { +#ifdef _DEBUG + 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. + virtual int AddRef() + { + UnderlyingAddRef(); + return CefThreadSafeBase::AddRef(); + } + virtual int Release() + { + UnderlyingRelease(); + return CefThreadSafeBase::Release(); + } + + // 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); + } + +#ifdef _DEBUG + // Simple tracking of allocated objects. + static long DebugObjCt; +#endif + +protected: + StructName* struct_; +}; + +#endif // _CTOCPP_H diff --git a/libcef_dll/ctocpp/frame_ctocpp.cc b/libcef_dll/ctocpp/frame_ctocpp.cc index 3a1e8fdf3..0040210b9 100644 --- a/libcef_dll/ctocpp/frame_ctocpp.cc +++ b/libcef_dll/ctocpp/frame_ctocpp.cc @@ -1,213 +1,213 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method implementations. See the translator.README.txt file in the -// tools directory for more information. -// - -#include "libcef_dll/ctocpp/frame_ctocpp.h" -#include "libcef_dll/ctocpp/request_ctocpp.h" -#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" - - -// VIRTUAL METHODS - Body may be edited by hand. - -void CefFrameCToCpp::Undo() -{ - if(CEF_MEMBER_MISSING(struct_, undo)) - return; - - struct_->undo(struct_); -} - -void CefFrameCToCpp::Redo() -{ - if(CEF_MEMBER_MISSING(struct_, redo)) - return; - - struct_->redo(struct_); -} - -void CefFrameCToCpp::Cut() -{ - if(CEF_MEMBER_MISSING(struct_, cut)) - return; - - struct_->cut(struct_); -} - -void CefFrameCToCpp::Copy() -{ - if(CEF_MEMBER_MISSING(struct_, copy)) - return; - - struct_->copy(struct_); -} - -void CefFrameCToCpp::Paste() -{ - if(CEF_MEMBER_MISSING(struct_, paste)) - return; - - struct_->paste(struct_); -} - -void CefFrameCToCpp::Delete() -{ - if(CEF_MEMBER_MISSING(struct_, del)) - return; - - struct_->del(struct_); -} - -void CefFrameCToCpp::SelectAll() -{ - if(CEF_MEMBER_MISSING(struct_, select_all)) - return; - - struct_->select_all(struct_); -} - -void CefFrameCToCpp::Print() -{ - if(CEF_MEMBER_MISSING(struct_, print)) - return; - - struct_->print(struct_); -} - -void CefFrameCToCpp::ViewSource() -{ - if(CEF_MEMBER_MISSING(struct_, view_source)) - return; - - struct_->view_source(struct_); -} - -std::wstring CefFrameCToCpp::GetSource() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_source)) - return str; - - cef_string_t cef_str = struct_->get_source(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - -std::wstring CefFrameCToCpp::GetText() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_text)) - return str; - - cef_string_t cef_str = struct_->get_text(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - -void CefFrameCToCpp::LoadRequest(CefRefPtr request) -{ - if(CEF_MEMBER_MISSING(struct_, load_request)) - return; - - struct_->load_request(struct_, CefRequestCToCpp::Unwrap(request)); -} - -void CefFrameCToCpp::LoadURL(const std::wstring& url) -{ - if(CEF_MEMBER_MISSING(struct_, load_url)) - return; - - struct_->load_url(struct_, url.c_str()); -} - -void CefFrameCToCpp::LoadString(const std::wstring& string, - const std::wstring& url) -{ - if(CEF_MEMBER_MISSING(struct_, load_string)) - return; - - struct_->load_string(struct_, string.c_str(), url.c_str()); -} - -void CefFrameCToCpp::LoadStream(CefRefPtr stream, - const std::wstring& url) -{ - if(CEF_MEMBER_MISSING(struct_, load_stream)) - return; - - struct_->load_stream(struct_, CefStreamReaderCToCpp::Unwrap(stream), - url.c_str()); -} - -void CefFrameCToCpp::ExecuteJavaScript(const std::wstring& jsCode, - const std::wstring& scriptUrl, int startLine) -{ - if(CEF_MEMBER_MISSING(struct_, execute_java_script)) - return; - - struct_->execute_java_script(struct_, jsCode.c_str(), scriptUrl.c_str(), - startLine); -} - -bool CefFrameCToCpp::IsMain() -{ - if(CEF_MEMBER_MISSING(struct_, is_main)) - return false; - - return struct_->is_main(struct_)?true:false; -} - -bool CefFrameCToCpp::IsFocused() -{ - if(CEF_MEMBER_MISSING(struct_, is_focused)) - return false; - - return struct_->is_focused(struct_)?true:false; -} - -std::wstring CefFrameCToCpp::GetName() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_name)) - return str; - - cef_string_t cef_str = struct_->get_name(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - -std::wstring CefFrameCToCpp::GetURL() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_url)) - return str; - - cef_string_t cef_str = struct_->get_url(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method implementations. See the translator.README.txt file in the +// tools directory for more information. +// + +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefFrameCToCpp::Undo() +{ + if(CEF_MEMBER_MISSING(struct_, undo)) + return; + + struct_->undo(struct_); +} + +void CefFrameCToCpp::Redo() +{ + if(CEF_MEMBER_MISSING(struct_, redo)) + return; + + struct_->redo(struct_); +} + +void CefFrameCToCpp::Cut() +{ + if(CEF_MEMBER_MISSING(struct_, cut)) + return; + + struct_->cut(struct_); +} + +void CefFrameCToCpp::Copy() +{ + if(CEF_MEMBER_MISSING(struct_, copy)) + return; + + struct_->copy(struct_); +} + +void CefFrameCToCpp::Paste() +{ + if(CEF_MEMBER_MISSING(struct_, paste)) + return; + + struct_->paste(struct_); +} + +void CefFrameCToCpp::Delete() +{ + if(CEF_MEMBER_MISSING(struct_, del)) + return; + + struct_->del(struct_); +} + +void CefFrameCToCpp::SelectAll() +{ + if(CEF_MEMBER_MISSING(struct_, select_all)) + return; + + struct_->select_all(struct_); +} + +void CefFrameCToCpp::Print() +{ + if(CEF_MEMBER_MISSING(struct_, print)) + return; + + struct_->print(struct_); +} + +void CefFrameCToCpp::ViewSource() +{ + if(CEF_MEMBER_MISSING(struct_, view_source)) + return; + + struct_->view_source(struct_); +} + +std::wstring CefFrameCToCpp::GetSource() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_source)) + return str; + + cef_string_t cef_str = struct_->get_source(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + +std::wstring CefFrameCToCpp::GetText() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_text)) + return str; + + cef_string_t cef_str = struct_->get_text(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + +void CefFrameCToCpp::LoadRequest(CefRefPtr request) +{ + if(CEF_MEMBER_MISSING(struct_, load_request)) + return; + + struct_->load_request(struct_, CefRequestCToCpp::Unwrap(request)); +} + +void CefFrameCToCpp::LoadURL(const std::wstring& url) +{ + if(CEF_MEMBER_MISSING(struct_, load_url)) + return; + + struct_->load_url(struct_, url.c_str()); +} + +void CefFrameCToCpp::LoadString(const std::wstring& string, + const std::wstring& url) +{ + if(CEF_MEMBER_MISSING(struct_, load_string)) + return; + + struct_->load_string(struct_, string.c_str(), url.c_str()); +} + +void CefFrameCToCpp::LoadStream(CefRefPtr stream, + const std::wstring& url) +{ + if(CEF_MEMBER_MISSING(struct_, load_stream)) + return; + + struct_->load_stream(struct_, CefStreamReaderCToCpp::Unwrap(stream), + url.c_str()); +} + +void CefFrameCToCpp::ExecuteJavaScript(const std::wstring& jsCode, + const std::wstring& scriptUrl, int startLine) +{ + if(CEF_MEMBER_MISSING(struct_, execute_java_script)) + return; + + struct_->execute_java_script(struct_, jsCode.c_str(), scriptUrl.c_str(), + startLine); +} + +bool CefFrameCToCpp::IsMain() +{ + if(CEF_MEMBER_MISSING(struct_, is_main)) + return false; + + return struct_->is_main(struct_)?true:false; +} + +bool CefFrameCToCpp::IsFocused() +{ + if(CEF_MEMBER_MISSING(struct_, is_focused)) + return false; + + return struct_->is_focused(struct_)?true:false; +} + +std::wstring CefFrameCToCpp::GetName() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_name)) + return str; + + cef_string_t cef_str = struct_->get_name(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + +std::wstring CefFrameCToCpp::GetURL() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_url)) + return str; + + cef_string_t cef_str = struct_->get_url(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/frame_ctocpp.h b/libcef_dll/ctocpp/frame_ctocpp.h index 83dfdaa3e..90d865175 100644 --- a/libcef_dll/ctocpp/frame_ctocpp.h +++ b/libcef_dll/ctocpp/frame_ctocpp.h @@ -1,60 +1,60 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _FRAME_CTOCPP_H -#define _FRAME_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefFrameCToCpp(cef_frame_t* str) - : CefCToCpp(str) {} - virtual ~CefFrameCToCpp() {} - - // CefFrame methods - virtual void Undo(); - virtual void Redo(); - virtual void Cut(); - virtual void Copy(); - virtual void Paste(); - virtual void Delete(); - virtual void SelectAll(); - virtual void Print(); - virtual void ViewSource(); - virtual std::wstring GetSource(); - virtual std::wstring GetText(); - virtual void LoadRequest(CefRefPtr request); - virtual void LoadURL(const std::wstring& url); - virtual void LoadString(const std::wstring& string, const std::wstring& url); - virtual void LoadStream(CefRefPtr stream, - const std::wstring& url); - virtual void ExecuteJavaScript(const std::wstring& jsCode, - const std::wstring& scriptUrl, int startLine); - virtual bool IsMain(); - virtual bool IsFocused(); - virtual std::wstring GetName(); - virtual std::wstring GetURL(); -}; - -#endif // USING_CEF_SHARED -#endif // _FRAME_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _FRAME_CTOCPP_H +#define _FRAME_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefFrameCToCpp(cef_frame_t* str) + : CefCToCpp(str) {} + virtual ~CefFrameCToCpp() {} + + // CefFrame methods + virtual void Undo(); + virtual void Redo(); + virtual void Cut(); + virtual void Copy(); + virtual void Paste(); + virtual void Delete(); + virtual void SelectAll(); + virtual void Print(); + virtual void ViewSource(); + virtual std::wstring GetSource(); + virtual std::wstring GetText(); + virtual void LoadRequest(CefRefPtr request); + virtual void LoadURL(const std::wstring& url); + virtual void LoadString(const std::wstring& string, const std::wstring& url); + virtual void LoadStream(CefRefPtr stream, + const std::wstring& url); + virtual void ExecuteJavaScript(const std::wstring& jsCode, + const std::wstring& scriptUrl, int startLine); + virtual bool IsMain(); + virtual bool IsFocused(); + virtual std::wstring GetName(); + virtual std::wstring GetURL(); +}; + +#endif // USING_CEF_SHARED +#endif // _FRAME_CTOCPP_H + diff --git a/libcef_dll/ctocpp/handler_ctocpp.cc b/libcef_dll/ctocpp/handler_ctocpp.cc index de7faf6b2..24b27ae07 100644 --- a/libcef_dll/ctocpp/handler_ctocpp.cc +++ b/libcef_dll/ctocpp/handler_ctocpp.cc @@ -1,417 +1,417 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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/v8value_cpptoc.h" -#include "libcef_dll/ctocpp/handler_ctocpp.h" -#include "libcef_dll/transfer_util.h" - - -// VIRTUAL METHODS - Body may be edited by hand. - -CefHandler::RetVal CefHandlerCToCpp::HandleBeforeCreated( - CefRefPtr parentBrowser, CefWindowInfo& windowInfo, bool popup, - CefRefPtr& handler, std::wstring& url) -{ - if(CEF_MEMBER_MISSING(struct_, handle_before_created)) - return RV_CONTINUE; - - cef_browser_t* browserStruct = NULL; - if(parentBrowser.get()) - browserStruct = CefBrowserCppToC::Wrap(parentBrowser); - - cef_handler_t* handlerStruct = NULL; - if(handler.get()) - handlerStruct = CefHandlerCToCpp::Unwrap(handler); - cef_handler_t *origHandlerStruct = handlerStruct; - - cef_string_t urlRet = NULL; - if(!url.empty()) - urlRet = cef_string_alloc(url.c_str()); - - cef_retval_t rv = struct_->handle_before_created(struct_, - browserStruct, &windowInfo, popup, &handlerStruct, &urlRet); - - if(handlerStruct && handlerStruct != origHandlerStruct) { - // The handler was changed. - if(handlerStruct) - handler = CefHandlerCToCpp::Wrap(handlerStruct); - else - handler = NULL; - } - - transfer_string_contents(urlRet, url, true); - - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleAfterCreated( - CefRefPtr browser) -{ - if(CEF_MEMBER_MISSING(struct_, handle_after_created)) - return RV_CONTINUE; - - return struct_->handle_after_created(struct_, - CefBrowserCppToC::Wrap(browser)); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleAddressChange( - CefRefPtr browser, CefRefPtr frame, - const std::wstring& url) -{ - if(CEF_MEMBER_MISSING(struct_, handle_address_change)) - return RV_CONTINUE; - - return struct_->handle_address_change(struct_, - CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), - url.c_str()); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleTitleChange( - CefRefPtr browser, const std::wstring& title) -{ - if(CEF_MEMBER_MISSING(struct_, handle_title_change)) - return RV_CONTINUE; - - return struct_->handle_title_change(struct_, CefBrowserCppToC::Wrap(browser), - title.c_str()); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleBeforeBrowse( - CefRefPtr browser, CefRefPtr frame, - CefRefPtr request, NavType navType, bool isRedirect) -{ - if(CEF_MEMBER_MISSING(struct_, handle_before_browse)) - return RV_CONTINUE; - - return struct_->handle_before_browse(struct_, CefBrowserCppToC::Wrap(browser), - CefFrameCppToC::Wrap(frame), CefRequestCppToC::Wrap(request), - navType, isRedirect); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleLoadStart( - CefRefPtr browser, CefRefPtr frame) -{ - if(CEF_MEMBER_MISSING(struct_, handle_load_start)) - return RV_CONTINUE; - - cef_frame_t* frameStruct = NULL; - if(frame.get()) - frameStruct = CefFrameCppToC::Wrap(frame); - - return struct_->handle_load_start(struct_, CefBrowserCppToC::Wrap(browser), - frameStruct); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleLoadEnd( - CefRefPtr browser, CefRefPtr frame) -{ - if(CEF_MEMBER_MISSING(struct_, handle_load_end)) - return RV_CONTINUE; - - cef_frame_t* frameStruct = NULL; - if(frame.get()) - frameStruct = CefFrameCppToC::Wrap(frame); - - return struct_->handle_load_end(struct_, CefBrowserCppToC::Wrap(browser), - frameStruct); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleLoadError( - CefRefPtr browser, CefRefPtr frame, - ErrorCode errorCode, const std::wstring& failedUrl, - std::wstring& errorText) -{ - if(CEF_MEMBER_MISSING(struct_, handle_load_error)) - return RV_CONTINUE; - - cef_string_t errorTextRet = NULL; - if(!errorText.empty()) - errorTextRet = cef_string_alloc(errorText.c_str()); - - cef_retval_t rv = struct_->handle_load_error(struct_, - CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), errorCode, - failedUrl.c_str(), &errorTextRet); - - transfer_string_contents(errorTextRet, errorText, true); - - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleBeforeResourceLoad( - CefRefPtr browser, CefRefPtr request, - std::wstring& redirectUrl, CefRefPtr& resourceStream, - std::wstring& mimeType, int loadFlags) -{ - if(CEF_MEMBER_MISSING(struct_, handle_before_resource_load)) - return RV_CONTINUE; - - cef_string_t redirectUrlRet = NULL; - cef_string_t mimeTypeRet = NULL; - cef_stream_reader_t* streamRet = NULL; - - if(!redirectUrl.empty()) - redirectUrlRet = cef_string_alloc(redirectUrl.c_str()); - - cef_retval_t rv = struct_->handle_before_resource_load(struct_, - CefBrowserCppToC::Wrap(browser), CefRequestCppToC::Wrap(request), - &redirectUrlRet, &streamRet, &mimeTypeRet, loadFlags); - - transfer_string_contents(redirectUrlRet, redirectUrl, true); - transfer_string_contents(mimeTypeRet, mimeType, true); - - if(streamRet) - resourceStream = CefStreamReaderCppToC::Unwrap(streamRet); - - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleBeforeMenu( - CefRefPtr browser, const MenuInfo& menuInfo) -{ - if(CEF_MEMBER_MISSING(struct_, handle_before_menu)) - return RV_CONTINUE; - - return struct_->handle_before_menu(struct_, CefBrowserCppToC::Wrap(browser), - &menuInfo); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleGetMenuLabel( - CefRefPtr browser, MenuId menuId, std::wstring& label) -{ - if(CEF_MEMBER_MISSING(struct_, handle_get_menu_label)) - return RV_CONTINUE; - - cef_string_t labelRet = NULL; - if(!label.empty()) - labelRet = cef_string_alloc(label.c_str()); - - cef_retval_t rv = struct_->handle_get_menu_label(struct_, - CefBrowserCppToC::Wrap(browser), menuId, &labelRet); - - transfer_string_contents(labelRet, label, true); - - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleMenuAction( - CefRefPtr browser, MenuId menuId) -{ - if(CEF_MEMBER_MISSING(struct_, handle_menu_action)) - return RV_CONTINUE; - - return struct_->handle_menu_action(struct_, CefBrowserCppToC::Wrap(browser), - menuId); -} - -CefHandler::RetVal CefHandlerCToCpp::HandlePrintOptions( - CefRefPtr browser, CefPrintOptions& printOptions) -{ - if (CEF_MEMBER_MISSING(struct_, handle_print_options)) - return RV_CONTINUE; - - return struct_->handle_print_options(struct_, CefBrowserCppToC::Wrap(browser), - &printOptions); -} - -CefHandler::RetVal CefHandlerCToCpp::HandlePrintHeaderFooter( - CefRefPtr browser, CefRefPtr frame, - CefPrintInfo& printInfo, const std::wstring& url, - const std::wstring& title, int currentPage, int maxPages, - std::wstring& topLeft, std::wstring& topCenter, std::wstring& topRight, - std::wstring& bottomLeft, std::wstring& bottomCenter, - std::wstring& bottomRight) -{ - if(CEF_MEMBER_MISSING(struct_, handle_print_header_footer)) - return RV_CONTINUE; - - cef_string_t topLeftRet = NULL, topCenterRet = NULL, topRightRet = NULL, - bottomLeftRet = NULL, bottomCenterRet = NULL, bottomRightRet = NULL; - - if(!topLeft.empty()) - topLeftRet = cef_string_alloc(topLeft.c_str()); - if(!topCenter.empty()) - topCenterRet = cef_string_alloc(topCenter.c_str()); - if(!topRight.empty()) - topRightRet = cef_string_alloc(topRight.c_str()); - if(!bottomLeft.empty()) - bottomLeftRet = cef_string_alloc(bottomLeft.c_str()); - if(!bottomCenter.empty()) - bottomCenterRet = cef_string_alloc(bottomCenter.c_str()); - if(!bottomRight.empty()) - bottomRightRet = cef_string_alloc(bottomRight.c_str()); - - cef_retval_t rv = struct_->handle_print_header_footer(struct_, - CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), - &printInfo, url.c_str(), title.c_str(), currentPage, maxPages, - &topLeftRet, &topCenterRet, &topRightRet, &bottomLeftRet, - &bottomCenterRet, &bottomRightRet); - - transfer_string_contents(topLeftRet, topLeft, true); - transfer_string_contents(topCenterRet, topCenter, true); - transfer_string_contents(topRightRet, topRight, true); - transfer_string_contents(bottomLeftRet, bottomLeft, true); - transfer_string_contents(bottomCenterRet, bottomCenter, true); - transfer_string_contents(bottomRightRet, bottomRight, true); - - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleJSAlert( - CefRefPtr browser, CefRefPtr frame, - const std::wstring& message) -{ - if(CEF_MEMBER_MISSING(struct_, handle_jsalert)) - return RV_CONTINUE; - - return struct_->handle_jsalert(struct_, CefBrowserCppToC::Wrap(browser), - CefFrameCppToC::Wrap(frame), message.c_str()); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleJSConfirm( - CefRefPtr browser, CefRefPtr frame, - const std::wstring& message, bool& retval) -{ - if(CEF_MEMBER_MISSING(struct_, handle_jsconfirm)) - return RV_CONTINUE; - - int ret = 0; - cef_retval_t rv = struct_->handle_jsconfirm(struct_, - CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), - message.c_str(), &ret); - retval = (ret ? true : false); - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleJSPrompt( - CefRefPtr browser, CefRefPtr frame, - const std::wstring& message, const std::wstring& defaultValue, - bool& retval, std::wstring& result) -{ - if(CEF_MEMBER_MISSING(struct_, handle_jsprompt)) - return RV_CONTINUE; - - cef_string_t resultRet = NULL; - if(!result.empty()) - resultRet = cef_string_alloc(result.c_str()); - - int ret = 0; - cef_retval_t rv = struct_->handle_jsprompt(struct_, - CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), - message.c_str(), defaultValue.c_str(), &ret, &resultRet); - retval = (ret ? true : false); - - transfer_string_contents(resultRet, result, true); - - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleJSBinding( - CefRefPtr browser, CefRefPtr frame, - CefRefPtr object) -{ - if(CEF_MEMBER_MISSING(struct_, handle_jsbinding)) - return RV_CONTINUE; - - return struct_->handle_jsbinding(struct_, CefBrowserCppToC::Wrap(browser), - CefFrameCppToC::Wrap(frame), CefV8ValueCppToC::Wrap(object)); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleBeforeWindowClose( - CefRefPtr browser) -{ - if(CEF_MEMBER_MISSING(struct_, handle_before_window_close)) - return RV_CONTINUE; - - return struct_->handle_before_window_close(struct_, - CefBrowserCppToC::Wrap(browser)); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleTakeFocus( - CefRefPtr browser, bool reverse) -{ - if(CEF_MEMBER_MISSING(struct_, handle_take_focus)) - return RV_CONTINUE; - - return struct_->handle_take_focus(struct_, CefBrowserCppToC::Wrap(browser), - reverse); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleSetFocus( - CefRefPtr browser, bool isWidget) -{ - if(CEF_MEMBER_MISSING(struct_, handle_set_focus)) - return RV_CONTINUE; - - return struct_->handle_set_focus(struct_, CefBrowserCppToC::Wrap(browser), - isWidget); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleKeyEvent( - CefRefPtr browser, KeyEventType type, int code, int modifiers, - bool isSystemKey) -{ - if(CEF_MEMBER_MISSING(struct_, handle_key_event)) - return RV_CONTINUE; - - return struct_->handle_key_event(struct_, CefBrowserCppToC::Wrap(browser), - type, code, modifiers, isSystemKey); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleTooltip( - CefRefPtr browser, std::wstring& text) -{ - if(CEF_MEMBER_MISSING(struct_, handle_tooltip)) - return RV_CONTINUE; - cef_string_t textRet = NULL; - if(!text.empty()) - textRet = cef_string_alloc(text.c_str()); - - cef_retval_t rv = struct_->handle_tooltip(struct_, - CefBrowserCppToC::Wrap(browser), &textRet); - - transfer_string_contents(textRet, text, true); - - return rv; -} - -CefHandler::RetVal CefHandlerCToCpp::HandleConsoleMessage( - CefRefPtr browser, const std::wstring& message, - const std::wstring& source, int line) -{ - if(CEF_MEMBER_MISSING(struct_, handle_console_message)) - return RV_CONTINUE; - - return struct_->handle_console_message(struct_, - CefBrowserCppToC::Wrap(browser), message.c_str(), source.c_str(), line); -} - -CefHandler::RetVal CefHandlerCToCpp::HandleFindResult( - CefRefPtr browser, int identifier, int count, - const CefRect& selectionRect, int activeMatchOrdinal, bool finalUpdate) -{ - if(CEF_MEMBER_MISSING(struct_, handle_find_result)) - return RV_CONTINUE; - - return struct_->handle_find_result(struct_, - CefBrowserCppToC::Wrap(browser), identifier, count, &selectionRect, - activeMatchOrdinal, finalUpdate); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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/v8value_cpptoc.h" +#include "libcef_dll/ctocpp/handler_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefHandler::RetVal CefHandlerCToCpp::HandleBeforeCreated( + CefRefPtr parentBrowser, CefWindowInfo& windowInfo, bool popup, + CefRefPtr& handler, std::wstring& url) +{ + if(CEF_MEMBER_MISSING(struct_, handle_before_created)) + return RV_CONTINUE; + + cef_browser_t* browserStruct = NULL; + if(parentBrowser.get()) + browserStruct = CefBrowserCppToC::Wrap(parentBrowser); + + cef_handler_t* handlerStruct = NULL; + if(handler.get()) + handlerStruct = CefHandlerCToCpp::Unwrap(handler); + cef_handler_t *origHandlerStruct = handlerStruct; + + cef_string_t urlRet = NULL; + if(!url.empty()) + urlRet = cef_string_alloc(url.c_str()); + + cef_retval_t rv = struct_->handle_before_created(struct_, + browserStruct, &windowInfo, popup, &handlerStruct, &urlRet); + + if(handlerStruct && handlerStruct != origHandlerStruct) { + // The handler was changed. + if(handlerStruct) + handler = CefHandlerCToCpp::Wrap(handlerStruct); + else + handler = NULL; + } + + transfer_string_contents(urlRet, url, true); + + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleAfterCreated( + CefRefPtr browser) +{ + if(CEF_MEMBER_MISSING(struct_, handle_after_created)) + return RV_CONTINUE; + + return struct_->handle_after_created(struct_, + CefBrowserCppToC::Wrap(browser)); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleAddressChange( + CefRefPtr browser, CefRefPtr frame, + const std::wstring& url) +{ + if(CEF_MEMBER_MISSING(struct_, handle_address_change)) + return RV_CONTINUE; + + return struct_->handle_address_change(struct_, + CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), + url.c_str()); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleTitleChange( + CefRefPtr browser, const std::wstring& title) +{ + if(CEF_MEMBER_MISSING(struct_, handle_title_change)) + return RV_CONTINUE; + + return struct_->handle_title_change(struct_, CefBrowserCppToC::Wrap(browser), + title.c_str()); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleBeforeBrowse( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr request, NavType navType, bool isRedirect) +{ + if(CEF_MEMBER_MISSING(struct_, handle_before_browse)) + return RV_CONTINUE; + + return struct_->handle_before_browse(struct_, CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), CefRequestCppToC::Wrap(request), + navType, isRedirect); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleLoadStart( + CefRefPtr browser, CefRefPtr frame) +{ + if(CEF_MEMBER_MISSING(struct_, handle_load_start)) + return RV_CONTINUE; + + cef_frame_t* frameStruct = NULL; + if(frame.get()) + frameStruct = CefFrameCppToC::Wrap(frame); + + return struct_->handle_load_start(struct_, CefBrowserCppToC::Wrap(browser), + frameStruct); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleLoadEnd( + CefRefPtr browser, CefRefPtr frame) +{ + if(CEF_MEMBER_MISSING(struct_, handle_load_end)) + return RV_CONTINUE; + + cef_frame_t* frameStruct = NULL; + if(frame.get()) + frameStruct = CefFrameCppToC::Wrap(frame); + + return struct_->handle_load_end(struct_, CefBrowserCppToC::Wrap(browser), + frameStruct); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleLoadError( + CefRefPtr browser, CefRefPtr frame, + ErrorCode errorCode, const std::wstring& failedUrl, + std::wstring& errorText) +{ + if(CEF_MEMBER_MISSING(struct_, handle_load_error)) + return RV_CONTINUE; + + cef_string_t errorTextRet = NULL; + if(!errorText.empty()) + errorTextRet = cef_string_alloc(errorText.c_str()); + + cef_retval_t rv = struct_->handle_load_error(struct_, + CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), errorCode, + failedUrl.c_str(), &errorTextRet); + + transfer_string_contents(errorTextRet, errorText, true); + + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleBeforeResourceLoad( + CefRefPtr browser, CefRefPtr request, + std::wstring& redirectUrl, CefRefPtr& resourceStream, + std::wstring& mimeType, int loadFlags) +{ + if(CEF_MEMBER_MISSING(struct_, handle_before_resource_load)) + return RV_CONTINUE; + + cef_string_t redirectUrlRet = NULL; + cef_string_t mimeTypeRet = NULL; + cef_stream_reader_t* streamRet = NULL; + + if(!redirectUrl.empty()) + redirectUrlRet = cef_string_alloc(redirectUrl.c_str()); + + cef_retval_t rv = struct_->handle_before_resource_load(struct_, + CefBrowserCppToC::Wrap(browser), CefRequestCppToC::Wrap(request), + &redirectUrlRet, &streamRet, &mimeTypeRet, loadFlags); + + transfer_string_contents(redirectUrlRet, redirectUrl, true); + transfer_string_contents(mimeTypeRet, mimeType, true); + + if(streamRet) + resourceStream = CefStreamReaderCppToC::Unwrap(streamRet); + + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleBeforeMenu( + CefRefPtr browser, const MenuInfo& menuInfo) +{ + if(CEF_MEMBER_MISSING(struct_, handle_before_menu)) + return RV_CONTINUE; + + return struct_->handle_before_menu(struct_, CefBrowserCppToC::Wrap(browser), + &menuInfo); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleGetMenuLabel( + CefRefPtr browser, MenuId menuId, std::wstring& label) +{ + if(CEF_MEMBER_MISSING(struct_, handle_get_menu_label)) + return RV_CONTINUE; + + cef_string_t labelRet = NULL; + if(!label.empty()) + labelRet = cef_string_alloc(label.c_str()); + + cef_retval_t rv = struct_->handle_get_menu_label(struct_, + CefBrowserCppToC::Wrap(browser), menuId, &labelRet); + + transfer_string_contents(labelRet, label, true); + + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleMenuAction( + CefRefPtr browser, MenuId menuId) +{ + if(CEF_MEMBER_MISSING(struct_, handle_menu_action)) + return RV_CONTINUE; + + return struct_->handle_menu_action(struct_, CefBrowserCppToC::Wrap(browser), + menuId); +} + +CefHandler::RetVal CefHandlerCToCpp::HandlePrintOptions( + CefRefPtr browser, CefPrintOptions& printOptions) +{ + if (CEF_MEMBER_MISSING(struct_, handle_print_options)) + return RV_CONTINUE; + + return struct_->handle_print_options(struct_, CefBrowserCppToC::Wrap(browser), + &printOptions); +} + +CefHandler::RetVal CefHandlerCToCpp::HandlePrintHeaderFooter( + CefRefPtr browser, CefRefPtr frame, + CefPrintInfo& printInfo, const std::wstring& url, + const std::wstring& title, int currentPage, int maxPages, + std::wstring& topLeft, std::wstring& topCenter, std::wstring& topRight, + std::wstring& bottomLeft, std::wstring& bottomCenter, + std::wstring& bottomRight) +{ + if(CEF_MEMBER_MISSING(struct_, handle_print_header_footer)) + return RV_CONTINUE; + + cef_string_t topLeftRet = NULL, topCenterRet = NULL, topRightRet = NULL, + bottomLeftRet = NULL, bottomCenterRet = NULL, bottomRightRet = NULL; + + if(!topLeft.empty()) + topLeftRet = cef_string_alloc(topLeft.c_str()); + if(!topCenter.empty()) + topCenterRet = cef_string_alloc(topCenter.c_str()); + if(!topRight.empty()) + topRightRet = cef_string_alloc(topRight.c_str()); + if(!bottomLeft.empty()) + bottomLeftRet = cef_string_alloc(bottomLeft.c_str()); + if(!bottomCenter.empty()) + bottomCenterRet = cef_string_alloc(bottomCenter.c_str()); + if(!bottomRight.empty()) + bottomRightRet = cef_string_alloc(bottomRight.c_str()); + + cef_retval_t rv = struct_->handle_print_header_footer(struct_, + CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), + &printInfo, url.c_str(), title.c_str(), currentPage, maxPages, + &topLeftRet, &topCenterRet, &topRightRet, &bottomLeftRet, + &bottomCenterRet, &bottomRightRet); + + transfer_string_contents(topLeftRet, topLeft, true); + transfer_string_contents(topCenterRet, topCenter, true); + transfer_string_contents(topRightRet, topRight, true); + transfer_string_contents(bottomLeftRet, bottomLeft, true); + transfer_string_contents(bottomCenterRet, bottomCenter, true); + transfer_string_contents(bottomRightRet, bottomRight, true); + + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleJSAlert( + CefRefPtr browser, CefRefPtr frame, + const std::wstring& message) +{ + if(CEF_MEMBER_MISSING(struct_, handle_jsalert)) + return RV_CONTINUE; + + return struct_->handle_jsalert(struct_, CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), message.c_str()); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleJSConfirm( + CefRefPtr browser, CefRefPtr frame, + const std::wstring& message, bool& retval) +{ + if(CEF_MEMBER_MISSING(struct_, handle_jsconfirm)) + return RV_CONTINUE; + + int ret = 0; + cef_retval_t rv = struct_->handle_jsconfirm(struct_, + CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), + message.c_str(), &ret); + retval = (ret ? true : false); + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleJSPrompt( + CefRefPtr browser, CefRefPtr frame, + const std::wstring& message, const std::wstring& defaultValue, + bool& retval, std::wstring& result) +{ + if(CEF_MEMBER_MISSING(struct_, handle_jsprompt)) + return RV_CONTINUE; + + cef_string_t resultRet = NULL; + if(!result.empty()) + resultRet = cef_string_alloc(result.c_str()); + + int ret = 0; + cef_retval_t rv = struct_->handle_jsprompt(struct_, + CefBrowserCppToC::Wrap(browser), CefFrameCppToC::Wrap(frame), + message.c_str(), defaultValue.c_str(), &ret, &resultRet); + retval = (ret ? true : false); + + transfer_string_contents(resultRet, result, true); + + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleJSBinding( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr object) +{ + if(CEF_MEMBER_MISSING(struct_, handle_jsbinding)) + return RV_CONTINUE; + + return struct_->handle_jsbinding(struct_, CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), CefV8ValueCppToC::Wrap(object)); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleBeforeWindowClose( + CefRefPtr browser) +{ + if(CEF_MEMBER_MISSING(struct_, handle_before_window_close)) + return RV_CONTINUE; + + return struct_->handle_before_window_close(struct_, + CefBrowserCppToC::Wrap(browser)); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleTakeFocus( + CefRefPtr browser, bool reverse) +{ + if(CEF_MEMBER_MISSING(struct_, handle_take_focus)) + return RV_CONTINUE; + + return struct_->handle_take_focus(struct_, CefBrowserCppToC::Wrap(browser), + reverse); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleSetFocus( + CefRefPtr browser, bool isWidget) +{ + if(CEF_MEMBER_MISSING(struct_, handle_set_focus)) + return RV_CONTINUE; + + return struct_->handle_set_focus(struct_, CefBrowserCppToC::Wrap(browser), + isWidget); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleKeyEvent( + CefRefPtr browser, KeyEventType type, int code, int modifiers, + bool isSystemKey) +{ + if(CEF_MEMBER_MISSING(struct_, handle_key_event)) + return RV_CONTINUE; + + return struct_->handle_key_event(struct_, CefBrowserCppToC::Wrap(browser), + type, code, modifiers, isSystemKey); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleTooltip( + CefRefPtr browser, std::wstring& text) +{ + if(CEF_MEMBER_MISSING(struct_, handle_tooltip)) + return RV_CONTINUE; + cef_string_t textRet = NULL; + if(!text.empty()) + textRet = cef_string_alloc(text.c_str()); + + cef_retval_t rv = struct_->handle_tooltip(struct_, + CefBrowserCppToC::Wrap(browser), &textRet); + + transfer_string_contents(textRet, text, true); + + return rv; +} + +CefHandler::RetVal CefHandlerCToCpp::HandleConsoleMessage( + CefRefPtr browser, const std::wstring& message, + const std::wstring& source, int line) +{ + if(CEF_MEMBER_MISSING(struct_, handle_console_message)) + return RV_CONTINUE; + + return struct_->handle_console_message(struct_, + CefBrowserCppToC::Wrap(browser), message.c_str(), source.c_str(), line); +} + +CefHandler::RetVal CefHandlerCToCpp::HandleFindResult( + CefRefPtr browser, int identifier, int count, + const CefRect& selectionRect, int activeMatchOrdinal, bool finalUpdate) +{ + if(CEF_MEMBER_MISSING(struct_, handle_find_result)) + return RV_CONTINUE; + + return struct_->handle_find_result(struct_, + CefBrowserCppToC::Wrap(browser), identifier, count, &selectionRect, + activeMatchOrdinal, finalUpdate); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/handler_ctocpp.h b/libcef_dll/ctocpp/handler_ctocpp.h index 16c5d4ff2..5fdaf5896 100644 --- a/libcef_dll/ctocpp/handler_ctocpp.h +++ b/libcef_dll/ctocpp/handler_ctocpp.h @@ -1,94 +1,94 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _HANDLER_CTOCPP_H -#define _HANDLER_CTOCPP_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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 CefHandlerCToCpp - : public CefCToCpp -{ -public: - CefHandlerCToCpp(cef_handler_t* str) - : CefCToCpp(str) {} - virtual ~CefHandlerCToCpp() {} - - // CefHandler methods - virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, - CefWindowInfo& windowInfo, bool popup, CefRefPtr& handler, - std::wstring& url); - virtual RetVal HandleAfterCreated(CefRefPtr browser); - virtual RetVal HandleAddressChange(CefRefPtr browser, - CefRefPtr frame, const std::wstring& url); - virtual RetVal HandleTitleChange(CefRefPtr browser, - const std::wstring& title); - virtual RetVal HandleBeforeBrowse(CefRefPtr browser, - CefRefPtr frame, CefRefPtr request, - NavType navType, bool isRedirect); - virtual RetVal HandleLoadStart(CefRefPtr browser, - CefRefPtr frame); - virtual RetVal HandleLoadEnd(CefRefPtr browser, - CefRefPtr frame); - virtual RetVal HandleLoadError(CefRefPtr browser, - CefRefPtr frame, ErrorCode errorCode, - const std::wstring& failedUrl, std::wstring& errorText); - virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, - CefRefPtr request, std::wstring& redirectUrl, - CefRefPtr& resourceStream, std::wstring& mimeType, - int loadFlags); - virtual RetVal HandleBeforeMenu(CefRefPtr browser, - const MenuInfo& menuInfo); - virtual RetVal HandleGetMenuLabel(CefRefPtr browser, - MenuId menuId, std::wstring& label); - virtual RetVal HandleMenuAction(CefRefPtr browser, MenuId menuId); - virtual RetVal HandlePrintOptions(CefRefPtr browser, - CefPrintOptions& printOptions); - virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, - CefRefPtr frame, CefPrintInfo& printInfo, - const std::wstring& url, const std::wstring& title, int currentPage, - int maxPages, std::wstring& topLeft, std::wstring& topCenter, - std::wstring& topRight, std::wstring& bottomLeft, - std::wstring& bottomCenter, std::wstring& bottomRight); - virtual RetVal HandleJSAlert(CefRefPtr browser, - CefRefPtr frame, const std::wstring& message); - virtual RetVal HandleJSConfirm(CefRefPtr browser, - CefRefPtr frame, const std::wstring& message, bool& retval); - virtual RetVal HandleJSPrompt(CefRefPtr browser, - CefRefPtr frame, const std::wstring& message, - const std::wstring& defaultValue, bool& retval, std::wstring& result); - virtual RetVal HandleJSBinding(CefRefPtr browser, - CefRefPtr frame, CefRefPtr object); - virtual RetVal HandleBeforeWindowClose(CefRefPtr browser); - virtual RetVal HandleTakeFocus(CefRefPtr browser, bool reverse); - virtual RetVal HandleSetFocus(CefRefPtr browser, bool isWidget); - virtual RetVal HandleKeyEvent(CefRefPtr browser, - KeyEventType type, int code, int modifiers, bool isSystemKey); - virtual RetVal HandleTooltip(CefRefPtr browser, - std::wstring& text); - virtual RetVal HandleConsoleMessage(CefRefPtr browser, - const std::wstring& message, const std::wstring& source, int line); - virtual RetVal HandleFindResult(CefRefPtr browser, int identifier, - int count, const CefRect& selectionRect, int activeMatchOrdinal, - bool finalUpdate); -}; - -#endif // BUILDING_CEF_SHARED -#endif // _HANDLER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _HANDLER_CTOCPP_H +#define _HANDLER_CTOCPP_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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 CefHandlerCToCpp + : public CefCToCpp +{ +public: + CefHandlerCToCpp(cef_handler_t* str) + : CefCToCpp(str) {} + virtual ~CefHandlerCToCpp() {} + + // CefHandler methods + virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, + CefWindowInfo& windowInfo, bool popup, CefRefPtr& handler, + std::wstring& url); + virtual RetVal HandleAfterCreated(CefRefPtr browser); + virtual RetVal HandleAddressChange(CefRefPtr browser, + CefRefPtr frame, const std::wstring& url); + virtual RetVal HandleTitleChange(CefRefPtr browser, + const std::wstring& title); + virtual RetVal HandleBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, CefRefPtr request, + NavType navType, bool isRedirect); + virtual RetVal HandleLoadStart(CefRefPtr browser, + CefRefPtr frame); + virtual RetVal HandleLoadEnd(CefRefPtr browser, + CefRefPtr frame); + virtual RetVal HandleLoadError(CefRefPtr browser, + CefRefPtr frame, ErrorCode errorCode, + const std::wstring& failedUrl, std::wstring& errorText); + virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, std::wstring& redirectUrl, + CefRefPtr& resourceStream, std::wstring& mimeType, + int loadFlags); + virtual RetVal HandleBeforeMenu(CefRefPtr browser, + const MenuInfo& menuInfo); + virtual RetVal HandleGetMenuLabel(CefRefPtr browser, + MenuId menuId, std::wstring& label); + virtual RetVal HandleMenuAction(CefRefPtr browser, MenuId menuId); + virtual RetVal HandlePrintOptions(CefRefPtr browser, + CefPrintOptions& printOptions); + virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, CefPrintInfo& printInfo, + const std::wstring& url, const std::wstring& title, int currentPage, + int maxPages, std::wstring& topLeft, std::wstring& topCenter, + std::wstring& topRight, std::wstring& bottomLeft, + std::wstring& bottomCenter, std::wstring& bottomRight); + virtual RetVal HandleJSAlert(CefRefPtr browser, + CefRefPtr frame, const std::wstring& message); + virtual RetVal HandleJSConfirm(CefRefPtr browser, + CefRefPtr frame, const std::wstring& message, bool& retval); + virtual RetVal HandleJSPrompt(CefRefPtr browser, + CefRefPtr frame, const std::wstring& message, + const std::wstring& defaultValue, bool& retval, std::wstring& result); + virtual RetVal HandleJSBinding(CefRefPtr browser, + CefRefPtr frame, CefRefPtr object); + virtual RetVal HandleBeforeWindowClose(CefRefPtr browser); + virtual RetVal HandleTakeFocus(CefRefPtr browser, bool reverse); + virtual RetVal HandleSetFocus(CefRefPtr browser, bool isWidget); + virtual RetVal HandleKeyEvent(CefRefPtr browser, + KeyEventType type, int code, int modifiers, bool isSystemKey); + virtual RetVal HandleTooltip(CefRefPtr browser, + std::wstring& text); + virtual RetVal HandleConsoleMessage(CefRefPtr browser, + const std::wstring& message, const std::wstring& source, int line); + virtual RetVal HandleFindResult(CefRefPtr browser, int identifier, + int count, const CefRect& selectionRect, int activeMatchOrdinal, + bool finalUpdate); +}; + +#endif // BUILDING_CEF_SHARED +#endif // _HANDLER_CTOCPP_H + diff --git a/libcef_dll/ctocpp/post_data_ctocpp.cc b/libcef_dll/ctocpp/post_data_ctocpp.cc index feff67377..97e3ba3b2 100644 --- a/libcef_dll/ctocpp/post_data_ctocpp.cc +++ b/libcef_dll/ctocpp/post_data_ctocpp.cc @@ -1,85 +1,85 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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() -{ - cef_post_data_t* impl = cef_post_data_create(); - if(impl) - return CefPostDataCToCpp::Wrap(impl); - return NULL; -} - - -// VIRTUAL METHODS - Body may be edited by hand. - -size_t CefPostDataCToCpp::GetElementCount() -{ - if(CEF_MEMBER_MISSING(struct_, get_element_count)) - return 0; - - return struct_->get_element_count(struct_); -} - -void CefPostDataCToCpp::GetElements(ElementVector& elements) -{ - if(CEF_MEMBER_MISSING(struct_, get_elements)) - return; - - int count = (int)GetElementCount(); - - cef_post_data_element_t* structPtr; - for(int i = 0; i < count; ++i) { - structPtr = struct_->get_elements(struct_, i); - if(structPtr) - elements.push_back(CefPostDataElementCToCpp::Wrap(structPtr)); - } -} - -bool CefPostDataCToCpp::RemoveElement(CefRefPtr element) -{ - DCHECK(element.get()); - if(CEF_MEMBER_MISSING(struct_, remove_element) || !element.get()) - return false; - - return struct_->remove_element(struct_, - CefPostDataElementCToCpp::Unwrap(element))?true:false; -} - -bool CefPostDataCToCpp::AddElement(CefRefPtr element) -{ - DCHECK(element.get()); - if(CEF_MEMBER_MISSING(struct_, add_element) || !element.get()) - return false; - - return struct_->add_element(struct_, - CefPostDataElementCToCpp::Unwrap(element))?true:false; -} - -void CefPostDataCToCpp::RemoveElements() -{ - if(CEF_MEMBER_MISSING(struct_, remove_elements)) - return; - - return struct_->remove_elements(struct_); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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() +{ + cef_post_data_t* impl = cef_post_data_create(); + if(impl) + return CefPostDataCToCpp::Wrap(impl); + return NULL; +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +size_t CefPostDataCToCpp::GetElementCount() +{ + if(CEF_MEMBER_MISSING(struct_, get_element_count)) + return 0; + + return struct_->get_element_count(struct_); +} + +void CefPostDataCToCpp::GetElements(ElementVector& elements) +{ + if(CEF_MEMBER_MISSING(struct_, get_elements)) + return; + + int count = (int)GetElementCount(); + + cef_post_data_element_t* structPtr; + for(int i = 0; i < count; ++i) { + structPtr = struct_->get_elements(struct_, i); + if(structPtr) + elements.push_back(CefPostDataElementCToCpp::Wrap(structPtr)); + } +} + +bool CefPostDataCToCpp::RemoveElement(CefRefPtr element) +{ + DCHECK(element.get()); + if(CEF_MEMBER_MISSING(struct_, remove_element) || !element.get()) + return false; + + return struct_->remove_element(struct_, + CefPostDataElementCToCpp::Unwrap(element))?true:false; +} + +bool CefPostDataCToCpp::AddElement(CefRefPtr element) +{ + DCHECK(element.get()); + if(CEF_MEMBER_MISSING(struct_, add_element) || !element.get()) + return false; + + return struct_->add_element(struct_, + CefPostDataElementCToCpp::Unwrap(element))?true:false; +} + +void CefPostDataCToCpp::RemoveElements() +{ + if(CEF_MEMBER_MISSING(struct_, remove_elements)) + return; + + return struct_->remove_elements(struct_); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/post_data_ctocpp.h b/libcef_dll/ctocpp/post_data_ctocpp.h index 500b1d5b3..ff9d17092 100644 --- a/libcef_dll/ctocpp/post_data_ctocpp.h +++ b/libcef_dll/ctocpp/post_data_ctocpp.h @@ -1,43 +1,43 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _POSTDATA_CTOCPP_H -#define _POSTDATA_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefPostDataCToCpp(cef_post_data_t* str) - : CefCToCpp(str) {} - virtual ~CefPostDataCToCpp() {} - - // CefPostData methods - virtual size_t GetElementCount(); - virtual void GetElements(ElementVector& elements); - virtual bool RemoveElement(CefRefPtr element); - virtual bool AddElement(CefRefPtr element); - virtual void RemoveElements(); -}; - -#endif // USING_CEF_SHARED -#endif // _POSTDATA_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _POSTDATA_CTOCPP_H +#define _POSTDATA_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefPostDataCToCpp(cef_post_data_t* str) + : CefCToCpp(str) {} + virtual ~CefPostDataCToCpp() {} + + // CefPostData methods + virtual size_t GetElementCount(); + virtual void GetElements(ElementVector& elements); + virtual bool RemoveElement(CefRefPtr element); + virtual bool AddElement(CefRefPtr element); + virtual void RemoveElements(); +}; + +#endif // USING_CEF_SHARED +#endif // _POSTDATA_CTOCPP_H + diff --git a/libcef_dll/ctocpp/post_data_element_ctocpp.cc b/libcef_dll/ctocpp/post_data_element_ctocpp.cc index 602468859..9323f2ba6 100644 --- a/libcef_dll/ctocpp/post_data_element_ctocpp.cc +++ b/libcef_dll/ctocpp/post_data_element_ctocpp.cc @@ -1,97 +1,97 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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() -{ - cef_post_data_element_t* impl = cef_post_data_element_create(); - if(impl) - return CefPostDataElementCToCpp::Wrap(impl); - return NULL; -} - - -// VIRTUAL METHODS - Body may be edited by hand. - -void CefPostDataElementCToCpp::SetToEmpty() -{ - if(CEF_MEMBER_MISSING(struct_, set_to_empty)) - return; - - return struct_->set_to_empty(struct_); -} - -void CefPostDataElementCToCpp::SetToFile(const std::wstring& fileName) -{ - if(CEF_MEMBER_MISSING(struct_, set_to_file)) - return; - - return struct_->set_to_file(struct_, fileName.c_str()); -} - -void CefPostDataElementCToCpp::SetToBytes(size_t size, const void* bytes) -{ - if(CEF_MEMBER_MISSING(struct_, set_to_bytes)) - return; - - return struct_->set_to_bytes(struct_, size, bytes); -} - -CefPostDataElement::Type CefPostDataElementCToCpp::GetType() -{ - if(CEF_MEMBER_MISSING(struct_, get_type)) - return PDE_TYPE_EMPTY; - - return struct_->get_type(struct_); -} - -std::wstring CefPostDataElementCToCpp::GetFile() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_file)) - return str; - - cef_string_t cef_str = struct_->get_file(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - - return str; -} - -size_t CefPostDataElementCToCpp::GetBytesCount() -{ - if(CEF_MEMBER_MISSING(struct_, get_bytes_count)) - return 0; - - return struct_->get_bytes_count(struct_); -} - -size_t CefPostDataElementCToCpp::GetBytes(size_t size, void* bytes) -{ - if(CEF_MEMBER_MISSING(struct_, get_bytes)) - return 0; - - return struct_->get_bytes(struct_, size, bytes); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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() +{ + cef_post_data_element_t* impl = cef_post_data_element_create(); + if(impl) + return CefPostDataElementCToCpp::Wrap(impl); + return NULL; +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefPostDataElementCToCpp::SetToEmpty() +{ + if(CEF_MEMBER_MISSING(struct_, set_to_empty)) + return; + + return struct_->set_to_empty(struct_); +} + +void CefPostDataElementCToCpp::SetToFile(const std::wstring& fileName) +{ + if(CEF_MEMBER_MISSING(struct_, set_to_file)) + return; + + return struct_->set_to_file(struct_, fileName.c_str()); +} + +void CefPostDataElementCToCpp::SetToBytes(size_t size, const void* bytes) +{ + if(CEF_MEMBER_MISSING(struct_, set_to_bytes)) + return; + + return struct_->set_to_bytes(struct_, size, bytes); +} + +CefPostDataElement::Type CefPostDataElementCToCpp::GetType() +{ + if(CEF_MEMBER_MISSING(struct_, get_type)) + return PDE_TYPE_EMPTY; + + return struct_->get_type(struct_); +} + +std::wstring CefPostDataElementCToCpp::GetFile() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_file)) + return str; + + cef_string_t cef_str = struct_->get_file(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + + return str; +} + +size_t CefPostDataElementCToCpp::GetBytesCount() +{ + if(CEF_MEMBER_MISSING(struct_, get_bytes_count)) + return 0; + + return struct_->get_bytes_count(struct_); +} + +size_t CefPostDataElementCToCpp::GetBytes(size_t size, void* bytes) +{ + if(CEF_MEMBER_MISSING(struct_, get_bytes)) + return 0; + + return struct_->get_bytes(struct_, size, bytes); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/post_data_element_ctocpp.h b/libcef_dll/ctocpp/post_data_element_ctocpp.h index 3effa0829..10d566e0f 100644 --- a/libcef_dll/ctocpp/post_data_element_ctocpp.h +++ b/libcef_dll/ctocpp/post_data_element_ctocpp.h @@ -1,47 +1,47 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _POSTDATAELEMENT_CTOCPP_H -#define _POSTDATAELEMENT_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefPostDataElementCToCpp(cef_post_data_element_t* str) - : CefCToCpp(str) {} - virtual ~CefPostDataElementCToCpp() {} - - // CefPostDataElement methods - virtual void SetToEmpty(); - virtual void SetToFile(const std::wstring& fileName); - virtual void SetToBytes(size_t size, const void* bytes); - virtual Type GetType(); - virtual std::wstring GetFile(); - virtual size_t GetBytesCount(); - virtual size_t GetBytes(size_t size, void* bytes); -}; - -#endif // USING_CEF_SHARED -#endif // _POSTDATAELEMENT_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _POSTDATAELEMENT_CTOCPP_H +#define _POSTDATAELEMENT_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefPostDataElementCToCpp(cef_post_data_element_t* str) + : CefCToCpp(str) {} + virtual ~CefPostDataElementCToCpp() {} + + // CefPostDataElement methods + virtual void SetToEmpty(); + virtual void SetToFile(const std::wstring& fileName); + virtual void SetToBytes(size_t size, const void* bytes); + virtual Type GetType(); + virtual std::wstring GetFile(); + virtual size_t GetBytesCount(); + virtual size_t GetBytes(size_t size, void* bytes); +}; + +#endif // USING_CEF_SHARED +#endif // _POSTDATAELEMENT_CTOCPP_H + diff --git a/libcef_dll/ctocpp/read_handler_ctocpp.cc b/libcef_dll/ctocpp/read_handler_ctocpp.cc index 4f9b0afa7..d0b2cd39c 100644 --- a/libcef_dll/ctocpp/read_handler_ctocpp.cc +++ b/libcef_dll/ctocpp/read_handler_ctocpp.cc @@ -1,55 +1,55 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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; - - return struct_->read(struct_, ptr, size, n); -} - -int CefReadHandlerCToCpp::Seek(long offset, int whence) -{ - if(CEF_MEMBER_MISSING(struct_, seek)) - return 0; - - return struct_->seek(struct_, offset, whence); -} - -long CefReadHandlerCToCpp::Tell() -{ - if(CEF_MEMBER_MISSING(struct_, tell)) - return 0; - - return struct_->tell(struct_); -} - -int CefReadHandlerCToCpp::Eof() -{ - if(CEF_MEMBER_MISSING(struct_, eof)) - return 0; - - return struct_->eof(struct_); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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; + + return struct_->read(struct_, ptr, size, n); +} + +int CefReadHandlerCToCpp::Seek(long offset, int whence) +{ + if(CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + return struct_->seek(struct_, offset, whence); +} + +long CefReadHandlerCToCpp::Tell() +{ + if(CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + return struct_->tell(struct_); +} + +int CefReadHandlerCToCpp::Eof() +{ + if(CEF_MEMBER_MISSING(struct_, eof)) + return 0; + + return struct_->eof(struct_); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/read_handler_ctocpp.h b/libcef_dll/ctocpp/read_handler_ctocpp.h index 75f51d635..1ec5b7cc5 100644 --- a/libcef_dll/ctocpp/read_handler_ctocpp.h +++ b/libcef_dll/ctocpp/read_handler_ctocpp.h @@ -1,43 +1,43 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _READHANDLER_CTOCPP_H -#define _READHANDLER_CTOCPP_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefReadHandlerCToCpp(cef_read_handler_t* str) - : CefCToCpp( - str) {} - virtual ~CefReadHandlerCToCpp() {} - - // CefReadHandler methods - virtual size_t Read(void* ptr, size_t size, size_t n); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Eof(); -}; - -#endif // BUILDING_CEF_SHARED -#endif // _READHANDLER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _READHANDLER_CTOCPP_H +#define _READHANDLER_CTOCPP_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefReadHandlerCToCpp(cef_read_handler_t* str) + : CefCToCpp( + str) {} + virtual ~CefReadHandlerCToCpp() {} + + // CefReadHandler methods + virtual size_t Read(void* ptr, size_t size, size_t n); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Eof(); +}; + +#endif // BUILDING_CEF_SHARED +#endif // _READHANDLER_CTOCPP_H + diff --git a/libcef_dll/ctocpp/request_ctocpp.cc b/libcef_dll/ctocpp/request_ctocpp.cc index 285d5de7f..3b3dc03bc 100644 --- a/libcef_dll/ctocpp/request_ctocpp.cc +++ b/libcef_dll/ctocpp/request_ctocpp.cc @@ -1,159 +1,159 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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() -{ - cef_request_t* impl = cef_request_create(); - if(impl) - return CefRequestCToCpp::Wrap(impl); - return NULL; -} - - -// VIRTUAL METHODS - Body may be edited by hand. - -std::wstring CefRequestCToCpp::GetURL() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_url)) - return str; - - cef_string_t cef_str = struct_->get_url(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - -void CefRequestCToCpp::SetURL(const std::wstring& url) -{ - if(CEF_MEMBER_MISSING(struct_, set_url)) - return; - - struct_->set_url(struct_, url.c_str()); -} - -std::wstring CefRequestCToCpp::GetMethod() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_method)) - return str; - - cef_string_t cef_str = struct_->get_method(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - -void CefRequestCToCpp::SetMethod(const std::wstring& method) -{ - if(CEF_MEMBER_MISSING(struct_, set_method)) - return; - - struct_->set_method(struct_, method.c_str()); -} - -CefRefPtr CefRequestCToCpp::GetPostData() -{ - if(CEF_MEMBER_MISSING(struct_, get_post_data)) - return NULL; - - cef_post_data_t* postDataStruct = struct_->get_post_data(struct_); - if(postDataStruct) - return CefPostDataCToCpp::Wrap(postDataStruct); - return NULL; -} - -void CefRequestCToCpp::SetPostData(CefRefPtr postData) -{ - if(CEF_MEMBER_MISSING(struct_, set_post_data)) - return; - - cef_post_data_t* postDataStruct = NULL; - if(postData.get()) - postDataStruct = CefPostDataCToCpp::Unwrap(postData); - - struct_->set_post_data(struct_, postDataStruct); -} - -void CefRequestCToCpp::GetHeaderMap(HeaderMap& headerMap) -{ - if(CEF_MEMBER_MISSING(struct_, get_header_map)) - return; - - cef_string_map_t map = cef_string_map_alloc(); - if(!map) - return; - - struct_->get_header_map(struct_, map); - transfer_string_map_contents(map, headerMap); - cef_string_map_free(map); -} - -void CefRequestCToCpp::SetHeaderMap(const HeaderMap& headerMap) -{ - if(CEF_MEMBER_MISSING(struct_, set_header_map)) - return; - - cef_string_map_t map = NULL; - if(!headerMap.empty()) { - map = cef_string_map_alloc(); - if(!map) - return; - transfer_string_map_contents(headerMap, map); - } - - struct_->set_header_map(struct_, map); - - if(map) - cef_string_map_free(map); -} - -void CefRequestCToCpp::Set(const std::wstring& url, const std::wstring& method, - CefRefPtr postData, const HeaderMap& headerMap) -{ - if(CEF_MEMBER_MISSING(struct_, set)) - return; - - cef_post_data_t* postDataStruct = NULL; - if(postData.get()) - postDataStruct = CefPostDataCToCpp::Unwrap(postData); - - cef_string_map_t map = NULL; - if(!headerMap.empty()) { - map = cef_string_map_alloc(); - if(!map) - return; - transfer_string_map_contents(headerMap, map); - } - - struct_->set(struct_, url.c_str(), method.c_str(), postDataStruct, map); - - if(map) - cef_string_map_free(map); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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() +{ + cef_request_t* impl = cef_request_create(); + if(impl) + return CefRequestCToCpp::Wrap(impl); + return NULL; +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +std::wstring CefRequestCToCpp::GetURL() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_url)) + return str; + + cef_string_t cef_str = struct_->get_url(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + +void CefRequestCToCpp::SetURL(const std::wstring& url) +{ + if(CEF_MEMBER_MISSING(struct_, set_url)) + return; + + struct_->set_url(struct_, url.c_str()); +} + +std::wstring CefRequestCToCpp::GetMethod() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_method)) + return str; + + cef_string_t cef_str = struct_->get_method(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + +void CefRequestCToCpp::SetMethod(const std::wstring& method) +{ + if(CEF_MEMBER_MISSING(struct_, set_method)) + return; + + struct_->set_method(struct_, method.c_str()); +} + +CefRefPtr CefRequestCToCpp::GetPostData() +{ + if(CEF_MEMBER_MISSING(struct_, get_post_data)) + return NULL; + + cef_post_data_t* postDataStruct = struct_->get_post_data(struct_); + if(postDataStruct) + return CefPostDataCToCpp::Wrap(postDataStruct); + return NULL; +} + +void CefRequestCToCpp::SetPostData(CefRefPtr postData) +{ + if(CEF_MEMBER_MISSING(struct_, set_post_data)) + return; + + cef_post_data_t* postDataStruct = NULL; + if(postData.get()) + postDataStruct = CefPostDataCToCpp::Unwrap(postData); + + struct_->set_post_data(struct_, postDataStruct); +} + +void CefRequestCToCpp::GetHeaderMap(HeaderMap& headerMap) +{ + if(CEF_MEMBER_MISSING(struct_, get_header_map)) + return; + + cef_string_map_t map = cef_string_map_alloc(); + if(!map) + return; + + struct_->get_header_map(struct_, map); + transfer_string_map_contents(map, headerMap); + cef_string_map_free(map); +} + +void CefRequestCToCpp::SetHeaderMap(const HeaderMap& headerMap) +{ + if(CEF_MEMBER_MISSING(struct_, set_header_map)) + return; + + cef_string_map_t map = NULL; + if(!headerMap.empty()) { + map = cef_string_map_alloc(); + if(!map) + return; + transfer_string_map_contents(headerMap, map); + } + + struct_->set_header_map(struct_, map); + + if(map) + cef_string_map_free(map); +} + +void CefRequestCToCpp::Set(const std::wstring& url, const std::wstring& method, + CefRefPtr postData, const HeaderMap& headerMap) +{ + if(CEF_MEMBER_MISSING(struct_, set)) + return; + + cef_post_data_t* postDataStruct = NULL; + if(postData.get()) + postDataStruct = CefPostDataCToCpp::Unwrap(postData); + + cef_string_map_t map = NULL; + if(!headerMap.empty()) { + map = cef_string_map_alloc(); + if(!map) + return; + transfer_string_map_contents(headerMap, map); + } + + struct_->set(struct_, url.c_str(), method.c_str(), postDataStruct, map); + + if(map) + cef_string_map_free(map); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/request_ctocpp.h b/libcef_dll/ctocpp/request_ctocpp.h index b6bc544f4..dcfe7527b 100644 --- a/libcef_dll/ctocpp/request_ctocpp.h +++ b/libcef_dll/ctocpp/request_ctocpp.h @@ -1,48 +1,48 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _REQUEST_CTOCPP_H -#define _REQUEST_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefRequestCToCpp(cef_request_t* str) - : CefCToCpp(str) {} - virtual ~CefRequestCToCpp() {} - - // CefRequest methods - virtual std::wstring GetURL(); - virtual void SetURL(const std::wstring& url); - virtual std::wstring GetMethod(); - virtual void SetMethod(const std::wstring& method); - virtual CefRefPtr GetPostData(); - virtual void SetPostData(CefRefPtr postData); - virtual void GetHeaderMap(HeaderMap& headerMap); - virtual void SetHeaderMap(const HeaderMap& headerMap); - virtual void Set(const std::wstring& url, const std::wstring& method, - CefRefPtr postData, const HeaderMap& headerMap); -}; - -#endif // USING_CEF_SHARED -#endif // _REQUEST_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _REQUEST_CTOCPP_H +#define _REQUEST_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefRequestCToCpp(cef_request_t* str) + : CefCToCpp(str) {} + virtual ~CefRequestCToCpp() {} + + // CefRequest methods + virtual std::wstring GetURL(); + virtual void SetURL(const std::wstring& url); + virtual std::wstring GetMethod(); + virtual void SetMethod(const std::wstring& method); + virtual CefRefPtr GetPostData(); + virtual void SetPostData(CefRefPtr postData); + virtual void GetHeaderMap(HeaderMap& headerMap); + virtual void SetHeaderMap(const HeaderMap& headerMap); + virtual void Set(const std::wstring& url, const std::wstring& method, + CefRefPtr postData, const HeaderMap& headerMap); +}; + +#endif // USING_CEF_SHARED +#endif // _REQUEST_CTOCPP_H + diff --git a/libcef_dll/ctocpp/scheme_handler_ctocpp.cc b/libcef_dll/ctocpp/scheme_handler_ctocpp.cc index b5b3c6835..c013036d5 100644 --- a/libcef_dll/ctocpp/scheme_handler_ctocpp.cc +++ b/libcef_dll/ctocpp/scheme_handler_ctocpp.cc @@ -1,61 +1,61 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method implementations. See the translator.README.txt file in the -// tools directory for more information. -// - -#include "libcef_dll/cpptoc/request_cpptoc.h" -#include "libcef_dll/ctocpp/scheme_handler_ctocpp.h" -#include "libcef_dll/transfer_util.h" - - -// VIRTUAL METHODS - Body may be edited by hand. - -bool CefSchemeHandlerCToCpp::ProcessRequest(CefRefPtr request, - std::wstring& mime_type, int* response_length) -{ - if(CEF_MEMBER_MISSING(struct_, process_request)) - return false; - - cef_string_t mimeTypeRet = NULL; - if(!mime_type.empty()) - mimeTypeRet = cef_string_alloc(mime_type.c_str()); - - int rv = struct_->process_request(struct_, CefRequestCppToC::Wrap(request), - &mimeTypeRet, response_length); - - transfer_string_contents(mimeTypeRet, mime_type, true); - - return rv ? true : false; -} - -void CefSchemeHandlerCToCpp::Cancel() -{ - if(CEF_MEMBER_MISSING(struct_, cancel)) - return; - - struct_->cancel(struct_); -} - -bool CefSchemeHandlerCToCpp::ReadResponse(void* data_out, int bytes_to_read, - int* bytes_read) -{ - if(CEF_MEMBER_MISSING(struct_, read_response)) - return false; - - return struct_->read_response(struct_, data_out, bytes_to_read, bytes_read) - ? true : false; -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method implementations. See the translator.README.txt file in the +// tools directory for more information. +// + +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/ctocpp/scheme_handler_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefSchemeHandlerCToCpp::ProcessRequest(CefRefPtr request, + std::wstring& mime_type, int* response_length) +{ + if(CEF_MEMBER_MISSING(struct_, process_request)) + return false; + + cef_string_t mimeTypeRet = NULL; + if(!mime_type.empty()) + mimeTypeRet = cef_string_alloc(mime_type.c_str()); + + int rv = struct_->process_request(struct_, CefRequestCppToC::Wrap(request), + &mimeTypeRet, response_length); + + transfer_string_contents(mimeTypeRet, mime_type, true); + + return rv ? true : false; +} + +void CefSchemeHandlerCToCpp::Cancel() +{ + if(CEF_MEMBER_MISSING(struct_, cancel)) + return; + + struct_->cancel(struct_); +} + +bool CefSchemeHandlerCToCpp::ReadResponse(void* data_out, int bytes_to_read, + int* bytes_read) +{ + if(CEF_MEMBER_MISSING(struct_, read_response)) + return false; + + return struct_->read_response(struct_, data_out, bytes_to_read, bytes_read) + ? true : false; +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/scheme_handler_ctocpp.h b/libcef_dll/ctocpp/scheme_handler_ctocpp.h index 2f1d7e6b3..9d36013f5 100644 --- a/libcef_dll/ctocpp/scheme_handler_ctocpp.h +++ b/libcef_dll/ctocpp/scheme_handler_ctocpp.h @@ -1,44 +1,44 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _SCHEMEHANDLER_CTOCPP_H -#define _SCHEMEHANDLER_CTOCPP_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefSchemeHandlerCToCpp(cef_scheme_handler_t* str) - : CefCToCpp(str) {} - virtual ~CefSchemeHandlerCToCpp() {} - - // CefSchemeHandler methods - virtual bool ProcessRequest(CefRefPtr request, - std::wstring& mime_type, int* response_length); - virtual void Cancel(); - virtual bool ReadResponse(void* data_out, int bytes_to_read, int* bytes_read); -}; - -#endif // BUILDING_CEF_SHARED -#endif // _SCHEMEHANDLER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _SCHEMEHANDLER_CTOCPP_H +#define _SCHEMEHANDLER_CTOCPP_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefSchemeHandlerCToCpp(cef_scheme_handler_t* str) + : CefCToCpp(str) {} + virtual ~CefSchemeHandlerCToCpp() {} + + // CefSchemeHandler methods + virtual bool ProcessRequest(CefRefPtr request, + std::wstring& mime_type, int* response_length); + virtual void Cancel(); + virtual bool ReadResponse(void* data_out, int bytes_to_read, int* bytes_read); +}; + +#endif // BUILDING_CEF_SHARED +#endif // _SCHEMEHANDLER_CTOCPP_H + diff --git a/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc index 949f5464c..ff97e6a96 100644 --- a/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc +++ b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc @@ -1,34 +1,34 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method implementations. See the translator.README.txt file in the -// tools directory for more information. -// - -#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() -{ - if(CEF_MEMBER_MISSING(struct_, create)) - return NULL; - - _cef_scheme_handler_t* rv = struct_->create(struct_); - - return CefSchemeHandlerCToCpp::Wrap(rv); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method implementations. See the translator.README.txt file in the +// tools directory for more information. +// + +#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() +{ + if(CEF_MEMBER_MISSING(struct_, create)) + return NULL; + + _cef_scheme_handler_t* rv = struct_->create(struct_); + + return CefSchemeHandlerCToCpp::Wrap(rv); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h index 4d5445b88..e32ca4d24 100644 --- a/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h +++ b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h @@ -1,41 +1,41 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _SCHEMEHANDLERFACTORY_CTOCPP_H -#define _SCHEMEHANDLERFACTORY_CTOCPP_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefSchemeHandlerFactoryCToCpp(cef_scheme_handler_factory_t* str) - : CefCToCpp(str) {} - virtual ~CefSchemeHandlerFactoryCToCpp() {} - - // CefSchemeHandlerFactory methods - virtual CefRefPtr Create(); -}; - -#endif // BUILDING_CEF_SHARED -#endif // _SCHEMEHANDLERFACTORY_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _SCHEMEHANDLERFACTORY_CTOCPP_H +#define _SCHEMEHANDLERFACTORY_CTOCPP_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefSchemeHandlerFactoryCToCpp(cef_scheme_handler_factory_t* str) + : CefCToCpp(str) {} + virtual ~CefSchemeHandlerFactoryCToCpp() {} + + // CefSchemeHandlerFactory methods + virtual CefRefPtr Create(); +}; + +#endif // BUILDING_CEF_SHARED +#endif // _SCHEMEHANDLERFACTORY_CTOCPP_H + diff --git a/libcef_dll/ctocpp/stream_reader_ctocpp.cc b/libcef_dll/ctocpp/stream_reader_ctocpp.cc index 270a4b10d..d21266598 100644 --- a/libcef_dll/ctocpp/stream_reader_ctocpp.cc +++ b/libcef_dll/ctocpp/stream_reader_ctocpp.cc @@ -1,88 +1,88 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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 std::wstring& fileName) -{ - cef_stream_reader_t* impl = - cef_stream_reader_create_for_file(fileName.c_str()); - if(impl) - return CefStreamReaderCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefStreamReader::CreateForData(void* data, - size_t size) -{ - cef_stream_reader_t* impl = cef_stream_reader_create_for_data(data, size); - if(impl) - return CefStreamReaderCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefStreamReader::CreateForHandler( - CefRefPtr handler) -{ - cef_stream_reader_t* impl = - cef_stream_reader_create_for_handler(CefReadHandlerCppToC::Wrap(handler)); - if(impl) - return CefStreamReaderCToCpp::Wrap(impl); - return NULL; -} - - -// 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; - - return struct_->read(struct_, ptr, size, n); -} - -int CefStreamReaderCToCpp::Seek(long offset, int whence) -{ - if(CEF_MEMBER_MISSING(struct_, seek)) - return 0; - - return struct_->seek(struct_, offset, whence); -} - -long CefStreamReaderCToCpp::Tell() -{ - if(CEF_MEMBER_MISSING(struct_, tell)) - return 0; - - return struct_->tell(struct_); -} - -int CefStreamReaderCToCpp::Eof() -{ - if(CEF_MEMBER_MISSING(struct_, eof)) - return 0; - - return struct_->eof(struct_); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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 std::wstring& fileName) +{ + cef_stream_reader_t* impl = + cef_stream_reader_create_for_file(fileName.c_str()); + if(impl) + return CefStreamReaderCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefStreamReader::CreateForData(void* data, + size_t size) +{ + cef_stream_reader_t* impl = cef_stream_reader_create_for_data(data, size); + if(impl) + return CefStreamReaderCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefStreamReader::CreateForHandler( + CefRefPtr handler) +{ + cef_stream_reader_t* impl = + cef_stream_reader_create_for_handler(CefReadHandlerCppToC::Wrap(handler)); + if(impl) + return CefStreamReaderCToCpp::Wrap(impl); + return NULL; +} + + +// 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; + + return struct_->read(struct_, ptr, size, n); +} + +int CefStreamReaderCToCpp::Seek(long offset, int whence) +{ + if(CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + return struct_->seek(struct_, offset, whence); +} + +long CefStreamReaderCToCpp::Tell() +{ + if(CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + return struct_->tell(struct_); +} + +int CefStreamReaderCToCpp::Eof() +{ + if(CEF_MEMBER_MISSING(struct_, eof)) + return 0; + + return struct_->eof(struct_); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/stream_reader_ctocpp.h b/libcef_dll/ctocpp/stream_reader_ctocpp.h index 7db108417..49cb20e10 100644 --- a/libcef_dll/ctocpp/stream_reader_ctocpp.h +++ b/libcef_dll/ctocpp/stream_reader_ctocpp.h @@ -1,44 +1,44 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _STREAMREADER_CTOCPP_H -#define _STREAMREADER_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefStreamReaderCToCpp(cef_stream_reader_t* str) - : CefCToCpp( - str) {} - virtual ~CefStreamReaderCToCpp() {} - - // CefStreamReader methods - virtual size_t Read(void* ptr, size_t size, size_t n); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Eof(); -}; - -#endif // USING_CEF_SHARED -#endif // _STREAMREADER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _STREAMREADER_CTOCPP_H +#define _STREAMREADER_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefStreamReaderCToCpp(cef_stream_reader_t* str) + : CefCToCpp( + str) {} + virtual ~CefStreamReaderCToCpp() {} + + // CefStreamReader methods + virtual size_t Read(void* ptr, size_t size, size_t n); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Eof(); +}; + +#endif // USING_CEF_SHARED +#endif // _STREAMREADER_CTOCPP_H + diff --git a/libcef_dll/ctocpp/stream_writer_ctocpp.cc b/libcef_dll/ctocpp/stream_writer_ctocpp.cc index 02e49edcb..899fec99f 100644 --- a/libcef_dll/ctocpp/stream_writer_ctocpp.cc +++ b/libcef_dll/ctocpp/stream_writer_ctocpp.cc @@ -1,88 +1,88 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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 std::wstring& fileName) -{ - DCHECK(!fileName.empty()); - if(fileName.empty()) - return NULL; - - cef_stream_writer_t* impl = - cef_stream_writer_create_for_file(fileName.c_str()); - if(impl) - return CefStreamWriterCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefStreamWriter::CreateForHandler( - CefRefPtr handler) -{ - DCHECK(handler.get()); - if(!handler.get()) - return NULL; - - cef_stream_writer_t* impl = - cef_stream_writer_create_for_handler( - CefWriteHandlerCppToC::Wrap(handler)); - if(impl) - return CefStreamWriterCToCpp::Wrap(impl); - return NULL; -} - - -// 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; - - return struct_->write(struct_, ptr, size, n); -} - -int CefStreamWriterCToCpp::Seek(long offset, int whence) -{ - if(CEF_MEMBER_MISSING(struct_, seek)) - return 0; - - return struct_->seek(struct_, offset, whence); -} - -long CefStreamWriterCToCpp::Tell() -{ - if(CEF_MEMBER_MISSING(struct_, tell)) - return 0; - - return struct_->tell(struct_); -} - -int CefStreamWriterCToCpp::Flush() -{ - if(CEF_MEMBER_MISSING(struct_, flush)) - return 0; - - return struct_->flush(struct_); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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 std::wstring& fileName) +{ + DCHECK(!fileName.empty()); + if(fileName.empty()) + return NULL; + + cef_stream_writer_t* impl = + cef_stream_writer_create_for_file(fileName.c_str()); + if(impl) + return CefStreamWriterCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefStreamWriter::CreateForHandler( + CefRefPtr handler) +{ + DCHECK(handler.get()); + if(!handler.get()) + return NULL; + + cef_stream_writer_t* impl = + cef_stream_writer_create_for_handler( + CefWriteHandlerCppToC::Wrap(handler)); + if(impl) + return CefStreamWriterCToCpp::Wrap(impl); + return NULL; +} + + +// 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; + + return struct_->write(struct_, ptr, size, n); +} + +int CefStreamWriterCToCpp::Seek(long offset, int whence) +{ + if(CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + return struct_->seek(struct_, offset, whence); +} + +long CefStreamWriterCToCpp::Tell() +{ + if(CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + return struct_->tell(struct_); +} + +int CefStreamWriterCToCpp::Flush() +{ + if(CEF_MEMBER_MISSING(struct_, flush)) + return 0; + + return struct_->flush(struct_); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/stream_writer_ctocpp.h b/libcef_dll/ctocpp/stream_writer_ctocpp.h index f698bbce0..eddcc5db7 100644 --- a/libcef_dll/ctocpp/stream_writer_ctocpp.h +++ b/libcef_dll/ctocpp/stream_writer_ctocpp.h @@ -1,44 +1,44 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _STREAMWRITER_CTOCPP_H -#define _STREAMWRITER_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - 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); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Flush(); -}; - -#endif // USING_CEF_SHARED -#endif // _STREAMWRITER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _STREAMWRITER_CTOCPP_H +#define _STREAMWRITER_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + 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); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Flush(); +}; + +#endif // USING_CEF_SHARED +#endif // _STREAMWRITER_CTOCPP_H + diff --git a/libcef_dll/ctocpp/task_ctocpp.cc b/libcef_dll/ctocpp/task_ctocpp.cc index 1597a252d..ec1c51bf4 100644 --- a/libcef_dll/ctocpp/task_ctocpp.cc +++ b/libcef_dll/ctocpp/task_ctocpp.cc @@ -1,30 +1,30 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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; - - struct_->execute(struct_, threadId); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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; + + struct_->execute(struct_, threadId); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/task_ctocpp.h b/libcef_dll/ctocpp/task_ctocpp.h index 24f0c2ee9..bfdc5fb99 100644 --- a/libcef_dll/ctocpp/task_ctocpp.h +++ b/libcef_dll/ctocpp/task_ctocpp.h @@ -1,39 +1,39 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _TASK_CTOCPP_H -#define _TASK_CTOCPP_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefTaskCToCpp(cef_task_t* str) - : CefCToCpp(str) {} - virtual ~CefTaskCToCpp() {} - - // CefTask methods - virtual void Execute(CefThreadId threadId); -}; - -#endif // BUILDING_CEF_SHARED -#endif // _TASK_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _TASK_CTOCPP_H +#define _TASK_CTOCPP_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefTaskCToCpp(cef_task_t* str) + : CefCToCpp(str) {} + virtual ~CefTaskCToCpp() {} + + // CefTask methods + virtual void Execute(CefThreadId threadId); +}; + +#endif // BUILDING_CEF_SHARED +#endif // _TASK_CTOCPP_H + diff --git a/libcef_dll/ctocpp/v8handler_ctocpp.cc b/libcef_dll/ctocpp/v8handler_ctocpp.cc index 95629e076..c5af7e9f9 100644 --- a/libcef_dll/ctocpp/v8handler_ctocpp.cc +++ b/libcef_dll/ctocpp/v8handler_ctocpp.cc @@ -1,58 +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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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 std::wstring& name, - CefRefPtr object, const CefV8ValueList& arguments, - CefRefPtr& retval, std::wstring& exception) -{ - if(CEF_MEMBER_MISSING(struct_, execute)) - return RV_CONTINUE; - - cef_v8value_t** argsStructPtr = NULL; - int argsSize = arguments.size(); - if(argsSize > 0) { - argsStructPtr = new cef_v8value_t*[argsSize]; - for(int i = 0; i < argsSize; ++i) - argsStructPtr[i] = CefV8ValueCppToC::Wrap(arguments[i]); - } - - cef_v8value_t* retvalStruct = NULL; - cef_string_t exceptionStr = NULL; - - int rv = struct_->execute(struct_, name.c_str(), - CefV8ValueCppToC::Wrap(object), argsSize, argsStructPtr, &retvalStruct, - &exceptionStr); - if(retvalStruct) - retval = CefV8ValueCppToC::Unwrap(retvalStruct); - if(exceptionStr) { - exception = exceptionStr; - cef_string_free(exceptionStr); - } - - if(argsStructPtr) - delete [] argsStructPtr; - - return rv ? true : false; -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = - 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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 std::wstring& name, + CefRefPtr object, const CefV8ValueList& arguments, + CefRefPtr& retval, std::wstring& exception) +{ + if(CEF_MEMBER_MISSING(struct_, execute)) + return RV_CONTINUE; + + cef_v8value_t** argsStructPtr = NULL; + int argsSize = arguments.size(); + if(argsSize > 0) { + argsStructPtr = new cef_v8value_t*[argsSize]; + for(int i = 0; i < argsSize; ++i) + argsStructPtr[i] = CefV8ValueCppToC::Wrap(arguments[i]); + } + + cef_v8value_t* retvalStruct = NULL; + cef_string_t exceptionStr = NULL; + + int rv = struct_->execute(struct_, name.c_str(), + CefV8ValueCppToC::Wrap(object), argsSize, argsStructPtr, &retvalStruct, + &exceptionStr); + if(retvalStruct) + retval = CefV8ValueCppToC::Unwrap(retvalStruct); + if(exceptionStr) { + exception = exceptionStr; + cef_string_free(exceptionStr); + } + + if(argsStructPtr) + delete [] argsStructPtr; + + return rv ? true : false; +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/ctocpp/v8handler_ctocpp.h b/libcef_dll/ctocpp/v8handler_ctocpp.h index c62549abc..c907f9047 100644 --- a/libcef_dll/ctocpp/v8handler_ctocpp.h +++ b/libcef_dll/ctocpp/v8handler_ctocpp.h @@ -1,41 +1,41 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _V8HANDLER_CTOCPP_H -#define _V8HANDLER_CTOCPP_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefV8HandlerCToCpp(cef_v8handler_t* str) - : CefCToCpp(str) {} - virtual ~CefV8HandlerCToCpp() {} - - // CefV8Handler methods - virtual bool Execute(const std::wstring& name, CefRefPtr object, - const CefV8ValueList& arguments, CefRefPtr& retval, - std::wstring& exception); -}; - -#endif // BUILDING_CEF_SHARED -#endif // _V8HANDLER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _V8HANDLER_CTOCPP_H +#define _V8HANDLER_CTOCPP_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefV8HandlerCToCpp(cef_v8handler_t* str) + : CefCToCpp(str) {} + virtual ~CefV8HandlerCToCpp() {} + + // CefV8Handler methods + virtual bool Execute(const std::wstring& name, CefRefPtr object, + const CefV8ValueList& arguments, CefRefPtr& retval, + std::wstring& exception); +}; + +#endif // BUILDING_CEF_SHARED +#endif // _V8HANDLER_CTOCPP_H + diff --git a/libcef_dll/ctocpp/v8value_ctocpp.cc b/libcef_dll/ctocpp/v8value_ctocpp.cc index 709db2a3b..623f5d5bc 100644 --- a/libcef_dll/ctocpp/v8value_ctocpp.cc +++ b/libcef_dll/ctocpp/v8value_ctocpp.cc @@ -1,389 +1,389 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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/v8handler_cpptoc.h" -#include "libcef_dll/ctocpp/v8value_ctocpp.h" - - -// STATIC METHODS - Body may be edited by hand. - -CefRefPtr CefV8Value::CreateUndefined() -{ - cef_v8value_t* impl = cef_v8value_create_undefined(); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateNull() -{ - cef_v8value_t* impl = cef_v8value_create_null(); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateBool(bool value) -{ - cef_v8value_t* impl = cef_v8value_create_bool(value); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateInt(int value) -{ - cef_v8value_t* impl = cef_v8value_create_int(value); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateDouble(double value) -{ - cef_v8value_t* impl = cef_v8value_create_double(value); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateString(const std::wstring& value) -{ - cef_v8value_t* impl = cef_v8value_create_string(value.c_str()); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateObject(CefRefPtr user_data) -{ - cef_base_t* baseStruct = NULL; - if(user_data) - baseStruct = CefBaseCppToC::Wrap(user_data); - - cef_v8value_t* impl = cef_v8value_create_object(baseStruct); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateArray() -{ - cef_v8value_t* impl = cef_v8value_create_array(); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - -CefRefPtr CefV8Value::CreateFunction(const std::wstring& name, - CefRefPtr handler) -{ - cef_v8handler_t* handlerStruct = NULL; - if(handler.get()) - handlerStruct = CefV8HandlerCppToC::Wrap(handler); - - cef_v8value_t* impl = cef_v8value_create_function(name.c_str(), - handlerStruct); - if(impl) - return CefV8ValueCToCpp::Wrap(impl); - return NULL; -} - - -// VIRTUAL METHODS - Body may be edited by hand. - -bool CefV8ValueCToCpp::IsUndefined() -{ - if(CEF_MEMBER_MISSING(struct_, is_undefined)) - return false; - - return struct_->is_undefined(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsNull() -{ - if(CEF_MEMBER_MISSING(struct_, is_null)) - return false; - - return struct_->is_null(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsBool() -{ - if(CEF_MEMBER_MISSING(struct_, is_bool)) - return false; - - return struct_->is_bool(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsInt() -{ - if(CEF_MEMBER_MISSING(struct_, is_int)) - return false; - - return struct_->is_int(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsDouble() -{ - if(CEF_MEMBER_MISSING(struct_, is_double)) - return false; - - return struct_->is_double(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsString() -{ - if(CEF_MEMBER_MISSING(struct_, is_string)) - return false; - - return struct_->is_string(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsObject() -{ - if(CEF_MEMBER_MISSING(struct_, is_object)) - return false; - - return struct_->is_object(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsArray() -{ - if(CEF_MEMBER_MISSING(struct_, is_array)) - return false; - - return struct_->is_array(struct_)?true:false; -} - -bool CefV8ValueCToCpp::IsFunction() -{ - if(CEF_MEMBER_MISSING(struct_, is_function)) - return false; - - return struct_->is_function(struct_)?true:false; -} - -bool CefV8ValueCToCpp::GetBoolValue() -{ - if(CEF_MEMBER_MISSING(struct_, get_bool_value)) - return false; - - return struct_->get_bool_value(struct_)?true:false; -} - -int CefV8ValueCToCpp::GetIntValue() -{ - if(CEF_MEMBER_MISSING(struct_, get_int_value)) - return 0; - - return struct_->get_int_value(struct_); -} - -double CefV8ValueCToCpp::GetDoubleValue() -{ - if(CEF_MEMBER_MISSING(struct_, get_double_value)) - return 0.; - - return struct_->get_double_value(struct_); -} - -std::wstring CefV8ValueCToCpp::GetStringValue() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_string_value)) - return str; - - cef_string_t cef_str = struct_->get_string_value(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - -bool CefV8ValueCToCpp::HasValue(const std::wstring& key) -{ - if(CEF_MEMBER_MISSING(struct_, has_value_bykey)) - return false; - - return struct_->has_value_bykey(struct_, key.c_str())?true:false; -} - -bool CefV8ValueCToCpp::HasValue(int index) -{ - if(CEF_MEMBER_MISSING(struct_, has_value_byindex)) - return false; - - return struct_->has_value_byindex(struct_, index)?true:false; -} - -bool CefV8ValueCToCpp::DeleteValue(const std::wstring& key) -{ - if(CEF_MEMBER_MISSING(struct_, delete_value_bykey)) - return false; - - return struct_->delete_value_bykey(struct_, key.c_str())?true:false; -} - -bool CefV8ValueCToCpp::DeleteValue(int index) -{ - if(CEF_MEMBER_MISSING(struct_, delete_value_byindex)) - return false; - - return struct_->delete_value_byindex(struct_, index)?true:false; -} - -CefRefPtr CefV8ValueCToCpp::GetValue(const std::wstring& key) -{ - if(CEF_MEMBER_MISSING(struct_, get_value_bykey)) - return false; - - cef_v8value_t* valueStruct = struct_->get_value_bykey(struct_, key.c_str()); - if(valueStruct) - return CefV8ValueCToCpp::Wrap(valueStruct); - return NULL; -} - -CefRefPtr CefV8ValueCToCpp::GetValue(int index) -{ - if(CEF_MEMBER_MISSING(struct_, get_value_byindex)) - return false; - - cef_v8value_t* valueStruct = struct_->get_value_byindex(struct_, index); - if(valueStruct) - return CefV8ValueCToCpp::Wrap(valueStruct); - return NULL; -} - -bool CefV8ValueCToCpp::SetValue(const std::wstring& key, - CefRefPtr value) -{ - if(CEF_MEMBER_MISSING(struct_, set_value_bykey)) - return false; - - return struct_->set_value_bykey(struct_, key.c_str(), - CefV8ValueCToCpp::Unwrap(value))?true:false; -} - -bool CefV8ValueCToCpp::SetValue(int index, CefRefPtr value) -{ - if(CEF_MEMBER_MISSING(struct_, set_value_byindex)) - return false; - - return struct_->set_value_byindex(struct_, index, - CefV8ValueCToCpp::Unwrap(value))?true:false; -} - -bool CefV8ValueCToCpp::GetKeys(std::vector& keys) -{ - if(CEF_MEMBER_MISSING(struct_, get_keys)) - return false; - - cef_string_list_t list = cef_string_list_alloc(); - if(struct_->get_keys(struct_, list)) { - cef_string_t str; - int size = cef_string_list_size(list); - for(int i = 0; i < size; ++i) { - str = cef_string_list_value(list, i); - keys.push_back(str); - cef_string_free(str); - } - cef_string_list_free(list); - return true; - } - return false; -} - -CefRefPtr CefV8ValueCToCpp::GetUserData() -{ - if(CEF_MEMBER_MISSING(struct_, get_user_data)) - return false; - - cef_base_t* baseStruct = struct_->get_user_data(struct_); - if(baseStruct) - return CefBaseCppToC::Unwrap(baseStruct); - return NULL; -} - -int CefV8ValueCToCpp::GetArrayLength() -{ - if(CEF_MEMBER_MISSING(struct_, get_array_length)) - return 0; - - return struct_->get_array_length(struct_); -} - -std::wstring CefV8ValueCToCpp::GetFunctionName() -{ - std::wstring str; - if(CEF_MEMBER_MISSING(struct_, get_function_name)) - return str; - - cef_string_t cef_str = struct_->get_function_name(struct_); - if(cef_str) { - str = cef_str; - cef_string_free(cef_str); - } - return str; -} - -CefRefPtr CefV8ValueCToCpp::GetFunctionHandler() -{ - if(CEF_MEMBER_MISSING(struct_, get_function_handler)) - return false; - - cef_v8handler_t* handlerStruct = struct_->get_function_handler(struct_); - if(handlerStruct) - return CefV8HandlerCppToC::Unwrap(handlerStruct); - return NULL; -} - -bool CefV8ValueCToCpp::ExecuteFunction(CefRefPtr object, - const CefV8ValueList& arguments, CefRefPtr& retval, - std::wstring& exception) -{ - if(CEF_MEMBER_MISSING(struct_, execute_function)) - return RV_CONTINUE; - - cef_v8value_t** argsStructPtr = NULL; - int argsSize = arguments.size(); - if(argsSize > 0) { - argsStructPtr = new cef_v8value_t*[argsSize]; - for(int i = 0; i < argsSize; ++i) - argsStructPtr[i] = CefV8ValueCToCpp::Unwrap(arguments[i]); - } - - cef_v8value_t* retvalStruct = NULL; - cef_string_t exceptionStr = NULL; - - int rv = struct_->execute_function(struct_, CefV8ValueCToCpp::Unwrap(object), - argsSize, argsStructPtr, &retvalStruct, &exceptionStr); - if(retvalStruct) - retval = CefV8ValueCToCpp::Wrap(retvalStruct); - if(exceptionStr) { - exception = exceptionStr; - cef_string_free(exceptionStr); - } - - if(argsStructPtr) - delete [] argsStructPtr; - - return rv?true:false; -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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/v8handler_cpptoc.h" +#include "libcef_dll/ctocpp/v8value_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefV8Value::CreateUndefined() +{ + cef_v8value_t* impl = cef_v8value_create_undefined(); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateNull() +{ + cef_v8value_t* impl = cef_v8value_create_null(); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateBool(bool value) +{ + cef_v8value_t* impl = cef_v8value_create_bool(value); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateInt(int value) +{ + cef_v8value_t* impl = cef_v8value_create_int(value); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateDouble(double value) +{ + cef_v8value_t* impl = cef_v8value_create_double(value); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateString(const std::wstring& value) +{ + cef_v8value_t* impl = cef_v8value_create_string(value.c_str()); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateObject(CefRefPtr user_data) +{ + cef_base_t* baseStruct = NULL; + if(user_data) + baseStruct = CefBaseCppToC::Wrap(user_data); + + cef_v8value_t* impl = cef_v8value_create_object(baseStruct); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateArray() +{ + cef_v8value_t* impl = cef_v8value_create_array(); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + +CefRefPtr CefV8Value::CreateFunction(const std::wstring& name, + CefRefPtr handler) +{ + cef_v8handler_t* handlerStruct = NULL; + if(handler.get()) + handlerStruct = CefV8HandlerCppToC::Wrap(handler); + + cef_v8value_t* impl = cef_v8value_create_function(name.c_str(), + handlerStruct); + if(impl) + return CefV8ValueCToCpp::Wrap(impl); + return NULL; +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefV8ValueCToCpp::IsUndefined() +{ + if(CEF_MEMBER_MISSING(struct_, is_undefined)) + return false; + + return struct_->is_undefined(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsNull() +{ + if(CEF_MEMBER_MISSING(struct_, is_null)) + return false; + + return struct_->is_null(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsBool() +{ + if(CEF_MEMBER_MISSING(struct_, is_bool)) + return false; + + return struct_->is_bool(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsInt() +{ + if(CEF_MEMBER_MISSING(struct_, is_int)) + return false; + + return struct_->is_int(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsDouble() +{ + if(CEF_MEMBER_MISSING(struct_, is_double)) + return false; + + return struct_->is_double(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsString() +{ + if(CEF_MEMBER_MISSING(struct_, is_string)) + return false; + + return struct_->is_string(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsObject() +{ + if(CEF_MEMBER_MISSING(struct_, is_object)) + return false; + + return struct_->is_object(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsArray() +{ + if(CEF_MEMBER_MISSING(struct_, is_array)) + return false; + + return struct_->is_array(struct_)?true:false; +} + +bool CefV8ValueCToCpp::IsFunction() +{ + if(CEF_MEMBER_MISSING(struct_, is_function)) + return false; + + return struct_->is_function(struct_)?true:false; +} + +bool CefV8ValueCToCpp::GetBoolValue() +{ + if(CEF_MEMBER_MISSING(struct_, get_bool_value)) + return false; + + return struct_->get_bool_value(struct_)?true:false; +} + +int CefV8ValueCToCpp::GetIntValue() +{ + if(CEF_MEMBER_MISSING(struct_, get_int_value)) + return 0; + + return struct_->get_int_value(struct_); +} + +double CefV8ValueCToCpp::GetDoubleValue() +{ + if(CEF_MEMBER_MISSING(struct_, get_double_value)) + return 0.; + + return struct_->get_double_value(struct_); +} + +std::wstring CefV8ValueCToCpp::GetStringValue() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_string_value)) + return str; + + cef_string_t cef_str = struct_->get_string_value(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + +bool CefV8ValueCToCpp::HasValue(const std::wstring& key) +{ + if(CEF_MEMBER_MISSING(struct_, has_value_bykey)) + return false; + + return struct_->has_value_bykey(struct_, key.c_str())?true:false; +} + +bool CefV8ValueCToCpp::HasValue(int index) +{ + if(CEF_MEMBER_MISSING(struct_, has_value_byindex)) + return false; + + return struct_->has_value_byindex(struct_, index)?true:false; +} + +bool CefV8ValueCToCpp::DeleteValue(const std::wstring& key) +{ + if(CEF_MEMBER_MISSING(struct_, delete_value_bykey)) + return false; + + return struct_->delete_value_bykey(struct_, key.c_str())?true:false; +} + +bool CefV8ValueCToCpp::DeleteValue(int index) +{ + if(CEF_MEMBER_MISSING(struct_, delete_value_byindex)) + return false; + + return struct_->delete_value_byindex(struct_, index)?true:false; +} + +CefRefPtr CefV8ValueCToCpp::GetValue(const std::wstring& key) +{ + if(CEF_MEMBER_MISSING(struct_, get_value_bykey)) + return false; + + cef_v8value_t* valueStruct = struct_->get_value_bykey(struct_, key.c_str()); + if(valueStruct) + return CefV8ValueCToCpp::Wrap(valueStruct); + return NULL; +} + +CefRefPtr CefV8ValueCToCpp::GetValue(int index) +{ + if(CEF_MEMBER_MISSING(struct_, get_value_byindex)) + return false; + + cef_v8value_t* valueStruct = struct_->get_value_byindex(struct_, index); + if(valueStruct) + return CefV8ValueCToCpp::Wrap(valueStruct); + return NULL; +} + +bool CefV8ValueCToCpp::SetValue(const std::wstring& key, + CefRefPtr value) +{ + if(CEF_MEMBER_MISSING(struct_, set_value_bykey)) + return false; + + return struct_->set_value_bykey(struct_, key.c_str(), + CefV8ValueCToCpp::Unwrap(value))?true:false; +} + +bool CefV8ValueCToCpp::SetValue(int index, CefRefPtr value) +{ + if(CEF_MEMBER_MISSING(struct_, set_value_byindex)) + return false; + + return struct_->set_value_byindex(struct_, index, + CefV8ValueCToCpp::Unwrap(value))?true:false; +} + +bool CefV8ValueCToCpp::GetKeys(std::vector& keys) +{ + if(CEF_MEMBER_MISSING(struct_, get_keys)) + return false; + + cef_string_list_t list = cef_string_list_alloc(); + if(struct_->get_keys(struct_, list)) { + cef_string_t str; + int size = cef_string_list_size(list); + for(int i = 0; i < size; ++i) { + str = cef_string_list_value(list, i); + keys.push_back(str); + cef_string_free(str); + } + cef_string_list_free(list); + return true; + } + return false; +} + +CefRefPtr CefV8ValueCToCpp::GetUserData() +{ + if(CEF_MEMBER_MISSING(struct_, get_user_data)) + return false; + + cef_base_t* baseStruct = struct_->get_user_data(struct_); + if(baseStruct) + return CefBaseCppToC::Unwrap(baseStruct); + return NULL; +} + +int CefV8ValueCToCpp::GetArrayLength() +{ + if(CEF_MEMBER_MISSING(struct_, get_array_length)) + return 0; + + return struct_->get_array_length(struct_); +} + +std::wstring CefV8ValueCToCpp::GetFunctionName() +{ + std::wstring str; + if(CEF_MEMBER_MISSING(struct_, get_function_name)) + return str; + + cef_string_t cef_str = struct_->get_function_name(struct_); + if(cef_str) { + str = cef_str; + cef_string_free(cef_str); + } + return str; +} + +CefRefPtr CefV8ValueCToCpp::GetFunctionHandler() +{ + if(CEF_MEMBER_MISSING(struct_, get_function_handler)) + return false; + + cef_v8handler_t* handlerStruct = struct_->get_function_handler(struct_); + if(handlerStruct) + return CefV8HandlerCppToC::Unwrap(handlerStruct); + return NULL; +} + +bool CefV8ValueCToCpp::ExecuteFunction(CefRefPtr object, + const CefV8ValueList& arguments, CefRefPtr& retval, + std::wstring& exception) +{ + if(CEF_MEMBER_MISSING(struct_, execute_function)) + return RV_CONTINUE; + + cef_v8value_t** argsStructPtr = NULL; + int argsSize = arguments.size(); + if(argsSize > 0) { + argsStructPtr = new cef_v8value_t*[argsSize]; + for(int i = 0; i < argsSize; ++i) + argsStructPtr[i] = CefV8ValueCToCpp::Unwrap(arguments[i]); + } + + cef_v8value_t* retvalStruct = NULL; + cef_string_t exceptionStr = NULL; + + int rv = struct_->execute_function(struct_, CefV8ValueCToCpp::Unwrap(object), + argsSize, argsStructPtr, &retvalStruct, &exceptionStr); + if(retvalStruct) + retval = CefV8ValueCToCpp::Wrap(retvalStruct); + if(exceptionStr) { + exception = exceptionStr; + cef_string_free(exceptionStr); + } + + if(argsStructPtr) + delete [] argsStructPtr; + + return rv?true:false; +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8value_ctocpp.h b/libcef_dll/ctocpp/v8value_ctocpp.h index 0061040d7..7e3c8c9ee 100644 --- a/libcef_dll/ctocpp/v8value_ctocpp.h +++ b/libcef_dll/ctocpp/v8value_ctocpp.h @@ -1,67 +1,67 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _V8VALUE_CTOCPP_H -#define _V8VALUE_CTOCPP_H - -#ifndef USING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") -#else // USING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - CefV8ValueCToCpp(cef_v8value_t* str) - : CefCToCpp(str) {} - virtual ~CefV8ValueCToCpp() {} - - // CefV8Value methods - virtual bool IsUndefined(); - virtual bool IsNull(); - virtual bool IsBool(); - virtual bool IsInt(); - virtual bool IsDouble(); - virtual bool IsString(); - virtual bool IsObject(); - virtual bool IsArray(); - virtual bool IsFunction(); - virtual bool GetBoolValue(); - virtual int GetIntValue(); - virtual double GetDoubleValue(); - virtual std::wstring GetStringValue(); - virtual bool HasValue(const std::wstring& key); - virtual bool HasValue(int index); - virtual bool DeleteValue(const std::wstring& key); - virtual bool DeleteValue(int index); - virtual CefRefPtr GetValue(const std::wstring& key); - virtual CefRefPtr GetValue(int index); - virtual bool SetValue(const std::wstring& key, CefRefPtr value); - virtual bool SetValue(int index, CefRefPtr value); - virtual bool GetKeys(std::vector& keys); - virtual CefRefPtr GetUserData(); - virtual int GetArrayLength(); - virtual std::wstring GetFunctionName(); - virtual CefRefPtr GetFunctionHandler(); - virtual bool ExecuteFunction(CefRefPtr object, - const CefV8ValueList& arguments, CefRefPtr& retval, - std::wstring& exception); -}; - -#endif // USING_CEF_SHARED -#endif // _V8VALUE_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _V8VALUE_CTOCPP_H +#define _V8VALUE_CTOCPP_H + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + CefV8ValueCToCpp(cef_v8value_t* str) + : CefCToCpp(str) {} + virtual ~CefV8ValueCToCpp() {} + + // CefV8Value methods + virtual bool IsUndefined(); + virtual bool IsNull(); + virtual bool IsBool(); + virtual bool IsInt(); + virtual bool IsDouble(); + virtual bool IsString(); + virtual bool IsObject(); + virtual bool IsArray(); + virtual bool IsFunction(); + virtual bool GetBoolValue(); + virtual int GetIntValue(); + virtual double GetDoubleValue(); + virtual std::wstring GetStringValue(); + virtual bool HasValue(const std::wstring& key); + virtual bool HasValue(int index); + virtual bool DeleteValue(const std::wstring& key); + virtual bool DeleteValue(int index); + virtual CefRefPtr GetValue(const std::wstring& key); + virtual CefRefPtr GetValue(int index); + virtual bool SetValue(const std::wstring& key, CefRefPtr value); + virtual bool SetValue(int index, CefRefPtr value); + virtual bool GetKeys(std::vector& keys); + virtual CefRefPtr GetUserData(); + virtual int GetArrayLength(); + virtual std::wstring GetFunctionName(); + virtual CefRefPtr GetFunctionHandler(); + virtual bool ExecuteFunction(CefRefPtr object, + const CefV8ValueList& arguments, CefRefPtr& retval, + std::wstring& exception); +}; + +#endif // USING_CEF_SHARED +#endif // _V8VALUE_CTOCPP_H + diff --git a/libcef_dll/ctocpp/write_handler_ctocpp.cc b/libcef_dll/ctocpp/write_handler_ctocpp.cc index 5d41cd37f..3355972a9 100644 --- a/libcef_dll/ctocpp/write_handler_ctocpp.cc +++ b/libcef_dll/ctocpp/write_handler_ctocpp.cc @@ -1,55 +1,55 @@ -// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method 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; - - return struct_->write(struct_, ptr, size, n); -} - -int CefWriteHandlerCToCpp::Seek(long offset, int whence) -{ - if(CEF_MEMBER_MISSING(struct_, seek)) - return 0; - - return struct_->seek(struct_, offset, whence); -} - -long CefWriteHandlerCToCpp::Tell() -{ - if(CEF_MEMBER_MISSING(struct_, tell)) - return 0; - - return struct_->tell(struct_); -} - -int CefWriteHandlerCToCpp::Flush() -{ - if(CEF_MEMBER_MISSING(struct_, flush)) - return 0; - - return struct_->flush(struct_); -} - - -#ifdef _DEBUG -long CefCToCpp::DebugObjCt = 0; -#endif - +// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method 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; + + return struct_->write(struct_, ptr, size, n); +} + +int CefWriteHandlerCToCpp::Seek(long offset, int whence) +{ + if(CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + return struct_->seek(struct_, offset, whence); +} + +long CefWriteHandlerCToCpp::Tell() +{ + if(CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + return struct_->tell(struct_); +} + +int CefWriteHandlerCToCpp::Flush() +{ + if(CEF_MEMBER_MISSING(struct_, flush)) + return 0; + + return struct_->flush(struct_); +} + + +#ifdef _DEBUG +long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/write_handler_ctocpp.h b/libcef_dll/ctocpp/write_handler_ctocpp.h index c7dd9dabf..a5fea1010 100644 --- a/libcef_dll/ctocpp/write_handler_ctocpp.h +++ b/libcef_dll/ctocpp/write_handler_ctocpp.h @@ -1,44 +1,44 @@ -// 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. -// -// ------------------------------------------------------------------------- -// -// 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 _WRITEHANDLER_CTOCPP_H -#define _WRITEHANDLER_CTOCPP_H - -#ifndef BUILDING_CEF_SHARED -#pragma message("Warning: "__FILE__" may be accessed DLL-side only") -#else // BUILDING_CEF_SHARED - -#include "include/cef.h" -#include "include/cef_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: - 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); - virtual int Seek(long offset, int whence); - virtual long Tell(); - virtual int Flush(); -}; - -#endif // BUILDING_CEF_SHARED -#endif // _WRITEHANDLER_CTOCPP_H - +// 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. +// +// ------------------------------------------------------------------------- +// +// 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 _WRITEHANDLER_CTOCPP_H +#define _WRITEHANDLER_CTOCPP_H + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef.h" +#include "include/cef_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: + 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); + virtual int Seek(long offset, int whence); + virtual long Tell(); + virtual int Flush(); +}; + +#endif // BUILDING_CEF_SHARED +#endif // _WRITEHANDLER_CTOCPP_H + diff --git a/libcef_dll/libcef_dll.cc b/libcef_dll/libcef_dll.cc index 4a0a2c293..6ba3aea69 100644 --- a/libcef_dll/libcef_dll.cc +++ b/libcef_dll/libcef_dll.cc @@ -1,161 +1,161 @@ -// 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/cef.h" -#include "include/cef_capi.h" -#include "include/cef_nplugin.h" -#include "include/cef_nplugin_capi.h" -#include "cef_logging.h" -#include "cpptoc/browser_cpptoc.h" -#include "cpptoc/post_data_cpptoc.h" -#include "cpptoc/post_data_element_cpptoc.h" -#include "cpptoc/request_cpptoc.h" -#include "cpptoc/stream_reader_cpptoc.h" -#include "cpptoc/stream_writer_cpptoc.h" -#include "cpptoc/v8value_cpptoc.h" -#include "ctocpp/handler_ctocpp.h" -#include "ctocpp/read_handler_ctocpp.h" -#include "ctocpp/scheme_handler_ctocpp.h" -#include "ctocpp/scheme_handler_factory_ctocpp.h" -#include "ctocpp/task_ctocpp.h" -#include "ctocpp/v8handler_ctocpp.h" -#include "ctocpp/write_handler_ctocpp.h" -#include "base/string_split.h" - - -CEF_EXPORT int cef_initialize(int multi_threaded_message_loop, - const wchar_t* cache_path) -{ - std::wstring cachePath; - if(cache_path) - cachePath = cache_path; - return CefInitialize(multi_threaded_message_loop?true:false, cachePath); -} - -CEF_EXPORT void cef_shutdown() -{ - CefShutdown(); - -#ifdef _DEBUG - // Check that all wrapper objects have been destroyed - DCHECK(CefBrowserCppToC::DebugObjCt == 0); - DCHECK(CefRequestCppToC::DebugObjCt == 0); - DCHECK(CefPostDataCppToC::DebugObjCt == 0); - DCHECK(CefPostDataElementCppToC::DebugObjCt == 0); - DCHECK(CefStreamReaderCppToC::DebugObjCt == 0); - DCHECK(CefStreamWriterCppToC::DebugObjCt == 0); - DCHECK(CefV8ValueCppToC::DebugObjCt == 0); - DCHECK(CefHandlerCToCpp::DebugObjCt == 0); - DCHECK(CefReadHandlerCToCpp::DebugObjCt == 0); - DCHECK(CefSchemeHandlerCToCpp::DebugObjCt == 0); - DCHECK(CefSchemeHandlerFactoryCToCpp::DebugObjCt == 0); - DCHECK(CefV8HandlerCToCpp::DebugObjCt == 0); - DCHECK(CefWriteHandlerCToCpp::DebugObjCt == 0); -#endif // _DEBUG -} - -CEF_EXPORT void cef_do_message_loop_work() -{ - CefDoMessageLoopWork(); -} - -CEF_EXPORT int cef_register_extension(const wchar_t* extension_name, - const wchar_t* javascript_code, - struct _cef_v8handler_t* handler) -{ - DCHECK(extension_name); - DCHECK(javascript_code); - - CefRefPtr handlerPtr; - std::wstring nameStr, codeStr; - - if(handler) - handlerPtr = CefV8HandlerCToCpp::Wrap(handler); - if(extension_name) - nameStr = extension_name; - if(javascript_code) - codeStr = javascript_code; - - return CefRegisterExtension(nameStr, codeStr, handlerPtr); -} - -CEF_EXPORT int cef_register_plugin(const cef_plugin_info_t* plugin_info) -{ - CefPluginInfo pluginInfo; - - pluginInfo.unique_name = plugin_info->unique_name; - pluginInfo.display_name = plugin_info->display_name; - pluginInfo.version = plugin_info->version; - pluginInfo.description = plugin_info->description; - - std::vector mime_types, file_extensions; - std::vector descriptions; - SplitString(plugin_info->mime_types, '|', &mime_types); - SplitString(plugin_info->file_extensions, '|', &file_extensions); - SplitString(plugin_info->type_descriptions, '|', &descriptions); - - for (size_t i = 0; i < mime_types.size(); ++i) { - CefPluginMimeType mimeType; - - mimeType.mime_type = mime_types[i]; - - if (file_extensions.size() > i) - SplitString(file_extensions[i], ',', &mimeType.file_extensions); - - if (descriptions.size() > i) - mimeType.description = descriptions[i]; - - pluginInfo.mime_types.push_back(mimeType); - } - - pluginInfo.np_getentrypoints = plugin_info->np_getentrypoints; - pluginInfo.np_initialize = plugin_info->np_initialize; - pluginInfo.np_shutdown = plugin_info->np_shutdown; - - return CefRegisterPlugin(pluginInfo); -} - -CEF_EXPORT int cef_register_scheme(const wchar_t* scheme_name, - const wchar_t* host_name, struct _cef_scheme_handler_factory_t* factory) -{ - DCHECK(scheme_name); - DCHECK(factory); - if(!scheme_name || !factory) - return 0; - - std::wstring nameStr, codeStr; - - if(scheme_name) - nameStr = scheme_name; - if(host_name) - codeStr = host_name; - - return CefRegisterScheme(nameStr, codeStr, - CefSchemeHandlerFactoryCToCpp::Wrap(factory)); -} - -CEF_EXPORT int cef_currently_on(cef_thread_id_t threadId) -{ - return CefCurrentlyOn(threadId); -} - -CEF_EXPORT int cef_post_task(cef_thread_id_t threadId, - struct _cef_task_t* task) -{ - DCHECK(task); - if(!task) - return 0; - - return CefPostTask(threadId, CefTaskCToCpp::Wrap(task)); -} - -CEF_EXPORT int cef_post_delayed_task(cef_thread_id_t threadId, - struct _cef_task_t* task, long delay_ms) -{ - DCHECK(task); - if(!task) - return 0; - - return CefPostDelayedTask(threadId, CefTaskCToCpp::Wrap(task), delay_ms); +// 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/cef.h" +#include "include/cef_capi.h" +#include "include/cef_nplugin.h" +#include "include/cef_nplugin_capi.h" +#include "cef_logging.h" +#include "cpptoc/browser_cpptoc.h" +#include "cpptoc/post_data_cpptoc.h" +#include "cpptoc/post_data_element_cpptoc.h" +#include "cpptoc/request_cpptoc.h" +#include "cpptoc/stream_reader_cpptoc.h" +#include "cpptoc/stream_writer_cpptoc.h" +#include "cpptoc/v8value_cpptoc.h" +#include "ctocpp/handler_ctocpp.h" +#include "ctocpp/read_handler_ctocpp.h" +#include "ctocpp/scheme_handler_ctocpp.h" +#include "ctocpp/scheme_handler_factory_ctocpp.h" +#include "ctocpp/task_ctocpp.h" +#include "ctocpp/v8handler_ctocpp.h" +#include "ctocpp/write_handler_ctocpp.h" +#include "base/string_split.h" + + +CEF_EXPORT int cef_initialize(int multi_threaded_message_loop, + const wchar_t* cache_path) +{ + std::wstring cachePath; + if(cache_path) + cachePath = cache_path; + return CefInitialize(multi_threaded_message_loop?true:false, cachePath); +} + +CEF_EXPORT void cef_shutdown() +{ + CefShutdown(); + +#ifdef _DEBUG + // Check that all wrapper objects have been destroyed + DCHECK(CefBrowserCppToC::DebugObjCt == 0); + DCHECK(CefRequestCppToC::DebugObjCt == 0); + DCHECK(CefPostDataCppToC::DebugObjCt == 0); + DCHECK(CefPostDataElementCppToC::DebugObjCt == 0); + DCHECK(CefStreamReaderCppToC::DebugObjCt == 0); + DCHECK(CefStreamWriterCppToC::DebugObjCt == 0); + DCHECK(CefV8ValueCppToC::DebugObjCt == 0); + DCHECK(CefHandlerCToCpp::DebugObjCt == 0); + DCHECK(CefReadHandlerCToCpp::DebugObjCt == 0); + DCHECK(CefSchemeHandlerCToCpp::DebugObjCt == 0); + DCHECK(CefSchemeHandlerFactoryCToCpp::DebugObjCt == 0); + DCHECK(CefV8HandlerCToCpp::DebugObjCt == 0); + DCHECK(CefWriteHandlerCToCpp::DebugObjCt == 0); +#endif // _DEBUG +} + +CEF_EXPORT void cef_do_message_loop_work() +{ + CefDoMessageLoopWork(); +} + +CEF_EXPORT int cef_register_extension(const wchar_t* extension_name, + const wchar_t* javascript_code, + struct _cef_v8handler_t* handler) +{ + DCHECK(extension_name); + DCHECK(javascript_code); + + CefRefPtr handlerPtr; + std::wstring nameStr, codeStr; + + if(handler) + handlerPtr = CefV8HandlerCToCpp::Wrap(handler); + if(extension_name) + nameStr = extension_name; + if(javascript_code) + codeStr = javascript_code; + + return CefRegisterExtension(nameStr, codeStr, handlerPtr); +} + +CEF_EXPORT int cef_register_plugin(const cef_plugin_info_t* plugin_info) +{ + CefPluginInfo pluginInfo; + + pluginInfo.unique_name = plugin_info->unique_name; + pluginInfo.display_name = plugin_info->display_name; + pluginInfo.version = plugin_info->version; + pluginInfo.description = plugin_info->description; + + std::vector mime_types, file_extensions; + std::vector descriptions; + SplitString(plugin_info->mime_types, '|', &mime_types); + SplitString(plugin_info->file_extensions, '|', &file_extensions); + SplitString(plugin_info->type_descriptions, '|', &descriptions); + + for (size_t i = 0; i < mime_types.size(); ++i) { + CefPluginMimeType mimeType; + + mimeType.mime_type = mime_types[i]; + + if (file_extensions.size() > i) + SplitString(file_extensions[i], ',', &mimeType.file_extensions); + + if (descriptions.size() > i) + mimeType.description = descriptions[i]; + + pluginInfo.mime_types.push_back(mimeType); + } + + pluginInfo.np_getentrypoints = plugin_info->np_getentrypoints; + pluginInfo.np_initialize = plugin_info->np_initialize; + pluginInfo.np_shutdown = plugin_info->np_shutdown; + + return CefRegisterPlugin(pluginInfo); +} + +CEF_EXPORT int cef_register_scheme(const wchar_t* scheme_name, + const wchar_t* host_name, struct _cef_scheme_handler_factory_t* factory) +{ + DCHECK(scheme_name); + DCHECK(factory); + if(!scheme_name || !factory) + return 0; + + std::wstring nameStr, codeStr; + + if(scheme_name) + nameStr = scheme_name; + if(host_name) + codeStr = host_name; + + return CefRegisterScheme(nameStr, codeStr, + CefSchemeHandlerFactoryCToCpp::Wrap(factory)); +} + +CEF_EXPORT int cef_currently_on(cef_thread_id_t threadId) +{ + return CefCurrentlyOn(threadId); +} + +CEF_EXPORT int cef_post_task(cef_thread_id_t threadId, + struct _cef_task_t* task) +{ + DCHECK(task); + if(!task) + return 0; + + return CefPostTask(threadId, CefTaskCToCpp::Wrap(task)); +} + +CEF_EXPORT int cef_post_delayed_task(cef_thread_id_t threadId, + struct _cef_task_t* task, long delay_ms) +{ + DCHECK(task); + if(!task) + return 0; + + return CefPostDelayedTask(threadId, CefTaskCToCpp::Wrap(task), delay_ms); } \ No newline at end of file diff --git a/libcef_dll/resource.h b/libcef_dll/resource.h index 61c1885e9..9553e1997 100644 --- a/libcef_dll/resource.h +++ b/libcef_dll/resource.h @@ -1,19 +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 +//{{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/libcef_dll/transfer_util.cpp b/libcef_dll/transfer_util.cpp index 1a15b2ecd..461bf8074 100644 --- a/libcef_dll/transfer_util.cpp +++ b/libcef_dll/transfer_util.cpp @@ -1,68 +1,68 @@ -// 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_map_contents(cef_string_map_t fromMap, - std::map& toMap) -{ - int size = cef_string_map_size(fromMap); - cef_string_t key, value; - std::wstring keystr, valuestr; - - for(int i = 0; i < size; ++i) { - key = cef_string_map_key(fromMap, i); - value = cef_string_map_value(fromMap, i); - - if(key) { - keystr = key; - cef_string_free(key); - } else if(!keystr.empty()) - keystr.clear(); - - if(value) { - valuestr = value; - cef_string_free(value); - } else if(!valuestr.empty()) - valuestr.clear(); - - toMap.insert(std::pair(keystr, valuestr)); - } -} - -void transfer_string_map_contents(const std::map& fromMap, - cef_string_map_t toMap) -{ - std::map::const_iterator it = fromMap.begin(); - for(; it != fromMap.end(); ++it) { - cef_string_map_append(toMap, it->first.c_str(), it->second.c_str()); - } -} - -void transfer_string_contents(const std::wstring& fromString, - cef_string_t* toString) -{ - if(*toString == NULL || *toString != fromString) { - if(*toString) { - cef_string_free(*toString); - *toString = NULL; - } - if(!fromString.empty()) - *toString = cef_string_alloc(fromString.c_str()); - } -} - -void transfer_string_contents(cef_string_t fromString, std::wstring& toString, - bool freeFromString) -{ - if(fromString == NULL || fromString != toString) { - if(fromString) { - toString = fromString; - if(freeFromString) - cef_string_free(fromString); - } else if(!toString.empty()) - toString.clear(); - } -} +// 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_map_contents(cef_string_map_t fromMap, + std::map& toMap) +{ + int size = cef_string_map_size(fromMap); + cef_string_t key, value; + std::wstring keystr, valuestr; + + for(int i = 0; i < size; ++i) { + key = cef_string_map_key(fromMap, i); + value = cef_string_map_value(fromMap, i); + + if(key) { + keystr = key; + cef_string_free(key); + } else if(!keystr.empty()) + keystr.clear(); + + if(value) { + valuestr = value; + cef_string_free(value); + } else if(!valuestr.empty()) + valuestr.clear(); + + toMap.insert(std::pair(keystr, valuestr)); + } +} + +void transfer_string_map_contents(const std::map& fromMap, + cef_string_map_t toMap) +{ + std::map::const_iterator it = fromMap.begin(); + for(; it != fromMap.end(); ++it) { + cef_string_map_append(toMap, it->first.c_str(), it->second.c_str()); + } +} + +void transfer_string_contents(const std::wstring& fromString, + cef_string_t* toString) +{ + if(*toString == NULL || *toString != fromString) { + if(*toString) { + cef_string_free(*toString); + *toString = NULL; + } + if(!fromString.empty()) + *toString = cef_string_alloc(fromString.c_str()); + } +} + +void transfer_string_contents(cef_string_t fromString, std::wstring& toString, + bool freeFromString) +{ + if(fromString == NULL || fromString != toString) { + if(fromString) { + toString = fromString; + if(freeFromString) + cef_string_free(fromString); + } else if(!toString.empty()) + toString.clear(); + } +} diff --git a/libcef_dll/transfer_util.h b/libcef_dll/transfer_util.h index ed5557764..fad7e0eb7 100644 --- a/libcef_dll/transfer_util.h +++ b/libcef_dll/transfer_util.h @@ -1,25 +1,25 @@ -// 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 _TRANSFER_UTIL_H -#define _TRANSFER_UTIL_H - -#include "include/cef_string.h" -#include "include/cef_string_map.h" -#include -#include - -// Copy contents from one map type to another. -void transfer_string_map_contents(cef_string_map_t fromMap, - std::map& toMap); -void transfer_string_map_contents(const std::map& fromMap, - cef_string_map_t toMap); - -// Copy the contents from one string type to another. -void transfer_string_contents(const std::wstring& fromString, - cef_string_t* toString); -void transfer_string_contents(cef_string_t fromString, std::wstring& toString, - bool freeFromString); - -#endif // _TRANSFER_UTIL_H +// 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 _TRANSFER_UTIL_H +#define _TRANSFER_UTIL_H + +#include "include/cef_string.h" +#include "include/cef_string_map.h" +#include +#include + +// Copy contents from one map type to another. +void transfer_string_map_contents(cef_string_map_t fromMap, + std::map& toMap); +void transfer_string_map_contents(const std::map& fromMap, + cef_string_map_t toMap); + +// Copy the contents from one string type to another. +void transfer_string_contents(const std::wstring& fromString, + cef_string_t* toString); +void transfer_string_contents(cef_string_t fromString, std::wstring& toString, + bool freeFromString); + +#endif // _TRANSFER_UTIL_H diff --git a/libcef_dll/wrapper/libcef_dll_wrapper.cc b/libcef_dll/wrapper/libcef_dll_wrapper.cc index 3f42948ee..f49dbcdd7 100644 --- a/libcef_dll/wrapper/libcef_dll_wrapper.cc +++ b/libcef_dll/wrapper/libcef_dll_wrapper.cc @@ -1,131 +1,131 @@ -// 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/cef.h" -#include "include/cef_capi.h" -#include "include/cef_nplugin.h" -#include "include/cef_nplugin_capi.h" -#include "libcef_dll/cpptoc/handler_cpptoc.h" -#include "libcef_dll/cpptoc/read_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/v8handler_cpptoc.h" -#include "libcef_dll/cpptoc/write_handler_cpptoc.h" -#include "libcef_dll/ctocpp/browser_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/stream_reader_ctocpp.h" -#include "libcef_dll/ctocpp/stream_writer_ctocpp.h" -#include "libcef_dll/ctocpp/v8value_ctocpp.h" - - -bool CefInitialize(bool multi_threaded_message_loop, - const std::wstring& cache_path) -{ - return cef_initialize(multi_threaded_message_loop, cache_path.c_str()) - ?true:false; -} - -void CefShutdown() -{ - cef_shutdown(); - -#ifdef _DEBUG - // Check that all wrapper objects have been destroyed - DCHECK(CefHandlerCppToC::DebugObjCt == 0); - DCHECK(CefReadHandlerCppToC::DebugObjCt == 0); - DCHECK(CefSchemeHandlerCppToC::DebugObjCt == 0); - DCHECK(CefSchemeHandlerFactoryCppToC::DebugObjCt == 0); - DCHECK(CefV8HandlerCppToC::DebugObjCt == 0); - DCHECK(CefWriteHandlerCppToC::DebugObjCt == 0); - DCHECK(CefBrowserCToCpp::DebugObjCt == 0); - DCHECK(CefRequestCToCpp::DebugObjCt == 0); - DCHECK(CefPostDataCToCpp::DebugObjCt == 0); - DCHECK(CefPostDataElementCToCpp::DebugObjCt == 0); - DCHECK(CefStreamReaderCToCpp::DebugObjCt == 0); - DCHECK(CefStreamWriterCToCpp::DebugObjCt == 0); - DCHECK(CefV8ValueCToCpp::DebugObjCt == 0); -#endif // _DEBUG -} - -void CefDoMessageLoopWork() -{ - cef_do_message_loop_work(); -} - -bool CefRegisterExtension(const std::wstring& extension_name, - const std::wstring& javascript_code, - CefRefPtr handler) -{ - return cef_register_extension(extension_name.c_str(), javascript_code.c_str(), - CefV8HandlerCppToC::Wrap(handler))?true:false; -} - -bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info) -{ - cef_plugin_info_t pluginInfo; - - pluginInfo.unique_name = plugin_info.unique_name.c_str(); - pluginInfo.display_name = plugin_info.display_name.c_str(); - pluginInfo.version =plugin_info.version.c_str(); - pluginInfo.description = plugin_info.description.c_str(); - - std::wstring mimeTypes, fileExtensions, typeDescriptions; - - for(size_t i = 0; i < plugin_info.mime_types.size(); ++i) { - if(i > 0) { - mimeTypes += L"|"; - fileExtensions += L"|"; - typeDescriptions += L"|"; - } - - mimeTypes += plugin_info.mime_types[i].mime_type; - typeDescriptions += plugin_info.mime_types[i].description; - - for(size_t j = 0; - j < plugin_info.mime_types[i].file_extensions.size(); ++j) { - if(j > 0) { - fileExtensions += L","; - } - fileExtensions += plugin_info.mime_types[i].file_extensions[j]; - } - } - - pluginInfo.mime_types = mimeTypes.c_str(); - pluginInfo.file_extensions = fileExtensions.c_str(); - pluginInfo.type_descriptions = typeDescriptions.c_str(); - - pluginInfo.np_getentrypoints = plugin_info.np_getentrypoints; - pluginInfo.np_initialize = plugin_info.np_initialize; - pluginInfo.np_shutdown = plugin_info.np_shutdown; - - return (cef_register_plugin(&pluginInfo) ? true : false); -} - -bool CefRegisterScheme(const std::wstring& scheme_name, - const std::wstring& host_name, - CefRefPtr factory) -{ - return cef_register_scheme(scheme_name.c_str(), host_name.c_str(), - CefSchemeHandlerFactoryCppToC::Wrap(factory))?true:false; -} - -bool CefCurrentlyOn(CefThreadId threadId) -{ - return cef_currently_on(threadId)?true:false; -} - -bool CefPostTask(CefThreadId threadId, CefRefPtr task) -{ - return cef_post_task(threadId, CefTaskCppToC::Wrap(task))?true:false; -} - -bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, - long delay_ms) -{ - return cef_post_delayed_task(threadId, CefTaskCppToC::Wrap(task), delay_ms)? - true:false; -} +// 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/cef.h" +#include "include/cef_capi.h" +#include "include/cef_nplugin.h" +#include "include/cef_nplugin_capi.h" +#include "libcef_dll/cpptoc/handler_cpptoc.h" +#include "libcef_dll/cpptoc/read_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/v8handler_cpptoc.h" +#include "libcef_dll/cpptoc/write_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_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/stream_reader_ctocpp.h" +#include "libcef_dll/ctocpp/stream_writer_ctocpp.h" +#include "libcef_dll/ctocpp/v8value_ctocpp.h" + + +bool CefInitialize(bool multi_threaded_message_loop, + const std::wstring& cache_path) +{ + return cef_initialize(multi_threaded_message_loop, cache_path.c_str()) + ?true:false; +} + +void CefShutdown() +{ + cef_shutdown(); + +#ifdef _DEBUG + // Check that all wrapper objects have been destroyed + DCHECK(CefHandlerCppToC::DebugObjCt == 0); + DCHECK(CefReadHandlerCppToC::DebugObjCt == 0); + DCHECK(CefSchemeHandlerCppToC::DebugObjCt == 0); + DCHECK(CefSchemeHandlerFactoryCppToC::DebugObjCt == 0); + DCHECK(CefV8HandlerCppToC::DebugObjCt == 0); + DCHECK(CefWriteHandlerCppToC::DebugObjCt == 0); + DCHECK(CefBrowserCToCpp::DebugObjCt == 0); + DCHECK(CefRequestCToCpp::DebugObjCt == 0); + DCHECK(CefPostDataCToCpp::DebugObjCt == 0); + DCHECK(CefPostDataElementCToCpp::DebugObjCt == 0); + DCHECK(CefStreamReaderCToCpp::DebugObjCt == 0); + DCHECK(CefStreamWriterCToCpp::DebugObjCt == 0); + DCHECK(CefV8ValueCToCpp::DebugObjCt == 0); +#endif // _DEBUG +} + +void CefDoMessageLoopWork() +{ + cef_do_message_loop_work(); +} + +bool CefRegisterExtension(const std::wstring& extension_name, + const std::wstring& javascript_code, + CefRefPtr handler) +{ + return cef_register_extension(extension_name.c_str(), javascript_code.c_str(), + CefV8HandlerCppToC::Wrap(handler))?true:false; +} + +bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info) +{ + cef_plugin_info_t pluginInfo; + + pluginInfo.unique_name = plugin_info.unique_name.c_str(); + pluginInfo.display_name = plugin_info.display_name.c_str(); + pluginInfo.version =plugin_info.version.c_str(); + pluginInfo.description = plugin_info.description.c_str(); + + std::wstring mimeTypes, fileExtensions, typeDescriptions; + + for(size_t i = 0; i < plugin_info.mime_types.size(); ++i) { + if(i > 0) { + mimeTypes += L"|"; + fileExtensions += L"|"; + typeDescriptions += L"|"; + } + + mimeTypes += plugin_info.mime_types[i].mime_type; + typeDescriptions += plugin_info.mime_types[i].description; + + for(size_t j = 0; + j < plugin_info.mime_types[i].file_extensions.size(); ++j) { + if(j > 0) { + fileExtensions += L","; + } + fileExtensions += plugin_info.mime_types[i].file_extensions[j]; + } + } + + pluginInfo.mime_types = mimeTypes.c_str(); + pluginInfo.file_extensions = fileExtensions.c_str(); + pluginInfo.type_descriptions = typeDescriptions.c_str(); + + pluginInfo.np_getentrypoints = plugin_info.np_getentrypoints; + pluginInfo.np_initialize = plugin_info.np_initialize; + pluginInfo.np_shutdown = plugin_info.np_shutdown; + + return (cef_register_plugin(&pluginInfo) ? true : false); +} + +bool CefRegisterScheme(const std::wstring& scheme_name, + const std::wstring& host_name, + CefRefPtr factory) +{ + return cef_register_scheme(scheme_name.c_str(), host_name.c_str(), + CefSchemeHandlerFactoryCppToC::Wrap(factory))?true:false; +} + +bool CefCurrentlyOn(CefThreadId threadId) +{ + return cef_currently_on(threadId)?true:false; +} + +bool CefPostTask(CefThreadId threadId, CefRefPtr task) +{ + return cef_post_task(threadId, CefTaskCppToC::Wrap(task))?true:false; +} + +bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, + long delay_ms) +{ + return cef_post_delayed_task(threadId, CefTaskCppToC::Wrap(task), delay_ms)? + true:false; +} diff --git a/patch/README.txt b/patch/README.txt index 02d01af58..a422f54af 100644 --- a/patch/README.txt +++ b/patch/README.txt @@ -1,27 +1,27 @@ -CEF development has faced delays in the past due to the time lapse between -submitting patches to the Chromium and WebKit projects and having those patches -accepted. A CEF developer will hopefully earn Chromium commit access at some -point which should partly mitigate this problem but will not eliminate it -completely. There may still 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 in the near term and with a minimum of -maintenance headaches (i.e. without forking) this project adds a patch -capability as part of the CEF build process. 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. The CEF "patch" project, which is a build dependency for the "webkit\config" - project, 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. +CEF development has faced delays in the past due to the time lapse between +submitting patches to the Chromium and WebKit projects and having those patches +accepted. A CEF developer will hopefully earn Chromium commit access at some +point which should partly mitigate this problem but will not eliminate it +completely. There may still 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 in the near term and with a minimum of +maintenance headaches (i.e. without forking) this project adds a patch +capability as part of the CEF build process. 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. The CEF "patch" project, which is a build dependency for the "webkit\config" + project, applies the patches to the Chromium/WebKit source tree using the + patcher.py tool in the tools directory. If necessary the patcher.py tool + also rewrites the "patch_state.h" file which defines the CEF_PATCHES_APPLIED + preprocessor value. + +To disable automatic application of patches to the Chromium/WebKit code base +create an empty "NOPATCH" file in the "patch" directory. Sections of the CEF +code base that otherwise require patches will be disabled using the +CEF_PATCHES_APPLIED preprocessor value defined in the "patch_state.h" file. Be +warned that not applying all required patches may break important CEF +functionality. diff --git a/patch/patch_build.cfg b/patch/patch_build.cfg index b156e73b8..c616ff34a 100644 --- a/patch/patch_build.cfg +++ b/patch/patch_build.cfg @@ -1,5 +1,5 @@ -# An element of this array associates a patch file with a target directory. -# All paths in the patch file must be relative to that directory. -patches = { - 'build' : '../build/' +# An element of this array associates a patch file with a target directory. +# All paths in the patch file must be relative to that directory. +patches = { + 'build' : '../build/' } diff --git a/patch/patch_source.cfg b/patch/patch_source.cfg index ad21d42fe..b65c28a20 100644 --- a/patch/patch_source.cfg +++ b/patch/patch_source.cfg @@ -1,6 +1,6 @@ -# An element of this array associates a patch file with a target directory. -# All paths in the patch file must be relative to that directory. Each patch -# file entry should be proceeded by the code review or bug report link that it -# relates to. -patches = { +# An element of this array associates a patch file with a target directory. +# All paths in the patch file must be relative to that directory. Each patch +# file entry should be proceeded by the code review or bug report link that it +# relates to. +patches = { } diff --git a/tests/cefclient/binding_test.cpp b/tests/cefclient/binding_test.cpp index 647638920..c4fcd5dd4 100644 --- a/tests/cefclient/binding_test.cpp +++ b/tests/cefclient/binding_test.cpp @@ -1,173 +1,173 @@ -// 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 "binding_test.h" -#include - - -// Implementation of the V8 handler class for the "window.cef_test.Dump" -// function. -class ClientV8FunctionHandler : public CefThreadSafeBase -{ -public: - ClientV8FunctionHandler() {} - virtual ~ClientV8FunctionHandler() {} - - // Execute with the specified argument list and return value. Return true if - // the method was handled. - virtual bool Execute(const std::wstring& name, - CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) - { - if(name == L"Dump") - { - // The "Dump" function will return a human-readable dump of the input - // arguments. - std::wstringstream stream; - size_t i; - - for(i = 0; i < arguments.size(); ++i) - { - stream << L"arg[" << i << L"] = "; - PrintValue(arguments[i], stream, 0); - stream << L"\n"; - } - - retval = CefV8Value::CreateString(stream.str()); - return true; - } - else if(name == L"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; - if(!arguments[0]->ExecuteFunction(object, argList, objectPtr, exception)) - return false; - // 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. - return funcPtr->ExecuteFunction(arguments[0], argList, retval, exception); - } - return false; - } - - // Simple function for formatted output of a V8 value. - void PrintValue(CefRefPtr value, std::wstringstream &stream, - int indent) - { - std::wstringstream indent_stream; - for(int i = 0; i < indent; ++i) - indent_stream << L" "; - std::wstring indent_str = indent_stream.str(); - - if(value->IsUndefined()) - stream << L"(undefined)"; - else if(value->IsNull()) - stream << L"(null)"; - else if(value->IsBool()) - stream << L"(bool) " << (value->GetBoolValue() ? L"true" : L"false"); - else if(value->IsInt()) - stream << L"(int) " << value->GetIntValue(); - else if(value->IsDouble()) - stream << L"(double) " << value->GetDoubleValue(); - else if(value->IsString()) - stream << L"(string) " << value->GetStringValue().c_str(); - else if(value->IsFunction()) - stream << L"(function) " << value->GetFunctionName().c_str(); - else if(value->IsArray()) { - stream << L"(array) ["; - int len = value->GetArrayLength(); - for(int i = 0; i < len; ++i) { - stream << L"\n " << indent_str.c_str() << i << L" = "; - PrintValue(value->GetValue(i), stream, indent+1); - } - stream << L"\n" << indent_str.c_str() << L"]"; - } else if(value->IsObject()) { - stream << L"(object) ["; - std::vector keys; - if(value->GetKeys(keys)) { - for(size_t i = 0; i < keys.size(); ++i) { - stream << L"\n " << indent_str.c_str() << keys[i].c_str() << L" = "; - PrintValue(value->GetValue(keys[i]), stream, indent+1); - } - } - stream << L"\n" << indent_str.c_str() << L"]"; - } - } -}; - - -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(L"cef_test", testObjPtr); - - // 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(L"Dump", - CefV8Value::CreateFunction(L"Dump", handlerPtr)); - // Add a new V8 function to the cef_test object with the name "Call". - testObjPtr->SetValue(L"Call", - CefV8Value::CreateFunction(L"Call", handlerPtr)); -} - -void RunBindingTest(CefRefPtr browser) -{ - std::wstring html = - L"ClientV8FunctionHandler says:
"
-    L""
-    L"
"; - browser->GetMainFrame()->LoadString(html, L"about:blank"); -} +// 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 "binding_test.h" +#include + + +// Implementation of the V8 handler class for the "window.cef_test.Dump" +// function. +class ClientV8FunctionHandler : public CefThreadSafeBase +{ +public: + ClientV8FunctionHandler() {} + virtual ~ClientV8FunctionHandler() {} + + // Execute with the specified argument list and return value. Return true if + // the method was handled. + virtual bool Execute(const std::wstring& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) + { + if(name == L"Dump") + { + // The "Dump" function will return a human-readable dump of the input + // arguments. + std::wstringstream stream; + size_t i; + + for(i = 0; i < arguments.size(); ++i) + { + stream << L"arg[" << i << L"] = "; + PrintValue(arguments[i], stream, 0); + stream << L"\n"; + } + + retval = CefV8Value::CreateString(stream.str()); + return true; + } + else if(name == L"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; + if(!arguments[0]->ExecuteFunction(object, argList, objectPtr, exception)) + return false; + // 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. + return funcPtr->ExecuteFunction(arguments[0], argList, retval, exception); + } + return false; + } + + // Simple function for formatted output of a V8 value. + void PrintValue(CefRefPtr value, std::wstringstream &stream, + int indent) + { + std::wstringstream indent_stream; + for(int i = 0; i < indent; ++i) + indent_stream << L" "; + std::wstring indent_str = indent_stream.str(); + + if(value->IsUndefined()) + stream << L"(undefined)"; + else if(value->IsNull()) + stream << L"(null)"; + else if(value->IsBool()) + stream << L"(bool) " << (value->GetBoolValue() ? L"true" : L"false"); + else if(value->IsInt()) + stream << L"(int) " << value->GetIntValue(); + else if(value->IsDouble()) + stream << L"(double) " << value->GetDoubleValue(); + else if(value->IsString()) + stream << L"(string) " << value->GetStringValue().c_str(); + else if(value->IsFunction()) + stream << L"(function) " << value->GetFunctionName().c_str(); + else if(value->IsArray()) { + stream << L"(array) ["; + int len = value->GetArrayLength(); + for(int i = 0; i < len; ++i) { + stream << L"\n " << indent_str.c_str() << i << L" = "; + PrintValue(value->GetValue(i), stream, indent+1); + } + stream << L"\n" << indent_str.c_str() << L"]"; + } else if(value->IsObject()) { + stream << L"(object) ["; + std::vector keys; + if(value->GetKeys(keys)) { + for(size_t i = 0; i < keys.size(); ++i) { + stream << L"\n " << indent_str.c_str() << keys[i].c_str() << L" = "; + PrintValue(value->GetValue(keys[i]), stream, indent+1); + } + } + stream << L"\n" << indent_str.c_str() << L"]"; + } + } +}; + + +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(L"cef_test", testObjPtr); + + // 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(L"Dump", + CefV8Value::CreateFunction(L"Dump", handlerPtr)); + // Add a new V8 function to the cef_test object with the name "Call". + testObjPtr->SetValue(L"Call", + CefV8Value::CreateFunction(L"Call", handlerPtr)); +} + +void RunBindingTest(CefRefPtr browser) +{ + std::wstring html = + L"ClientV8FunctionHandler says:
"
+    L""
+    L"
"; + browser->GetMainFrame()->LoadString(html, L"about:blank"); +} diff --git a/tests/cefclient/binding_test.h b/tests/cefclient/binding_test.h index f760ffab3..65162466b 100644 --- a/tests/cefclient/binding_test.h +++ b/tests/cefclient/binding_test.h @@ -1,14 +1,14 @@ -// 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. - -#pragma once -#include "include/cef.h" - -// Add the V8 bindings. -void InitBindingTest(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr object); - -// Run the test. -void RunBindingTest(CefRefPtr browser); +// 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. + +#pragma once +#include "include/cef.h" + +// Add the V8 bindings. +void InitBindingTest(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object); + +// Run the test. +void RunBindingTest(CefRefPtr browser); diff --git a/tests/cefclient/cefclient.cpp b/tests/cefclient/cefclient.cpp index f4d13ed04..fc3fe6667 100644 --- a/tests/cefclient/cefclient.cpp +++ b/tests/cefclient/cefclient.cpp @@ -1,1170 +1,1170 @@ -// 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.h" -#include "cefclient.h" -#include "binding_test.h" -#include "extension_test.h" -#include "plugin_test.h" -#include "resource_util.h" -#include "scheme_test.h" -#include "string_util.h" -#include "uiplugin_test.h" -#include -#include - -#define MAX_LOADSTRING 100 -#define MAX_URL_LENGTH 255 -#define BUTTON_WIDTH 72 -#define URLBAR_HEIGHT 24 - -// Define this value to run CEF with messages processed using the current -// application's message loop. -#define TEST_SINGLE_THREADED_MESSAGE_LOOP - -// Global Variables: -HINSTANCE hInst; // current instance -TCHAR szTitle[MAX_LOADSTRING]; // The title bar text -TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name -TCHAR 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); - -#ifdef _WIN32 -// 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='*'\"") -#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(_wgetcwd(szWorkingDir, MAX_PATH) == NULL) - szWorkingDir[0] = 0; - -#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP - // Initialize the CEF with messages processed using the current application's - // message loop. - CefInitialize(false, std::wstring()); -#else - // Initialize the CEF with messages processed using a separate UI thread. - CefInitialize(true, std::wstring()); -#endif - - // Register the internal client plugin. - InitPluginTest(); - - // Register the internal UI client plugin. - InitUIPluginTest(); - - // Register the V8 extension handler. - InitExtensionTest(); - - // Register the scheme handler. - InitSchemeTest(); - - MSG msg; - 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); - - // Main message loop - while (GetMessage(&msg, NULL, 0, 0)) - { -#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP - // Allow the CEF to do its message loop processing. - CefDoMessageLoopWork(); -#endif - - // Allow processing of find dialog messages. - if(hFindDlg && IsDialogMessage(hFindDlg, &msg)) - continue; - - if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - // Shut down the CEF - CefShutdown(); - - return (int) msg.wParam; -} - -// -// 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; -} - - -// Client implementation of the browser handler class -class ClientHandler : public CefThreadSafeBase -{ -public: - ClientHandler() - { - m_MainHwnd = NULL; - m_BrowserHwnd = NULL; - m_EditHwnd = NULL; - m_bLoading = false; - m_bCanGoBack = false; - m_bCanGoForward = false; - } - - ~ClientHandler() - { - } - - // Event called before a new window is created. The |parentBrowser| parameter - // will point to the parent browser window, if any. The |popup| parameter - // will be true if the new window is a popup window. If you create the window - // yourself you should populate the window handle member of |createInfo| and - // return RV_HANDLED. Otherwise, return RV_CONTINUE and the framework will - // create the window. By default, a newly created window will recieve the - // same handler as the parent window. To change the handler for the new - // window modify the object that |handler| points to. - virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, - CefWindowInfo& createInfo, bool popup, - CefRefPtr& handler, - std::wstring& url) - { - return RV_CONTINUE; - } - - // Event called after a new window is created. The return value is currently - // ignored. - virtual RetVal HandleAfterCreated(CefRefPtr browser) - { - Lock(); - if(!browser->IsPopup()) - { - // We need to keep the main child window, but not popup windows - m_Browser = browser; - m_BrowserHwnd = browser->GetWindowHandle(); - } - Unlock(); - return RV_CONTINUE; - } - - // Event called when the address bar changes. The return value is currently - // ignored. - virtual RetVal HandleAddressChange(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& url) - { - if(m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) - { - // Set the edit window text - SetWindowText(m_EditHwnd, url.c_str()); - } - return RV_CONTINUE; - } - - // Event called when the page title changes. The return value is currently - // ignored. - virtual RetVal HandleTitleChange(CefRefPtr browser, - const std::wstring& title) - { - // Set the frame window title bar - HWND hwnd = browser->GetWindowHandle(); - if(!browser->IsPopup()) - { - // The frame window will be the parent of the browser window - hwnd = GetParent(hwnd); - } - SetWindowText(hwnd, title.c_str()); - return RV_CONTINUE; - } - - // Event called before browser navigation. The client has an opportunity to - // modify the |request| object if desired. Return RV_HANDLED to cancel - // navigation. - virtual RetVal HandleBeforeBrowse(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr request, - NavType navType, bool isRedirect) - { - return RV_CONTINUE; - } - - // Event called when the browser begins loading a page. The |frame| pointer - // will be empty if the event represents the overall load status and not the - // load status for a particular frame. The return value is currently ignored. - virtual RetVal HandleLoadStart(CefRefPtr browser, - CefRefPtr frame) - { - if(!browser->IsPopup() && !frame.get()) - { - Lock(); - // We've just started loading a page - m_bLoading = true; - m_bCanGoBack = false; - m_bCanGoForward = false; - Unlock(); - } - return RV_CONTINUE; - } - - // Event called when the browser is done loading a page. The |frame| pointer - // will be empty if the event represents the overall load status and not the - // load status for a particular frame. This event will be generated - // irrespective of whether the request completes successfully. The return - // value is currently ignored. - virtual RetVal HandleLoadEnd(CefRefPtr browser, - CefRefPtr frame) - { - if(!browser->IsPopup() && !frame.get()) - { - Lock(); - // We've just finished loading a page - m_bLoading = false; - m_bCanGoBack = browser->CanGoBack(); - m_bCanGoForward = browser->CanGoForward(); - Unlock(); - } - return RV_CONTINUE; - } - - // 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 - // RV_HANDLED. Otherwise, return RV_CONTINUE for the default error text. - virtual RetVal HandleLoadError(CefRefPtr browser, - CefRefPtr frame, - ErrorCode errorCode, - const std::wstring& failedUrl, - std::wstring& errorText) - { - if(errorCode == ERR_CACHE_MISS) - { - // Usually caused by navigating to a page with POST data via back or - // forward buttons. - errorText = L"Expired Form Data" - L"

Expired Form Data

" - L"

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

" - L""; - } - else - { - // All other messages. - std::wstringstream ss; - ss << L"Load Failed" - L"

Load Failed

" - L"

Load of URL " << failedUrl << - L"failed with error code " << static_cast(errorCode) << - L".

" - L""; - errorText = ss.str(); - } - return RV_HANDLED; - } - - // Event called before a resource is loaded. To allow the resource to load - // normally return RV_CONTINUE. To redirect the resource to a new url - // populate the |redirectUrl| value and return RV_CONTINUE. To specify - // data for the resource return a CefStream object in |resourceStream|, set - // 'mimeType| to the resource stream's mime type, and return RV_CONTINUE. - // To cancel loading of the resource return RV_HANDLED. - virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, - CefRefPtr request, - std::wstring& redirectUrl, - CefRefPtr& resourceStream, - std::wstring& mimeType, - int loadFlags) - { - DWORD dwSize; - LPBYTE pBytes; - - std::wstring url = request->GetURL(); - if(url == L"http://tests/request") { - // Show the request contents - std::wstring dump; - DumpRequestContents(request, dump); - resourceStream = CefStreamReader::CreateForData( - (void*)dump.c_str(), dump.size() * sizeof(wchar_t)); - mimeType = L"text/plain"; - } else if(url == L"http://tests/uiapp") { - // Show the uiapp contents - if(LoadBinaryResource(IDS_UIPLUGIN, dwSize, pBytes)) { - resourceStream = CefStreamReader::CreateForHandler( - new ClientReadHandler(pBytes, dwSize)); - mimeType = L"text/html"; - } - } else if(wcsstr(url.c_str(), L"/logo1w.png") != NULL) { - // Any time we find "logo.gif" in the URL substitute in our own image - if(LoadBinaryResource(IDS_LOGO, dwSize, pBytes)) { - resourceStream = CefStreamReader::CreateForHandler( - new ClientReadHandler(pBytes, dwSize)); - mimeType = L"image/png"; - } - } else if(wcsstr(url.c_str(), L"/logoball.png") != NULL) { - // Load the "logoball.png" image resource. - if(LoadBinaryResource(IDS_LOGOBALL, dwSize, pBytes)) { - resourceStream = CefStreamReader::CreateForHandler( - new ClientReadHandler(pBytes, dwSize)); - mimeType = L"image/png"; - } - } - return RV_CONTINUE; - } - - // Event called before a context menu is displayed. To cancel display of the - // default context menu return RV_HANDLED. - virtual RetVal HandleBeforeMenu(CefRefPtr browser, - const MenuInfo& menuInfo) - { - return RV_CONTINUE; - } - - - // Event 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. The return value is currently ignored. - virtual RetVal HandleGetMenuLabel(CefRefPtr browser, - MenuId menuId, std::wstring& label) - { - return RV_CONTINUE; - } - - // Event called when an option is selected from the default context menu. - // Return RV_HANDLED to cancel default handling of the action. - virtual RetVal HandleMenuAction(CefRefPtr browser, - MenuId menuId) - { - return RV_CONTINUE; - } - - // Event 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 RV_CONTINUE to display the default print options or - // RV_HANDLED to display the modified |printOptions|. - virtual RetVal HandlePrintOptions(CefRefPtr browser, - CefPrintOptions& printOptions) - { - return RV_CONTINUE; - } - - // Event 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 RV_HANDLED. Otherwise, populate the approprate - // variables and return RV_CONTINUE. - virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, - CefRefPtr frame, - CefPrintInfo& printInfo, - const std::wstring& url, - const std::wstring& title, - int currentPage, int maxPages, - std::wstring& topLeft, - std::wstring& topCenter, - std::wstring& topRight, - std::wstring& bottomLeft, - std::wstring& bottomCenter, - std::wstring& bottomRight) - { - // 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::wstringstream strstream; - strstream << L"Page " << currentPage << L" of " << maxPages; - bottomCenter = strstream.str(); - - return RV_CONTINUE; - } - - // Run a JS alert message. Return RV_CONTINUE to display the default alert - // or RV_HANDLED if you displayed a custom alert. - virtual RetVal HandleJSAlert(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message) - { - return RV_CONTINUE; - } - - // Run a JS confirm request. Return RV_CONTINUE to display the default alert - // or RV_HANDLED if you displayed a custom alert. If you handled the alert - // set |retval| to true if the user accepted the confirmation. - virtual RetVal HandleJSConfirm(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message, bool& retval) - { - return RV_CONTINUE; - } - - // Run a JS prompt request. Return RV_CONTINUE to display the default prompt - // or RV_HANDLED 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. - virtual RetVal HandleJSPrompt(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message, - const std::wstring& defaultValue, - bool& retval, - std::wstring& result) - { - return RV_CONTINUE; - } - - // Event called for binding to a frame's JavaScript global object. The - // return value is currently ignored. - virtual RetVal HandleJSBinding(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr object) - { - // Add the V8 bindings. - InitBindingTest(browser, frame, object); - - return RV_HANDLED; - } - - // Called just before a window is closed. The return value is currently - // ignored. - virtual RetVal HandleBeforeWindowClose(CefRefPtr browser) - { - if(m_BrowserHwnd == browser->GetWindowHandle()) - { - // Free the browser pointer so that the browser can be destroyed - m_Browser = NULL; - } - return RV_CONTINUE; - } - - // 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. - // The return value is currently ignored. - virtual RetVal HandleTakeFocus(CefRefPtr browser, bool reverse) - { - return RV_CONTINUE; - } - - // Called when the browser component is requesting focus. |isWidget| will be - // true if the focus is requested for a child widget of the browser window. - // Return RV_CONTINUE to allow the focus to be set or RV_HANDLED to cancel - // setting the focus. - virtual RetVal HandleSetFocus(CefRefPtr browser, - bool isWidget) - { - return RV_CONTINUE; - } - - // Event 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 RV_HANDLED. Otherwise, - // you can optionally modify |text| and then return RV_CONTINUE to allow - // the browser to display the tooltip. - virtual RetVal HandleTooltip(CefRefPtr browser, - std::wstring& text) - { - return RV_CONTINUE; - } - - // Called when the browser component receives a keyboard event. - // |type| is the type of keyboard event (see |KeyEventType|). - // |code| is the windows scan-code for the event. - // |modifiers| is a set of bit-flags describing any pressed modifier keys. - // |isSystemKey| is set if Windows considers this a 'system key' message; - // (see http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx) - // Return RV_HANDLED if the keyboard event was handled or RV_CONTINUE - // to allow the browser component to handle the event. - RetVal HandleKeyEvent(CefRefPtr browser, - KeyEventType type, - int code, - int modifiers, - bool isSystemKey) - { - return RV_CONTINUE; - } - - // Called to display a console message. Return RV_HANDLED to stop the message - // from being output to the console. - RetVal HandleConsoleMessage(CefRefPtr browser, - const std::wstring& message, - const std::wstring& source, int line) - { - Lock(); - bool first_message = m_LogFile.empty(); - if(first_message) { - std::wstringstream ss; - ss << szWorkingDir << L"\\console.log"; - m_LogFile = ss.str(); - } - std::wstring logFile = m_LogFile; - Unlock(); - - FILE* file = NULL; - _wfopen_s(&file, logFile.c_str(), L"a, ccs=UTF-8"); - - if(file) { - std::wstringstream ss; - ss << L"Message: " << message << L"\r\nSource: " << source << - L"\r\nLine: " << line << L"\r\n-----------------------\r\n"; - fputws(ss.str().c_str(), file); - fclose(file); - - if(first_message) { - // Show the message box on the main application thread. - PostMessage(m_MainHwnd, WM_COMMAND, ID_WARN_CONSOLEMESSAGE, 0); - } - } - - return RV_HANDLED; - } - - // 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. The return value is currently ignored. - virtual RetVal HandleFindResult(CefRefPtr browser, - int identifier, int count, - const CefRect& selectionRect, - int activeMatchOrdinal, bool finalUpdate) - { - return RV_CONTINUE; - } - - // Retrieve the current navigation state flags - void GetNavState(bool &isLoading, bool &canGoBack, bool &canGoForward) - { - Lock(); - isLoading = m_bLoading; - canGoBack = m_bCanGoBack; - canGoForward = m_bCanGoForward; - Unlock(); - } - - void SetMainHwnd(HWND hwnd) - { - Lock(); - m_MainHwnd = hwnd; - Unlock(); - } - HWND GetMainHwnd() { return m_MainHwnd; } - - void SetEditHwnd(HWND hwnd) - { - Lock(); - m_EditHwnd = hwnd; - Unlock(); - } - - CefRefPtr GetBrowser() - { - return m_Browser; - } - - HWND GetBrowserHwnd() - { - return m_BrowserHwnd; - } - - std::wstring GetLogFile() - { - Lock(); - std::wstring str = m_LogFile; - Unlock(); - return str; - } - -protected: - // The child browser window - CefRefPtr m_Browser; - - // The main frame window handle - HWND m_MainHwnd; - - // The child browser window handle - HWND m_BrowserHwnd; - - // The edit window handle - HWND m_EditHwnd; - - // True if the page is currently loading - bool m_bLoading; - // True if the user can navigate backwards - bool m_bCanGoBack; - // True if the user can navigate forwards - bool m_bCanGoForward; - - std::wstring m_LogFile; -}; - -// global handler instance -CefRefPtr g_handler; - -CefRefPtr AppGetBrowser() -{ - if(!g_handler.get()) - return NULL; - return g_handler->GetBrowser(); -} - -HWND AppGetMainHwnd() -{ - if(!g_handler.get()) - return NULL; - return g_handler->GetMainHwnd(); -} - -// Retrieve the current page source and display. -static void RunGetSourceTest(CefRefPtr frame) -{ - std::wstring source = frame->GetSource(); - source = StringReplace(source, L"<", L"<"); - source = StringReplace(source, L">", L">"); - std::wstringstream ss; - ss << L"Source:" << L"
" << source
-      << L"
"; - frame->LoadString(ss.str(), L"http://tests/getsource"); -} - -// Retrieve the current page text and display. -static void RunGetTextTest(CefRefPtr frame) -{ - std::wstring text = frame->GetText(); - text = StringReplace(text, L"<", L"<"); - text = StringReplace(text, L">", L">"); - std::wstringstream ss; - ss << L"Text:" << L"
" << text
-      << L"
"; - frame->LoadString(ss.str(), L"http://tests/gettext"); -} - -// -// 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] = {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); - - rect.top += URLBAR_HEIGHT; - - CefWindowInfo info; - - // Initialize window info to the defaults for a child window - info.SetAsChild(hWnd, rect); - - // Creat the new child child browser window - CefBrowser::CreateBrowser(info, false, - static_cast>(g_handler), - L"http://www.google.com"); - - // Start the timer that will be used to update child window state - SetTimer(hWnd, 1, 250, NULL); - } - return 0; - - case WM_TIMER: - if(g_handler.get() && g_handler->GetBrowserHwnd()) - { - // Retrieve the current navigation state - bool isLoading, canGoBack, canGoForward; - g_handler->GetNavState(isLoading, canGoBack, canGoForward); - - // Update the status of child windows - EnableWindow(editWnd, TRUE); - EnableWindow(backWnd, canGoBack); - EnableWindow(forwardWnd, canGoForward); - EnableWindow(reloadWnd, !isLoading); - EnableWindow(stopWnd, isLoading); - } - 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 " - << g_handler->GetLogFile(); - MessageBoxW(hWnd, ss.str().c_str(), L"Console Messages", - 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()) { -#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP - RunGetSourceTest(browser->GetMainFrame()); -#else // !TEST_SINGLE_THREADED_MESSAGE_LOOP - // Execute the GetSource() call on the FILE thread to avoid blocking - // the UI thread when using a multi-threaded message loop - // (issue #79). - class ExecTask : public CefThreadSafeBase - { - public: - ExecTask(CefRefPtr frame) : m_Frame(frame) {} - virtual void Execute(CefThreadId threadId) - { - RunGetSourceTest(m_Frame); - } - private: - CefRefPtr m_Frame; - }; - CefPostTask(TID_FILE, new ExecTask(browser->GetMainFrame())); -#endif // !TEST_SINGLE_THREADED_MESSAGE_LOOP - } - return 0; - case ID_TESTS_GETTEXT: // Test the GetText function - if(browser.get()) { -#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP - RunGetTextTest(browser->GetMainFrame()); -#else // !TEST_SINGLE_THREADED_MESSAGE_LOOP - // Execute the GetText() call on the FILE thread to avoid blocking - // the UI thread when using a multi-threaded message loop - // (issue #79). - class ExecTask : public CefThreadSafeBase - { - public: - ExecTask(CefRefPtr frame) : m_Frame(frame) {} - virtual void Execute(CefThreadId threadId) - { - RunGetTextTest(m_Frame); - } - private: - CefRefPtr m_Frame; - }; - CefPostTask(TID_FILE, new ExecTask(browser->GetMainFrame())); -#endif // !TEST_SINGLE_THREADED_MESSAGE_LOOP - } - 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_EXECUTE: // Test execution of javascript - if(browser.get()) - { - browser->GetMainFrame()->ExecuteJavaScript( - L"alert('JavaScript execute works!');", - L"about:blank", 0); - } - return 0; - case ID_TESTS_PLUGIN: // Test the custom plugin - if(browser.get()) - RunPluginTest(browser); - return 0; - case ID_TESTS_POPUP: // Test a popup window - if(browser.get()) - { - browser->GetMainFrame()->ExecuteJavaScript( - L"window.open('http://www.google.com');", - L"about:blank", 0); - } - return 0; - case ID_TESTS_REQUEST: // Test a request - if(browser.get()) - { - // Create a new request - CefRefPtr request(CefRequest::CreateRequest()); - - // Set the request URL - request->SetURL(L"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(L"X-My-Header", L"My Header Value")); - request->SetHeaderMap(headerMap); - - // Load the request - browser->GetMainFrame()->LoadRequest(request); - } - 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; - } - } - 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_DESTROY: - // The frame window has exited - KillTimer(hWnd, 1); - 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; -} +// 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.h" +#include "cefclient.h" +#include "binding_test.h" +#include "extension_test.h" +#include "plugin_test.h" +#include "resource_util.h" +#include "scheme_test.h" +#include "string_util.h" +#include "uiplugin_test.h" +#include +#include + +#define MAX_LOADSTRING 100 +#define MAX_URL_LENGTH 255 +#define BUTTON_WIDTH 72 +#define URLBAR_HEIGHT 24 + +// Define this value to run CEF with messages processed using the current +// application's message loop. +#define TEST_SINGLE_THREADED_MESSAGE_LOOP + +// Global Variables: +HINSTANCE hInst; // current instance +TCHAR szTitle[MAX_LOADSTRING]; // The title bar text +TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name +TCHAR 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); + +#ifdef _WIN32 +// 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='*'\"") +#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(_wgetcwd(szWorkingDir, MAX_PATH) == NULL) + szWorkingDir[0] = 0; + +#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP + // Initialize the CEF with messages processed using the current application's + // message loop. + CefInitialize(false, std::wstring()); +#else + // Initialize the CEF with messages processed using a separate UI thread. + CefInitialize(true, std::wstring()); +#endif + + // Register the internal client plugin. + InitPluginTest(); + + // Register the internal UI client plugin. + InitUIPluginTest(); + + // Register the V8 extension handler. + InitExtensionTest(); + + // Register the scheme handler. + InitSchemeTest(); + + MSG msg; + 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); + + // Main message loop + while (GetMessage(&msg, NULL, 0, 0)) + { +#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP + // Allow the CEF to do its message loop processing. + CefDoMessageLoopWork(); +#endif + + // Allow processing of find dialog messages. + if(hFindDlg && IsDialogMessage(hFindDlg, &msg)) + continue; + + if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + + // Shut down the CEF + CefShutdown(); + + return (int) msg.wParam; +} + +// +// 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; +} + + +// Client implementation of the browser handler class +class ClientHandler : public CefThreadSafeBase +{ +public: + ClientHandler() + { + m_MainHwnd = NULL; + m_BrowserHwnd = NULL; + m_EditHwnd = NULL; + m_bLoading = false; + m_bCanGoBack = false; + m_bCanGoForward = false; + } + + ~ClientHandler() + { + } + + // Event called before a new window is created. The |parentBrowser| parameter + // will point to the parent browser window, if any. The |popup| parameter + // will be true if the new window is a popup window. If you create the window + // yourself you should populate the window handle member of |createInfo| and + // return RV_HANDLED. Otherwise, return RV_CONTINUE and the framework will + // create the window. By default, a newly created window will recieve the + // same handler as the parent window. To change the handler for the new + // window modify the object that |handler| points to. + virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, + CefWindowInfo& createInfo, bool popup, + CefRefPtr& handler, + std::wstring& url) + { + return RV_CONTINUE; + } + + // Event called after a new window is created. The return value is currently + // ignored. + virtual RetVal HandleAfterCreated(CefRefPtr browser) + { + Lock(); + if(!browser->IsPopup()) + { + // We need to keep the main child window, but not popup windows + m_Browser = browser; + m_BrowserHwnd = browser->GetWindowHandle(); + } + Unlock(); + return RV_CONTINUE; + } + + // Event called when the address bar changes. The return value is currently + // ignored. + virtual RetVal HandleAddressChange(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& url) + { + if(m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) + { + // Set the edit window text + SetWindowText(m_EditHwnd, url.c_str()); + } + return RV_CONTINUE; + } + + // Event called when the page title changes. The return value is currently + // ignored. + virtual RetVal HandleTitleChange(CefRefPtr browser, + const std::wstring& title) + { + // Set the frame window title bar + HWND hwnd = browser->GetWindowHandle(); + if(!browser->IsPopup()) + { + // The frame window will be the parent of the browser window + hwnd = GetParent(hwnd); + } + SetWindowText(hwnd, title.c_str()); + return RV_CONTINUE; + } + + // Event called before browser navigation. The client has an opportunity to + // modify the |request| object if desired. Return RV_HANDLED to cancel + // navigation. + virtual RetVal HandleBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, bool isRedirect) + { + return RV_CONTINUE; + } + + // Event called when the browser begins loading a page. The |frame| pointer + // will be empty if the event represents the overall load status and not the + // load status for a particular frame. The return value is currently ignored. + virtual RetVal HandleLoadStart(CefRefPtr browser, + CefRefPtr frame) + { + if(!browser->IsPopup() && !frame.get()) + { + Lock(); + // We've just started loading a page + m_bLoading = true; + m_bCanGoBack = false; + m_bCanGoForward = false; + Unlock(); + } + return RV_CONTINUE; + } + + // Event called when the browser is done loading a page. The |frame| pointer + // will be empty if the event represents the overall load status and not the + // load status for a particular frame. This event will be generated + // irrespective of whether the request completes successfully. The return + // value is currently ignored. + virtual RetVal HandleLoadEnd(CefRefPtr browser, + CefRefPtr frame) + { + if(!browser->IsPopup() && !frame.get()) + { + Lock(); + // We've just finished loading a page + m_bLoading = false; + m_bCanGoBack = browser->CanGoBack(); + m_bCanGoForward = browser->CanGoForward(); + Unlock(); + } + return RV_CONTINUE; + } + + // 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 + // RV_HANDLED. Otherwise, return RV_CONTINUE for the default error text. + virtual RetVal HandleLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const std::wstring& failedUrl, + std::wstring& errorText) + { + if(errorCode == ERR_CACHE_MISS) + { + // Usually caused by navigating to a page with POST data via back or + // forward buttons. + errorText = L"Expired Form Data" + L"

Expired Form Data

" + L"

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

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

Load Failed

" + L"

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

" + L""; + errorText = ss.str(); + } + return RV_HANDLED; + } + + // Event called before a resource is loaded. To allow the resource to load + // normally return RV_CONTINUE. To redirect the resource to a new url + // populate the |redirectUrl| value and return RV_CONTINUE. To specify + // data for the resource return a CefStream object in |resourceStream|, set + // 'mimeType| to the resource stream's mime type, and return RV_CONTINUE. + // To cancel loading of the resource return RV_HANDLED. + virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + std::wstring& redirectUrl, + CefRefPtr& resourceStream, + std::wstring& mimeType, + int loadFlags) + { + DWORD dwSize; + LPBYTE pBytes; + + std::wstring url = request->GetURL(); + if(url == L"http://tests/request") { + // Show the request contents + std::wstring dump; + DumpRequestContents(request, dump); + resourceStream = CefStreamReader::CreateForData( + (void*)dump.c_str(), dump.size() * sizeof(wchar_t)); + mimeType = L"text/plain"; + } else if(url == L"http://tests/uiapp") { + // Show the uiapp contents + if(LoadBinaryResource(IDS_UIPLUGIN, dwSize, pBytes)) { + resourceStream = CefStreamReader::CreateForHandler( + new ClientReadHandler(pBytes, dwSize)); + mimeType = L"text/html"; + } + } else if(wcsstr(url.c_str(), L"/logo1w.png") != NULL) { + // Any time we find "logo.gif" in the URL substitute in our own image + if(LoadBinaryResource(IDS_LOGO, dwSize, pBytes)) { + resourceStream = CefStreamReader::CreateForHandler( + new ClientReadHandler(pBytes, dwSize)); + mimeType = L"image/png"; + } + } else if(wcsstr(url.c_str(), L"/logoball.png") != NULL) { + // Load the "logoball.png" image resource. + if(LoadBinaryResource(IDS_LOGOBALL, dwSize, pBytes)) { + resourceStream = CefStreamReader::CreateForHandler( + new ClientReadHandler(pBytes, dwSize)); + mimeType = L"image/png"; + } + } + return RV_CONTINUE; + } + + // Event called before a context menu is displayed. To cancel display of the + // default context menu return RV_HANDLED. + virtual RetVal HandleBeforeMenu(CefRefPtr browser, + const MenuInfo& menuInfo) + { + return RV_CONTINUE; + } + + + // Event 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. The return value is currently ignored. + virtual RetVal HandleGetMenuLabel(CefRefPtr browser, + MenuId menuId, std::wstring& label) + { + return RV_CONTINUE; + } + + // Event called when an option is selected from the default context menu. + // Return RV_HANDLED to cancel default handling of the action. + virtual RetVal HandleMenuAction(CefRefPtr browser, + MenuId menuId) + { + return RV_CONTINUE; + } + + // Event 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 RV_CONTINUE to display the default print options or + // RV_HANDLED to display the modified |printOptions|. + virtual RetVal HandlePrintOptions(CefRefPtr browser, + CefPrintOptions& printOptions) + { + return RV_CONTINUE; + } + + // Event 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 RV_HANDLED. Otherwise, populate the approprate + // variables and return RV_CONTINUE. + virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, + CefPrintInfo& printInfo, + const std::wstring& url, + const std::wstring& title, + int currentPage, int maxPages, + std::wstring& topLeft, + std::wstring& topCenter, + std::wstring& topRight, + std::wstring& bottomLeft, + std::wstring& bottomCenter, + std::wstring& bottomRight) + { + // 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::wstringstream strstream; + strstream << L"Page " << currentPage << L" of " << maxPages; + bottomCenter = strstream.str(); + + return RV_CONTINUE; + } + + // Run a JS alert message. Return RV_CONTINUE to display the default alert + // or RV_HANDLED if you displayed a custom alert. + virtual RetVal HandleJSAlert(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message) + { + return RV_CONTINUE; + } + + // Run a JS confirm request. Return RV_CONTINUE to display the default alert + // or RV_HANDLED if you displayed a custom alert. If you handled the alert + // set |retval| to true if the user accepted the confirmation. + virtual RetVal HandleJSConfirm(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message, bool& retval) + { + return RV_CONTINUE; + } + + // Run a JS prompt request. Return RV_CONTINUE to display the default prompt + // or RV_HANDLED 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. + virtual RetVal HandleJSPrompt(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message, + const std::wstring& defaultValue, + bool& retval, + std::wstring& result) + { + return RV_CONTINUE; + } + + // Event called for binding to a frame's JavaScript global object. The + // return value is currently ignored. + virtual RetVal HandleJSBinding(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object) + { + // Add the V8 bindings. + InitBindingTest(browser, frame, object); + + return RV_HANDLED; + } + + // Called just before a window is closed. The return value is currently + // ignored. + virtual RetVal HandleBeforeWindowClose(CefRefPtr browser) + { + if(m_BrowserHwnd == browser->GetWindowHandle()) + { + // Free the browser pointer so that the browser can be destroyed + m_Browser = NULL; + } + return RV_CONTINUE; + } + + // 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. + // The return value is currently ignored. + virtual RetVal HandleTakeFocus(CefRefPtr browser, bool reverse) + { + return RV_CONTINUE; + } + + // Called when the browser component is requesting focus. |isWidget| will be + // true if the focus is requested for a child widget of the browser window. + // Return RV_CONTINUE to allow the focus to be set or RV_HANDLED to cancel + // setting the focus. + virtual RetVal HandleSetFocus(CefRefPtr browser, + bool isWidget) + { + return RV_CONTINUE; + } + + // Event 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 RV_HANDLED. Otherwise, + // you can optionally modify |text| and then return RV_CONTINUE to allow + // the browser to display the tooltip. + virtual RetVal HandleTooltip(CefRefPtr browser, + std::wstring& text) + { + return RV_CONTINUE; + } + + // Called when the browser component receives a keyboard event. + // |type| is the type of keyboard event (see |KeyEventType|). + // |code| is the windows scan-code for the event. + // |modifiers| is a set of bit-flags describing any pressed modifier keys. + // |isSystemKey| is set if Windows considers this a 'system key' message; + // (see http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx) + // Return RV_HANDLED if the keyboard event was handled or RV_CONTINUE + // to allow the browser component to handle the event. + RetVal HandleKeyEvent(CefRefPtr browser, + KeyEventType type, + int code, + int modifiers, + bool isSystemKey) + { + return RV_CONTINUE; + } + + // Called to display a console message. Return RV_HANDLED to stop the message + // from being output to the console. + RetVal HandleConsoleMessage(CefRefPtr browser, + const std::wstring& message, + const std::wstring& source, int line) + { + Lock(); + bool first_message = m_LogFile.empty(); + if(first_message) { + std::wstringstream ss; + ss << szWorkingDir << L"\\console.log"; + m_LogFile = ss.str(); + } + std::wstring logFile = m_LogFile; + Unlock(); + + FILE* file = NULL; + _wfopen_s(&file, logFile.c_str(), L"a, ccs=UTF-8"); + + if(file) { + std::wstringstream ss; + ss << L"Message: " << message << L"\r\nSource: " << source << + L"\r\nLine: " << line << L"\r\n-----------------------\r\n"; + fputws(ss.str().c_str(), file); + fclose(file); + + if(first_message) { + // Show the message box on the main application thread. + PostMessage(m_MainHwnd, WM_COMMAND, ID_WARN_CONSOLEMESSAGE, 0); + } + } + + return RV_HANDLED; + } + + // 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. The return value is currently ignored. + virtual RetVal HandleFindResult(CefRefPtr browser, + int identifier, int count, + const CefRect& selectionRect, + int activeMatchOrdinal, bool finalUpdate) + { + return RV_CONTINUE; + } + + // Retrieve the current navigation state flags + void GetNavState(bool &isLoading, bool &canGoBack, bool &canGoForward) + { + Lock(); + isLoading = m_bLoading; + canGoBack = m_bCanGoBack; + canGoForward = m_bCanGoForward; + Unlock(); + } + + void SetMainHwnd(HWND hwnd) + { + Lock(); + m_MainHwnd = hwnd; + Unlock(); + } + HWND GetMainHwnd() { return m_MainHwnd; } + + void SetEditHwnd(HWND hwnd) + { + Lock(); + m_EditHwnd = hwnd; + Unlock(); + } + + CefRefPtr GetBrowser() + { + return m_Browser; + } + + HWND GetBrowserHwnd() + { + return m_BrowserHwnd; + } + + std::wstring GetLogFile() + { + Lock(); + std::wstring str = m_LogFile; + Unlock(); + return str; + } + +protected: + // The child browser window + CefRefPtr m_Browser; + + // The main frame window handle + HWND m_MainHwnd; + + // The child browser window handle + HWND m_BrowserHwnd; + + // The edit window handle + HWND m_EditHwnd; + + // True if the page is currently loading + bool m_bLoading; + // True if the user can navigate backwards + bool m_bCanGoBack; + // True if the user can navigate forwards + bool m_bCanGoForward; + + std::wstring m_LogFile; +}; + +// global handler instance +CefRefPtr g_handler; + +CefRefPtr AppGetBrowser() +{ + if(!g_handler.get()) + return NULL; + return g_handler->GetBrowser(); +} + +HWND AppGetMainHwnd() +{ + if(!g_handler.get()) + return NULL; + return g_handler->GetMainHwnd(); +} + +// Retrieve the current page source and display. +static void RunGetSourceTest(CefRefPtr frame) +{ + std::wstring source = frame->GetSource(); + source = StringReplace(source, L"<", L"<"); + source = StringReplace(source, L">", L">"); + std::wstringstream ss; + ss << L"Source:" << L"
" << source
+      << L"
"; + frame->LoadString(ss.str(), L"http://tests/getsource"); +} + +// Retrieve the current page text and display. +static void RunGetTextTest(CefRefPtr frame) +{ + std::wstring text = frame->GetText(); + text = StringReplace(text, L"<", L"<"); + text = StringReplace(text, L">", L">"); + std::wstringstream ss; + ss << L"Text:" << L"
" << text
+      << L"
"; + frame->LoadString(ss.str(), L"http://tests/gettext"); +} + +// +// 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] = {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); + + rect.top += URLBAR_HEIGHT; + + CefWindowInfo info; + + // Initialize window info to the defaults for a child window + info.SetAsChild(hWnd, rect); + + // Creat the new child child browser window + CefBrowser::CreateBrowser(info, false, + static_cast>(g_handler), + L"http://www.google.com"); + + // Start the timer that will be used to update child window state + SetTimer(hWnd, 1, 250, NULL); + } + return 0; + + case WM_TIMER: + if(g_handler.get() && g_handler->GetBrowserHwnd()) + { + // Retrieve the current navigation state + bool isLoading, canGoBack, canGoForward; + g_handler->GetNavState(isLoading, canGoBack, canGoForward); + + // Update the status of child windows + EnableWindow(editWnd, TRUE); + EnableWindow(backWnd, canGoBack); + EnableWindow(forwardWnd, canGoForward); + EnableWindow(reloadWnd, !isLoading); + EnableWindow(stopWnd, isLoading); + } + 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 " + << g_handler->GetLogFile(); + MessageBoxW(hWnd, ss.str().c_str(), L"Console Messages", + 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()) { +#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP + RunGetSourceTest(browser->GetMainFrame()); +#else // !TEST_SINGLE_THREADED_MESSAGE_LOOP + // Execute the GetSource() call on the FILE thread to avoid blocking + // the UI thread when using a multi-threaded message loop + // (issue #79). + class ExecTask : public CefThreadSafeBase + { + public: + ExecTask(CefRefPtr frame) : m_Frame(frame) {} + virtual void Execute(CefThreadId threadId) + { + RunGetSourceTest(m_Frame); + } + private: + CefRefPtr m_Frame; + }; + CefPostTask(TID_FILE, new ExecTask(browser->GetMainFrame())); +#endif // !TEST_SINGLE_THREADED_MESSAGE_LOOP + } + return 0; + case ID_TESTS_GETTEXT: // Test the GetText function + if(browser.get()) { +#ifdef TEST_SINGLE_THREADED_MESSAGE_LOOP + RunGetTextTest(browser->GetMainFrame()); +#else // !TEST_SINGLE_THREADED_MESSAGE_LOOP + // Execute the GetText() call on the FILE thread to avoid blocking + // the UI thread when using a multi-threaded message loop + // (issue #79). + class ExecTask : public CefThreadSafeBase + { + public: + ExecTask(CefRefPtr frame) : m_Frame(frame) {} + virtual void Execute(CefThreadId threadId) + { + RunGetTextTest(m_Frame); + } + private: + CefRefPtr m_Frame; + }; + CefPostTask(TID_FILE, new ExecTask(browser->GetMainFrame())); +#endif // !TEST_SINGLE_THREADED_MESSAGE_LOOP + } + 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_EXECUTE: // Test execution of javascript + if(browser.get()) + { + browser->GetMainFrame()->ExecuteJavaScript( + L"alert('JavaScript execute works!');", + L"about:blank", 0); + } + return 0; + case ID_TESTS_PLUGIN: // Test the custom plugin + if(browser.get()) + RunPluginTest(browser); + return 0; + case ID_TESTS_POPUP: // Test a popup window + if(browser.get()) + { + browser->GetMainFrame()->ExecuteJavaScript( + L"window.open('http://www.google.com');", + L"about:blank", 0); + } + return 0; + case ID_TESTS_REQUEST: // Test a request + if(browser.get()) + { + // Create a new request + CefRefPtr request(CefRequest::CreateRequest()); + + // Set the request URL + request->SetURL(L"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(L"X-My-Header", L"My Header Value")); + request->SetHeaderMap(headerMap); + + // Load the request + browser->GetMainFrame()->LoadRequest(request); + } + 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; + } + } + 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_DESTROY: + // The frame window has exited + KillTimer(hWnd, 1); + 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; +} diff --git a/tests/cefclient/cefclient.h b/tests/cefclient/cefclient.h index cbe090164..96cdc9296 100644 --- a/tests/cefclient/cefclient.h +++ b/tests/cefclient/cefclient.h @@ -1,14 +1,14 @@ -// 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. - -#pragma once - -#include "resource.h" -#include "include/cef.h" - -// Return the main browser window instance. -CefRefPtr AppGetBrowser(); - -// Return the main application window handle. -HWND AppGetMainHwnd(); +// 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. + +#pragma once + +#include "resource.h" +#include "include/cef.h" + +// Return the main browser window instance. +CefRefPtr AppGetBrowser(); + +// Return the main application window handle. +HWND AppGetMainHwnd(); diff --git a/tests/cefclient/clientplugin.cpp b/tests/cefclient/clientplugin.cpp index c9c2a9904..9a33d4b2a 100644 --- a/tests/cefclient/clientplugin.cpp +++ b/tests/cefclient/clientplugin.cpp @@ -1,186 +1,186 @@ -// 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 "clientplugin.h" - -// Initialized in NP_Initialize. -NPNetscapeFuncs* g_browser = NULL; - -static -NPError NPP_New(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_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; -} - -static -NPError NPP_Destroy(NPP instance, NPSavedData** save) { - ClientPlugin* plugin_impl = reinterpret_cast(instance->pdata); - - if (plugin_impl) { - plugin_impl->Shutdown(); - delete plugin_impl; - } - - return NPERR_NO_ERROR; -} - -static -NPError NPP_SetWindow(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; -} - -NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) -{ - pFuncs->newp = NPP_New; - pFuncs->destroy = NPP_Destroy; - pFuncs->setwindow = NPP_SetWindow; - return NPERR_NO_ERROR; -} - -NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs) -{ - g_browser = pFuncs; - return NPERR_NO_ERROR; -} - -NPError API_CALL NP_Shutdown(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) -{ - static LPCWSTR text = L"Left click in the green area for a message box!"; - - PAINTSTRUCT paint_struct; - BeginPaint(&paint_struct); - - RECT client_rect; - GetClientRect(&client_rect); - - int old_mode = SetBkMode(paint_struct.hdc, TRANSPARENT); - COLORREF old_color = SetTextColor(paint_struct.hdc, RGB(0, 0, 255)); - - RECT text_rect = client_rect; - DrawText(paint_struct.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(paint_struct.hdc, text, -1, &client_rect, DT_CENTER); - - SetBkMode(paint_struct.hdc, old_mode); - SetTextColor(paint_struct.hdc, old_color); - - EndPaint(&paint_struct); - 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(); -} +// 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 "clientplugin.h" + +// Initialized in NP_Initialize. +NPNetscapeFuncs* g_browser = NULL; + +static +NPError NPP_New(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_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; +} + +static +NPError NPP_Destroy(NPP instance, NPSavedData** save) { + ClientPlugin* plugin_impl = reinterpret_cast(instance->pdata); + + if (plugin_impl) { + plugin_impl->Shutdown(); + delete plugin_impl; + } + + return NPERR_NO_ERROR; +} + +static +NPError NPP_SetWindow(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; +} + +NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) +{ + pFuncs->newp = NPP_New; + pFuncs->destroy = NPP_Destroy; + pFuncs->setwindow = NPP_SetWindow; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs) +{ + g_browser = pFuncs; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_Shutdown(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) +{ + static LPCWSTR text = L"Left click in the green area for a message box!"; + + PAINTSTRUCT paint_struct; + BeginPaint(&paint_struct); + + RECT client_rect; + GetClientRect(&client_rect); + + int old_mode = SetBkMode(paint_struct.hdc, TRANSPARENT); + COLORREF old_color = SetTextColor(paint_struct.hdc, RGB(0, 0, 255)); + + RECT text_rect = client_rect; + DrawText(paint_struct.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(paint_struct.hdc, text, -1, &client_rect, DT_CENTER); + + SetBkMode(paint_struct.hdc, old_mode); + SetTextColor(paint_struct.hdc, old_color); + + EndPaint(&paint_struct); + 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(); +} diff --git a/tests/cefclient/clientplugin.h b/tests/cefclient/clientplugin.h index 7684a7ac9..fe46f2ab5 100644 --- a/tests/cefclient/clientplugin.h +++ b/tests/cefclient/clientplugin.h @@ -1,88 +1,88 @@ -// 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 - -#pragma once - -#include -#include -#include "include/cef_nplugin.h" - -extern NPNetscapeFuncs* g_browser; - -NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs); -NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs); -NPError API_CALL NP_Shutdown(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_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 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(); - - private: - // The plugins opaque instance handle - NPP instance_; - // The plugin instantiation mode (NP_FULL or NP_EMBED) - int16 mode_; +// 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 + +#pragma once + +#include +#include +#include "include/cef_nplugin.h" + +extern NPNetscapeFuncs* g_browser; + +NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs); +NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs); +NPError API_CALL NP_Shutdown(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_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 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(); + + private: + // The plugins opaque instance handle + NPP instance_; + // The plugin instantiation mode (NP_FULL or NP_EMBED) + int16 mode_; }; \ No newline at end of file diff --git a/tests/cefclient/extension_test.cpp b/tests/cefclient/extension_test.cpp index 909eb8f64..002407ceb 100644 --- a/tests/cefclient/extension_test.cpp +++ b/tests/cefclient/extension_test.cpp @@ -1,111 +1,111 @@ -// 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 "extension_test.h" - - -// Implementation of the V8 handler class for the "cef.test" extension. -class ClientV8ExtensionHandler : public CefThreadSafeBase -{ -public: - ClientV8ExtensionHandler() : test_param_(L"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 std::wstring& name, - CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) - { - if(name == L"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 == L"GetTestParam") - { - // Handle the GetTestParam native function by returning the local member - // value. - retval = CefV8Value::CreateString(test_param_); - return true; - } - else if(name == L"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(L"param", CefV8Value::CreateString( - L"Retrieving a parameter on a native object succeeded.")); - // Add a function to the new V8 object. - retval->SetValue(L"GetMessage", - CefV8Value::CreateFunction(L"GetMessage", this)); - return true; - } - else if(name == L"GetMessage") - { - // Handle the GetMessage object function by returning a string. - retval = CefV8Value::CreateString( - L"Calling a function on a native object succeeded."); - return true; - } - return false; - } - -private: - std::wstring test_param_; -}; - - -void InitExtensionTest() -{ - // Register a V8 extension with the below JavaScript code that calls native - // methods implemented in ClientV8ExtensionHandler. - std::wstring code = L"var cef;" - L"if (!cef)" - L" cef = {};" - L"if (!cef.test)" - L" cef.test = {};" - L"(function() {" - L" cef.test.__defineGetter__('test_param', function() {" - L" native function GetTestParam();" - L" return GetTestParam();" - L" });" - L" cef.test.__defineSetter__('test_param', function(b) {" - L" native function SetTestParam();" - L" if(b) SetTestParam(b);" - L" });" - L" cef.test.test_object = function() {" - L" native function GetTestObject();" - L" return GetTestObject();" - L" };" - L"})();"; - CefRegisterExtension(L"v8/test", code, new ClientV8ExtensionHandler()); -} - -void RunExtensionTest(CefRefPtr browser) -{ - std::wstring html = - L"ClientV8ExtensionHandler says:
"
-    L""
-    L"
"; - browser->GetMainFrame()->LoadString(html, L"about:blank"); -} +// 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 "extension_test.h" + + +// Implementation of the V8 handler class for the "cef.test" extension. +class ClientV8ExtensionHandler : public CefThreadSafeBase +{ +public: + ClientV8ExtensionHandler() : test_param_(L"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 std::wstring& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) + { + if(name == L"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 == L"GetTestParam") + { + // Handle the GetTestParam native function by returning the local member + // value. + retval = CefV8Value::CreateString(test_param_); + return true; + } + else if(name == L"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(L"param", CefV8Value::CreateString( + L"Retrieving a parameter on a native object succeeded.")); + // Add a function to the new V8 object. + retval->SetValue(L"GetMessage", + CefV8Value::CreateFunction(L"GetMessage", this)); + return true; + } + else if(name == L"GetMessage") + { + // Handle the GetMessage object function by returning a string. + retval = CefV8Value::CreateString( + L"Calling a function on a native object succeeded."); + return true; + } + return false; + } + +private: + std::wstring test_param_; +}; + + +void InitExtensionTest() +{ + // Register a V8 extension with the below JavaScript code that calls native + // methods implemented in ClientV8ExtensionHandler. + std::wstring code = L"var cef;" + L"if (!cef)" + L" cef = {};" + L"if (!cef.test)" + L" cef.test = {};" + L"(function() {" + L" cef.test.__defineGetter__('test_param', function() {" + L" native function GetTestParam();" + L" return GetTestParam();" + L" });" + L" cef.test.__defineSetter__('test_param', function(b) {" + L" native function SetTestParam();" + L" if(b) SetTestParam(b);" + L" });" + L" cef.test.test_object = function() {" + L" native function GetTestObject();" + L" return GetTestObject();" + L" };" + L"})();"; + CefRegisterExtension(L"v8/test", code, new ClientV8ExtensionHandler()); +} + +void RunExtensionTest(CefRefPtr browser) +{ + std::wstring html = + L"ClientV8ExtensionHandler says:
"
+    L""
+    L"
"; + browser->GetMainFrame()->LoadString(html, L"about:blank"); +} diff --git a/tests/cefclient/extension_test.h b/tests/cefclient/extension_test.h index 3d48936b6..cdfcb73a7 100644 --- a/tests/cefclient/extension_test.h +++ b/tests/cefclient/extension_test.h @@ -1,12 +1,12 @@ -// 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. - -#pragma once -#include "include/cef.h" - -// Register the V8 extension handler. -void InitExtensionTest(); - -// Run the test. -void RunExtensionTest(CefRefPtr browser); +// 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. + +#pragma once +#include "include/cef.h" + +// Register the V8 extension handler. +void InitExtensionTest(); + +// Run the test. +void RunExtensionTest(CefRefPtr browser); diff --git a/tests/cefclient/plugin_test.cpp b/tests/cefclient/plugin_test.cpp index 189ea1be4..67da3f7f1 100644 --- a/tests/cefclient/plugin_test.cpp +++ b/tests/cefclient/plugin_test.cpp @@ -1,38 +1,38 @@ -// 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.h" -#include "clientplugin.h" - -void InitPluginTest() -{ - // Structure providing information about the client plugin. - CefPluginInfo plugin_info; - plugin_info.display_name = L"Client Plugin"; - plugin_info.unique_name = L"client_plugin"; - plugin_info.version = L"1, 0, 0, 1"; - plugin_info.description = L"My Example Client Plugin"; - - CefPluginMimeType mime_type; - mime_type.mime_type = L"application/x-client-plugin"; - mime_type.file_extensions.push_back(L"*"); - plugin_info.mime_types.push_back(mime_type); - - plugin_info.np_getentrypoints = NP_GetEntryPoints; - plugin_info.np_initialize = NP_Initialize; - plugin_info.np_shutdown = NP_Shutdown; - - // Register the internal client plugin - CefRegisterPlugin(plugin_info); -} - -void RunPluginTest(CefRefPtr browser) -{ - std::wstring html = - L"Client Plugin:
" - L"" - L""; - browser->GetMainFrame()->LoadString(html, L"about:blank"); -} +// 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.h" +#include "clientplugin.h" + +void InitPluginTest() +{ + // Structure providing information about the client plugin. + CefPluginInfo plugin_info; + plugin_info.display_name = L"Client Plugin"; + plugin_info.unique_name = L"client_plugin"; + plugin_info.version = L"1, 0, 0, 1"; + plugin_info.description = L"My Example Client Plugin"; + + CefPluginMimeType mime_type; + mime_type.mime_type = L"application/x-client-plugin"; + mime_type.file_extensions.push_back(L"*"); + plugin_info.mime_types.push_back(mime_type); + + plugin_info.np_getentrypoints = NP_GetEntryPoints; + plugin_info.np_initialize = NP_Initialize; + plugin_info.np_shutdown = NP_Shutdown; + + // Register the internal client plugin + CefRegisterPlugin(plugin_info); +} + +void RunPluginTest(CefRefPtr browser) +{ + std::wstring html = + L"Client Plugin:
" + L"" + L""; + browser->GetMainFrame()->LoadString(html, L"about:blank"); +} diff --git a/tests/cefclient/plugin_test.h b/tests/cefclient/plugin_test.h index d91d4ef63..c4ed2ac15 100644 --- a/tests/cefclient/plugin_test.h +++ b/tests/cefclient/plugin_test.h @@ -1,12 +1,12 @@ -// 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. - -#pragma once -#include "include/cef.h" - -// Register the internal client plugin. -void InitPluginTest(); - -// Run the test. -void RunPluginTest(CefRefPtr browser); +// 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. + +#pragma once +#include "include/cef.h" + +// Register the internal client plugin. +void InitPluginTest(); + +// Run the test. +void RunPluginTest(CefRefPtr browser); diff --git a/tests/cefclient/res/uiplugin.html b/tests/cefclient/res/uiplugin.html index 4e8df8b32..8d982db0b 100644 --- a/tests/cefclient/res/uiplugin.html +++ b/tests/cefclient/res/uiplugin.html @@ -1,57 +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: -
- - -
-
-
- - - + + +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/tests/cefclient/resource.h b/tests/cefclient/resource.h index ea53c5d78..1fbc4b9e6 100644 --- a/tests/cefclient/resource.h +++ b/tests/cefclient/resource.h @@ -1,55 +1,55 @@ -// 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_FIND 32001 -#define ID_PRINT 32002 -#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 IDC_STATIC -1 -#define IDS_LOGO 1000 -#define IDS_UIPLUGIN 1001 -#define IDS_LOGOBALL 1002 - -// 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 32773 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 110 -#endif -#endif +// 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_FIND 32001 +#define ID_PRINT 32002 +#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 IDC_STATIC -1 +#define IDS_LOGO 1000 +#define IDS_UIPLUGIN 1001 +#define IDS_LOGOBALL 1002 + +// 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 32773 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 110 +#endif +#endif diff --git a/tests/cefclient/resource_util.cpp b/tests/cefclient/resource_util.cpp index 30dc6fc55..e18a8c28f 100644 --- a/tests/cefclient/resource_util.cpp +++ b/tests/cefclient/resource_util.cpp @@ -1,90 +1,90 @@ -// 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 "resource_util.h" - - -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; -} - - -// ClientReadHandler implementation - -ClientReadHandler::ClientReadHandler(LPBYTE pBytes, DWORD dwSize) - : bytes_(pBytes), size_(dwSize), offset_(0) {} - -size_t ClientReadHandler::Read(void* ptr, size_t size, size_t n) -{ - Lock(); - size_t s = (size_ - offset_) / size; - size_t ret = min(n, s); - memcpy(ptr, bytes_ + offset_, ret * size); - offset_ += ret * size; - Unlock(); - return ret; -} - -int ClientReadHandler::Seek(long offset, int whence) -{ - int rv = -1L; - Lock(); - switch(whence) { - case SEEK_CUR: - if(offset_ + offset > size_) { - break; - } - offset_ += offset; - rv = offset_; - break; - case SEEK_END: - if(offset > (int)size_) { - break; - } - offset_ = size_ - offset; - rv = offset_; - case SEEK_SET: - if(offset > (int)size_) { - break; - } - offset_ = offset; - rv = offset_; - break; - } - Unlock(); - - return rv; -} - -long ClientReadHandler::Tell() -{ - Lock(); - long rv = offset_; - Unlock(); - return rv; -} - -int ClientReadHandler::Eof() -{ - Lock(); - int rv = (offset_ >= size_); - Unlock(); - return rv; -} +// 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 "resource_util.h" + + +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; +} + + +// ClientReadHandler implementation + +ClientReadHandler::ClientReadHandler(LPBYTE pBytes, DWORD dwSize) + : bytes_(pBytes), size_(dwSize), offset_(0) {} + +size_t ClientReadHandler::Read(void* ptr, size_t size, size_t n) +{ + Lock(); + size_t s = (size_ - offset_) / size; + size_t ret = min(n, s); + memcpy(ptr, bytes_ + offset_, ret * size); + offset_ += ret * size; + Unlock(); + return ret; +} + +int ClientReadHandler::Seek(long offset, int whence) +{ + int rv = -1L; + Lock(); + switch(whence) { + case SEEK_CUR: + if(offset_ + offset > size_) { + break; + } + offset_ += offset; + rv = offset_; + break; + case SEEK_END: + if(offset > (int)size_) { + break; + } + offset_ = size_ - offset; + rv = offset_; + case SEEK_SET: + if(offset > (int)size_) { + break; + } + offset_ = offset; + rv = offset_; + break; + } + Unlock(); + + return rv; +} + +long ClientReadHandler::Tell() +{ + Lock(); + long rv = offset_; + Unlock(); + return rv; +} + +int ClientReadHandler::Eof() +{ + Lock(); + int rv = (offset_ >= size_); + Unlock(); + return rv; +} diff --git a/tests/cefclient/resource_util.h b/tests/cefclient/resource_util.h index 7fdac3dab..d60384c85 100644 --- a/tests/cefclient/resource_util.h +++ b/tests/cefclient/resource_util.h @@ -1,39 +1,39 @@ -// 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. - -#pragma once - -#include "include/cef.h" - -#ifndef min -#define min(a,b) ((a)<(b)?(a):(b)) -#endif - -// Load a resource of type BINARY -bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes); - - -// Implementation of the stream read handler for reading in-memory data. -class ClientReadHandler : public CefThreadSafeBase -{ -public: - ClientReadHandler(LPBYTE pBytes, DWORD dwSize); - - // 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(long offset, int whence); - - // Return the current offset position. - virtual long Tell(); - - // Return non-zero if at end of file. - virtual int Eof(); - -private: - LPBYTE bytes_; - DWORD size_, offset_; -}; +// 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. + +#pragma once + +#include "include/cef.h" + +#ifndef min +#define min(a,b) ((a)<(b)?(a):(b)) +#endif + +// Load a resource of type BINARY +bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes); + + +// Implementation of the stream read handler for reading in-memory data. +class ClientReadHandler : public CefThreadSafeBase +{ +public: + ClientReadHandler(LPBYTE pBytes, DWORD dwSize); + + // 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(long offset, int whence); + + // Return the current offset position. + virtual long Tell(); + + // Return non-zero if at end of file. + virtual int Eof(); + +private: + LPBYTE bytes_; + DWORD size_, offset_; +}; diff --git a/tests/cefclient/scheme_test.cpp b/tests/cefclient/scheme_test.cpp index 7e833fb85..1bbd02fc6 100644 --- a/tests/cefclient/scheme_test.cpp +++ b/tests/cefclient/scheme_test.cpp @@ -1,133 +1,133 @@ -// 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 "scheme_test.h" -#include "string_util.h" -#include "resource_util.h" -#include "resource.h" - - -// Implementation of the schema handler for client:// requests. -class ClientSchemeHandler : public CefThreadSafeBase -{ -public: - ClientSchemeHandler() : size_(0), offset_(0), bytes_(NULL) {} - - // Process the request. All response generation should take place in this - // method. If there is no response set |response_length| to zero and - // ReadResponse() will not be called. If the response length is not known then - // set |response_length| to -1 and ReadResponse() will be called until it - // returns false or until the value of |bytes_read| is set to 0. Otherwise, - // set |response_length| to a positive value and ReadResponse() will be called - // until it returns false, the value of |bytes_read| is set to 0 or the - // specified number of bytes have been read. If there is a response set - // |mime_type| to the mime type for the response. - virtual bool ProcessRequest(CefRefPtr request, - std::wstring& mime_type, int* response_length) - { - bool handled = false; - - Lock(); - std::wstring url = request->GetURL(); - if(wcsstr(url.c_str(), L"handler.html") != NULL) { - // Build the response html - html_ = "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::wstring dump;
-      DumpRequestContents(request, dump);
-      html_.append(WStringToString(dump));
-
-      html_.append("

Try the test form:" - "
" - "" - "" - "" - "
"); - - handled = true; - size_ = html_.size(); - bytes_ = (LPBYTE)html_.c_str(); - - // Set the resulting mime type - mime_type = L"text/html"; - } - else if(wcsstr(url.c_str(), L"client.gif") != NULL) { - // Load the response image - if(LoadBinaryResource(IDS_LOGO, size_, bytes_)) { - handled = true; - // Set the resulting mime type - mime_type = L"image/jpg"; - } - } - - // Set the resulting response length - *response_length = size_; - Unlock(); - - return handled; - } - - // Cancel processing of the request. - virtual void Cancel() - { - } - - // Copy up to |bytes_to_read| bytes into |data_out|. If the copy succeeds - // set |bytes_read| to the number of bytes copied and return true. If the - // copy fails return false and ReadResponse() will not be called again. - virtual bool ReadResponse(void* data_out, int bytes_to_read, - int* bytes_read) - { - bool has_data = false; - *bytes_read = 0; - - Lock(); - - if(offset_ < size_) { - // Copy the next block of data into the buffer. - int transfer_size = min(bytes_to_read, static_cast(size_ - offset_)); - memcpy(data_out, bytes_ + offset_, transfer_size); - offset_ += transfer_size; - - *bytes_read = transfer_size; - has_data = true; - } - - Unlock(); - - return has_data; - } - -private: - DWORD size_, offset_; - LPBYTE bytes_; - std::string html_; -}; - -// Implementation of the factory for for creating schema handlers. -class ClientSchemeHandlerFactory : - public CefThreadSafeBase -{ -public: - // Return a new scheme handler instance to handle the request. - virtual CefRefPtr Create() - { - return new ClientSchemeHandler(); - } -}; - -void InitSchemeTest() -{ - CefRegisterScheme(L"client", L"tests", new ClientSchemeHandlerFactory()); -} - -void RunSchemeTest(CefRefPtr browser) -{ - browser->GetMainFrame()->LoadURL(L"client://tests/handler.html"); -} +// 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 "scheme_test.h" +#include "string_util.h" +#include "resource_util.h" +#include "resource.h" + + +// Implementation of the schema handler for client:// requests. +class ClientSchemeHandler : public CefThreadSafeBase +{ +public: + ClientSchemeHandler() : size_(0), offset_(0), bytes_(NULL) {} + + // Process the request. All response generation should take place in this + // method. If there is no response set |response_length| to zero and + // ReadResponse() will not be called. If the response length is not known then + // set |response_length| to -1 and ReadResponse() will be called until it + // returns false or until the value of |bytes_read| is set to 0. Otherwise, + // set |response_length| to a positive value and ReadResponse() will be called + // until it returns false, the value of |bytes_read| is set to 0 or the + // specified number of bytes have been read. If there is a response set + // |mime_type| to the mime type for the response. + virtual bool ProcessRequest(CefRefPtr request, + std::wstring& mime_type, int* response_length) + { + bool handled = false; + + Lock(); + std::wstring url = request->GetURL(); + if(wcsstr(url.c_str(), L"handler.html") != NULL) { + // Build the response html + html_ = "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::wstring dump;
+      DumpRequestContents(request, dump);
+      html_.append(WStringToString(dump));
+
+      html_.append("

Try the test form:" + "
" + "" + "" + "" + "
"); + + handled = true; + size_ = html_.size(); + bytes_ = (LPBYTE)html_.c_str(); + + // Set the resulting mime type + mime_type = L"text/html"; + } + else if(wcsstr(url.c_str(), L"client.gif") != NULL) { + // Load the response image + if(LoadBinaryResource(IDS_LOGO, size_, bytes_)) { + handled = true; + // Set the resulting mime type + mime_type = L"image/jpg"; + } + } + + // Set the resulting response length + *response_length = size_; + Unlock(); + + return handled; + } + + // Cancel processing of the request. + virtual void Cancel() + { + } + + // Copy up to |bytes_to_read| bytes into |data_out|. If the copy succeeds + // set |bytes_read| to the number of bytes copied and return true. If the + // copy fails return false and ReadResponse() will not be called again. + virtual bool ReadResponse(void* data_out, int bytes_to_read, + int* bytes_read) + { + bool has_data = false; + *bytes_read = 0; + + Lock(); + + if(offset_ < size_) { + // Copy the next block of data into the buffer. + int transfer_size = min(bytes_to_read, static_cast(size_ - offset_)); + memcpy(data_out, bytes_ + offset_, transfer_size); + offset_ += transfer_size; + + *bytes_read = transfer_size; + has_data = true; + } + + Unlock(); + + return has_data; + } + +private: + DWORD size_, offset_; + LPBYTE bytes_; + std::string html_; +}; + +// Implementation of the factory for for creating schema handlers. +class ClientSchemeHandlerFactory : + public CefThreadSafeBase +{ +public: + // Return a new scheme handler instance to handle the request. + virtual CefRefPtr Create() + { + return new ClientSchemeHandler(); + } +}; + +void InitSchemeTest() +{ + CefRegisterScheme(L"client", L"tests", new ClientSchemeHandlerFactory()); +} + +void RunSchemeTest(CefRefPtr browser) +{ + browser->GetMainFrame()->LoadURL(L"client://tests/handler.html"); +} diff --git a/tests/cefclient/scheme_test.h b/tests/cefclient/scheme_test.h index b46502e8e..2cb192fd3 100644 --- a/tests/cefclient/scheme_test.h +++ b/tests/cefclient/scheme_test.h @@ -1,12 +1,12 @@ -// 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. - -#pragma once -#include "include/cef.h" - -// Register the scheme handler. -void InitSchemeTest(); - -// Run the test. -void RunSchemeTest(CefRefPtr browser); +// 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. + +#pragma once +#include "include/cef.h" + +// Register the scheme handler. +void InitSchemeTest(); + +// Run the test. +void RunSchemeTest(CefRefPtr browser); diff --git a/tests/cefclient/string_util.cpp b/tests/cefclient/string_util.cpp index a50a1002e..528bdd0ed 100644 --- a/tests/cefclient/string_util.cpp +++ b/tests/cefclient/string_util.cpp @@ -1,100 +1,100 @@ -// 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 "string_util.h" -#include - - -std::wstring StringToWString(const std::string& s) -{ - wchar_t* wch; - UINT bytes = MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size()+1, NULL, 0); - wch = new wchar_t[bytes]; - if(wch) - bytes = MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size()+1, wch, bytes); - std::wstring str = wch; - delete [] wch; - return str; -} - -std::string WStringToString(const std::wstring& s) -{ - char* ch; - UINT bytes = WideCharToMultiByte(CP_ACP, 0, s.c_str(), s.size()+1, NULL, 0, - NULL, NULL); - ch = new char[bytes]; - if(ch) - bytes = WideCharToMultiByte(CP_ACP, 0, s.c_str(), s.size()+1, ch, bytes, - NULL, NULL); - std::string str = ch; - delete [] ch; - return str; -} - -void DumpRequestContents(CefRefPtr request, std::wstring& str) -{ - std::wstringstream ss; - - ss << L"URL: " << request->GetURL(); - ss << L"\nMethod: " << request->GetMethod(); - - CefRequest::HeaderMap headerMap; - request->GetHeaderMap(headerMap); - if(headerMap.size() > 0) { - ss << L"\nHeaders:"; - CefRequest::HeaderMap::const_iterator it = headerMap.begin(); - for(; it != headerMap.end(); ++it) { - ss << L"\n\t" << (*it).first << L": " << (*it).second; - } - } - - CefRefPtr postData = request->GetPostData(); - if(postData.get()) { - CefPostData::ElementVector elements; - postData->GetElements(elements); - if(elements.size() > 0) { - ss << L"\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 << L"\n\tBytes: "; - if(element->GetBytesCount() == 0) - ss << L"(empty)"; - else { - // retrieve the data. - size_t size = element->GetBytesCount(); - char* bytes = new char[size]; - element->GetBytes(size, bytes); - ss << StringToWString(std::string(bytes, size)); - delete [] bytes; - } - } else if(element->GetType() == PDE_TYPE_FILE) { - ss << L"\n\tFile: " << element->GetFile(); - } - } - } - } - - str = ss.str(); -} - -std::wstring StringReplace(const std::wstring& str, const std::wstring& from, - const std::wstring& to) -{ - std::wstring result = str; - std::wstring::size_type pos = 0; - std::wstring::size_type from_len = from.length(); - std::wstring::size_type to_len = to.length(); - do { - pos = result.find(from, pos); - if(pos != std::wstring::npos) { - result.replace(pos, from_len, to); - pos += to_len; - } - } while(pos != std::wstring::npos); - return result; -} +// 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 "string_util.h" +#include + + +std::wstring StringToWString(const std::string& s) +{ + wchar_t* wch; + UINT bytes = MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size()+1, NULL, 0); + wch = new wchar_t[bytes]; + if(wch) + bytes = MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size()+1, wch, bytes); + std::wstring str = wch; + delete [] wch; + return str; +} + +std::string WStringToString(const std::wstring& s) +{ + char* ch; + UINT bytes = WideCharToMultiByte(CP_ACP, 0, s.c_str(), s.size()+1, NULL, 0, + NULL, NULL); + ch = new char[bytes]; + if(ch) + bytes = WideCharToMultiByte(CP_ACP, 0, s.c_str(), s.size()+1, ch, bytes, + NULL, NULL); + std::string str = ch; + delete [] ch; + return str; +} + +void DumpRequestContents(CefRefPtr request, std::wstring& str) +{ + std::wstringstream ss; + + ss << L"URL: " << request->GetURL(); + ss << L"\nMethod: " << request->GetMethod(); + + CefRequest::HeaderMap headerMap; + request->GetHeaderMap(headerMap); + if(headerMap.size() > 0) { + ss << L"\nHeaders:"; + CefRequest::HeaderMap::const_iterator it = headerMap.begin(); + for(; it != headerMap.end(); ++it) { + ss << L"\n\t" << (*it).first << L": " << (*it).second; + } + } + + CefRefPtr postData = request->GetPostData(); + if(postData.get()) { + CefPostData::ElementVector elements; + postData->GetElements(elements); + if(elements.size() > 0) { + ss << L"\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 << L"\n\tBytes: "; + if(element->GetBytesCount() == 0) + ss << L"(empty)"; + else { + // retrieve the data. + size_t size = element->GetBytesCount(); + char* bytes = new char[size]; + element->GetBytes(size, bytes); + ss << StringToWString(std::string(bytes, size)); + delete [] bytes; + } + } else if(element->GetType() == PDE_TYPE_FILE) { + ss << L"\n\tFile: " << element->GetFile(); + } + } + } + } + + str = ss.str(); +} + +std::wstring StringReplace(const std::wstring& str, const std::wstring& from, + const std::wstring& to) +{ + std::wstring result = str; + std::wstring::size_type pos = 0; + std::wstring::size_type from_len = from.length(); + std::wstring::size_type to_len = to.length(); + do { + pos = result.find(from, pos); + if(pos != std::wstring::npos) { + result.replace(pos, from_len, to); + pos += to_len; + } + } while(pos != std::wstring::npos); + return result; +} diff --git a/tests/cefclient/string_util.h b/tests/cefclient/string_util.h index 8a2ed7d3e..963891c46 100644 --- a/tests/cefclient/string_util.h +++ b/tests/cefclient/string_util.h @@ -1,22 +1,22 @@ -// 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. - -#pragma once - -#include "include/cef.h" -#include - - -// Convert a std::string to a std::wstring -std::wstring StringToWString(const std::string& s); - -// Convert a std::wstring to a std::string -std::string WStringToString(const std::wstring& s); - -// Dump the contents of the request into a string. -void DumpRequestContents(CefRefPtr request, std::wstring& str); - -// Replace all instances of |from| with |to| in |str|. -std::wstring StringReplace(const std::wstring& str, const std::wstring& from, +// 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. + +#pragma once + +#include "include/cef.h" +#include + + +// Convert a std::string to a std::wstring +std::wstring StringToWString(const std::string& s); + +// Convert a std::wstring to a std::string +std::string WStringToString(const std::wstring& s); + +// Dump the contents of the request into a string. +void DumpRequestContents(CefRefPtr request, std::wstring& str); + +// Replace all instances of |from| with |to| in |str|. +std::wstring StringReplace(const std::wstring& str, const std::wstring& from, const std::wstring& to); \ No newline at end of file diff --git a/tests/cefclient/uiplugin.cpp b/tests/cefclient/uiplugin.cpp index 6ab591040..1afc19e31 100644 --- a/tests/cefclient/uiplugin.cpp +++ b/tests/cefclient/uiplugin.cpp @@ -1,283 +1,283 @@ -// 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 "uiplugin.h" -#include "cefclient.h" -#include -#include - - -// Initialized in NP_Initialize. -NPNetscapeFuncs* g_uibrowser = NULL; - -// 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); - -static -NPError NPP_New(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; -} - -static -NPError NPP_Destroy(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; -} - -static -NPError NPP_SetWindow(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); - - // 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; -} - -NPError API_CALL NP_UIGetEntryPoints(NPPluginFuncs* pFuncs) -{ - pFuncs->newp = NPP_New; - pFuncs->destroy = NPP_Destroy; - pFuncs->setwindow = NPP_SetWindow; - 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; -} - -// Send the notification to the browser as a JavaScript function call. -static void NotifyNewRotation(float value) -{ - std::wstringstream buf; - buf << L"notifyNewRotation(" << value << L");"; - AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(buf.str(), std::wstring(), - 0); -} - -void ModifyRotation(float value) -{ - g_rotationspeed += value; - NotifyNewRotation(g_rotationspeed); -} - -void ResetRotation() -{ - g_rotationspeed = 0.0; - NotifyNewRotation(g_rotationspeed); -} - -// 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) -{ - HDC hDC; - int width, height; - - 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: - // Resize the OpenGL viewport to match the window size. - width = LOWORD(lParam); - height = HIWORD(lParam); - glViewport(0, 0, width, height); - break; - - case WM_ERASEBKGND: - return 0; - - case WM_TIMER: - // Adjust the theta value and redraw the display when the timer fires. - hDC = GetDC(hWnd); - - 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(hDC); - ReleaseDC(hWnd, 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); - wglMakeCurrent(*hDC, *hRC); -} - -// Disable OpenGL. -void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC) -{ - wglMakeCurrent(NULL, NULL); - wglDeleteContext(hRC); - ReleaseDC(hWnd, hDC); -} +// 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 "uiplugin.h" +#include "cefclient.h" +#include +#include + + +// Initialized in NP_Initialize. +NPNetscapeFuncs* g_uibrowser = NULL; + +// 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); + +static +NPError NPP_New(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; +} + +static +NPError NPP_Destroy(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; +} + +static +NPError NPP_SetWindow(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); + + // 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; +} + +NPError API_CALL NP_UIGetEntryPoints(NPPluginFuncs* pFuncs) +{ + pFuncs->newp = NPP_New; + pFuncs->destroy = NPP_Destroy; + pFuncs->setwindow = NPP_SetWindow; + 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; +} + +// Send the notification to the browser as a JavaScript function call. +static void NotifyNewRotation(float value) +{ + std::wstringstream buf; + buf << L"notifyNewRotation(" << value << L");"; + AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(buf.str(), std::wstring(), + 0); +} + +void ModifyRotation(float value) +{ + g_rotationspeed += value; + NotifyNewRotation(g_rotationspeed); +} + +void ResetRotation() +{ + g_rotationspeed = 0.0; + NotifyNewRotation(g_rotationspeed); +} + +// 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) +{ + HDC hDC; + int width, height; + + 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: + // Resize the OpenGL viewport to match the window size. + width = LOWORD(lParam); + height = HIWORD(lParam); + glViewport(0, 0, width, height); + break; + + case WM_ERASEBKGND: + return 0; + + case WM_TIMER: + // Adjust the theta value and redraw the display when the timer fires. + hDC = GetDC(hWnd); + + 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(hDC); + ReleaseDC(hWnd, 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); + wglMakeCurrent(*hDC, *hRC); +} + +// Disable OpenGL. +void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC) +{ + wglMakeCurrent(NULL, NULL); + wglDeleteContext(hRC); + ReleaseDC(hWnd, hDC); +} diff --git a/tests/cefclient/uiplugin.h b/tests/cefclient/uiplugin.h index 9990c8304..a42501f78 100644 --- a/tests/cefclient/uiplugin.h +++ b/tests/cefclient/uiplugin.h @@ -1,22 +1,22 @@ -// 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 - -#pragma once - -#include "include/cef_nplugin.h" - -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. +// 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 + +#pragma once + +#include "include/cef_nplugin.h" + +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(); \ No newline at end of file diff --git a/tests/cefclient/uiplugin_test.cpp b/tests/cefclient/uiplugin_test.cpp index 9e1a2976f..e938a7c63 100644 --- a/tests/cefclient/uiplugin_test.cpp +++ b/tests/cefclient/uiplugin_test.cpp @@ -1,105 +1,105 @@ -// 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 "uiplugin_test.h" -#include "uiplugin.h" -#include "cefclient.h" - - -// Implementation of the V8 handler class for the "window.uiapp" functions. -class ClientV8UIHandler : public CefThreadSafeBase -{ -public: - ClientV8UIHandler() {} - - // Execute with the specified argument list and return value. Return true if - // the method was handled. - virtual bool Execute(const std::wstring& name, - CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) - { - if(name == L"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 == L"resetRotation") { - // Reset the rotation value. - ResetRotation(); - return true; - } else if(name == L"viewSource") { - // View the page source. - AppGetBrowser()->GetMainFrame()->ViewSource(); - return true; - } - - return false; - } -}; - -void InitUIPluginTest() -{ - // Structure providing information about the client plugin. - CefPluginInfo plugin_info; - plugin_info.display_name = L"Client UI Plugin"; - plugin_info.unique_name = L"client_ui_plugin"; - plugin_info.version = L"1, 0, 0, 1"; - plugin_info.description = L"My Example Client UI Plugin"; - - CefPluginMimeType mime_type; - mime_type.mime_type = L"application/x-client-ui-plugin"; - mime_type.file_extensions.push_back(L"*"); - plugin_info.mime_types.push_back(mime_type); - - 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::wstring code = L"var cef;" - L"if (!cef)" - L" cef = {};" - L"if (!cef.uiapp)" - L" cef.uiapp = {};" - L"(function() {" - L" cef.uiapp.modifyRotation = function(val) {" - L" native function modifyRotation();" - L" return modifyRotation(val);" - L" };" - L" cef.uiapp.resetRotation = function() {" - L" native function resetRotation();" - L" return resetRotation();" - L" };" - L" cef.uiapp.viewSource = function() {" - L" native function viewSource();" - L" return viewSource();" - L" };" - L"})();"; - CefRegisterExtension(L"uiplugin/test", code, new ClientV8UIHandler()); -} - -void RunUIPluginTest(CefRefPtr browser) -{ - browser->GetMainFrame()->LoadURL(L"http://tests/uiapp"); -} +// 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 "uiplugin_test.h" +#include "uiplugin.h" +#include "cefclient.h" + + +// Implementation of the V8 handler class for the "window.uiapp" functions. +class ClientV8UIHandler : public CefThreadSafeBase +{ +public: + ClientV8UIHandler() {} + + // Execute with the specified argument list and return value. Return true if + // the method was handled. + virtual bool Execute(const std::wstring& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) + { + if(name == L"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 == L"resetRotation") { + // Reset the rotation value. + ResetRotation(); + return true; + } else if(name == L"viewSource") { + // View the page source. + AppGetBrowser()->GetMainFrame()->ViewSource(); + return true; + } + + return false; + } +}; + +void InitUIPluginTest() +{ + // Structure providing information about the client plugin. + CefPluginInfo plugin_info; + plugin_info.display_name = L"Client UI Plugin"; + plugin_info.unique_name = L"client_ui_plugin"; + plugin_info.version = L"1, 0, 0, 1"; + plugin_info.description = L"My Example Client UI Plugin"; + + CefPluginMimeType mime_type; + mime_type.mime_type = L"application/x-client-ui-plugin"; + mime_type.file_extensions.push_back(L"*"); + plugin_info.mime_types.push_back(mime_type); + + 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::wstring code = L"var cef;" + L"if (!cef)" + L" cef = {};" + L"if (!cef.uiapp)" + L" cef.uiapp = {};" + L"(function() {" + L" cef.uiapp.modifyRotation = function(val) {" + L" native function modifyRotation();" + L" return modifyRotation(val);" + L" };" + L" cef.uiapp.resetRotation = function() {" + L" native function resetRotation();" + L" return resetRotation();" + L" };" + L" cef.uiapp.viewSource = function() {" + L" native function viewSource();" + L" return viewSource();" + L" };" + L"})();"; + CefRegisterExtension(L"uiplugin/test", code, new ClientV8UIHandler()); +} + +void RunUIPluginTest(CefRefPtr browser) +{ + browser->GetMainFrame()->LoadURL(L"http://tests/uiapp"); +} diff --git a/tests/cefclient/uiplugin_test.h b/tests/cefclient/uiplugin_test.h index 388e1d079..1d1579b66 100644 --- a/tests/cefclient/uiplugin_test.h +++ b/tests/cefclient/uiplugin_test.h @@ -1,12 +1,12 @@ -// 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. - -#pragma once -#include "include/cef.h" - -// Register the internal client plugin and V8 extension. -void InitUIPluginTest(); - -// Run the test. -void RunUIPluginTest(CefRefPtr browser); +// 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. + +#pragma once +#include "include/cef.h" + +// Register the internal client plugin and V8 extension. +void InitUIPluginTest(); + +// Run the test. +void RunUIPluginTest(CefRefPtr browser); diff --git a/tests/unittests/request_unittest.cc b/tests/unittests/request_unittest.cc index ed5ae264c..15b660ea9 100644 --- a/tests/unittests/request_unittest.cc +++ b/tests/unittests/request_unittest.cc @@ -1,426 +1,426 @@ -// 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/cef.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "test_handler.h" - - -// Verify that CefRequest::HeaderMap objects are equal -// If |allowExtras| is true then additional header fields will be allowed in -// |map2|. -static void VerifyMapEqual(CefRequest::HeaderMap &map1, - CefRequest::HeaderMap &map2, - bool allowExtras) -{ - if(!allowExtras) - ASSERT_EQ(map1.size(), map2.size()); - CefRequest::HeaderMap::const_iterator it1, it2; - - for(it1 = map1.begin(); it1 != map1.end(); ++it1) { - it2 = map2.find(it1->first); - ASSERT_TRUE(it2 != map2.end()); - ASSERT_EQ(it1->second, it2->second); - } -} - -// Verify that CefPostDataElement objects are equal -static void VerifyPostDataElementEqual(CefRefPtr elem1, - CefRefPtr elem2) -{ - ASSERT_EQ(elem1->GetType(), elem2->GetType()); - switch(elem1->GetType()) { - case PDE_TYPE_BYTES: { - ASSERT_EQ(elem1->GetBytesCount(), elem2->GetBytesCount()); - char *buff1, *buff2; - size_t bytesCt = elem1->GetBytesCount(); - buff1 = new char[bytesCt]; - buff2 = new char[bytesCt]; - elem1->GetBytes(bytesCt, buff1); - elem2->GetBytes(bytesCt, buff2); - ASSERT_TRUE(!memcmp(buff1, buff2, bytesCt)); - delete [] buff1; - delete [] buff2; - } break; - case PDE_TYPE_FILE: - ASSERT_EQ(elem1->GetFile(), elem2->GetFile()); - break; - } -} - -// Verify that CefPostData objects are equal -static void VerifyPostDataEqual(CefRefPtr postData1, - CefRefPtr postData2) -{ - ASSERT_TRUE(!(postData1.get()) == !(postData2.get())); - ASSERT_EQ(postData1->GetElementCount(), postData2->GetElementCount()); - - CefPostData::ElementVector ev1, ev2; - postData1->GetElements(ev1); - postData1->GetElements(ev2); - ASSERT_EQ(ev1.size(), ev2.size()); - - CefPostData::ElementVector::const_iterator it1 = ev1.begin(); - CefPostData::ElementVector::const_iterator it2 = ev2.begin(); - for(; it1 != ev1.end() && it2 != ev2.end(); ++it1, ++it2) - VerifyPostDataElementEqual((*it1), (*it2)); -} - -// Verify that CefRequest objects are equal -// If |allowExtras| is true then additional header fields will be allowed in -// |request2|. -static void VerifyRequestEqual(CefRefPtr request1, - CefRefPtr request2, - bool allowExtras) -{ - ASSERT_EQ(request1->GetURL(), request2->GetURL()); - ASSERT_EQ(request1->GetMethod(), request2->GetMethod()); - - CefRequest::HeaderMap headers1, headers2; - request1->GetHeaderMap(headers1); - request2->GetHeaderMap(headers2); - VerifyMapEqual(headers1, headers2, allowExtras); - - VerifyPostDataEqual(request1->GetPostData(), request2->GetPostData()); -} - -// Verify Set/Get methods for CefRequest, CefPostData and CefPostDataElement. -TEST(RequestTest, SetGet) -{ - // CefRequest CreateRequest - CefRefPtr request(CefRequest::CreateRequest()); - ASSERT_TRUE(request.get() != NULL); - - std::wstring url = L"http://tests/run.html"; - std::wstring method = L"POST"; - CefRequest::HeaderMap setHeaders, getHeaders; - setHeaders.insert(std::make_pair(L"HeaderA", L"ValueA")); - setHeaders.insert(std::make_pair(L"HeaderB", L"ValueB")); - - // CefPostData CreatePostData - CefRefPtr postData(CefPostData::CreatePostData()); - ASSERT_TRUE(postData.get() != NULL); - - // CefPostDataElement CreatePostDataElement - CefRefPtr element1( - CefPostDataElement::CreatePostDataElement()); - ASSERT_TRUE(element1.get() != NULL); - CefRefPtr element2( - CefPostDataElement::CreatePostDataElement()); - ASSERT_TRUE(element2.get() != NULL); - - // CefPostDataElement SetToFile - std::wstring file = L"c:\\path\\to\\file.ext"; - element1->SetToFile(file); - ASSERT_EQ(PDE_TYPE_FILE, element1->GetType()); - ASSERT_EQ(file, element1->GetFile()); - - // CefPostDataElement SetToBytes - char bytes[] = "Test Bytes"; - element2->SetToBytes(sizeof(bytes), bytes); - ASSERT_EQ(PDE_TYPE_BYTES, element2->GetType()); - ASSERT_EQ(sizeof(bytes), element2->GetBytesCount()); - char bytesOut[sizeof(bytes)]; - element2->GetBytes(sizeof(bytes), bytesOut); - ASSERT_TRUE(!memcmp(bytes, bytesOut, sizeof(bytes))); - - // CefPostData AddElement - postData->AddElement(element1); - postData->AddElement(element2); - ASSERT_EQ(2, postData->GetElementCount()); - - // CefPostData RemoveElement - postData->RemoveElement(element1); - ASSERT_EQ(1, postData->GetElementCount()); - - // CefPostData RemoveElements - postData->RemoveElements(); - ASSERT_EQ(0, postData->GetElementCount()); - - postData->AddElement(element1); - postData->AddElement(element2); - ASSERT_EQ(2, postData->GetElementCount()); - CefPostData::ElementVector elements; - postData->GetElements(elements); - CefPostData::ElementVector::const_iterator it = elements.begin(); - for(size_t i = 0; it != elements.end(); ++it, ++i) { - if(i == 0) - VerifyPostDataElementEqual(element1, (*it).get()); - else if(i == 1) - VerifyPostDataElementEqual(element2, (*it).get()); - } - - // CefRequest SetURL - request->SetURL(url); - ASSERT_EQ(url, request->GetURL()); - - // CefRequest SetMethod - request->SetMethod(method); - ASSERT_EQ(method, request->GetMethod()); - - // CefRequest SetHeaderMap - request->SetHeaderMap(setHeaders); - request->GetHeaderMap(getHeaders); - VerifyMapEqual(setHeaders, getHeaders, false); - getHeaders.clear(); - - // CefRequest SetPostData - request->SetPostData(postData); - VerifyPostDataEqual(postData, request->GetPostData()); - - request = CefRequest::CreateRequest(); - ASSERT_TRUE(request.get() != NULL); - - // CefRequest Set - request->Set(url, method, postData, setHeaders); - ASSERT_EQ(url, request->GetURL()); - ASSERT_EQ(method, request->GetMethod()); - request->GetHeaderMap(getHeaders); - VerifyMapEqual(setHeaders, getHeaders, false); - getHeaders.clear(); - VerifyPostDataEqual(postData, request->GetPostData()); -} - -static void CreateRequest(CefRefPtr& request) -{ - request = CefRequest::CreateRequest(); - ASSERT_TRUE(request.get() != NULL); - - request->SetURL(L"http://tests/run.html"); - request->SetMethod(L"POST"); - - CefRequest::HeaderMap headers; - headers.insert(std::make_pair(L"HeaderA", L"ValueA")); - headers.insert(std::make_pair(L"HeaderB", L"ValueB")); - request->SetHeaderMap(headers); - - CefRefPtr postData(CefPostData::CreatePostData()); - ASSERT_TRUE(postData.get() != NULL); - - CefRefPtr element1( - CefPostDataElement::CreatePostDataElement()); - ASSERT_TRUE(element1.get() != NULL); - element1->SetToFile(L"c:\\path\\to\\file.ext"); - postData->AddElement(element1); - - CefRefPtr element2( - CefPostDataElement::CreatePostDataElement()); - ASSERT_TRUE(element2.get() != NULL); - char bytes[] = "Test Bytes"; - element2->SetToBytes(sizeof(bytes), bytes); - postData->AddElement(element2); - - request->SetPostData(postData); -} - -bool g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled; -bool g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled; - -class RequestSendRecvTestHandler : public TestHandler -{ -public: - RequestSendRecvTestHandler() {} - - virtual void RunTest() - { - // Create the test request - CreateRequest(request_); - - // Create the browser - CreateBrowser(std::wstring()); - } - - virtual RetVal HandleAfterCreated(CefRefPtr browser) - { - TestHandler::HandleAfterCreated(browser); - - // Load the test request - browser->GetMainFrame()->LoadRequest(request_); - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeBrowse(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr request, - NavType navType, bool isRedirect) - { - g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled = true; - - // Verify that the request is the same - VerifyRequestEqual(request_, request, true); - - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, - CefRefPtr request, - std::wstring& redirectUrl, - CefRefPtr& resourceStream, - std::wstring& mimeType, - int loadFlags) - { - g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled = true; - - // Verify that the request is the same - VerifyRequestEqual(request_, request, true); - - // No results - return RV_HANDLED; - } - - virtual RetVal HandleLoadEnd(CefRefPtr browser, - CefRefPtr frame) - { - if(!browser->IsPopup() && !frame.get()) - DestroyTest(); - return RV_CONTINUE; - } - - CefRefPtr request_; -}; - -// Verify send and recieve -TEST(RequestTest, SendRecv) -{ - g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled = false; - g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled = false; - - CefRefPtr handler = - new RequestSendRecvTestHandler(); - handler->ExecuteTest(); - - ASSERT_TRUE(g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled); - ASSERT_TRUE(g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled); -} - -bool g_RequestHistoryNavTestDidLoadRequest; -bool g_RequestHistoryNavTestDidReloadRequest; - -class RequestHistoryNavTestHandler : public TestHandler -{ -public: - RequestHistoryNavTestHandler() : navigated_(false) {} - - virtual void RunTest() - { - // Create the test request - CreateRequest(request_); - - // Add the resource that we will navigate to/from - AddResource(L"http://tests/goto.html", "To", L"text/html"); - - // Create the browser - CreateBrowser(std::wstring()); - } - - virtual RetVal HandleAfterCreated(CefRefPtr browser) - { - TestHandler::HandleAfterCreated(browser); - - // Load the test request - browser->GetMainFrame()->LoadRequest(request_); - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeBrowse(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr request, - NavType navType, bool isRedirect) - { - std::wstring url = request->GetURL(); - if(url == L"http://tests/run.html") - { - // Verify that the request is the same - VerifyRequestEqual(request_, request, true); - } - - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, - CefRefPtr request, - std::wstring& redirectUrl, - CefRefPtr& resourceStream, - std::wstring& mimeType, - int loadFlags) - { - std::wstring url = request->GetURL(); - if(url == L"http://tests/run.html") - { - // Verify that the request is the same - VerifyRequestEqual(request_, request, true); - - if(!navigated_) - { - // Loading the request for the 1st time - g_RequestHistoryNavTestDidLoadRequest = true; - } - else - { - // Re-loading the request - g_RequestHistoryNavTestDidReloadRequest = true; - } - - // Return dummy results - std::string output = "Request"; - resourceStream = CefStreamReader::CreateForData((void*)output.c_str(), - output.length()); - mimeType = L"text/html"; - return RV_CONTINUE; - } - else - { - // Pass to the default handler to return the to/from page - return TestHandler::HandleBeforeResourceLoad(browser, request, - redirectUrl, resourceStream, mimeType, loadFlags); - } - } - - virtual RetVal HandleLoadEnd(CefRefPtr browser, - CefRefPtr frame) - { - if(!browser->IsPopup() && !frame.get()) - { - std::wstring url = browser->GetMainFrame()->GetURL(); - if(url == L"http://tests/run.html") - { - if(!navigated_) - { - // First resource load, go to the next page - navigated_ = true; - browser->GetMainFrame()->LoadURL(L"http://tests/goto.html"); - } - else - { - // Resource re-load, end the test - DestroyTest(); - } - } - else - { - // To/from page load, go back the the request page - browser->GoBack(); - } - } - return RV_CONTINUE; - } - - CefRefPtr request_; - bool navigated_; -}; - -// Verify history navigation -// This test will only pass if the patches for issue #42 are applied. -TEST(RequestTest, HistoryNav) -{ - g_RequestHistoryNavTestDidLoadRequest = false; - g_RequestHistoryNavTestDidReloadRequest = false; - - CefRefPtr handler = - new RequestHistoryNavTestHandler(); - handler->ExecuteTest(); - - ASSERT_TRUE(g_RequestHistoryNavTestDidLoadRequest); - ASSERT_TRUE(g_RequestHistoryNavTestDidReloadRequest); -} +// 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/cef.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "test_handler.h" + + +// Verify that CefRequest::HeaderMap objects are equal +// If |allowExtras| is true then additional header fields will be allowed in +// |map2|. +static void VerifyMapEqual(CefRequest::HeaderMap &map1, + CefRequest::HeaderMap &map2, + bool allowExtras) +{ + if(!allowExtras) + ASSERT_EQ(map1.size(), map2.size()); + CefRequest::HeaderMap::const_iterator it1, it2; + + for(it1 = map1.begin(); it1 != map1.end(); ++it1) { + it2 = map2.find(it1->first); + ASSERT_TRUE(it2 != map2.end()); + ASSERT_EQ(it1->second, it2->second); + } +} + +// Verify that CefPostDataElement objects are equal +static void VerifyPostDataElementEqual(CefRefPtr elem1, + CefRefPtr elem2) +{ + ASSERT_EQ(elem1->GetType(), elem2->GetType()); + switch(elem1->GetType()) { + case PDE_TYPE_BYTES: { + ASSERT_EQ(elem1->GetBytesCount(), elem2->GetBytesCount()); + char *buff1, *buff2; + size_t bytesCt = elem1->GetBytesCount(); + buff1 = new char[bytesCt]; + buff2 = new char[bytesCt]; + elem1->GetBytes(bytesCt, buff1); + elem2->GetBytes(bytesCt, buff2); + ASSERT_TRUE(!memcmp(buff1, buff2, bytesCt)); + delete [] buff1; + delete [] buff2; + } break; + case PDE_TYPE_FILE: + ASSERT_EQ(elem1->GetFile(), elem2->GetFile()); + break; + } +} + +// Verify that CefPostData objects are equal +static void VerifyPostDataEqual(CefRefPtr postData1, + CefRefPtr postData2) +{ + ASSERT_TRUE(!(postData1.get()) == !(postData2.get())); + ASSERT_EQ(postData1->GetElementCount(), postData2->GetElementCount()); + + CefPostData::ElementVector ev1, ev2; + postData1->GetElements(ev1); + postData1->GetElements(ev2); + ASSERT_EQ(ev1.size(), ev2.size()); + + CefPostData::ElementVector::const_iterator it1 = ev1.begin(); + CefPostData::ElementVector::const_iterator it2 = ev2.begin(); + for(; it1 != ev1.end() && it2 != ev2.end(); ++it1, ++it2) + VerifyPostDataElementEqual((*it1), (*it2)); +} + +// Verify that CefRequest objects are equal +// If |allowExtras| is true then additional header fields will be allowed in +// |request2|. +static void VerifyRequestEqual(CefRefPtr request1, + CefRefPtr request2, + bool allowExtras) +{ + ASSERT_EQ(request1->GetURL(), request2->GetURL()); + ASSERT_EQ(request1->GetMethod(), request2->GetMethod()); + + CefRequest::HeaderMap headers1, headers2; + request1->GetHeaderMap(headers1); + request2->GetHeaderMap(headers2); + VerifyMapEqual(headers1, headers2, allowExtras); + + VerifyPostDataEqual(request1->GetPostData(), request2->GetPostData()); +} + +// Verify Set/Get methods for CefRequest, CefPostData and CefPostDataElement. +TEST(RequestTest, SetGet) +{ + // CefRequest CreateRequest + CefRefPtr request(CefRequest::CreateRequest()); + ASSERT_TRUE(request.get() != NULL); + + std::wstring url = L"http://tests/run.html"; + std::wstring method = L"POST"; + CefRequest::HeaderMap setHeaders, getHeaders; + setHeaders.insert(std::make_pair(L"HeaderA", L"ValueA")); + setHeaders.insert(std::make_pair(L"HeaderB", L"ValueB")); + + // CefPostData CreatePostData + CefRefPtr postData(CefPostData::CreatePostData()); + ASSERT_TRUE(postData.get() != NULL); + + // CefPostDataElement CreatePostDataElement + CefRefPtr element1( + CefPostDataElement::CreatePostDataElement()); + ASSERT_TRUE(element1.get() != NULL); + CefRefPtr element2( + CefPostDataElement::CreatePostDataElement()); + ASSERT_TRUE(element2.get() != NULL); + + // CefPostDataElement SetToFile + std::wstring file = L"c:\\path\\to\\file.ext"; + element1->SetToFile(file); + ASSERT_EQ(PDE_TYPE_FILE, element1->GetType()); + ASSERT_EQ(file, element1->GetFile()); + + // CefPostDataElement SetToBytes + char bytes[] = "Test Bytes"; + element2->SetToBytes(sizeof(bytes), bytes); + ASSERT_EQ(PDE_TYPE_BYTES, element2->GetType()); + ASSERT_EQ(sizeof(bytes), element2->GetBytesCount()); + char bytesOut[sizeof(bytes)]; + element2->GetBytes(sizeof(bytes), bytesOut); + ASSERT_TRUE(!memcmp(bytes, bytesOut, sizeof(bytes))); + + // CefPostData AddElement + postData->AddElement(element1); + postData->AddElement(element2); + ASSERT_EQ(2, postData->GetElementCount()); + + // CefPostData RemoveElement + postData->RemoveElement(element1); + ASSERT_EQ(1, postData->GetElementCount()); + + // CefPostData RemoveElements + postData->RemoveElements(); + ASSERT_EQ(0, postData->GetElementCount()); + + postData->AddElement(element1); + postData->AddElement(element2); + ASSERT_EQ(2, postData->GetElementCount()); + CefPostData::ElementVector elements; + postData->GetElements(elements); + CefPostData::ElementVector::const_iterator it = elements.begin(); + for(size_t i = 0; it != elements.end(); ++it, ++i) { + if(i == 0) + VerifyPostDataElementEqual(element1, (*it).get()); + else if(i == 1) + VerifyPostDataElementEqual(element2, (*it).get()); + } + + // CefRequest SetURL + request->SetURL(url); + ASSERT_EQ(url, request->GetURL()); + + // CefRequest SetMethod + request->SetMethod(method); + ASSERT_EQ(method, request->GetMethod()); + + // CefRequest SetHeaderMap + request->SetHeaderMap(setHeaders); + request->GetHeaderMap(getHeaders); + VerifyMapEqual(setHeaders, getHeaders, false); + getHeaders.clear(); + + // CefRequest SetPostData + request->SetPostData(postData); + VerifyPostDataEqual(postData, request->GetPostData()); + + request = CefRequest::CreateRequest(); + ASSERT_TRUE(request.get() != NULL); + + // CefRequest Set + request->Set(url, method, postData, setHeaders); + ASSERT_EQ(url, request->GetURL()); + ASSERT_EQ(method, request->GetMethod()); + request->GetHeaderMap(getHeaders); + VerifyMapEqual(setHeaders, getHeaders, false); + getHeaders.clear(); + VerifyPostDataEqual(postData, request->GetPostData()); +} + +static void CreateRequest(CefRefPtr& request) +{ + request = CefRequest::CreateRequest(); + ASSERT_TRUE(request.get() != NULL); + + request->SetURL(L"http://tests/run.html"); + request->SetMethod(L"POST"); + + CefRequest::HeaderMap headers; + headers.insert(std::make_pair(L"HeaderA", L"ValueA")); + headers.insert(std::make_pair(L"HeaderB", L"ValueB")); + request->SetHeaderMap(headers); + + CefRefPtr postData(CefPostData::CreatePostData()); + ASSERT_TRUE(postData.get() != NULL); + + CefRefPtr element1( + CefPostDataElement::CreatePostDataElement()); + ASSERT_TRUE(element1.get() != NULL); + element1->SetToFile(L"c:\\path\\to\\file.ext"); + postData->AddElement(element1); + + CefRefPtr element2( + CefPostDataElement::CreatePostDataElement()); + ASSERT_TRUE(element2.get() != NULL); + char bytes[] = "Test Bytes"; + element2->SetToBytes(sizeof(bytes), bytes); + postData->AddElement(element2); + + request->SetPostData(postData); +} + +bool g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled; +bool g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled; + +class RequestSendRecvTestHandler : public TestHandler +{ +public: + RequestSendRecvTestHandler() {} + + virtual void RunTest() + { + // Create the test request + CreateRequest(request_); + + // Create the browser + CreateBrowser(std::wstring()); + } + + virtual RetVal HandleAfterCreated(CefRefPtr browser) + { + TestHandler::HandleAfterCreated(browser); + + // Load the test request + browser->GetMainFrame()->LoadRequest(request_); + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, bool isRedirect) + { + g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled = true; + + // Verify that the request is the same + VerifyRequestEqual(request_, request, true); + + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + std::wstring& redirectUrl, + CefRefPtr& resourceStream, + std::wstring& mimeType, + int loadFlags) + { + g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled = true; + + // Verify that the request is the same + VerifyRequestEqual(request_, request, true); + + // No results + return RV_HANDLED; + } + + virtual RetVal HandleLoadEnd(CefRefPtr browser, + CefRefPtr frame) + { + if(!browser->IsPopup() && !frame.get()) + DestroyTest(); + return RV_CONTINUE; + } + + CefRefPtr request_; +}; + +// Verify send and recieve +TEST(RequestTest, SendRecv) +{ + g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled = false; + g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled = false; + + CefRefPtr handler = + new RequestSendRecvTestHandler(); + handler->ExecuteTest(); + + ASSERT_TRUE(g_RequestSendRecvTestHandlerHandleBeforeBrowseCalled); + ASSERT_TRUE(g_RequestSendRecvTestHandlerHandleBeforeResourceLoadCalled); +} + +bool g_RequestHistoryNavTestDidLoadRequest; +bool g_RequestHistoryNavTestDidReloadRequest; + +class RequestHistoryNavTestHandler : public TestHandler +{ +public: + RequestHistoryNavTestHandler() : navigated_(false) {} + + virtual void RunTest() + { + // Create the test request + CreateRequest(request_); + + // Add the resource that we will navigate to/from + AddResource(L"http://tests/goto.html", "To", L"text/html"); + + // Create the browser + CreateBrowser(std::wstring()); + } + + virtual RetVal HandleAfterCreated(CefRefPtr browser) + { + TestHandler::HandleAfterCreated(browser); + + // Load the test request + browser->GetMainFrame()->LoadRequest(request_); + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, bool isRedirect) + { + std::wstring url = request->GetURL(); + if(url == L"http://tests/run.html") + { + // Verify that the request is the same + VerifyRequestEqual(request_, request, true); + } + + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + std::wstring& redirectUrl, + CefRefPtr& resourceStream, + std::wstring& mimeType, + int loadFlags) + { + std::wstring url = request->GetURL(); + if(url == L"http://tests/run.html") + { + // Verify that the request is the same + VerifyRequestEqual(request_, request, true); + + if(!navigated_) + { + // Loading the request for the 1st time + g_RequestHistoryNavTestDidLoadRequest = true; + } + else + { + // Re-loading the request + g_RequestHistoryNavTestDidReloadRequest = true; + } + + // Return dummy results + std::string output = "Request"; + resourceStream = CefStreamReader::CreateForData((void*)output.c_str(), + output.length()); + mimeType = L"text/html"; + return RV_CONTINUE; + } + else + { + // Pass to the default handler to return the to/from page + return TestHandler::HandleBeforeResourceLoad(browser, request, + redirectUrl, resourceStream, mimeType, loadFlags); + } + } + + virtual RetVal HandleLoadEnd(CefRefPtr browser, + CefRefPtr frame) + { + if(!browser->IsPopup() && !frame.get()) + { + std::wstring url = browser->GetMainFrame()->GetURL(); + if(url == L"http://tests/run.html") + { + if(!navigated_) + { + // First resource load, go to the next page + navigated_ = true; + browser->GetMainFrame()->LoadURL(L"http://tests/goto.html"); + } + else + { + // Resource re-load, end the test + DestroyTest(); + } + } + else + { + // To/from page load, go back the the request page + browser->GoBack(); + } + } + return RV_CONTINUE; + } + + CefRefPtr request_; + bool navigated_; +}; + +// Verify history navigation +// This test will only pass if the patches for issue #42 are applied. +TEST(RequestTest, HistoryNav) +{ + g_RequestHistoryNavTestDidLoadRequest = false; + g_RequestHistoryNavTestDidReloadRequest = false; + + CefRefPtr handler = + new RequestHistoryNavTestHandler(); + handler->ExecuteTest(); + + ASSERT_TRUE(g_RequestHistoryNavTestDidLoadRequest); + ASSERT_TRUE(g_RequestHistoryNavTestDidReloadRequest); +} diff --git a/tests/unittests/run_all_unittests.cc b/tests/unittests/run_all_unittests.cc index 660ff775a..1fcfe45f8 100644 --- a/tests/unittests/run_all_unittests.cc +++ b/tests/unittests/run_all_unittests.cc @@ -1,6 +1,6 @@ -// 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. +// 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 "test_suite.h" diff --git a/tests/unittests/stream_unittest.cc b/tests/unittests/stream_unittest.cc index fe22abb01..8a8047b9d 100644 --- a/tests/unittests/stream_unittest.cc +++ b/tests/unittests/stream_unittest.cc @@ -1,6 +1,6 @@ -// 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. +// 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/cef.h" #include "testing/gtest/include/gtest/gtest.h" @@ -140,63 +140,63 @@ TEST(StreamTest, WriteFile) bool g_ReadHandlerTesterDeleted = false; -class ReadHandlerTester : public CefThreadSafeBase -{ -public: - ReadHandlerTester() - : read_called_(false), read_ptr_(NULL), read_size_(0), read_n_(0), - seek_called_(false), seek_offset_(0), seek_whence_(0), - tell_called_(false), eof_called_(false) - { - } - virtual ~ReadHandlerTester() - { - g_ReadHandlerTesterDeleted = true; - } - - virtual size_t Read(void* ptr, size_t size, size_t n) - { - read_called_ = true; - read_ptr_ = ptr; - read_size_ = size; - read_n_ = n; - return 10; - } - - virtual int Seek(long offset, int whence) - { - seek_called_ = true; - seek_offset_ = offset; - seek_whence_ = whence; - return 10; - } - - virtual long Tell() - { - tell_called_ = true; - return 10; - } - - virtual int Eof() - { - eof_called_ = true; - return 10; - } - - bool read_called_; - const void* read_ptr_; - size_t read_size_; - size_t read_n_; - - bool seek_called_; - long seek_offset_; - int seek_whence_; - - bool tell_called_; - - bool eof_called_; -}; - +class ReadHandlerTester : public CefThreadSafeBase +{ +public: + ReadHandlerTester() + : read_called_(false), read_ptr_(NULL), read_size_(0), read_n_(0), + seek_called_(false), seek_offset_(0), seek_whence_(0), + tell_called_(false), eof_called_(false) + { + } + virtual ~ReadHandlerTester() + { + g_ReadHandlerTesterDeleted = true; + } + + virtual size_t Read(void* ptr, size_t size, size_t n) + { + read_called_ = true; + read_ptr_ = ptr; + read_size_ = size; + read_n_ = n; + return 10; + } + + virtual int Seek(long offset, int whence) + { + seek_called_ = true; + seek_offset_ = offset; + seek_whence_ = whence; + return 10; + } + + virtual long Tell() + { + tell_called_ = true; + return 10; + } + + virtual int Eof() + { + eof_called_ = true; + return 10; + } + + bool read_called_; + const void* read_ptr_; + size_t read_size_; + size_t read_n_; + + bool seek_called_; + long seek_offset_; + int seek_whence_; + + bool tell_called_; + + bool eof_called_; +}; + TEST(StreamTest, ReadHandler) { ReadHandlerTester* handler = new ReadHandlerTester(); @@ -244,63 +244,63 @@ TEST(StreamTest, ReadHandler) bool g_WriteHandlerTesterDeleted = false; -class WriteHandlerTester : public CefThreadSafeBase -{ -public: - WriteHandlerTester() - : write_called_(false), write_ptr_(NULL), write_size_(0), write_n_(0), - seek_called_(false), seek_offset_(0), seek_whence_(0), - tell_called_(false), flush_called_(false) - { - } - virtual ~WriteHandlerTester() - { - g_WriteHandlerTesterDeleted = true; - } - - virtual size_t Write(const void* ptr, size_t size, size_t n) - { - write_called_ = true; - write_ptr_ = ptr; - write_size_ = size; - write_n_ = n; - return 10; - } - - virtual int Seek(long offset, int whence) - { - seek_called_ = true; - seek_offset_ = offset; - seek_whence_ = whence; - return 10; - } - - virtual long Tell() - { - tell_called_ = true; - return 10; - } - - virtual int Flush() - { - flush_called_ = true; - return 10; - } - - bool write_called_; - const void* write_ptr_; - size_t write_size_; - size_t write_n_; - - bool seek_called_; - long seek_offset_; - int seek_whence_; - - bool tell_called_; - - bool flush_called_; -}; - +class WriteHandlerTester : public CefThreadSafeBase +{ +public: + WriteHandlerTester() + : write_called_(false), write_ptr_(NULL), write_size_(0), write_n_(0), + seek_called_(false), seek_offset_(0), seek_whence_(0), + tell_called_(false), flush_called_(false) + { + } + virtual ~WriteHandlerTester() + { + g_WriteHandlerTesterDeleted = true; + } + + virtual size_t Write(const void* ptr, size_t size, size_t n) + { + write_called_ = true; + write_ptr_ = ptr; + write_size_ = size; + write_n_ = n; + return 10; + } + + virtual int Seek(long offset, int whence) + { + seek_called_ = true; + seek_offset_ = offset; + seek_whence_ = whence; + return 10; + } + + virtual long Tell() + { + tell_called_ = true; + return 10; + } + + virtual int Flush() + { + flush_called_ = true; + return 10; + } + + bool write_called_; + const void* write_ptr_; + size_t write_size_; + size_t write_n_; + + bool seek_called_; + long seek_offset_; + int seek_whence_; + + bool tell_called_; + + bool flush_called_; +}; + TEST(StreamTest, WriteHandler) { WriteHandlerTester* handler = new WriteHandlerTester(); diff --git a/tests/unittests/test_handler.h b/tests/unittests/test_handler.h index 5e888db5d..2df7d681e 100644 --- a/tests/unittests/test_handler.h +++ b/tests/unittests/test_handler.h @@ -1,311 +1,311 @@ -// 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 _TEST_HANDLER_H -#define _TEST_HANDLER_H - -#include "include/cef.h" -#include "base/waitable_event.h" -#include "testing/gtest/include/gtest/gtest.h" - -// Base implementation of CefHandler for unit tests. -class TestHandler : public CefThreadSafeBase -{ -public: - TestHandler() : browser_hwnd_(NULL), completion_event_(true, false) - { - } - - virtual ~TestHandler() - { - } - - // Implement this method to run the test - virtual void RunTest() =0; - - virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, - CefWindowInfo& createInfo, bool popup, - CefRefPtr& handler, - std::wstring& url) - { - return RV_CONTINUE; - } - - virtual RetVal HandleAfterCreated(CefRefPtr browser) - { - Lock(); - if(!browser->IsPopup()) - { - // Keep the main child window, but not popup windows - browser_ = browser; - browser_hwnd_ = browser->GetWindowHandle(); - } - Unlock(); - return RV_CONTINUE; - } - - virtual RetVal HandleAddressChange(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& url) - { - return RV_CONTINUE; - } - - virtual RetVal HandleTitleChange(CefRefPtr browser, - const std::wstring& title) - { - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeBrowse(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr request, - NavType navType, bool isRedirect) - { - return RV_CONTINUE; - } - - virtual RetVal HandleLoadStart(CefRefPtr browser, - CefRefPtr frame) - { - return RV_CONTINUE; - } - - virtual RetVal HandleLoadEnd(CefRefPtr browser, - CefRefPtr frame) - { - return RV_CONTINUE; - } - - virtual RetVal HandleLoadError(CefRefPtr browser, - CefRefPtr frame, - ErrorCode errorCode, - const std::wstring& failedUrl, - std::wstring& errorText) - { - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, - CefRefPtr request, - std::wstring& redirectUrl, - CefRefPtr& resourceStream, - std::wstring& mimeType, - int loadFlags) - { - Lock(); - if(resource_map_.size() > 0) { - std::wstring url = request->GetURL(); - ResourceMap::const_iterator it = resource_map_.find(url); - if(it != resource_map_.end()) { - // Return the previously mapped resource - resourceStream = CefStreamReader::CreateForData( - (void*)it->second.first.c_str(), it->second.first.length()); - mimeType = it->second.second; - } - } - Unlock(); - - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeMenu(CefRefPtr browser, - const MenuInfo& menuInfo) - { - return RV_CONTINUE; - } - - - virtual RetVal HandleGetMenuLabel(CefRefPtr browser, - MenuId menuId, std::wstring& label) - { - return RV_CONTINUE; - } - - virtual RetVal HandleMenuAction(CefRefPtr browser, - MenuId menuId) - { - return RV_CONTINUE; - } - - virtual RetVal HandlePrintOptions(CefRefPtr browser, - CefPrintOptions& printOptions) - { - return RV_CONTINUE; - } - - virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, - CefRefPtr frame, - CefPrintInfo& printInfo, - const std::wstring& url, - const std::wstring& title, - int currentPage, int maxPages, - std::wstring& topLeft, - std::wstring& topCenter, - std::wstring& topRight, - std::wstring& bottomLeft, - std::wstring& bottomCenter, - std::wstring& bottomRight) - { - return RV_CONTINUE; - } - - virtual RetVal HandleJSAlert(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message) - { - return RV_CONTINUE; - } - - virtual RetVal HandleJSConfirm(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message, bool& retval) - { - return RV_CONTINUE; - } - - virtual RetVal HandleJSPrompt(CefRefPtr browser, - CefRefPtr frame, - const std::wstring& message, - const std::wstring& defaultValue, - bool& retval, - std::wstring& result) - { - return RV_CONTINUE; - } - - virtual RetVal HandleJSBinding(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr object) - { - return RV_CONTINUE; - } - - virtual RetVal HandleBeforeWindowClose(CefRefPtr browser) - { - Lock(); - if(browser_hwnd_ == browser->GetWindowHandle()) - { - // Free the browser pointer so that the browser can be destroyed - browser_ = NULL; - browser_hwnd_ = NULL; - - // Signal that the test is now complete. - completion_event_.Signal(); - } - Unlock(); - return RV_CONTINUE; - } - - virtual RetVal HandleTakeFocus(CefRefPtr browser, bool reverse) - { - return RV_CONTINUE; - } - - virtual RetVal HandleSetFocus(CefRefPtr browser, - bool isWidget) - { - return RV_CONTINUE; - } - - virtual RetVal HandleKeyEvent(CefRefPtr browser, - KeyEventType type, int code, - int modifiers, bool isSystemKey) - { - return RV_CONTINUE; - } - - virtual RetVal HandleTooltip(CefRefPtr browser, - std::wstring& text) - { - return RV_CONTINUE; - } - - virtual RetVal HandleConsoleMessage(CefRefPtr browser, - const std::wstring& message, - const std::wstring& source, int line) - { - return RV_CONTINUE; - } - - virtual RetVal HandleFindResult(CefRefPtr browser, - int identifier, int count, - const CefRect& selectionRect, - int activeMatchOrdinal, bool finalUpdate) - { - return RV_CONTINUE; - } - - CefRefPtr GetBrowser() - { - return browser_; - } - - HWND GetBrowserHwnd() - { - return browser_hwnd_; - } - - // Called by the test function to execute the test. This method blocks until - // the test is complete. Do not reference the object after this method - // returns. - void ExecuteTest() - { - // Run the test - RunTest(); - - // Wait for the test to complete - completion_event_.Wait(); - } - -protected: - // Destroy the browser window. Once the window is destroyed test completion - // will be signaled. - void DestroyTest() - { - Lock(); -#if defined(OS_WIN) - if(browser_hwnd_ != NULL) - PostMessage(browser_hwnd_, WM_CLOSE, 0, 0); -#endif - Unlock(); - } - - void CreateBrowser(const std::wstring& url) - { - CefWindowInfo windowInfo; -#if defined(OS_WIN) - windowInfo.SetAsPopup(NULL, L"CefUnitTest"); - windowInfo.m_dwStyle |= WS_VISIBLE; -#endif - CefBrowser::CreateBrowser(windowInfo, false, this, url); - } - - void AddResource(const std::wstring& key, const std::string& value, - const std::wstring& mimeType) - { - resource_map_.insert(std::make_pair(key, std::make_pair(value, mimeType))); - } - - void ClearResources() - { - resource_map_.clear(); - } - -private: - // The child browser window - CefRefPtr browser_; - - // The browser window handle - CefWindowHandle browser_hwnd_; - - // Handle used to notify when the test is complete - base::WaitableEvent completion_event_; - - // Map of resources that can be automatically loaded - typedef std::map> ResourceMap; - ResourceMap resource_map_; -}; - -#endif // _TEST_HANDLER_H +// 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 _TEST_HANDLER_H +#define _TEST_HANDLER_H + +#include "include/cef.h" +#include "base/waitable_event.h" +#include "testing/gtest/include/gtest/gtest.h" + +// Base implementation of CefHandler for unit tests. +class TestHandler : public CefThreadSafeBase +{ +public: + TestHandler() : browser_hwnd_(NULL), completion_event_(true, false) + { + } + + virtual ~TestHandler() + { + } + + // Implement this method to run the test + virtual void RunTest() =0; + + virtual RetVal HandleBeforeCreated(CefRefPtr parentBrowser, + CefWindowInfo& createInfo, bool popup, + CefRefPtr& handler, + std::wstring& url) + { + return RV_CONTINUE; + } + + virtual RetVal HandleAfterCreated(CefRefPtr browser) + { + Lock(); + if(!browser->IsPopup()) + { + // Keep the main child window, but not popup windows + browser_ = browser; + browser_hwnd_ = browser->GetWindowHandle(); + } + Unlock(); + return RV_CONTINUE; + } + + virtual RetVal HandleAddressChange(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& url) + { + return RV_CONTINUE; + } + + virtual RetVal HandleTitleChange(CefRefPtr browser, + const std::wstring& title) + { + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, bool isRedirect) + { + return RV_CONTINUE; + } + + virtual RetVal HandleLoadStart(CefRefPtr browser, + CefRefPtr frame) + { + return RV_CONTINUE; + } + + virtual RetVal HandleLoadEnd(CefRefPtr browser, + CefRefPtr frame) + { + return RV_CONTINUE; + } + + virtual RetVal HandleLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const std::wstring& failedUrl, + std::wstring& errorText) + { + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + std::wstring& redirectUrl, + CefRefPtr& resourceStream, + std::wstring& mimeType, + int loadFlags) + { + Lock(); + if(resource_map_.size() > 0) { + std::wstring url = request->GetURL(); + ResourceMap::const_iterator it = resource_map_.find(url); + if(it != resource_map_.end()) { + // Return the previously mapped resource + resourceStream = CefStreamReader::CreateForData( + (void*)it->second.first.c_str(), it->second.first.length()); + mimeType = it->second.second; + } + } + Unlock(); + + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeMenu(CefRefPtr browser, + const MenuInfo& menuInfo) + { + return RV_CONTINUE; + } + + + virtual RetVal HandleGetMenuLabel(CefRefPtr browser, + MenuId menuId, std::wstring& label) + { + return RV_CONTINUE; + } + + virtual RetVal HandleMenuAction(CefRefPtr browser, + MenuId menuId) + { + return RV_CONTINUE; + } + + virtual RetVal HandlePrintOptions(CefRefPtr browser, + CefPrintOptions& printOptions) + { + return RV_CONTINUE; + } + + virtual RetVal HandlePrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, + CefPrintInfo& printInfo, + const std::wstring& url, + const std::wstring& title, + int currentPage, int maxPages, + std::wstring& topLeft, + std::wstring& topCenter, + std::wstring& topRight, + std::wstring& bottomLeft, + std::wstring& bottomCenter, + std::wstring& bottomRight) + { + return RV_CONTINUE; + } + + virtual RetVal HandleJSAlert(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message) + { + return RV_CONTINUE; + } + + virtual RetVal HandleJSConfirm(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message, bool& retval) + { + return RV_CONTINUE; + } + + virtual RetVal HandleJSPrompt(CefRefPtr browser, + CefRefPtr frame, + const std::wstring& message, + const std::wstring& defaultValue, + bool& retval, + std::wstring& result) + { + return RV_CONTINUE; + } + + virtual RetVal HandleJSBinding(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object) + { + return RV_CONTINUE; + } + + virtual RetVal HandleBeforeWindowClose(CefRefPtr browser) + { + Lock(); + if(browser_hwnd_ == browser->GetWindowHandle()) + { + // Free the browser pointer so that the browser can be destroyed + browser_ = NULL; + browser_hwnd_ = NULL; + + // Signal that the test is now complete. + completion_event_.Signal(); + } + Unlock(); + return RV_CONTINUE; + } + + virtual RetVal HandleTakeFocus(CefRefPtr browser, bool reverse) + { + return RV_CONTINUE; + } + + virtual RetVal HandleSetFocus(CefRefPtr browser, + bool isWidget) + { + return RV_CONTINUE; + } + + virtual RetVal HandleKeyEvent(CefRefPtr browser, + KeyEventType type, int code, + int modifiers, bool isSystemKey) + { + return RV_CONTINUE; + } + + virtual RetVal HandleTooltip(CefRefPtr browser, + std::wstring& text) + { + return RV_CONTINUE; + } + + virtual RetVal HandleConsoleMessage(CefRefPtr browser, + const std::wstring& message, + const std::wstring& source, int line) + { + return RV_CONTINUE; + } + + virtual RetVal HandleFindResult(CefRefPtr browser, + int identifier, int count, + const CefRect& selectionRect, + int activeMatchOrdinal, bool finalUpdate) + { + return RV_CONTINUE; + } + + CefRefPtr GetBrowser() + { + return browser_; + } + + HWND GetBrowserHwnd() + { + return browser_hwnd_; + } + + // Called by the test function to execute the test. This method blocks until + // the test is complete. Do not reference the object after this method + // returns. + void ExecuteTest() + { + // Run the test + RunTest(); + + // Wait for the test to complete + completion_event_.Wait(); + } + +protected: + // Destroy the browser window. Once the window is destroyed test completion + // will be signaled. + void DestroyTest() + { + Lock(); +#if defined(OS_WIN) + if(browser_hwnd_ != NULL) + PostMessage(browser_hwnd_, WM_CLOSE, 0, 0); +#endif + Unlock(); + } + + void CreateBrowser(const std::wstring& url) + { + CefWindowInfo windowInfo; +#if defined(OS_WIN) + windowInfo.SetAsPopup(NULL, L"CefUnitTest"); + windowInfo.m_dwStyle |= WS_VISIBLE; +#endif + CefBrowser::CreateBrowser(windowInfo, false, this, url); + } + + void AddResource(const std::wstring& key, const std::string& value, + const std::wstring& mimeType) + { + resource_map_.insert(std::make_pair(key, std::make_pair(value, mimeType))); + } + + void ClearResources() + { + resource_map_.clear(); + } + +private: + // The child browser window + CefRefPtr browser_; + + // The browser window handle + CefWindowHandle browser_hwnd_; + + // Handle used to notify when the test is complete + base::WaitableEvent completion_event_; + + // Map of resources that can be automatically loaded + typedef std::map> ResourceMap; + ResourceMap resource_map_; +}; + +#endif // _TEST_HANDLER_H diff --git a/tests/unittests/test_suite.h b/tests/unittests/test_suite.h index bb697770c..3439d9d4d 100644 --- a/tests/unittests/test_suite.h +++ b/tests/unittests/test_suite.h @@ -1,35 +1,35 @@ -// 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_TEST_SUITE_H -#define _CEF_TEST_SUITE_H - -#include "build/build_config.h" -#include "base/platform_thread.h" -#include "base/test/test_suite.h" -#include "include/cef.h" - -class CefTestSuite : public TestSuite { - public: - CefTestSuite(int argc, char** argv) : TestSuite(argc, argv) { - } - - protected: - - virtual void Initialize() { - TestSuite::Initialize(); - CefInitialize(true, std::wstring()); - } - - virtual void Shutdown() { - // Delay a bit so that the system has a chance to finish destroying windows - // before CefShutdown() checks for memory leaks. - PlatformThread::Sleep(500); - - CefShutdown(); - TestSuite::Shutdown(); - } -}; - -#endif // _CEF_TEST_SUITE_H +// 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_TEST_SUITE_H +#define _CEF_TEST_SUITE_H + +#include "build/build_config.h" +#include "base/platform_thread.h" +#include "base/test/test_suite.h" +#include "include/cef.h" + +class CefTestSuite : public TestSuite { + public: + CefTestSuite(int argc, char** argv) : TestSuite(argc, argv) { + } + + protected: + + virtual void Initialize() { + TestSuite::Initialize(); + CefInitialize(true, std::wstring()); + } + + virtual void Shutdown() { + // Delay a bit so that the system has a chance to finish destroying windows + // before CefShutdown() checks for memory leaks. + PlatformThread::Sleep(500); + + CefShutdown(); + TestSuite::Shutdown(); + } +}; + +#endif // _CEF_TEST_SUITE_H diff --git a/tests/unittests/v8_unittest.cc b/tests/unittests/v8_unittest.cc index fc31f993d..bf9ffb0a6 100644 --- a/tests/unittests/v8_unittest.cc +++ b/tests/unittests/v8_unittest.cc @@ -1,352 +1,352 @@ -// 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/cef.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "test_handler.h" - -bool g_V8TestV8HandlerExecuteCalled; -bool g_V8TestV8HandlerExecute2Called; - -class V8TestV8Handler : public CefThreadSafeBase -{ -public: - V8TestV8Handler(bool bindingTest) { binding_test_ = bindingTest; } - - virtual bool Execute(const std::wstring& name, - CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) - { - TestExecute(name, object, arguments, retval, exception); - return true; - } - - void TestExecute(const std::wstring& name, - CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - std::wstring& exception) - { - if(name == L"execute") { - g_V8TestV8HandlerExecuteCalled = true; - - ASSERT_EQ(8, arguments.size()); - int argct = 0; - - // basic types - ASSERT_TRUE(arguments[argct]->IsInt()); - ASSERT_EQ(5, arguments[argct]->GetIntValue()); - argct++; - - ASSERT_TRUE(arguments[argct]->IsDouble()); - ASSERT_EQ(6.543, arguments[argct]->GetDoubleValue()); - argct++; - - ASSERT_TRUE(arguments[argct]->IsBool()); - ASSERT_EQ(true, arguments[argct]->GetBoolValue()); - argct++; - - ASSERT_TRUE(arguments[argct]->IsString()); - ASSERT_EQ(L"test string", arguments[argct]->GetStringValue()); - argct++; - - CefRefPtr value; - - // array - ASSERT_TRUE(arguments[argct]->IsArray()); - ASSERT_EQ(4, arguments[argct]->GetArrayLength()); - { - int subargct = 0; - value = arguments[argct]->GetValue(subargct); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsInt()); - ASSERT_EQ(7, value->GetIntValue()); - subargct++; - - value = arguments[argct]->GetValue(subargct); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsDouble()); - ASSERT_EQ(5.432, value->GetDoubleValue()); - subargct++; - - value = arguments[argct]->GetValue(subargct); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsBool()); - ASSERT_EQ(false, value->GetBoolValue()); - subargct++; - - value = arguments[argct]->GetValue(subargct); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsString()); - ASSERT_EQ(L"another string", value->GetStringValue()); - subargct++; - } - argct++; - - // object - ASSERT_TRUE(arguments[argct]->IsObject()); - { - value = arguments[argct]->GetValue(L"arg0"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsInt()); - ASSERT_EQ(2, value->GetIntValue()); - - value = arguments[argct]->GetValue(L"arg1"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsDouble()); - ASSERT_EQ(3.433, value->GetDoubleValue()); - - value = arguments[argct]->GetValue(L"arg2"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsBool()); - ASSERT_EQ(true, value->GetBoolValue()); - - value = arguments[argct]->GetValue(L"arg3"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsString()); - ASSERT_EQ(L"some string", value->GetStringValue()); - } - argct++; - - // function that returns a value - ASSERT_TRUE(arguments[argct]->IsFunction()); - { - CefV8ValueList args; - args.push_back(CefV8Value::CreateInt(5)); - args.push_back(CefV8Value::CreateDouble(3.5)); - args.push_back(CefV8Value::CreateBool(true)); - args.push_back(CefV8Value::CreateString(L"10")); - CefRefPtr rv; - std::wstring exception; - ASSERT_TRUE(arguments[argct]->ExecuteFunction( - arguments[argct], args, rv, exception)); - ASSERT_TRUE(rv.get() != NULL); - ASSERT_TRUE(rv->IsDouble()); - ASSERT_EQ(19.5, rv->GetDoubleValue()); - } - argct++; - - // function that throws an exception - ASSERT_TRUE(arguments[argct]->IsFunction()); - { - CefV8ValueList args; - args.push_back(CefV8Value::CreateDouble(5)); - args.push_back(CefV8Value::CreateDouble(0)); - CefRefPtr rv; - std::wstring exception; - ASSERT_TRUE(arguments[argct]->ExecuteFunction( - arguments[argct], args, rv, exception)); - ASSERT_EQ(L"Uncaught My Exception", exception); - } - argct++; - - if(binding_test_) - { - // values - value = object->GetValue(L"intVal"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsInt()); - ASSERT_EQ(12, value->GetIntValue()); - - value = object->GetValue(L"doubleVal"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsDouble()); - ASSERT_EQ(5.432, value->GetDoubleValue()); - - value = object->GetValue(L"boolVal"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsBool()); - ASSERT_EQ(true, value->GetBoolValue()); - - value = object->GetValue(L"stringVal"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsString()); - ASSERT_EQ(L"the string", value->GetStringValue()); - - value = object->GetValue(L"arrayVal"); - ASSERT_TRUE(value.get() != NULL); - ASSERT_TRUE(value->IsArray()); - { - CefRefPtr value2; - int subargct = 0; - value2 = value->GetValue(subargct); - ASSERT_TRUE(value2.get() != NULL); - ASSERT_TRUE(value2->IsInt()); - ASSERT_EQ(4, value2->GetIntValue()); - subargct++; - - value2 = value->GetValue(subargct); - ASSERT_TRUE(value2.get() != NULL); - ASSERT_TRUE(value2->IsDouble()); - ASSERT_EQ(120.43, value2->GetDoubleValue()); - subargct++; - - value2 = value->GetValue(subargct); - ASSERT_TRUE(value2.get() != NULL); - ASSERT_TRUE(value2->IsBool()); - ASSERT_EQ(true, value2->GetBoolValue()); - subargct++; - - value2 = value->GetValue(subargct); - ASSERT_TRUE(value2.get() != NULL); - ASSERT_TRUE(value2->IsString()); - ASSERT_EQ(L"a string", value2->GetStringValue()); - subargct++; - } - } - - retval = CefV8Value::CreateInt(5); - } else if(name == L"execute2") { - g_V8TestV8HandlerExecute2Called = true; - - // check the result of calling the "execute" function - ASSERT_EQ(1, arguments.size()); - ASSERT_TRUE(arguments[0]->IsInt()); - ASSERT_EQ(5, arguments[0]->GetIntValue()); - } - } - - bool binding_test_; -}; - -class V8TestHandler : public TestHandler -{ -public: - V8TestHandler(bool bindingTest) { binding_test_ = bindingTest; } - - virtual void RunTest() - { - std::string object; - if(binding_test_) { - // binding uses the window object - object = "window.test"; - } else { - // extension uses a global object - object = "test"; - } - - std::stringstream testHtml; - testHtml << - "" - "" - ""; - - AddResource(L"http://tests/run.html", testHtml.str(), L"text/html"); - CreateBrowser(L"http://tests/run.html"); - } - - virtual RetVal HandleLoadEnd(CefRefPtr browser, - CefRefPtr frame) - { - if(!browser->IsPopup() && !frame.get()) - DestroyTest(); - return RV_CONTINUE; - } - - virtual RetVal HandleJSBinding(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr object) - { - if(binding_test_) { - TestHandleJSBinding(browser, frame, object); - return RV_HANDLED; - } - return RV_CONTINUE; - } - - void TestHandleJSBinding(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr object) - { - // Create the new V8 object - CefRefPtr testObj = CefV8Value::CreateObject(NULL); - ASSERT_TRUE(testObj.get() != NULL); - ASSERT_TRUE(object->SetValue(L"test", testObj)); - - // Create an instance of V8ExecuteV8Handler - CefRefPtr testHandler(new V8TestV8Handler(true)); - ASSERT_TRUE(testHandler.get() != NULL); - - // Add the functions - CefRefPtr testFunc; - testFunc = CefV8Value::CreateFunction(L"execute", testHandler); - ASSERT_TRUE(testFunc.get() != NULL); - ASSERT_TRUE(testObj->SetValue(L"execute", testFunc)); - testFunc = CefV8Value::CreateFunction(L"execute2", testHandler); - ASSERT_TRUE(testFunc.get() != NULL); - ASSERT_TRUE(testObj->SetValue(L"execute2", testFunc)); - - // Add the values - ASSERT_TRUE(testObj->SetValue(L"intVal", - CefV8Value::CreateInt(12))); - ASSERT_TRUE(testObj->SetValue(L"doubleVal", - CefV8Value::CreateDouble(5.432))); - ASSERT_TRUE(testObj->SetValue(L"boolVal", - CefV8Value::CreateBool(true))); - ASSERT_TRUE(testObj->SetValue(L"stringVal", - CefV8Value::CreateString(L"the string"))); - - CefRefPtr testArray(CefV8Value::CreateArray()); - ASSERT_TRUE(testArray.get() != NULL); - ASSERT_TRUE(testObj->SetValue(L"arrayVal", testArray)); - ASSERT_TRUE(testArray->SetValue(0, CefV8Value::CreateInt(4))); - ASSERT_TRUE(testArray->SetValue(1, CefV8Value::CreateDouble(120.43))); - ASSERT_TRUE(testArray->SetValue(2, CefV8Value::CreateBool(true))); - ASSERT_TRUE(testArray->SetValue(3, CefV8Value::CreateString(L"a string"))); - } - - bool binding_test_; -}; - -// Verify window binding -TEST(V8Test, Binding) -{ - g_V8TestV8HandlerExecuteCalled = false; - g_V8TestV8HandlerExecute2Called = false; - - CefRefPtr handler = new V8TestHandler(true); - handler->ExecuteTest(); - - ASSERT_TRUE(g_V8TestV8HandlerExecuteCalled); - ASSERT_TRUE(g_V8TestV8HandlerExecute2Called); -} - -// Verify extensions -TEST(V8Test, Extension) -{ - g_V8TestV8HandlerExecuteCalled = false; - g_V8TestV8HandlerExecute2Called = false; - - std::wstring extensionCode = - L"var test;" - L"if (!test)" - L" test = {};" - L"(function() {" - L" test.execute = function(a,b,c,d,e,f,g,h) {" - L" native function execute();" - L" return execute(a,b,c,d,e,f,g,h);" - L" };" - L" test.execute2 = function(a) {" - L" native function execute2();" - L" return execute2(a);" - L" };" - L"})();"; - CefRegisterExtension(L"v8/test", extensionCode, new V8TestV8Handler(false)); - - CefRefPtr handler = new V8TestHandler(false); - handler->ExecuteTest(); - - ASSERT_TRUE(g_V8TestV8HandlerExecuteCalled); - ASSERT_TRUE(g_V8TestV8HandlerExecute2Called); -} +// 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/cef.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "test_handler.h" + +bool g_V8TestV8HandlerExecuteCalled; +bool g_V8TestV8HandlerExecute2Called; + +class V8TestV8Handler : public CefThreadSafeBase +{ +public: + V8TestV8Handler(bool bindingTest) { binding_test_ = bindingTest; } + + virtual bool Execute(const std::wstring& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) + { + TestExecute(name, object, arguments, retval, exception); + return true; + } + + void TestExecute(const std::wstring& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + std::wstring& exception) + { + if(name == L"execute") { + g_V8TestV8HandlerExecuteCalled = true; + + ASSERT_EQ(8, arguments.size()); + int argct = 0; + + // basic types + ASSERT_TRUE(arguments[argct]->IsInt()); + ASSERT_EQ(5, arguments[argct]->GetIntValue()); + argct++; + + ASSERT_TRUE(arguments[argct]->IsDouble()); + ASSERT_EQ(6.543, arguments[argct]->GetDoubleValue()); + argct++; + + ASSERT_TRUE(arguments[argct]->IsBool()); + ASSERT_EQ(true, arguments[argct]->GetBoolValue()); + argct++; + + ASSERT_TRUE(arguments[argct]->IsString()); + ASSERT_EQ(L"test string", arguments[argct]->GetStringValue()); + argct++; + + CefRefPtr value; + + // array + ASSERT_TRUE(arguments[argct]->IsArray()); + ASSERT_EQ(4, arguments[argct]->GetArrayLength()); + { + int subargct = 0; + value = arguments[argct]->GetValue(subargct); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsInt()); + ASSERT_EQ(7, value->GetIntValue()); + subargct++; + + value = arguments[argct]->GetValue(subargct); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsDouble()); + ASSERT_EQ(5.432, value->GetDoubleValue()); + subargct++; + + value = arguments[argct]->GetValue(subargct); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsBool()); + ASSERT_EQ(false, value->GetBoolValue()); + subargct++; + + value = arguments[argct]->GetValue(subargct); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsString()); + ASSERT_EQ(L"another string", value->GetStringValue()); + subargct++; + } + argct++; + + // object + ASSERT_TRUE(arguments[argct]->IsObject()); + { + value = arguments[argct]->GetValue(L"arg0"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsInt()); + ASSERT_EQ(2, value->GetIntValue()); + + value = arguments[argct]->GetValue(L"arg1"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsDouble()); + ASSERT_EQ(3.433, value->GetDoubleValue()); + + value = arguments[argct]->GetValue(L"arg2"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsBool()); + ASSERT_EQ(true, value->GetBoolValue()); + + value = arguments[argct]->GetValue(L"arg3"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsString()); + ASSERT_EQ(L"some string", value->GetStringValue()); + } + argct++; + + // function that returns a value + ASSERT_TRUE(arguments[argct]->IsFunction()); + { + CefV8ValueList args; + args.push_back(CefV8Value::CreateInt(5)); + args.push_back(CefV8Value::CreateDouble(3.5)); + args.push_back(CefV8Value::CreateBool(true)); + args.push_back(CefV8Value::CreateString(L"10")); + CefRefPtr rv; + std::wstring exception; + ASSERT_TRUE(arguments[argct]->ExecuteFunction( + arguments[argct], args, rv, exception)); + ASSERT_TRUE(rv.get() != NULL); + ASSERT_TRUE(rv->IsDouble()); + ASSERT_EQ(19.5, rv->GetDoubleValue()); + } + argct++; + + // function that throws an exception + ASSERT_TRUE(arguments[argct]->IsFunction()); + { + CefV8ValueList args; + args.push_back(CefV8Value::CreateDouble(5)); + args.push_back(CefV8Value::CreateDouble(0)); + CefRefPtr rv; + std::wstring exception; + ASSERT_TRUE(arguments[argct]->ExecuteFunction( + arguments[argct], args, rv, exception)); + ASSERT_EQ(L"Uncaught My Exception", exception); + } + argct++; + + if(binding_test_) + { + // values + value = object->GetValue(L"intVal"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsInt()); + ASSERT_EQ(12, value->GetIntValue()); + + value = object->GetValue(L"doubleVal"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsDouble()); + ASSERT_EQ(5.432, value->GetDoubleValue()); + + value = object->GetValue(L"boolVal"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsBool()); + ASSERT_EQ(true, value->GetBoolValue()); + + value = object->GetValue(L"stringVal"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsString()); + ASSERT_EQ(L"the string", value->GetStringValue()); + + value = object->GetValue(L"arrayVal"); + ASSERT_TRUE(value.get() != NULL); + ASSERT_TRUE(value->IsArray()); + { + CefRefPtr value2; + int subargct = 0; + value2 = value->GetValue(subargct); + ASSERT_TRUE(value2.get() != NULL); + ASSERT_TRUE(value2->IsInt()); + ASSERT_EQ(4, value2->GetIntValue()); + subargct++; + + value2 = value->GetValue(subargct); + ASSERT_TRUE(value2.get() != NULL); + ASSERT_TRUE(value2->IsDouble()); + ASSERT_EQ(120.43, value2->GetDoubleValue()); + subargct++; + + value2 = value->GetValue(subargct); + ASSERT_TRUE(value2.get() != NULL); + ASSERT_TRUE(value2->IsBool()); + ASSERT_EQ(true, value2->GetBoolValue()); + subargct++; + + value2 = value->GetValue(subargct); + ASSERT_TRUE(value2.get() != NULL); + ASSERT_TRUE(value2->IsString()); + ASSERT_EQ(L"a string", value2->GetStringValue()); + subargct++; + } + } + + retval = CefV8Value::CreateInt(5); + } else if(name == L"execute2") { + g_V8TestV8HandlerExecute2Called = true; + + // check the result of calling the "execute" function + ASSERT_EQ(1, arguments.size()); + ASSERT_TRUE(arguments[0]->IsInt()); + ASSERT_EQ(5, arguments[0]->GetIntValue()); + } + } + + bool binding_test_; +}; + +class V8TestHandler : public TestHandler +{ +public: + V8TestHandler(bool bindingTest) { binding_test_ = bindingTest; } + + virtual void RunTest() + { + std::string object; + if(binding_test_) { + // binding uses the window object + object = "window.test"; + } else { + // extension uses a global object + object = "test"; + } + + std::stringstream testHtml; + testHtml << + "" + "" + ""; + + AddResource(L"http://tests/run.html", testHtml.str(), L"text/html"); + CreateBrowser(L"http://tests/run.html"); + } + + virtual RetVal HandleLoadEnd(CefRefPtr browser, + CefRefPtr frame) + { + if(!browser->IsPopup() && !frame.get()) + DestroyTest(); + return RV_CONTINUE; + } + + virtual RetVal HandleJSBinding(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object) + { + if(binding_test_) { + TestHandleJSBinding(browser, frame, object); + return RV_HANDLED; + } + return RV_CONTINUE; + } + + void TestHandleJSBinding(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object) + { + // Create the new V8 object + CefRefPtr testObj = CefV8Value::CreateObject(NULL); + ASSERT_TRUE(testObj.get() != NULL); + ASSERT_TRUE(object->SetValue(L"test", testObj)); + + // Create an instance of V8ExecuteV8Handler + CefRefPtr testHandler(new V8TestV8Handler(true)); + ASSERT_TRUE(testHandler.get() != NULL); + + // Add the functions + CefRefPtr testFunc; + testFunc = CefV8Value::CreateFunction(L"execute", testHandler); + ASSERT_TRUE(testFunc.get() != NULL); + ASSERT_TRUE(testObj->SetValue(L"execute", testFunc)); + testFunc = CefV8Value::CreateFunction(L"execute2", testHandler); + ASSERT_TRUE(testFunc.get() != NULL); + ASSERT_TRUE(testObj->SetValue(L"execute2", testFunc)); + + // Add the values + ASSERT_TRUE(testObj->SetValue(L"intVal", + CefV8Value::CreateInt(12))); + ASSERT_TRUE(testObj->SetValue(L"doubleVal", + CefV8Value::CreateDouble(5.432))); + ASSERT_TRUE(testObj->SetValue(L"boolVal", + CefV8Value::CreateBool(true))); + ASSERT_TRUE(testObj->SetValue(L"stringVal", + CefV8Value::CreateString(L"the string"))); + + CefRefPtr testArray(CefV8Value::CreateArray()); + ASSERT_TRUE(testArray.get() != NULL); + ASSERT_TRUE(testObj->SetValue(L"arrayVal", testArray)); + ASSERT_TRUE(testArray->SetValue(0, CefV8Value::CreateInt(4))); + ASSERT_TRUE(testArray->SetValue(1, CefV8Value::CreateDouble(120.43))); + ASSERT_TRUE(testArray->SetValue(2, CefV8Value::CreateBool(true))); + ASSERT_TRUE(testArray->SetValue(3, CefV8Value::CreateString(L"a string"))); + } + + bool binding_test_; +}; + +// Verify window binding +TEST(V8Test, Binding) +{ + g_V8TestV8HandlerExecuteCalled = false; + g_V8TestV8HandlerExecute2Called = false; + + CefRefPtr handler = new V8TestHandler(true); + handler->ExecuteTest(); + + ASSERT_TRUE(g_V8TestV8HandlerExecuteCalled); + ASSERT_TRUE(g_V8TestV8HandlerExecute2Called); +} + +// Verify extensions +TEST(V8Test, Extension) +{ + g_V8TestV8HandlerExecuteCalled = false; + g_V8TestV8HandlerExecute2Called = false; + + std::wstring extensionCode = + L"var test;" + L"if (!test)" + L" test = {};" + L"(function() {" + L" test.execute = function(a,b,c,d,e,f,g,h) {" + L" native function execute();" + L" return execute(a,b,c,d,e,f,g,h);" + L" };" + L" test.execute2 = function(a) {" + L" native function execute2();" + L" return execute2(a);" + L" };" + L"})();"; + CefRegisterExtension(L"v8/test", extensionCode, new V8TestV8Handler(false)); + + CefRefPtr handler = new V8TestHandler(false); + handler->ExecuteTest(); + + ASSERT_TRUE(g_V8TestV8HandlerExecuteCalled); + ASSERT_TRUE(g_V8TestV8HandlerExecute2Called); +} diff --git a/tools/cef_parser.py b/tools/cef_parser.py index 3f605631f..64524df71 100644 --- a/tools/cef_parser.py +++ b/tools/cef_parser.py @@ -1,1335 +1,1335 @@ -# 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 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 read_file(name, normalize = True): - """ Function for reading 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 '+filename+': '+strerror) - raise - else: - f.close() - -def write_file(name, data): - """ Function for writing a file. """ - notify('Writing file '+name) - 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 file_exists(name): - """ Returns true if the file currently exists. """ - return os.path.exists(name) - -def backup_file(name): - """ Renames the file to a name that includes the current time stamp. """ - notify('Creating a backup of file '+name) - shutil.move(name, name+'.'+time.strftime('%Y-%m-%d-%H-%M-%S')) - - -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_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] == '/*': - continue - elif line[0:2] == '//': - result.append(line[3:]) - 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 line is None or len(line) == 0 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] == ' ': - # blank lines or anything that's further indented should be - # output as-is - result += indent+'//' - if len(line) > 0: - 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 = '' - - # 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. """ - 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) - dict[string.strip(sparts[0])] = string.strip(sparts[1]) - return dict - -def dict_to_str(dict): - """ Convert a dictionary to a string. """ - str = [] - for name in dict.keys(): - str.append(name+'='+dict[name]) - return string.join(str, ',') - - -# regex for matching comment-formatted attributes -_cre_attrib = '/\*--cef\(([A-Za-z0-9_ ,=]{0,})\)--\*/' -# regex for matching class and function names -_cre_cfname = '([A-Za-z0-9_]{1,})' -# regex for matching typedef values and function return values -_cre_retval = '([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,}' - - -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 - -class obj_header: - """ Class representing a C++ header file. """ - - def __init__(self, filename): - self.filename = filename; - - # read the input file into memory - data = read_file(filename) - - # extract global typedefs - p = re.compile('\ntypedef'+_cre_space+_cre_retval+ - _cre_space+_cre_cfname+';', - re.MULTILINE | re.DOTALL) - list = p.findall(data) - - # build the global typedef objects - self.typedefs = [] - for value, alias in list: - self.typedefs.append(obj_typedef(self, value, alias)) - - # extract global functions - p = re.compile('\n'+_cre_attrib+'\n'+_cre_func+'\((.*?)\)', - re.MULTILINE | re.DOTALL) - list = p.findall(data) - - # build the global function objects - self.funcs = [] - for attrib, retval, argval in list: - comment = get_comment(data, retval+'('+argval+');') - self.funcs.append(obj_function(self, attrib, retval, argval, - comment)) - - # extract classes - p = re.compile('\n'+_cre_attrib+ - '\nclass'+_cre_space+_cre_cfname+_cre_space+ - ':'+_cre_space+'public'+_cre_space+'CefBase'+ - '\n{(.*?)}', re.MULTILINE | re.DOTALL) - list = p.findall(data) - - # build the class objects - self.classes = [] - for attrib, name, body in list: - comment = get_comment(data, name+' : public CefBase') - self.classes.append( - obj_class(self, attrib, name, body, comment)) - - 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_name(self): - """ Return the file name. """ - return self.filename - - def get_typedefs(self): - """ Return the array of typedef objects. """ - return self.typedefs - - def get_funcs(self): - """ Return the array of function objects. """ - return self.funcs - - def get_classes(self): - """ Return the array of class objects. """ - return self.classes - - 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_handler_menuinfo_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, attrib, name, body, comment): - if not isinstance(parent, obj_header): - raise Exception('Invalid parent object type') - - self.parent = parent - self.attribs = str_to_dict(attrib) - self.name = name - self.comment = comment - - # extract typedefs - p = re.compile('\n'+_cre_space+'typedef'+_cre_space+_cre_retval+ - _cre_space+_cre_cfname+';', - re.MULTILINE | re.DOTALL) - list = p.findall(body) - - # build the typedef objects - self.typedefs = [] - for value, alias in list: - self.typedefs.append(obj_typedef(self, 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_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_attribs(self): - """ Return the class attributes as a dictionary. """ - return self.attribs; - - def get_typedefs(self): - """ Return the array of typedef objects. """ - return self.typedefs; - - 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, value, alias): - if not isinstance(parent, obj_header) \ - and not isinstance(parent, obj_class): - raise Exception('Invalid parent object type') - - self.parent = parent - self.alias = alias - self.value = self.parent.get_analysis(value, False) - - def __repr__(self): - return 'typedef '+self.value.get_type()+' '+self.alias+';' - - 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, attrib, retval, argval, comment): - self.parent = parent - 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: - self.arguments.append(obj_argument(self, arg)) - - def __repr__(self): - return '/* '+dict_to_str(self.attribs)+' */ '+self.get_cpp_proto() - - def get_name(self): - """ Return the function name. """ - return 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 the function attributes as a dictionary. """ - return self.attribs - - 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 = type.get_name() - if type[-1] == 's': - type = type[:-1] - args.append('size_t '+type+'Count') - args.append(dict['value']) - elif dict['format'] == 'multi-func': - # change the function to return one value of the - # required type based on an index parameter - type = type.get_name() - if type[-1] == 's': - type = type[:-1] - args.append('int '+type+'Index') - retval = 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 - type = self.get_retval().get_type() - if type.is_result_struct() and not type.is_byref() \ - and not type.is_byaddr(): - 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 - - -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, 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, 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 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 - - -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 - - # 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 = value[12:-1] - self.result_value = [ - self._get_basic(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 basic types - basic = self._get_basic(value) - if not basic is None: - self.result_type = basic['result_type'] - self.result_value = basic['result_value'] - return True - - return False - - def _get_basic(self, value): - # check for string values - if value == "std::wstring": - return { - 'result_type' : 'string', - 'result_value' : None - } - - # check for simple direct translations - structuretypes = { - 'CefPrintInfo' : 'cef_print_info_t', - 'CefWindowInfo' : 'cef_window_info_t' - } - if value in structuretypes.keys(): - return { - 'result_type' : 'structure', - 'result_value' : structuretypes[value] - } - - # check for simple direct translations - simpletypes = { - 'void' : 'void', - 'int' : 'int', - 'double' : 'double', - 'long' : 'long', - 'unsigned long' : 'unsigned long', - 'size_t' : 'size_t', - 'bool' : 'int', - 'CefWindowHandle' : 'cef_window_handle_t', - 'CefRect' : 'cef_rect_t', - 'CefThreadId' : 'cef_thread_id_t', - } - if value in simpletypes.keys(): - return { - 'result_type' : 'simple', - 'result_value' : simpletypes[value] - } - - # 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)+'*' - } - - 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 name. """ - return self.value - - def get_type(self): - """ Return the type. """ - return self.type - - 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(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 is_result_refptr(self): - """ Returns true if this is a reference pointer type. """ - return (self.result_type == 'refptr') - - 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 get_result_struct_type(self, defined_structs = []): - """ Return the structure or enumeration type. """ - result = '' - # structure values that are passed by reference or address must be - # structures and not enumerations - if self.is_byref() or self.is_byaddr(): - if self.is_const(): - result += 'const ' - if not self.result_value in defined_structs: - result += 'struct _' - else: - result += 'enum ' - result += self.result_value - if self.is_byref() or self.is_byaddr(): - 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 the string is a return value, or if the string is passed by - # reference or address then use the read-write string type - if not self.has_name(): - return 'cef_string_t' - elif not self.is_const() and (self.is_byref() or self.is_byaddr()): - return 'cef_string_t*' - return 'const wchar_t*' - - def is_result_vector(self): - """ Returns true if this is a vector type. """ - return (self.result_type == 'vector') - - 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': - result['value'] = value - elif type == 'refptr': - str = '' - if not value[:-1] in defined_structs: - str += 'struct _' - str += value - if self.is_const(): - str += ' const*' - result['value'] = str - else: - raise Exception('Unsupported vector type: '+type) - - if self.is_const(): - # const vector values must be passed as the value array parameter - # and a size parameter - result['format'] = 'multi-arg' - else: - # non-const vector values must be passed as one function to get the - # size and another function to get the element at a specified index - result['format'] = 'multi-func' - return result - - def is_result_map(self): - """ Returns true if this is a map type. """ - return (self.result_type == 'map') - - 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': - return { - 'value' : 'cef_string_map_t', - 'format' : 'single' - } - 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': - result += resdict['value'] - else: - raise Exception('Only single-value map types are supported') - 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() and format != 'multi-func': - 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(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')) +# 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 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 read_file(name, normalize = True): + """ Function for reading 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 '+filename+': '+strerror) + raise + else: + f.close() + +def write_file(name, data): + """ Function for writing a file. """ + notify('Writing file '+name) + 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 file_exists(name): + """ Returns true if the file currently exists. """ + return os.path.exists(name) + +def backup_file(name): + """ Renames the file to a name that includes the current time stamp. """ + notify('Creating a backup of file '+name) + shutil.move(name, name+'.'+time.strftime('%Y-%m-%d-%H-%M-%S')) + + +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_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] == '/*': + continue + elif line[0:2] == '//': + result.append(line[3:]) + 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 line is None or len(line) == 0 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] == ' ': + # blank lines or anything that's further indented should be + # output as-is + result += indent+'//' + if len(line) > 0: + 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 = '' + + # 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. """ + 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) + dict[string.strip(sparts[0])] = string.strip(sparts[1]) + return dict + +def dict_to_str(dict): + """ Convert a dictionary to a string. """ + str = [] + for name in dict.keys(): + str.append(name+'='+dict[name]) + return string.join(str, ',') + + +# regex for matching comment-formatted attributes +_cre_attrib = '/\*--cef\(([A-Za-z0-9_ ,=]{0,})\)--\*/' +# regex for matching class and function names +_cre_cfname = '([A-Za-z0-9_]{1,})' +# regex for matching typedef values and function return values +_cre_retval = '([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,}' + + +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 + +class obj_header: + """ Class representing a C++ header file. """ + + def __init__(self, filename): + self.filename = filename; + + # read the input file into memory + data = read_file(filename) + + # extract global typedefs + p = re.compile('\ntypedef'+_cre_space+_cre_retval+ + _cre_space+_cre_cfname+';', + re.MULTILINE | re.DOTALL) + list = p.findall(data) + + # build the global typedef objects + self.typedefs = [] + for value, alias in list: + self.typedefs.append(obj_typedef(self, value, alias)) + + # extract global functions + p = re.compile('\n'+_cre_attrib+'\n'+_cre_func+'\((.*?)\)', + re.MULTILINE | re.DOTALL) + list = p.findall(data) + + # build the global function objects + self.funcs = [] + for attrib, retval, argval in list: + comment = get_comment(data, retval+'('+argval+');') + self.funcs.append(obj_function(self, attrib, retval, argval, + comment)) + + # extract classes + p = re.compile('\n'+_cre_attrib+ + '\nclass'+_cre_space+_cre_cfname+_cre_space+ + ':'+_cre_space+'public'+_cre_space+'CefBase'+ + '\n{(.*?)}', re.MULTILINE | re.DOTALL) + list = p.findall(data) + + # build the class objects + self.classes = [] + for attrib, name, body in list: + comment = get_comment(data, name+' : public CefBase') + self.classes.append( + obj_class(self, attrib, name, body, comment)) + + 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_name(self): + """ Return the file name. """ + return self.filename + + def get_typedefs(self): + """ Return the array of typedef objects. """ + return self.typedefs + + def get_funcs(self): + """ Return the array of function objects. """ + return self.funcs + + def get_classes(self): + """ Return the array of class objects. """ + return self.classes + + 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_handler_menuinfo_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, attrib, name, body, comment): + if not isinstance(parent, obj_header): + raise Exception('Invalid parent object type') + + self.parent = parent + self.attribs = str_to_dict(attrib) + self.name = name + self.comment = comment + + # extract typedefs + p = re.compile('\n'+_cre_space+'typedef'+_cre_space+_cre_retval+ + _cre_space+_cre_cfname+';', + re.MULTILINE | re.DOTALL) + list = p.findall(body) + + # build the typedef objects + self.typedefs = [] + for value, alias in list: + self.typedefs.append(obj_typedef(self, 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_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_attribs(self): + """ Return the class attributes as a dictionary. """ + return self.attribs; + + def get_typedefs(self): + """ Return the array of typedef objects. """ + return self.typedefs; + + 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, value, alias): + if not isinstance(parent, obj_header) \ + and not isinstance(parent, obj_class): + raise Exception('Invalid parent object type') + + self.parent = parent + self.alias = alias + self.value = self.parent.get_analysis(value, False) + + def __repr__(self): + return 'typedef '+self.value.get_type()+' '+self.alias+';' + + 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, attrib, retval, argval, comment): + self.parent = parent + 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: + self.arguments.append(obj_argument(self, arg)) + + def __repr__(self): + return '/* '+dict_to_str(self.attribs)+' */ '+self.get_cpp_proto() + + def get_name(self): + """ Return the function name. """ + return 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 the function attributes as a dictionary. """ + return self.attribs + + 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 = type.get_name() + if type[-1] == 's': + type = type[:-1] + args.append('size_t '+type+'Count') + args.append(dict['value']) + elif dict['format'] == 'multi-func': + # change the function to return one value of the + # required type based on an index parameter + type = type.get_name() + if type[-1] == 's': + type = type[:-1] + args.append('int '+type+'Index') + retval = 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 + type = self.get_retval().get_type() + if type.is_result_struct() and not type.is_byref() \ + and not type.is_byaddr(): + 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 + + +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, 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, 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 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 + + +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 + + # 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 = value[12:-1] + self.result_value = [ + self._get_basic(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 basic types + basic = self._get_basic(value) + if not basic is None: + self.result_type = basic['result_type'] + self.result_value = basic['result_value'] + return True + + return False + + def _get_basic(self, value): + # check for string values + if value == "std::wstring": + return { + 'result_type' : 'string', + 'result_value' : None + } + + # check for simple direct translations + structuretypes = { + 'CefPrintInfo' : 'cef_print_info_t', + 'CefWindowInfo' : 'cef_window_info_t' + } + if value in structuretypes.keys(): + return { + 'result_type' : 'structure', + 'result_value' : structuretypes[value] + } + + # check for simple direct translations + simpletypes = { + 'void' : 'void', + 'int' : 'int', + 'double' : 'double', + 'long' : 'long', + 'unsigned long' : 'unsigned long', + 'size_t' : 'size_t', + 'bool' : 'int', + 'CefWindowHandle' : 'cef_window_handle_t', + 'CefRect' : 'cef_rect_t', + 'CefThreadId' : 'cef_thread_id_t', + } + if value in simpletypes.keys(): + return { + 'result_type' : 'simple', + 'result_value' : simpletypes[value] + } + + # 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)+'*' + } + + 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 name. """ + return self.value + + def get_type(self): + """ Return the type. """ + return self.type + + 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(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 is_result_refptr(self): + """ Returns true if this is a reference pointer type. """ + return (self.result_type == 'refptr') + + 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 get_result_struct_type(self, defined_structs = []): + """ Return the structure or enumeration type. """ + result = '' + # structure values that are passed by reference or address must be + # structures and not enumerations + if self.is_byref() or self.is_byaddr(): + if self.is_const(): + result += 'const ' + if not self.result_value in defined_structs: + result += 'struct _' + else: + result += 'enum ' + result += self.result_value + if self.is_byref() or self.is_byaddr(): + 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 the string is a return value, or if the string is passed by + # reference or address then use the read-write string type + if not self.has_name(): + return 'cef_string_t' + elif not self.is_const() and (self.is_byref() or self.is_byaddr()): + return 'cef_string_t*' + return 'const wchar_t*' + + def is_result_vector(self): + """ Returns true if this is a vector type. """ + return (self.result_type == 'vector') + + 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': + result['value'] = value + elif type == 'refptr': + str = '' + if not value[:-1] in defined_structs: + str += 'struct _' + str += value + if self.is_const(): + str += ' const*' + result['value'] = str + else: + raise Exception('Unsupported vector type: '+type) + + if self.is_const(): + # const vector values must be passed as the value array parameter + # and a size parameter + result['format'] = 'multi-arg' + else: + # non-const vector values must be passed as one function to get the + # size and another function to get the element at a specified index + result['format'] = 'multi-func' + return result + + def is_result_map(self): + """ Returns true if this is a map type. """ + return (self.result_type == 'map') + + 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': + return { + 'value' : 'cef_string_map_t', + 'format' : 'single' + } + 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': + result += resdict['value'] + else: + raise Exception('Only single-value map types are supported') + 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() and format != 'multi-func': + 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(sys.argv[1]) + + # output the type mapping + types = {} + header.get_types(types) + pp.pprint(types) + sys.stdout.write('\n') + + # output the parsed C++ data + sys.stdout.write(wrap_code(str(header), '\t')) + + # output the C API formatted data + defined_names = header.get_defined_structs() + result = '' + + # global functions + funcs = header.get_funcs() + if len(funcs) > 0: + for func in funcs: + result += func.get_capi_proto(defined_names)+';\n' + result += '\n' + + classes = header.get_classes() + for cls in classes: + # virtual functions are inside a structure + result += 'struct '+cls.get_capi_name()+'\n{\n' + funcs = cls.get_virtual_funcs() + if len(funcs) > 0: + for func in funcs: + result += '\t'+func.get_capi_proto(defined_names)+';\n' + result += '}\n\n' + + defined_names.append(cls.get_capi_name()) + + # static functions become global + funcs = cls.get_static_funcs() + if len(funcs) > 0: + for func in funcs: + result += func.get_capi_proto(defined_names)+';\n' + result += '\n' + sys.stdout.write(wrap_code(result, '\t')) diff --git a/tools/file_util.py b/tools/file_util.py index 851c735d5..65b363a83 100644 --- a/tools/file_util.py +++ b/tools/file_util.py @@ -1,44 +1,44 @@ -# 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 os -import shutil -import sys -import time - -def read_file(name, normalize = True): - """ Function for reading 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 '+filename+': '+strerror) - raise - else: - f.close() - -def write_file(name, data): - """ Function for writing 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 file_exists(name): - """ Returns true if the file currently exists. """ - return os.path.exists(name) - -def backup_file(name): - """ Renames the file to a name that includes the current time stamp. """ - shutil.move(name, name+'.'+time.strftime('%Y-%m-%d-%H-%M-%S')) +# 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 os +import shutil +import sys +import time + +def read_file(name, normalize = True): + """ Function for reading 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 '+filename+': '+strerror) + raise + else: + f.close() + +def write_file(name, data): + """ Function for writing 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 file_exists(name): + """ Returns true if the file currently exists. """ + return os.path.exists(name) + +def backup_file(name): + """ Renames the file to a name that includes the current time stamp. """ + shutil.move(name, name+'.'+time.strftime('%Y-%m-%d-%H-%M-%S')) diff --git a/tools/make_capi_header.py b/tools/make_capi_header.py index afd3e6743..bc29e8df7 100644 --- a/tools/make_capi_header.py +++ b/tools/make_capi_header.py @@ -1,194 +1,194 @@ -# 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. - -from cef_parser 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_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_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): - # 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) 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. -// -// --------------------------------------------------------------------------- -// -// 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_CAPI_H -#define _CEF_CAPI_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "cef_export.h" -#include "cef_string.h" -#include "cef_string_list.h" -#include "cef_string_map.h" -#include "cef_types.h" - -""" - - # output global functions - result += make_capi_global_funcs(header.get_funcs(), defined_names, - translate_map, '') - - # before classes string - result += \ -""" -typedef struct _cef_base_t -{ - // Size of the data structure. - size_t size; - - // Increment the reference count. - int (CEF_CALLBACK *add_ref)(struct _cef_base_t* self); - // Decrement the reference count. Delete this object when no references - // remain. - int (CEF_CALLBACK *release)(struct _cef_base_t* self); - // Returns the current number of references. - int (CEF_CALLBACK *get_refct)(struct _cef_base_t* self); - -} cef_base_t; - - -// Check that the structure |s|, which is defined with a cef_base_t member named -// |base|, is large enough to contain the specified member |f|. -#define CEF_MEMBER_EXISTS(s, f) \\ - ((int)&((s)->f) - (int)(s) + sizeof((s)->f) <= (s)->base.size) - -#define CEF_MEMBER_MISSING(s, f) (!CEF_MEMBER_EXISTS(s, f) || !((s)->f)) - -""" - - # output classes - classes = header.get_classes() - for cls in classes: - # virtual functions are inside the structure - classname = cls.get_capi_name() - result += '\n'+format_comment(cls.get_comment(), '', translate_map); - result += 'typedef struct _'+classname+ \ - '\n{\n // Base structure.\n cef_base_t base;\n' - funcs = cls.get_virtual_funcs() - result += make_capi_member_funcs(funcs, defined_names, - translate_map, ' ') - result += '\n} '+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 // _CEF_CAPI_H -""" - - return result - - -def write_capi_header(header, file, backup): - if file_exists(file): - oldcontents = read_file(file) - else: - oldcontents = '' - - newcontents = make_capi_header(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(sys.argv[1]) - - # dump the result to stdout - sys.stdout.write(make_capi_header(header)) +# 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. + +from cef_parser 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_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_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): + # 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) 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. +// +// --------------------------------------------------------------------------- +// +// 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_CAPI_H +#define _CEF_CAPI_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cef_export.h" +#include "cef_string.h" +#include "cef_string_list.h" +#include "cef_string_map.h" +#include "cef_types.h" + +""" + + # output global functions + result += make_capi_global_funcs(header.get_funcs(), defined_names, + translate_map, '') + + # before classes string + result += \ +""" +typedef struct _cef_base_t +{ + // Size of the data structure. + size_t size; + + // Increment the reference count. + int (CEF_CALLBACK *add_ref)(struct _cef_base_t* self); + // Decrement the reference count. Delete this object when no references + // remain. + int (CEF_CALLBACK *release)(struct _cef_base_t* self); + // Returns the current number of references. + int (CEF_CALLBACK *get_refct)(struct _cef_base_t* self); + +} cef_base_t; + + +// Check that the structure |s|, which is defined with a cef_base_t member named +// |base|, is large enough to contain the specified member |f|. +#define CEF_MEMBER_EXISTS(s, f) \\ + ((int)&((s)->f) - (int)(s) + sizeof((s)->f) <= (s)->base.size) + +#define CEF_MEMBER_MISSING(s, f) (!CEF_MEMBER_EXISTS(s, f) || !((s)->f)) + +""" + + # output classes + classes = header.get_classes() + for cls in classes: + # virtual functions are inside the structure + classname = cls.get_capi_name() + result += '\n'+format_comment(cls.get_comment(), '', translate_map); + result += 'typedef struct _'+classname+ \ + '\n{\n // Base structure.\n cef_base_t base;\n' + funcs = cls.get_virtual_funcs() + result += make_capi_member_funcs(funcs, defined_names, + translate_map, ' ') + result += '\n} '+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 // _CEF_CAPI_H +""" + + return result + + +def write_capi_header(header, file, backup): + if file_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + newcontents = make_capi_header(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(sys.argv[1]) + + # dump the result to stdout + sys.stdout.write(make_capi_header(header)) diff --git a/tools/make_cpptoc_header.py b/tools/make_cpptoc_header.py index 0a896ba4d..9f2bf7f40 100644 --- a/tools/make_cpptoc_header.py +++ b/tools/make_cpptoc_header.py @@ -1,106 +1,106 @@ -# 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. - -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(clsname[3:]) - capiname = cls.get_capi_name() - - result = \ -"""// 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. -// -// --------------------------------------------------------------------------- -// -// 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. -// -""" - result += '#ifndef _'+defname+'_CPPTOC_H\n'+ \ - '#define _'+defname+'_CPPTOC_H\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 -""" - - result += """ -#include "include/cef.h" -#include "include/cef_capi.h" -#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'+ \ - '{\n'+ \ - 'public:\n'+ \ - ' '+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 // _'+defname+'_CPPTOC_H\n' - - return wrap_code(result) - - -def write_cpptoc_header(header, clsname, dir, backup): - file = dir+'\\'+get_capi_name(clsname[3:], False)+'_cpptoc.h' - - if file_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(sys.argv[1]) - - # dump the result to stdout - sys.stdout.write(make_cpptoc_header(header, sys.argv[2])) +# 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. + +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(clsname[3:]) + capiname = cls.get_capi_name() + + result = \ +"""// 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. +// +// --------------------------------------------------------------------------- +// +// 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. +// +""" + result += '#ifndef _'+defname+'_CPPTOC_H\n'+ \ + '#define _'+defname+'_CPPTOC_H\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 +""" + + result += """ +#include "include/cef.h" +#include "include/cef_capi.h" +#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'+ \ + '{\n'+ \ + 'public:\n'+ \ + ' '+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 // _'+defname+'_CPPTOC_H\n' + + return wrap_code(result) + + +def write_cpptoc_header(header, clsname, dir, backup): + file = dir+'\\'+get_capi_name(clsname[3:], False)+'_cpptoc.h' + + if file_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(sys.argv[1]) + + # dump the result to stdout + sys.stdout.write(make_cpptoc_header(header, sys.argv[2])) diff --git a/tools/make_cpptoc_impl.py b/tools/make_cpptoc_impl.py index ca814e621..060e9bfe1 100644 --- a/tools/make_cpptoc_impl.py +++ b/tools/make_cpptoc_impl.py @@ -1,184 +1,184 @@ -# 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. - -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 wrap_code(proto) - -def make_cpptoc_impl_existing(name, func, impl, defined_names): - # retrieve the C API prototype parts - parts = func.get_capi_parts(defined_names) - - changes = format_translation_changes(impl, parts) - if len(changes) > 0: - notify('Changed prototype for '+name) - - return make_cpptoc_impl_proto(name, func, parts)+'{'+ \ - changes+impl['body']+'\n}\n\n' - return result - -def make_cpptoc_impl_new(name, func, defined_names): - notify('Added implementation for '+name) - - # retrieve the C API prototype parts - parts = func.get_capi_parts(defined_names) - result = make_cpptoc_impl_proto(name, func, parts)+'{' - - result += '\n // BEGIN DELETE BEFORE MODIFYING' - result += '\n // AUTO-GENERATED CONTENT' - - result += '\n #pragma message("Warning: "__FILE__": '+name+' is not implemented")' - - result += '\n // END DELETE BEFORE MODIFYING' - - result += '\n}\n\n' - return result - -def make_cpptoc_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) - - defname = string.upper(clsname[3:]) - 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 = '' - funcs = cls.get_virtual_funcs() - for func in funcs: - name = prefixname+'_'+func.get_capi_name() - value = get_next_function_impl(existing, name) - if not value is None \ - and value['body'].find('// AUTO-GEN') < 0: - # an implementation exists that was not auto-generated - virtualimpl += make_cpptoc_impl_existing(name, func, value, - defined_names) - else: - virtualimpl += make_cpptoc_impl_new(name, func, 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 = '' - funcs = cls.get_static_funcs() - for func in funcs: - 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 - staticimpl += make_cpptoc_impl_existing(name, func, value, - defined_names) - else: - staticimpl += make_cpptoc_impl_new(name, func, 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 = \ -"""// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing function -// implementations. See the translator.README.txt file in the tools directory -// for more information. -// - -""" - - 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'+ \ - '{\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'+ \ - '#ifdef _DEBUG\n'+ \ - 'long CefCppToC<'+clsname+'CppToC, '+clsname+', '+capiname+'>::DebugObjCt = 0;\n'+ \ - '#endif\n' - result += wrap_code(const) - - return result - - -def write_cpptoc_impl(header, clsname, dir, backup): - file = dir+'\\'+get_capi_name(clsname[3:], False)+'_cpptoc.cc' - - if file_exists(file): - oldcontents = read_file(file) - else: - oldcontents = '' - - newcontents = make_cpptoc_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(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_impl(header, sys.argv[2], data)) +# 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. + +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 wrap_code(proto) + +def make_cpptoc_impl_existing(name, func, impl, defined_names): + # retrieve the C API prototype parts + parts = func.get_capi_parts(defined_names) + + changes = format_translation_changes(impl, parts) + if len(changes) > 0: + notify('Changed prototype for '+name) + + return make_cpptoc_impl_proto(name, func, parts)+'{'+ \ + changes+impl['body']+'\n}\n\n' + return result + +def make_cpptoc_impl_new(name, func, defined_names): + notify('Added implementation for '+name) + + # retrieve the C API prototype parts + parts = func.get_capi_parts(defined_names) + result = make_cpptoc_impl_proto(name, func, parts)+'{' + + result += '\n // BEGIN DELETE BEFORE MODIFYING' + result += '\n // AUTO-GENERATED CONTENT' + + result += '\n #pragma message("Warning: "__FILE__": '+name+' is not implemented")' + + result += '\n // END DELETE BEFORE MODIFYING' + + result += '\n}\n\n' + return result + +def make_cpptoc_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) + + defname = string.upper(clsname[3:]) + 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 = '' + funcs = cls.get_virtual_funcs() + for func in funcs: + name = prefixname+'_'+func.get_capi_name() + value = get_next_function_impl(existing, name) + if not value is None \ + and value['body'].find('// AUTO-GEN') < 0: + # an implementation exists that was not auto-generated + virtualimpl += make_cpptoc_impl_existing(name, func, value, + defined_names) + else: + virtualimpl += make_cpptoc_impl_new(name, func, 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 = '' + funcs = cls.get_static_funcs() + for func in funcs: + 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 + staticimpl += make_cpptoc_impl_existing(name, func, value, + defined_names) + else: + staticimpl += make_cpptoc_impl_new(name, func, 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 = \ +"""// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +""" + + 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'+ \ + '{\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'+ \ + '#ifdef _DEBUG\n'+ \ + 'long CefCppToC<'+clsname+'CppToC, '+clsname+', '+capiname+'>::DebugObjCt = 0;\n'+ \ + '#endif\n' + result += wrap_code(const) + + return result + + +def write_cpptoc_impl(header, clsname, dir, backup): + file = dir+'\\'+get_capi_name(clsname[3:], False)+'_cpptoc.cc' + + if file_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + newcontents = make_cpptoc_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(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_impl(header, sys.argv[2], data)) diff --git a/tools/make_ctocpp_header.py b/tools/make_ctocpp_header.py index 05b3d2c72..84c6479a7 100644 --- a/tools/make_ctocpp_header.py +++ b/tools/make_ctocpp_header.py @@ -1,114 +1,114 @@ -# 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. - -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(clsname[3:]) - capiname = cls.get_capi_name() - - result = \ -"""// 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. -// -// ------------------------------------------------------------------------- -// -// 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. -// - -""" - result += '#ifndef _'+defname+'_CTOCPP_H\n'+ \ - '#define _'+defname+'_CTOCPP_H\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 -""" - - result += """ -#include "include/cef.h" -#include "include/cef_capi.h" -#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'+ \ - '{\n'+ \ - 'public:\n'+ \ - ' '+clsname+'CToCpp('+capiname+'* str)\n'+ \ - ' : CefCToCpp<'+clsname+'CToCpp, '+clsname+', '+capiname+'>(str) {}\n'+ \ - ' virtual ~'+clsname+'CToCpp() {}\n\n'+ \ - ' // '+clsname+' methods\n'; - - funcs = cls.get_virtual_funcs() - for func in funcs: - result += ' virtual '+func.get_cpp_proto()+';\n' - - result += '};\n\n' - - if clientside: - result += '#endif // BUILDING_CEF_SHARED\n' - else: - result += '#endif // USING_CEF_SHARED\n' - - result += '#endif // _'+defname+'_CTOCPP_H\n' - - return wrap_code(result) - - -def write_ctocpp_header(header, clsname, dir, backup): - file = dir+'\\'+get_capi_name(clsname[3:], False)+'_ctocpp.h' - - if file_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(sys.argv[1]) - - # dump the result to stdout - sys.stdout.write(make_ctocpp_header(header, sys.argv[2])) +# 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. + +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(clsname[3:]) + capiname = cls.get_capi_name() + + result = \ +"""// 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. +// +// ------------------------------------------------------------------------- +// +// 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. +// + +""" + result += '#ifndef _'+defname+'_CTOCPP_H\n'+ \ + '#define _'+defname+'_CTOCPP_H\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 +""" + + result += """ +#include "include/cef.h" +#include "include/cef_capi.h" +#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'+ \ + '{\n'+ \ + 'public:\n'+ \ + ' '+clsname+'CToCpp('+capiname+'* str)\n'+ \ + ' : CefCToCpp<'+clsname+'CToCpp, '+clsname+', '+capiname+'>(str) {}\n'+ \ + ' virtual ~'+clsname+'CToCpp() {}\n\n'+ \ + ' // '+clsname+' methods\n'; + + funcs = cls.get_virtual_funcs() + for func in funcs: + result += ' virtual '+func.get_cpp_proto()+';\n' + + result += '};\n\n' + + if clientside: + result += '#endif // BUILDING_CEF_SHARED\n' + else: + result += '#endif // USING_CEF_SHARED\n' + + result += '#endif // _'+defname+'_CTOCPP_H\n' + + return wrap_code(result) + + +def write_ctocpp_header(header, clsname, dir, backup): + file = dir+'\\'+get_capi_name(clsname[3:], False)+'_ctocpp.h' + + if file_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(sys.argv[1]) + + # dump the result to stdout + sys.stdout.write(make_ctocpp_header(header, sys.argv[2])) diff --git a/tools/make_ctocpp_impl.py b/tools/make_ctocpp_impl.py index 04d5d63c2..063bb5424 100644 --- a/tools/make_ctocpp_impl.py +++ b/tools/make_ctocpp_impl.py @@ -1,170 +1,170 @@ -# 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. - -from cef_parser import * - -def make_ctocpp_impl_proto(clsname, name, func, parts): - proto = parts['retval']+' '+clsname - const = '' - if isinstance(func, obj_function_virtual): - proto += 'CToCpp' - if func.is_const(): - const = ' const' - - proto += '::'+name+'('+string.join(parts['args'], ', ')+')'+const - return wrap_code(proto) - -def make_ctocpp_impl_existing(clsname, name, func, impl): - # retrieve the C++ prototype parts - parts = func.get_cpp_parts(True) - - changes = format_translation_changes(impl, parts) - if len(changes) > 0: - if isinstance(func, obj_function_virtual): - notify('Changed prototype for '+clsname+'CToCpp::'+name) - else: - notify('Changed prototype for '+clsname+'::'+name) - - return make_ctocpp_impl_proto(clsname, name, func, parts)+'{'+ \ - changes+impl['body']+'\n}\n\n' - -def make_ctocpp_impl_new(clsname, name, func): - if isinstance(func, obj_function_virtual): - notify('Added implementation for '+clsname+'CToCpp::'+name) - else: - notify('Added implementation for '+clsname+'::'+name) - - # retrieve the C++ prototype parts - parts = func.get_cpp_parts(True) - result = make_ctocpp_impl_proto(clsname, name, func, parts)+'{' - - result += '\n // BEGIN DELETE BEFORE MODIFYING' - result += '\n // AUTO-GENERATED CONTENT' - - result += '\n #pragma message("Warning: "__FILE__": '+name+' is not implemented")' - - result += '\n // END DELETE BEFORE MODIFYING' - - result += '\n}\n\n' - return result - -def make_ctocpp_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 = '' - funcs = cls.get_virtual_funcs() - 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-GEN') < 0: - # an implementation exists that was not auto-generated - virtualimpl += make_ctocpp_impl_existing(clsname, name, func, - value) - else: - virtualimpl += make_ctocpp_impl_new(clsname, name, func) - - 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 = '' - funcs = cls.get_static_funcs() - 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 - staticimpl += make_ctocpp_impl_existing(clsname, name, func, - value) - else: - staticimpl += make_ctocpp_impl_new(clsname, name, func) - - 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 = \ -"""// 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. -// -// --------------------------------------------------------------------------- -// -// A portion of this file was generated by the CEF translator tool. When -// making changes by hand only do so within the body of existing static and -// virtual method implementations. See the translator.README.txt file in the -// tools directory for more information. -// - -""" - - result += includes+'\n'+resultingimpl+'\n' - - result += wrap_code('#ifdef _DEBUG\n'+ \ - 'long CefCToCpp<'+clsname+'CToCpp, '+clsname+', '+capiname+'>::DebugObjCt = 0;\n'+ \ - '#endif\n') - - return result - - -def write_ctocpp_impl(header, clsname, dir, backup): - file = dir+'\\'+get_capi_name(clsname[3:], False)+'_ctocpp.cc' - - if file_exists(file): - oldcontents = read_file(file) - else: - oldcontents = '' - - newcontents = make_ctocpp_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(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_impl(header, sys.argv[2], data)) +# 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. + +from cef_parser import * + +def make_ctocpp_impl_proto(clsname, name, func, parts): + proto = parts['retval']+' '+clsname + const = '' + if isinstance(func, obj_function_virtual): + proto += 'CToCpp' + if func.is_const(): + const = ' const' + + proto += '::'+name+'('+string.join(parts['args'], ', ')+')'+const + return wrap_code(proto) + +def make_ctocpp_impl_existing(clsname, name, func, impl): + # retrieve the C++ prototype parts + parts = func.get_cpp_parts(True) + + changes = format_translation_changes(impl, parts) + if len(changes) > 0: + if isinstance(func, obj_function_virtual): + notify('Changed prototype for '+clsname+'CToCpp::'+name) + else: + notify('Changed prototype for '+clsname+'::'+name) + + return make_ctocpp_impl_proto(clsname, name, func, parts)+'{'+ \ + changes+impl['body']+'\n}\n\n' + +def make_ctocpp_impl_new(clsname, name, func): + if isinstance(func, obj_function_virtual): + notify('Added implementation for '+clsname+'CToCpp::'+name) + else: + notify('Added implementation for '+clsname+'::'+name) + + # retrieve the C++ prototype parts + parts = func.get_cpp_parts(True) + result = make_ctocpp_impl_proto(clsname, name, func, parts)+'{' + + result += '\n // BEGIN DELETE BEFORE MODIFYING' + result += '\n // AUTO-GENERATED CONTENT' + + result += '\n #pragma message("Warning: "__FILE__": '+name+' is not implemented")' + + result += '\n // END DELETE BEFORE MODIFYING' + + result += '\n}\n\n' + return result + +def make_ctocpp_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 = '' + funcs = cls.get_virtual_funcs() + 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-GEN') < 0: + # an implementation exists that was not auto-generated + virtualimpl += make_ctocpp_impl_existing(clsname, name, func, + value) + else: + virtualimpl += make_ctocpp_impl_new(clsname, name, func) + + 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 = '' + funcs = cls.get_static_funcs() + 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 + staticimpl += make_ctocpp_impl_existing(clsname, name, func, + value) + else: + staticimpl += make_ctocpp_impl_new(clsname, name, func) + + 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 = \ +"""// 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. +// +// --------------------------------------------------------------------------- +// +// A portion of this file was generated by the CEF translator tool. When +// making changes by hand only do so within the body of existing static and +// virtual method implementations. See the translator.README.txt file in the +// tools directory for more information. +// + +""" + + result += includes+'\n'+resultingimpl+'\n' + + result += wrap_code('#ifdef _DEBUG\n'+ \ + 'long CefCToCpp<'+clsname+'CToCpp, '+clsname+', '+capiname+'>::DebugObjCt = 0;\n'+ \ + '#endif\n') + + return result + + +def write_ctocpp_impl(header, clsname, dir, backup): + file = dir+'\\'+get_capi_name(clsname[3:], False)+'_ctocpp.cc' + + if file_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + newcontents = make_ctocpp_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(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_impl(header, sys.argv[2], data)) diff --git a/tools/patch_util.py b/tools/patch_util.py index 1b65fe456..dde6ce69e 100644 --- a/tools/patch_util.py +++ b/tools/patch_util.py @@ -1,551 +1,551 @@ -""" 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 re -# 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): - src = open(srcname, "rb") - tgt = open(tgtname, "wb") - - debug("processing target file %s" % tgtname) - - tgt.writelines(patch_stream(src, hunks)) - - tgt.close() - src.close() - 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 +""" 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 re +# 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): + src = open(srcname, "rb") + tgt = open(tgtname, "wb") + + debug("processing target file %s" % tgtname) + + tgt.writelines(patch_stream(src, hunks)) + + tgt.close() + src.close() + return True + + + + + + +from optparse import OptionParser +from os.path import exists +import sys + +if __name__ == "__main__": + opt = OptionParser(usage="%prog [options] unipatch-file", version="python-patch %s" % __version__) + opt.add_option("-d", action="store_true", dest="debugmode", help="debug mode") + (options, args) = opt.parse_args() + + if not args: + opt.print_version() + print("") + opt.print_help() + sys.exit() + debugmode = options.debugmode + patchfile = args[0] + if not exists(patchfile) or not isfile(patchfile): + sys.exit("patch file does not exist - %s" % patchfile) + + + if debugmode: + logging.basicConfig(level=logging.DEBUG, format="%(levelname)8s %(message)s") + else: + logging.basicConfig(level=logging.INFO, format="%(message)s") + + + + patch = from_file(patchfile) + #pprint(patch) + patch.apply() + + # todo: document and test line ends handling logic - patch.py detects proper line-endings + # for inserted hunks and issues a warning if patched file has incosistent line ends diff --git a/tools/patcher.README.txt b/tools/patcher.README.txt index 397d9b9a0..2078770a4 100644 --- a/tools/patcher.README.txt +++ b/tools/patcher.README.txt @@ -1,32 +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. +Chromium Embedded Framework (CEF) Patch Application Tool -- patcher.py +------------------------------------------------------------------------------- + +Document Last Updated: July 23, 2009 + + +OVERVIEW +-------- + +The CEF patch application tool is used by the patch project to apply patches +to the Chromium and WebKit code bases. Currently only unified diff format is +supported. See the README.txt file in the patch directory for information on +how the patch project uses this tool. + +The 'patcher.bat' file can be used to run the patch application tool with +command-line arguments that match the default CEF directory structure and +output options. Run 'patcher.py -h' for a complete list of available command- +line arguments. + + +CREDITS +------- + +Thanks go to techtonik for developing the python-patch script. The +patch_util.py file is a slightly modified version of the original script which +can be found here: http://code.google.com/p/python-patch/ + + +WORK REMAINING +-------------- + +o Add support for the GIT patch format. diff --git a/tools/patcher.py b/tools/patcher.py index a11038f0d..2aa720e19 100644 --- a/tools/patcher.py +++ b/tools/patcher.py @@ -1,89 +1,89 @@ -# 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.path -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 name in patches.keys(): - file = patchdir+'patches/'+name+'.patch' - 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 = patches[name] - 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') +# 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.path +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 name in patches.keys(): + file = patchdir+'patches/'+name+'.patch' + 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 = patches[name] + 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/tools/translator.README.txt b/tools/translator.README.txt index c694b8d29..a38999135 100644 --- a/tools/translator.README.txt +++ b/tools/translator.README.txt @@ -1,248 +1,248 @@ -Chromium Embedded Framework (CEF) Translator Tool -- translator.py -------------------------------------------------------------------------------- - -Document Last Updated: June 20, 2009 - - -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) 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 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") - -Place-holder 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 place-holder implementations exist. Delete -the indicated portion of the generated code after adding the implementation by -hand. - - 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 - } - -The 'translator.bat' 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 attributes: - - capi_name=[string] (Optional) Force a specific output name for the - resulting C API 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. - - -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() - - -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' built-in 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. - - Boolean type translation (argument or return value): - C++: bool - C API: int - - String const by reference type translation (argument only) - C++: const std::wstring& value - C API: const wchar_t* value - - String non-const by reference type translation (argument only) - C++: std::wstring& value - C API (result must be freed by the user): - cef_string_t* value - - String non-const by reference type translation (return value only) - C++: std::wstring - C API (result must be freed by the user): - cef_string_t - - Smart pointer type translation (argument or return value) - C++: CefRefPtr - C API: cef_browser_t* - - Smart pointer by reference type translation (argument only) - C++: CefRefPtr& value - C API: cef_browser_t** value - - String vector by reference type translation (argument only) - C++: std::vector& value - C API (must be allocated and freed by the user): - cef_string_list_t value - - Non-string vector non-const by reference type translation (argument only) - C++: std::vector>& elements - C API (changes the function prototype): - cef_post_data_element_t* func(..., int elementIndex, ...) - - Non-string vector const by reference type translation (argument only) - C++: const std::vector>& arguments - C API (changes the function prototype): - ... func(..., size_t argumentCount, - const struct _cef_v8value_t** arguments, ...) - - String-to-string map by reference type translation (argument only) - C++: std::map& value - C API (must be allocated and freed by the user): - cef_string_map_t value - - -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 = {}; - - -WORK REMAINING --------------- - -o Generate place-holder implementations for C++ global functions. -o Automatically generate some function implementations based on an analysis of - the function prototype. +Chromium Embedded Framework (CEF) Translator Tool -- translator.py +------------------------------------------------------------------------------- + +Document Last Updated: June 20, 2009 + + +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) 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 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") + +Place-holder 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 place-holder implementations exist. Delete +the indicated portion of the generated code after adding the implementation by +hand. + + 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 + } + +The 'translator.bat' 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 attributes: + + capi_name=[string] (Optional) Force a specific output name for the + resulting C API 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. + + +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() + + +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' built-in 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. + + Boolean type translation (argument or return value): + C++: bool + C API: int + + String const by reference type translation (argument only) + C++: const std::wstring& value + C API: const wchar_t* value + + String non-const by reference type translation (argument only) + C++: std::wstring& value + C API (result must be freed by the user): + cef_string_t* value + + String non-const by reference type translation (return value only) + C++: std::wstring + C API (result must be freed by the user): + cef_string_t + + Smart pointer type translation (argument or return value) + C++: CefRefPtr + C API: cef_browser_t* + + Smart pointer by reference type translation (argument only) + C++: CefRefPtr& value + C API: cef_browser_t** value + + String vector by reference type translation (argument only) + C++: std::vector& value + C API (must be allocated and freed by the user): + cef_string_list_t value + + Non-string vector non-const by reference type translation (argument only) + C++: std::vector>& elements + C API (changes the function prototype): + cef_post_data_element_t* func(..., int elementIndex, ...) + + Non-string vector const by reference type translation (argument only) + C++: const std::vector>& arguments + C API (changes the function prototype): + ... func(..., size_t argumentCount, + const struct _cef_v8value_t** arguments, ...) + + String-to-string map by reference type translation (argument only) + C++: std::map& value + C API (must be allocated and freed by the user): + cef_string_map_t value + + +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 = {}; + + +WORK REMAINING +-------------- + +o Generate place-holder implementations for C++ global functions. +o Automatically generate some function implementations based on an analysis of + the function prototype. diff --git a/tools/translator.py b/tools/translator.py index bed9c90b5..b326bd736 100644 --- a/tools/translator.py +++ b/tools/translator.py @@ -1,130 +1,130 @@ -# 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 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', dest='cppheader', metavar='FILE', - help='source CEF C++ header file [required]') -parser.add_option('--capi-header', dest='capiheader', metavar='FILE', - help='output CEF C API header file') -parser.add_option('--cpptoc-dir', dest='cpptocdir', metavar='DIR', - help='input/output directory for CppToC translations') -parser.add_option('--ctocpp-dir', dest='ctocppdir', metavar='DIR', - help='input/output directory for CppToC translations') -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.cppheader is None: - parser.print_help(sys.stdout) - sys.exit() - -# make sure the header exists -if not file_exists(options.cppheader): - sys.stderr.write('File '+options.cppheader+' does not exist.') - sys.exit() - -# create the header object -if not options.quiet: - sys.stdout.write('Parsing '+options.cppheader+'...\n') -header = obj_header(options.cppheader) - -writect = 0 - -if not options.capiheader is None: - #output the C API header - if not options.quiet: - sys.stdout.write('Generating C API header...\n') - writect += write_capi_header(header, options.capiheader, - 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.cpptocdir is None: - #output CppToC 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 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 implementation...\n') - writect += write_cpptoc_impl(header, cls, options.cpptocdir, - not options.nobackup) - -if not options.ctocppdir is None: - #output CppToC 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 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 implementation...\n') - writect += write_ctocpp_impl(header, cls, options.ctocppdir, - not options.nobackup) - -if not options.quiet: - sys.stdout.write('Done - Wrote '+str(writect)+' files.\n') - - +# 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 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', dest='cppheader', metavar='FILE', + help='source CEF C++ header file [required]') +parser.add_option('--capi-header', dest='capiheader', metavar='FILE', + help='output CEF C API header file') +parser.add_option('--cpptoc-dir', dest='cpptocdir', metavar='DIR', + help='input/output directory for CppToC translations') +parser.add_option('--ctocpp-dir', dest='ctocppdir', metavar='DIR', + help='input/output directory for CppToC translations') +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.cppheader is None: + parser.print_help(sys.stdout) + sys.exit() + +# make sure the header exists +if not file_exists(options.cppheader): + sys.stderr.write('File '+options.cppheader+' does not exist.') + sys.exit() + +# create the header object +if not options.quiet: + sys.stdout.write('Parsing '+options.cppheader+'...\n') +header = obj_header(options.cppheader) + +writect = 0 + +if not options.capiheader is None: + #output the C API header + if not options.quiet: + sys.stdout.write('Generating C API header...\n') + writect += write_capi_header(header, options.capiheader, + 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.cpptocdir is None: + #output CppToC 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 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 implementation...\n') + writect += write_cpptoc_impl(header, cls, options.cpptocdir, + not options.nobackup) + +if not options.ctocppdir is None: + #output CppToC 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 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 implementation...\n') + writect += write_ctocpp_impl(header, cls, options.ctocppdir, + not options.nobackup) + +if not options.quiet: + sys.stdout.write('Done - Wrote '+str(writect)+' files.\n') + +