Compare commits

...

58 Commits
5112 ... 963

Author SHA1 Message Date
Marshall Greenblatt
bf0acb75b9 Move devtools resources to a separate devtools_resources.pak file (issue #714).
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@763 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-09-05 22:36:13 +00:00
Marshall Greenblatt
c0517941f3 Merge revision 756 changes:
- Rename PROXY_TYPE values to avoid naming conflict (issue #548).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@758 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-09-04 18:56:53 +00:00
Marshall Greenblatt
d366763847 Merge revision 745 changes:
- Improve the handling of invalidation/painting for off-screen rendering (issue #695).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@746 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-08-21 19:49:11 +00:00
Marshall Greenblatt
90472b1155 Merge revision 743 changes:
- Optimize the cefclient off-screen rendering example (issue #697).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@744 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-08-16 19:22:25 +00:00
Marshall Greenblatt
4292533524 Merge revision 741 changes:
- Add the ability to customize the animation frame rate (issue #697).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@742 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-08-15 15:16:39 +00:00
Marshall Greenblatt
34af061616 Merge revision 739 changes:
- Add the ability to customize the animation frame rate (issue #697).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@740 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-08-14 23:34:56 +00:00
Marshall Greenblatt
b04a3cad07 Merge revision 736 and revision 737 changes:
- Fix crashes/assertions when CefBrowserImpl is destroyed on a non-UI thread (issue #694).
- Improve the handling of invalidation/painting for off-screen rendering (issue #695).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@738 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-08-13 16:36:57 +00:00
Marshall Greenblatt
bcc07f0333 Merge revision 734 changes:
- Only release the request context proxy if it exists (issue #677).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@735 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-08-07 17:19:31 +00:00
Marshall Greenblatt
939b5a2008 Merge revision 644 and 725 changes:
- Add new CefV8StackTrace and CefV8StackFrame interfaces to support retrieval of the JavaScript stack trace for the currently active V8 context (issue #682).
- Add CefV8Context::Eval method for synchronous JavaScript execution that returns a value or exception (issue #444).
- Refactor V8 unit tests (issue #480).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@726 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-07-25 09:54:04 +00:00
Marshall Greenblatt
a0feffdba6 Merge revision 686 changes:
- Mac: Fix the need to press the delete key twice to delete a character after changing the IME language (issue #635).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@687 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-06-11 18:44:29 +00:00
Marshall Greenblatt
8c395163d2 Update the AUTHORS.txt file.
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@685 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-06-11 17:40:38 +00:00
Marshall Greenblatt
260b5e4246 Merge revision 676 changes:
- Mac: Add IME support (issue #557).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@677 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-06-07 18:44:21 +00:00
Marshall Greenblatt
da3df8bc18 Merge revision 663 changes:
- Mac: Delay destroying the browser window until pending drag operations have completed (issue #610).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@664 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-06-01 18:43:15 +00:00
Marshall Greenblatt
22bc38ed2c Merge revision 661 changes:
- Fix misspelling of the Referer HTTP header (issue #619).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@662 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-06-01 17:42:50 +00:00
Marshall Greenblatt
cf34d1f08a Merge revision 655 changes:
- Windows: Delay destroying the browser window until pending drag operations have completed (issue #610).
- Revert: Windows: Reset the window procedure in the WebWidgetHost destructor to avoid crashes if messages are delivered after the window is destroyed.

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@656 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-30 18:06:58 +00:00
Marshall Greenblatt
f2cb8680ba Merge revision 650 changes:
- Make sure BrowserRequestContextProxy is only used on the IO thread (issue #542).
- Windows: Reset the window procedure in the WebWidgetHost destructor to avoid crashes if messages are delivered after the window is destroyed.

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@651 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-25 20:46:44 +00:00
Marshall Greenblatt
253d8ad4e5 Merge revision 643 and revision 648 changes:
- Improve the cefclient transparency test by adding the ability to view individual pixel values (issue #584).
- Change cefclient off-screen rendering example to account for premultiplied alpha values (issue #584).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@649 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-25 14:33:01 +00:00
Marshall Greenblatt
d9b85ac1db Merge revision 568 changes:
- Execute the CefFocusHandler::OnSetFocus callback for calls to CefBrowser::SetFocus and mouse clicks on the view (issue #563).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@637 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-22 15:29:13 +00:00
Marshall Greenblatt
c9be1aa8e4 Merge revision 635 changes:
- Win: Fix mouse wheel scrolling in second monitor (issue #595).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@636 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-18 21:58:38 +00:00
Marshall Greenblatt
a63833acfd Merge revision 482 changes:
- Mac: Fix the "no autorelease pool in place" error by initializing an NSAutoreleasePool on every thread (issue #502).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@629 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-17 20:04:23 +00:00
Marshall Greenblatt
266f4e7a27 Add geolocation support (issue #365).
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@628 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-17 19:51:58 +00:00
Marshall Greenblatt
e193688d10 Merge revision 569 and 624 changes:
- Add off-screen rendering support for Mac OS-X (issue #540).
- Avoid calling OnSetFocus multiple times (issue #563).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@627 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-16 17:03:23 +00:00
Marshall Greenblatt
75a4730637 Merge revision 617 changes:
- Fix usage of ReadRawData return value in scheme handler implementation (issue #534).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@618 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-04 18:35:09 +00:00
Marshall Greenblatt
4d0a87ae47 Speculative fix for crashes related to CookieStoreProxy on Windows (issue #591).
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@615 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-05-03 20:59:30 +00:00
Marshall Greenblatt
4ee46079b6 Add patch to fix crash in WebCore::Document::webkitRequestAnimationFrame.
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@606 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-04-26 14:10:24 +00:00
Marshall Greenblatt
c5e4fef620 Merge revision 603 changes:
- Fix memory leak when returning zero-length strings from V8 (issue #581).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@605 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-04-25 20:01:47 +00:00
Marshall Greenblatt
1707bb75e5 Merge revision 600 changes:
- Add ability to directly retrieve plugin information (issue #575).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@601 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-04-20 21:15:58 +00:00
Marshall Greenblatt
dacb86d363 Merge revision 598 changes:
- Mac: Add flagsChanged: signal handler so that modifier keys are correctly passed to JS (issue #574).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@599 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-04-20 18:49:43 +00:00
Marshall Greenblatt
82390e4676 Merge revision 574 changes:
- Add CefCookieManager::SetSupportedSchemes method which supports cookie storage for non-http(s) schemes (issue #567).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@576 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-04-03 19:26:28 +00:00
Marshall Greenblatt
0cf1388a2c Merge revision 561 changes:
- Fix problem with CefBrowser::GetMainFrame() clearing the frame URL value (issue #556).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@563 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-03-30 17:20:26 +00:00
Marshall Greenblatt
407b10012d Merge revision 556 changes:
- Fix race condition in CefCookieManagerImpl constructor (issue #542).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@557 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-03-29 16:52:40 +00:00
Marshall Greenblatt
0d485419a7 Fix compile errors.
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@545 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-03-22 23:52:16 +00:00
Marshall Greenblatt
bba09e1319 Merge revision 542 changes:
- Add CefCookieManager interface and CefRequestHandler::GetCookieManager for custom cookie handling (issue #542).
- Support getting and setting cookies with custom scheme handlers (issue #555).
- Support calling CefFrame::GetIdentifier and CefFrame::GetURL on any thread (issue #556).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@544 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-03-22 22:10:49 +00:00
Marshall Greenblatt
1d54b2de7d Revert revision 536 changes: Add CefCookieManager interface and CefRequestHandler::GetCookieManager for custom cookie handling (issue #542).
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@539 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-03-21 16:12:31 +00:00
Marshall Greenblatt
6a23cfd5c6 Merge revision 534 changes:
- Add CefCookieManager interface and CefRequestHandler::GetCookieManager for custom cookie handling (issue #542).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@536 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-03-15 22:40:45 +00:00
Marshall Greenblatt
542e115b9b Merge revision 526 changes:
- Invalidate the entire scroll rect when using off-screen rendering mode (issue #469).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@528 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-03-13 15:09:34 +00:00
Marshall Greenblatt
9ba4603109 Merge revision 457 changes:
- Add the ability to restrict V8 extension loading by frame using a new CefPermissionHandler::OnBeforeScriptExtensionLoad() callback (issue #471).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@519 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-24 17:33:50 +00:00
Marshall Greenblatt
4560ab916b Merge revision 457 changes:
- Add the ability to restrict V8 extension loading by frame using a new CefPermissionHandler::OnBeforeScriptExtensionLoad() callback (issue #471).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@518 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-24 15:37:39 +00:00
Marshall Greenblatt
a15f7a968d Allow inspection of drag&drop clipboard contents for non-local schemes (issue #533).
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@517 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-23 23:14:15 +00:00
Marshall Greenblatt
2fd388c036 Merge revision 514 changes:
- Windows: Fix crash in cefclient when entering long URLs via the address bar (issue #532).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@516 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-21 22:51:37 +00:00
Marshall Greenblatt
fdcea1583c Merge revision 502 changes:
- Setting the OnBeforeResourceLoad redirectUrl value should behave the same as using request->SetURL() (issue #529).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@503 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-16 20:13:44 +00:00
Marshall Greenblatt
e2c233100d Merge revision 497 changes:
- Fix memory leak in CefV8ValueImpl::ExecuteFunctionWithContext (issue #526).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@498 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-15 16:21:53 +00:00
Marshall Greenblatt
b5ef1d0e61 Merge revision 470 changes:
- Don't add the "--expose-gc" V8 flag by default for all CEF users (issue #483).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@494 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-14 18:08:00 +00:00
Marshall Greenblatt
24788d33b3 Merge revision 491 changes:
- Fix memory leak due to CToCpp argument lists not being deleted (issue #526).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@493 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-14 17:54:38 +00:00
Marshall Greenblatt
7947abaaa0 Revert revision 476: Add patch to fix GDI object leak in FontCacheChromiumWin.cpp createFontIndirectAndGetWinName (issue #499).
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@478 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-07 21:03:26 +00:00
Marshall Greenblatt
d1ec7b7e9b Merge revision 476 changes:
- Add patch to fix GDI object leak in FontCacheChromiumWin.cpp createFontIndirectAndGetWinName (issue #499).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@477 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-02-07 20:47:53 +00:00
Marshall Greenblatt
2240f2cf36 Merge revision 472 changes:
- Fix bug in CefZipArchive::Clear() (issue #486).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@473 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-01-23 15:52:05 +00:00
Marshall Greenblatt
c028cc796e Mac: Add work-around for windowless flash plugins do not get keyboard input in text fields (issue #477).
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@465 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-01-13 21:55:24 +00:00
Marshall Greenblatt
589ec0a4e3 Merge revision 461 changes:
- Add #ifndef guards in cef_build.h to avoid conflicts with other projects using Chromium code.

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@462 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-01-05 20:16:56 +00:00
Marshall Greenblatt
cf2d8bd082 Linux: Fix compile error.
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@456 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-01-03 19:38:36 +00:00
Marshall Greenblatt
715a056e70 Merge revision 448 and 453 changes:
- Add support for running unit tests without multi-threaded message loop mode (issue #338).
- Mac: Fix unit test expectations.
- Mac: cef_time_t.day_of_week is not supported.
- Mac: Add support for building the 'Run cef_unittests' target from the command line.


git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@455 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-01-03 19:07:42 +00:00
Marshall Greenblatt
58c8cfcd0a Merge revision 449-452 changes:
- Linux: Fix window destruction crash.
- Linux: Fix cefclient shutdown crash.
- Remove WebURLRequestTest.CANCEL test with WUR_STATE_LOADING due to flakiness.
- Linux: Initialize the 'proxy_type' variable to make the compiler happy.

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@454 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2012-01-03 18:07:21 +00:00
Marshall Greenblatt
912baa9f49 Merge revision 446 changes:
- Create separate implementation file for TestHandler methods and globals.

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@447 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2011-12-29 20:36:53 +00:00
Marshall Greenblatt
11edadd02c Merge revision 434 and 436 changes:
- Make the |url| parameter to OnBeforePopup() optional.
- Include CEF and Chromium version information in binary distributions (issue #325).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@437 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2011-12-21 19:25:38 +00:00
Marshall Greenblatt
5bd72a4688 Merge revision 432 change:
- Add support to check_revision.py for building release branches (issue #325).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@433 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2011-12-20 16:36:41 +00:00
Marshall Greenblatt
9e3e86c10a Rebase webcore_v8_custom.patch file.
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@431 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2011-12-20 16:18:21 +00:00
Marshall Greenblatt
a450e52970 Merge revision 428 and 429 changes:
- Add support to automate.py for building release branches (issue #325).
- Windows: Update the libcef.dll version number to include the Chrome branch version (issue #325).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@430 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2011-12-19 23:26:56 +00:00
Marshall Greenblatt
22deeebe2e Create 963 release branch.
git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@427 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2011-12-19 22:36:08 +00:00
359 changed files with 15594 additions and 5537 deletions

View File

@@ -2,4 +2,25 @@
# Names should be added to this file like so:
# Name or Organization <email address>
Marshall Greenblatt <magreenblatt@gmail.com>
Marshall Greenblatt <magreenblatt@gmail.com>
Jamie Kirkpatrick <jkp@spotify.com>
Johan Lindström <johanl@spotify.com>
Igor Pavlov <igor.arabesc.pavlov@gmail.com>
Yanko Yankov <yyankov@gmail.com>
Emerick Rogul <emerick@gmail.com>
Valve Corporation <mac@valvesoftware.com>
Anthony Taranto <anthony.taranto@gmail.com>
Joe Andrieu <joe@joeandrieu.com>
Keith Poole <platima@gmail.com>
Aviv Rind <avivrind@gmail.com>
Michael Kaminski <mikeyk730@gmail.com>
ADInstruments Ltd. <dev.team@adinstruments.com>
Gus Verdun <gusverdun@gmail.com>
Joinerysoft Ltd. <cpinfold@joinerysoft.com>
Johan Björk <phb@spotify.com>
Dmitry Azaraev <dmitry.azaraev@gmail.com>
David Xue <ddxue27@gmail.com>
Russell (Rusty) Richards <fe3o4y@gmail.com>
Brian Power <powerbf.it@gmail.com>
Corey Lucier <clucier@adobe.com>
Mihai Tica <mitica@adobe.com>

View File

@@ -16,6 +16,5 @@
# http://dev.chromium.org/developers/how-tos/get-the-code
{
'chromium_url': 'http://src.chromium.org/svn/trunk/src',
'chromium_revision': '113143',
'release_url': 'http://src.chromium.org/svn/releases/17.0.963.15',
}

179
cef.gyp
View File

@@ -46,6 +46,7 @@
],
'mac_bundle_resources': [
'<@(cefclient_bundle_resources_mac)',
'<(grit_out_dir)/devtools_resources.pak',
],
'mac_bundle_resources!': [
# TODO(mark): Come up with a fancier way to do this (mac_info_plist?)
@@ -84,24 +85,6 @@
'<@(locales)',
],
},
{
# On Windows chrome.pak will contain only the inspector resources.
# Other resources are built into libcef.dll.
'action_name': 'repack_resources',
'variables': {
'pak_inputs': [
'<(grit_out_dir)/devtools_resources.pak',
],
},
'inputs': [
'<(repack_path)',
'<@(pak_inputs)',
],
'outputs': [
'<(INTERMEDIATE_DIR)/repack/chrome.pak',
],
'action': ['python', '<(repack_path)', '<@(_outputs)', '<@(pak_inputs)'],
},
],
'copies': [
{
@@ -113,7 +96,7 @@
{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(INTERMEDIATE_DIR)/repack/chrome.pak'
'<(grit_out_dir)/devtools_resources.pak'
],
},
],
@@ -172,7 +155,6 @@
'process_outputs_as_mac_bundle_resources': 1,
'variables': {
'pak_inputs': [
'<(grit_out_dir)/devtools_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/net/net_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/ui/gfx/gfx_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_chromium_resources.pak',
@@ -209,6 +191,7 @@
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/AppKit.framework',
'$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
],
},
'sources': [
@@ -251,7 +234,6 @@
'action_name': 'repack_resources',
'variables': {
'pak_inputs': [
'<(grit_out_dir)/devtools_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/net/net_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/ui/gfx/gfx_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_chromium_resources.pak',
@@ -278,7 +260,8 @@
{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(INTERMEDIATE_DIR)/repack/chrome.pak'
'<(INTERMEDIATE_DIR)/repack/chrome.pak',
'<(grit_out_dir)/devtools_resources.pak',
],
},
{
@@ -294,6 +277,7 @@
{
'target_name': 'cef_unittests',
'type': 'executable',
'mac_bundle': 1,
'msvs_guid': '8500027C-B11A-11DE-A16E-B80256D89593',
'dependencies': [
'../base/base.gyp:base',
@@ -306,6 +290,8 @@
'libcef_dll_wrapper',
],
'sources': [
'tests/cefclient/cefclient_switches.cpp',
'tests/cefclient/cefclient_switches.h',
'tests/unittests/command_line_unittest.cc',
'tests/unittests/content_filter_unittest.cc',
'tests/unittests/cookie_unittest.cc',
@@ -317,6 +303,7 @@
'tests/unittests/stream_unittest.cc',
'tests/unittests/string_unittest.cc',
'tests/unittests/storage_unittest.cc',
'tests/unittests/test_handler.cc',
'tests/unittests/test_handler.h',
'tests/unittests/test_suite.cc',
'tests/unittests/test_suite.h',
@@ -326,10 +313,100 @@
'tests/unittests/xml_reader_unittest.cc',
'tests/unittests/zip_reader_unittest.cc',
],
'mac_bundle_resources': [
'tests/unittests/mac/unittests.icns',
'tests/unittests/mac/English.lproj/InfoPlist.strings',
'tests/unittests/mac/English.lproj/MainMenu.xib',
'tests/unittests/mac/Info.plist',
],
'mac_bundle_resources!': [
# TODO(mark): Come up with a fancier way to do this (mac_info_plist?)
# that automatically sets the correct INFOPLIST_FILE setting and adds
# the file to a source group.
'tests/unittests/mac/Info.plist',
],
'xcode_settings': {
'INFOPLIST_FILE': 'tests/unittests/mac/Info.plist',
},
'include_dirs': [
'.',
'..',
],
'conditions': [
[ 'OS=="mac"', {
'product_name': 'cef_unittests',
'variables': {
'repack_path': '../tools/grit/grit/format/repack.py',
},
'run_as': {
'action': ['${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/MacOS/${PRODUCT_NAME}'],
},
'actions': [
{
'action_name': 'repack_locales',
'process_outputs_as_mac_bundle_resources': 1,
'inputs': [
'tools/repack_locales.py',
# NOTE: Ideally the common command args would be shared
# amongst inputs/outputs/action, but the args include shell
# variables which need to be passed intact, and command
# expansion wants to expand the shell variables. Adding the
# explicit quoting here was the only way it seemed to work.
'>!@(<(repack_locales_cmd) -i -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))',
],
'outputs': [
'>!@(<(repack_locales_cmd) -o -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))',
],
'action': [
'<@(repack_locales_cmd)',
'-g', '<(grit_out_dir)',
'-s', '<(SHARED_INTERMEDIATE_DIR)',
'-x', '<(INTERMEDIATE_DIR)',
'<@(locales)',
],
},
{
'action_name': 'repack_resources',
'process_outputs_as_mac_bundle_resources': 1,
'variables': {
'pak_inputs': [
'<(grit_out_dir)/devtools_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/net/net_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/ui/gfx/gfx_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_chromium_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_resources.pak',
],
},
'inputs': [
'<(repack_path)',
'<@(pak_inputs)',
],
'outputs': [
'<(INTERMEDIATE_DIR)/repack/chrome.pak',
],
'action': ['python', '<(repack_path)', '<@(_outputs)', '<@(pak_inputs)'],
},
],
'copies': [
{
# Add library dependencies to the bundle.
'destination': '<(PRODUCT_DIR)/cef_unittests.app/Contents/MacOS/',
'files': [
'<(PRODUCT_DIR)/libcef.dylib',
'<(PRODUCT_DIR)/ffmpegsumo.so',
],
},
],
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/AppKit.framework',
],
},
'sources': [
'tests/unittests/run_all_unittests_mac.mm',
],
}],
],
},
{
'target_name': 'libcef',
@@ -393,6 +470,8 @@
'libcef_dll/cpptoc/browser_cpptoc.h',
'libcef_dll/cpptoc/command_line_cpptoc.cc',
'libcef_dll/cpptoc/command_line_cpptoc.h',
'libcef_dll/cpptoc/cookie_manager_cpptoc.cc',
'libcef_dll/cpptoc/cookie_manager_cpptoc.h',
'libcef_dll/cpptoc/cpptoc.h',
'libcef_dll/cpptoc/domdocument_cpptoc.cc',
'libcef_dll/cpptoc/domdocument_cpptoc.h',
@@ -404,6 +483,8 @@
'libcef_dll/cpptoc/drag_data_cpptoc.h',
'libcef_dll/cpptoc/frame_cpptoc.cc',
'libcef_dll/cpptoc/frame_cpptoc.h',
'libcef_dll/cpptoc/geolocation_callback_cpptoc.cc',
'libcef_dll/cpptoc/geolocation_callback_cpptoc.h',
'libcef_dll/cpptoc/post_data_cpptoc.cc',
'libcef_dll/cpptoc/post_data_cpptoc.h',
'libcef_dll/cpptoc/post_data_element_cpptoc.cc',
@@ -422,8 +503,14 @@
'libcef_dll/cpptoc/v8context_cpptoc.h',
'libcef_dll/cpptoc/v8exception_cpptoc.cc',
'libcef_dll/cpptoc/v8exception_cpptoc.h',
'libcef_dll/cpptoc/v8stack_frame_cpptoc.cc',
'libcef_dll/cpptoc/v8stack_frame_cpptoc.h',
'libcef_dll/cpptoc/v8stack_trace_cpptoc.cc',
'libcef_dll/cpptoc/v8stack_trace_cpptoc.h',
'libcef_dll/cpptoc/v8value_cpptoc.cc',
'libcef_dll/cpptoc/v8value_cpptoc.h',
'libcef_dll/cpptoc/web_plugin_info_cpptoc.cc',
'libcef_dll/cpptoc/web_plugin_info_cpptoc.h',
'libcef_dll/cpptoc/web_urlrequest_cpptoc.cc',
'libcef_dll/cpptoc/web_urlrequest_cpptoc.h',
'libcef_dll/cpptoc/xml_reader_cpptoc.cc',
@@ -453,6 +540,8 @@
'libcef_dll/ctocpp/find_handler_ctocpp.h',
'libcef_dll/ctocpp/focus_handler_ctocpp.cc',
'libcef_dll/ctocpp/focus_handler_ctocpp.h',
'libcef_dll/ctocpp/geolocation_handler_ctocpp.cc',
'libcef_dll/ctocpp/geolocation_handler_ctocpp.h',
'libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc',
'libcef_dll/ctocpp/jsdialog_handler_ctocpp.h',
'libcef_dll/ctocpp/keyboard_handler_ctocpp.cc',
@@ -463,6 +552,8 @@
'libcef_dll/ctocpp/load_handler_ctocpp.h',
'libcef_dll/ctocpp/menu_handler_ctocpp.cc',
'libcef_dll/ctocpp/menu_handler_ctocpp.h',
'libcef_dll/ctocpp/permission_handler_ctocpp.cc',
'libcef_dll/ctocpp/permission_handler_ctocpp.h',
'libcef_dll/ctocpp/print_handler_ctocpp.cc',
'libcef_dll/ctocpp/print_handler_ctocpp.h',
'libcef_dll/ctocpp/proxy_handler_ctocpp.cc',
@@ -522,6 +613,7 @@
'link_settings': {
'libraries': [
'-lcomctl32.lib',
'-llocationapi.lib',
],
},
'msvs_settings': {
@@ -687,12 +779,15 @@
'libcef/browser_persistent_cookie_store.h',
'libcef/browser_request_context.cc',
'libcef/browser_request_context.h',
'libcef/browser_request_context_proxy.cc',
'libcef/browser_request_context_proxy.h',
'libcef/browser_resource_loader_bridge.cc',
'libcef/browser_resource_loader_bridge.h',
'libcef/browser_settings.cc',
'libcef/browser_settings.h',
'libcef/browser_socket_stream_bridge.cc',
'libcef/browser_socket_stream_bridge.h',
'libcef/browser_thread_stub.cc',
'libcef/browser_webcookiejar_impl.cc',
'libcef/browser_webcookiejar_impl.h',
'libcef/browser_webblobregistry_impl.cc',
@@ -728,6 +823,10 @@
'libcef/cef_time.cc',
'libcef/cef_time_util.h',
'libcef/command_line_impl.cc',
'libcef/cookie_manager_impl.cc',
'libcef/cookie_manager_impl.h',
'libcef/cookie_store_proxy.cc',
'libcef/cookie_store_proxy.h',
'libcef/drag_data_impl.cc',
'libcef/drag_data_impl.h',
'libcef/drag_download_file.cc',
@@ -750,6 +849,8 @@
'libcef/download_util.cc',
'libcef/download_util.h',
'libcef/external_protocol_handler.h',
'libcef/geolocation_client.cc',
'libcef/geolocation_client.h',
'libcef/http_header_utils.cc',
'libcef/http_header_utils.h',
'libcef/origin_whitelist_impl.cc',
@@ -765,6 +866,7 @@
'libcef/tracker.h',
'libcef/v8_impl.cc',
'libcef/v8_impl.h',
'libcef/web_plugin_impl.cc',
'libcef/web_urlrequest_impl.cc',
'libcef/web_urlrequest_impl.h',
'libcef/webview_host.cc',
@@ -777,6 +879,19 @@
'libcef/zip_reader_impl.h',
# DevTools resource IDs generated by grit
'<(grit_out_dir)/grit/devtools_resources_map.cc',
# Geolocation implementation
'../content/browser/cancelable_request.cc',
'../content/browser/geolocation/access_token_store.cc',
'../content/browser/geolocation/device_data_provider.cc',
'../content/browser/geolocation/empty_device_data_provider.cc',
'../content/browser/geolocation/geolocation_provider.cc',
'../content/browser/geolocation/location_arbitrator.cc',
'../content/browser/geolocation/location_provider.cc',
'../content/browser/geolocation/network_location_provider.cc',
'../content/browser/geolocation/network_location_request.cc',
'../content/browser/geolocation/wifi_data_provider_common.cc',
'../content/common/geoposition.cc',
'../content/common/net/url_fetcher_impl.cc',
],
'conditions': [
['OS=="win"', {
@@ -807,6 +922,11 @@
'libcef/web_drop_target_win.h',
'libcef/webview_host_win.cc',
'libcef/webwidget_host_win.cc',
# Geolocation implementation
'../content/browser/geolocation/wifi_data_provider_common_win.cc',
'../content/browser/geolocation/wifi_data_provider_win.cc',
'../content/browser/geolocation/win7_location_api_win.cc',
'../content/browser/geolocation/win7_location_provider_win.cc',
],
}],
[ 'OS=="mac"', {
@@ -829,16 +949,25 @@
'libcef/web_drag_utils_mac.mm',
'libcef/web_drop_target_mac.h',
'libcef/web_drop_target_mac.mm',
# Build necessary Mozilla sources
# Necessary Mozilla sources
'../third_party/mozilla/NSPasteboard+Utils.h',
'../third_party/mozilla/NSPasteboard+Utils.mm',
'../third_party/mozilla/NSString+Utils.h',
'../third_party/mozilla/NSString+Utils.mm',
'../third_party/mozilla/NSURL+Utils.h',
'../third_party/mozilla/NSURL+Utils.m',
# Geolocation implementation
'../content/browser/geolocation/core_location_data_provider_mac.mm',
'../content/browser/geolocation/core_location_provider_mac.mm',
'../content/browser/geolocation/wifi_data_provider_corewlan_mac.mm',
'../content/browser/geolocation/wifi_data_provider_mac.cc',
],
}],
[ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', {
'dependencies': [
'../build/linux/system.gyp:dbus',
'../dbus/dbus.gyp:dbus',
],
'sources': [
'<@(includes_linux)',
'libcef/browser_impl_gtk.cc',
@@ -848,6 +977,10 @@
'libcef/external_protocol_handler_gtk.cc',
'libcef/webview_host_gtk.cc',
'libcef/webwidget_host_gtk.cc',
# Geolocation implementation
'../content/browser/geolocation/gps_location_provider_linux.cc',
'../content/browser/geolocation/libgps_wrapper_linux.cc',
'../content/browser/geolocation/wifi_data_provider_linux.cc',
],
}],
],

View File

@@ -73,6 +73,8 @@
'tests/cefclient/client_handler_win.cpp',
'tests/cefclient/clientplugin.cpp',
'tests/cefclient/clientplugin.h',
'tests/cefclient/osrenderer.cpp',
'tests/cefclient/osrenderer.h',
'tests/cefclient/osrplugin.cpp',
'tests/cefclient/osrplugin.h',
'tests/cefclient/osrplugin_test.cpp',
@@ -97,6 +99,10 @@
'cefclient_sources_mac': [
'tests/cefclient/cefclient_mac.mm',
'tests/cefclient/client_handler_mac.mm',
'tests/cefclient/osrenderer.cpp',
'tests/cefclient/osrenderer.h',
'tests/cefclient/osrtest_mac.h',
'tests/cefclient/osrtest_mac.mm',
'tests/cefclient/resource_util_mac.mm',
],
'cefclient_bundle_resources_mac': [
@@ -109,6 +115,9 @@
'tests/cefclient/res/extensionperf.html',
'tests/cefclient/res/localstorage.html',
'tests/cefclient/res/logo.png',
'tests/cefclient/res/logoball.png',
'tests/cefclient/res/osrtest.html',
'tests/cefclient/res/transparency.html',
'tests/cefclient/res/xmlhttprequest.html',
],
'cefclient_sources_linux': [
@@ -149,6 +158,8 @@
'libcef_dll/cpptoc/find_handler_cpptoc.h',
'libcef_dll/cpptoc/focus_handler_cpptoc.cc',
'libcef_dll/cpptoc/focus_handler_cpptoc.h',
'libcef_dll/cpptoc/geolocation_handler_cpptoc.cc',
'libcef_dll/cpptoc/geolocation_handler_cpptoc.h',
'libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc',
'libcef_dll/cpptoc/jsdialog_handler_cpptoc.h',
'libcef_dll/cpptoc/keyboard_handler_cpptoc.cc',
@@ -159,6 +170,8 @@
'libcef_dll/cpptoc/load_handler_cpptoc.h',
'libcef_dll/cpptoc/menu_handler_cpptoc.cc',
'libcef_dll/cpptoc/menu_handler_cpptoc.h',
'libcef_dll/cpptoc/permission_handler_cpptoc.cc',
'libcef_dll/cpptoc/permission_handler_cpptoc.h',
'libcef_dll/cpptoc/print_handler_cpptoc.cc',
'libcef_dll/cpptoc/print_handler_cpptoc.h',
'libcef_dll/cpptoc/proxy_handler_cpptoc.cc',
@@ -192,6 +205,8 @@
'libcef_dll/ctocpp/browser_ctocpp.h',
'libcef_dll/ctocpp/command_line_ctocpp.cc',
'libcef_dll/ctocpp/command_line_ctocpp.h',
'libcef_dll/ctocpp/cookie_manager_ctocpp.cc',
'libcef_dll/ctocpp/cookie_manager_ctocpp.h',
'libcef_dll/ctocpp/ctocpp.h',
'libcef_dll/ctocpp/domdocument_ctocpp.cc',
'libcef_dll/ctocpp/domdocument_ctocpp.h',
@@ -203,6 +218,8 @@
'libcef_dll/ctocpp/drag_data_ctocpp.h',
'libcef_dll/ctocpp/frame_ctocpp.cc',
'libcef_dll/ctocpp/frame_ctocpp.h',
'libcef_dll/ctocpp/geolocation_callback_ctocpp.cc',
'libcef_dll/ctocpp/geolocation_callback_ctocpp.h',
'libcef_dll/ctocpp/post_data_ctocpp.cc',
'libcef_dll/ctocpp/post_data_ctocpp.h',
'libcef_dll/ctocpp/post_data_element_ctocpp.cc',
@@ -221,8 +238,14 @@
'libcef_dll/ctocpp/v8context_ctocpp.h',
'libcef_dll/ctocpp/v8exception_ctocpp.cc',
'libcef_dll/ctocpp/v8exception_ctocpp.h',
'libcef_dll/ctocpp/v8stack_frame_ctocpp.cc',
'libcef_dll/ctocpp/v8stack_frame_ctocpp.h',
'libcef_dll/ctocpp/v8stack_trace_ctocpp.cc',
'libcef_dll/ctocpp/v8stack_trace_ctocpp.h',
'libcef_dll/ctocpp/v8value_ctocpp.cc',
'libcef_dll/ctocpp/v8value_ctocpp.h',
'libcef_dll/ctocpp/web_plugin_info_ctocpp.cc',
'libcef_dll/ctocpp/web_plugin_info_ctocpp.h',
'libcef_dll/ctocpp/web_urlrequest_ctocpp.cc',
'libcef_dll/ctocpp/web_urlrequest_ctocpp.h',
'libcef_dll/ctocpp/xml_reader_ctocpp.cc',

View File

@@ -79,8 +79,11 @@ class CefStreamReader;
class CefStreamWriter;
class CefTask;
class CefV8Context;
class CefV8Exception;
class CefV8Handler;
class CefV8StackFrame;
class CefV8Value;
class CefWebPluginInfo;
class CefWebURLRequest;
class CefWebURLRequestClient;
@@ -371,54 +374,6 @@ bool CefParseURL(const CefString& url,
bool CefCreateURL(const CefURLParts& parts,
CefString& url);
///
// Visit all cookies. The returned cookies are ordered by longest path, then by
// earliest creation date. Returns false if cookies cannot be accessed.
///
/*--cef()--*/
bool CefVisitAllCookies(CefRefPtr<CefCookieVisitor> visitor);
///
// Visit a subset of cookies. The results are filtered by the given url scheme,
// host, domain and path. If |includeHttpOnly| is true HTTP-only cookies will
// also be included in the results. The returned cookies are ordered by longest
// path, then by earliest creation date. Returns false if cookies cannot be
// accessed.
///
/*--cef()--*/
bool CefVisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor);
///
// Sets a cookie given a valid URL and explicit user-provided cookie attributes.
// This function expects each attribute to be well-formed. It will check for
// disallowed characters (e.g. the ';' character is disallowed within the cookie
// value attribute) and will return false without setting the cookie if such
// characters are found. This method must be called on the IO thread.
///
/*--cef()--*/
bool CefSetCookie(const CefString& url, const CefCookie& cookie);
///
// Delete all cookies that match the specified parameters. If both |url| and
// |cookie_name| are specified all host and domain cookies matching both values
// will be deleted. If only |url| is specified all host cookies (but not domain
// cookies) irrespective of path will be deleted. If |url| is empty all cookies
// for all hosts and domains will be deleted. Returns false if a non-empty
// invalid URL is specified or if cookies cannot be accessed. This method must
// be called on the IO thread.
///
/*--cef(optional_param=url,optional_param=cookie_name)--*/
bool CefDeleteCookies(const CefString& url, const CefString& cookie_name);
///
// Sets the directory path that will be used for storing cookie data. If |path|
// is empty data will be stored in memory only. By default the cookie path is
// the same as the cache path. Returns false if cookies cannot be accessed.
///
/*--cef(optional_param=path)--*/
bool CefSetCookiePath(const CefString& path);
typedef cef_storage_type_t CefStorageType;
@@ -464,6 +419,27 @@ bool CefDeleteStorage(CefStorageType type, const CefString& origin,
/*--cef(optional_param=path)--*/
bool CefSetStoragePath(CefStorageType type, const CefString& path);
///
// Returns the number of installed web plugins. This method must be called on
// the UI thread.
///
/*--cef()--*/
size_t CefGetWebPluginCount();
///
// Returns information for web plugin at the specified zero-based index. This
// method must be called on the UI thread.
///
/*--cef()--*/
CefRefPtr<CefWebPluginInfo> CefGetWebPluginInfo(int index);
///
// Returns information for web plugin with the specified name. This method must
// be called on the UI thread.
///
/*--cef(capi_name=cef_get_web_plugin_info_byname)--*/
CefRefPtr<CefWebPluginInfo> CefGetWebPluginInfo(const CefString& name);
///
// Interface defining the reference count implementation methods. All framework
@@ -583,6 +559,88 @@ public:
};
///
// Class used for managing cookies. The methods of this class may be called on
// any thread unless otherwise indicated.
///
/*--cef(source=library)--*/
class CefCookieManager : public virtual CefBase
{
public:
///
// Returns the global cookie manager. By default data will be stored at
// CefSettings.cache_path if specified or in memory otherwise.
///
/*--cef()--*/
static CefRefPtr<CefCookieManager> GetGlobalManager();
///
// Creates a new cookie manager. If |path| is empty data will be stored in
// memory only. Returns NULL if creation fails.
///
/*--cef(optional_param=path)--*/
static CefRefPtr<CefCookieManager> CreateManager(const CefString& path);
///
// Set the schemes supported by this manager. By default only "http" and
// "https" schemes are supported. Must be called before any cookies are
// accessed.
///
/*--cef()--*/
virtual void SetSupportedSchemes(const std::vector<CefString>& schemes) =0;
///
// Visit all cookies. The returned cookies are ordered by longest path, then
// by earliest creation date. Returns false if cookies cannot be accessed.
///
/*--cef()--*/
virtual bool VisitAllCookies(CefRefPtr<CefCookieVisitor> visitor) =0;
///
// Visit a subset of cookies. The results are filtered by the given url
// scheme, host, domain and path. If |includeHttpOnly| is true HTTP-only
// cookies will also be included in the results. The returned cookies are
// ordered by longest path, then by earliest creation date. Returns false if
// cookies cannot be accessed.
///
/*--cef()--*/
virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor) =0;
///
// Sets a cookie given a valid URL and explicit user-provided cookie
// attributes. This function expects each attribute to be well-formed. It will
// check for disallowed characters (e.g. the ';' character is disallowed
// within the cookie value attribute) and will return false without setting
// the cookie if such characters are found. This method must be called on the
// IO thread.
///
/*--cef()--*/
virtual bool SetCookie(const CefString& url, const CefCookie& cookie) =0;
///
// Delete all cookies that match the specified parameters. If both |url| and
// values |cookie_name| are specified all host and domain cookies matching
// both will be deleted. If only |url| is specified all host cookies (but not
// domain cookies) irrespective of path will be deleted. If |url| is empty all
// cookies for all hosts and domains will be deleted. Returns false if a non-
// empty invalid URL is specified or if cookies cannot be accessed. This
// method must be called on the IO thread.
///
/*--cef(optional_param=url,optional_param=cookie_name)--*/
virtual bool DeleteCookies(const CefString& url,
const CefString& cookie_name) =0;
///
// Sets the directory path that will be used for storing cookie data. If
// |path| is empty data will be stored in memory only. Returns false if
// cookies cannot be accessed.
///
/*--cef(optional_param=path)--*/
virtual bool SetStoragePath(const CefString& path) =0;
};
///
// Interface to implement for visiting cookie values. The methods of this class
// will always be called on the IO thread.
@@ -877,8 +935,8 @@ public:
// Send a key event to the browser.
///
/*--cef()--*/
virtual void SendKeyEvent(KeyType type, int key, int modifiers, bool sysChar,
bool imeChar) =0;
virtual void SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo,
int modifiers) =0;
///
// Send a mouse click event to the browser. The |x| and |y| coordinates are
@@ -900,7 +958,7 @@ public:
// relative to the upper-left corner of the view.
///
/*--cef()--*/
virtual void SendMouseWheelEvent(int x, int y, int delta) =0;
virtual void SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) =0;
///
// Send a focus event to the browser.
@@ -1050,11 +1108,10 @@ public:
virtual CefString GetName() =0;
///
// Returns the globally unique identifier for this frame. This method should
// only be called on the UI thread.
// Returns the globally unique identifier for this frame.
///
/*--cef()--*/
virtual long long GetIdentifier() =0;
virtual int64 GetIdentifier() =0;
///
// Returns the parent of this frame or NULL if this is the main (top-level)
@@ -1064,8 +1121,7 @@ public:
virtual CefRefPtr<CefFrame> GetParent() =0;
///
// Returns the URL currently loaded in this frame. This method should only be
// called on the UI thread.
// Returns the URL currently loaded in this frame.
///
/*--cef()--*/
virtual CefString GetURL() =0;
@@ -1142,7 +1198,7 @@ public:
// modify the object that |client| points to. To change the settings for the
// new window modify the |settings| structure.
///
/*--cef()--*/
/*--cef(optional_param=url)--*/
virtual bool OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
@@ -1343,6 +1399,17 @@ public:
const CefString& scheme,
CefString& username,
CefString& password) { return false; }
///
// Called on the IO thread to retrieve the cookie manager. |main_url| is the
// URL of the top-level frame. Cookies managers can be unique per browser or
// shared across multiple browsers. The global cookie manager will be used if
// this method returns NULL.
///
/*--cef()--*/
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser,
const CefString& main_url) { return NULL; }
};
@@ -1536,6 +1603,28 @@ public:
};
///
// Implement this interface to handle events related to browser permissions.
// The methods of this class will be called on the UI thread.
///
/*--cef(source=client)--*/
class CefPermissionHandler : public virtual CefBase
{
public:
///
// Called on the UI thread before a script extension is loaded.
// Return false to let the extension load normally.
///
/*--cef()--*/
virtual bool OnBeforeScriptExtensionLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& extensionName)
{
return false;
}
};
///
// Implement this interface to handle events related to printing. The methods of
// this class will be called on the UI thread.
@@ -1742,7 +1831,9 @@ public:
// element is the view or the popup widget. |buffer| contains the pixel data
// for the whole image. |dirtyRects| contains the set of rectangles that need
// to be repainted. On Windows |buffer| will be width*height*4 bytes in size
// and represents a BGRA image with an upper-left origin.
// and represents a BGRA image with an upper-left origin. The
// CefBrowserSettings.animation_frame_rate value controls the rate at which
// this method is called.
///
/*--cef()--*/
virtual void OnPaint(CefRefPtr<CefBrowser> browser,
@@ -1793,6 +1884,58 @@ public:
};
///
// Callback interface used for asynchronous continuation of geolocation
// permission requests.
///
/*--cef(source=library)--*/
class CefGeolocationCallback : public virtual CefBase
{
public:
///
// Call to allow or deny geolocation access.
///
/*--cef(capi_name=cont)--*/
virtual void Continue(bool allow) =0;
};
///
// Implement this interface to handle events related to geolocation permission
// requests. The methods of this class will be called on the UI thread.
///
/*--cef(source=client)--*/
class CefGeolocationHandler : public virtual CefBase
{
public:
///
// Called when a page requests permission to access geolocation information.
// |requesting_url| is the URL requesting permission and |request_id| is the
// unique ID for the permission request. Call CefGeolocationCallback::Continue
// to allow or deny the permission request.
///
/*--cef()--*/
virtual void OnRequestGeolocationPermission(
CefRefPtr<CefBrowser> browser,
const CefString& requesting_url,
int request_id,
CefRefPtr<CefGeolocationCallback> callback) {
}
///
// Called when a geolocation access request is canceled. |requesting_url| is
// the URL that originally requested permission and |request_id| is the unique
// ID for the permission request.
///
/*--cef()--*/
virtual void OnCancelGeolocationPermission(
CefRefPtr<CefBrowser> browser,
const CefString& requesting_url,
int request_id) {
}
};
///
// Implement this interface to provide handler implementations.
///
@@ -1842,6 +1985,14 @@ public:
/*--cef()--*/
virtual CefRefPtr<CefMenuHandler> GetMenuHandler() { return NULL; }
///
// Return the handler for browser permission events.
///
/*--cef()--*/
virtual CefRefPtr<CefPermissionHandler> GetPermissionHandler() {
return NULL;
}
///
// Return the handler for printing events.
///
@@ -1877,6 +2028,15 @@ public:
///
/*--cef()--*/
virtual CefRefPtr<CefDragHandler> GetDragHandler() { return NULL; }
///
// Return the handler for geolocation permissions requests. If no handler is
// provided geolocation access will be denied by default.
///
/*--cef()--*/
virtual CefRefPtr<CefGeolocationHandler> GetGeolocationHandler() {
return NULL;
}
};
@@ -2389,6 +2549,17 @@ public:
///
/*--cef()--*/
virtual bool IsSame(CefRefPtr<CefV8Context> that) =0;
///
// Evaluates the specified JavaScript code using this context's global object.
// On success |retval| will be set to the return value, if any, and the
// function will return true. On failure |exception| will be set to the
// exception, if any, and the function will return false.
///
/*--cef()--*/
virtual bool Eval(const CefString& code,
CefRefPtr<CefV8Value>& retval,
CefRefPtr<CefV8Exception>& exception) =0;
};
@@ -2817,6 +2988,89 @@ public:
bool rethrow_exception) =0;
};
///
// Class representing a V8 stack trace. The methods of this class may only be
// called on the UI thread.
///
/*--cef(source=library)--*/
class CefV8StackTrace : public virtual CefBase
{
public:
///
// Returns the stack trace for the currently active context. |frame_limit| is
// the maximum number of frames that will be captured.
///
/*--cef()--*/
static CefRefPtr<CefV8StackTrace> GetCurrent(int frame_limit);
///
// Returns the number of stack frames.
///
/*--cef()--*/
virtual int GetFrameCount() =0;
///
// Returns the stack frame at the specified 0-based index.
///
/*--cef()--*/
virtual CefRefPtr<CefV8StackFrame> GetFrame(int index) =0;
};
///
// Class representing a V8 stack frame. The methods of this class may only be
// called on the UI thread.
///
/*--cef(source=library)--*/
class CefV8StackFrame : public virtual CefBase
{
public:
///
// Returns the name of the resource script that contains the function.
///
/*--cef()--*/
virtual CefString GetScriptName() =0;
///
// Returns the name of the resource script that contains the function or the
// sourceURL value if the script name is undefined and its source ends with
// a "//@ sourceURL=..." string.
///
/*--cef()--*/
virtual CefString GetScriptNameOrSourceURL() =0;
///
// Returns the name of the function.
///
/*--cef()--*/
virtual CefString GetFunctionName() =0;
///
// Returns the 1-based line number for the function call or 0 if unknown.
///
/*--cef()--*/
virtual int GetLineNumber() =0;
///
// Returns the 1-based column offset on the line for the function call or 0 if
// unknown.
///
/*--cef()--*/
virtual int GetColumn() =0;
///
// Returns true if the function was compiled using eval().
///
/*--cef()--*/
virtual bool IsEval() =0;
///
// Returns true if the function was called as a constructor via "new".
///
/*--cef()--*/
virtual bool IsConstructor() =0;
};
///
// Class that creates CefSchemeHandler instances. The methods of this class will
@@ -2829,7 +3083,8 @@ public:
///
// Return a new scheme handler instance to handle the request. |browser| will
// be the browser window that initiated the request. If the request was
// initiated using the CefWebURLRequest API |browser| will be NULL.
// initiated using the CefWebURLRequest API |browser| will be NULL. The
// |request| object passed to this method will not contain cookie data.
///
/*--cef()--*/
virtual CefRefPtr<CefSchemeHandler> Create(CefRefPtr<CefBrowser> browser,
@@ -3972,4 +4227,37 @@ public:
virtual void AppendArgument(const CefString& argument) =0;
};
///
// Information about a specific web plugin.
///
/*--cef(source=library)--*/
class CefWebPluginInfo : public virtual CefBase
{
public:
///
// Returns the plugin name (i.e. Flash).
///
/*--cef()--*/
virtual CefString GetName() =0;
///
// Returns the plugin file path (DLL/bundle/library).
///
/*--cef()--*/
virtual CefString GetPath() =0;
///
// Returns the version of the plugin (may be OS-specific).
///
/*--cef()--*/
virtual CefString GetVersion() =0;
///
// Returns a description of the plugin from the version information.
///
/*--cef()--*/
virtual CefString GetDescription() =0;
};
#endif // _CEF_H

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved.
// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
@@ -310,51 +310,6 @@ CEF_EXPORT int cef_parse_url(const cef_string_t* url,
CEF_EXPORT int cef_create_url(const struct _cef_urlparts_t* parts,
cef_string_t* url);
///
// Visit all cookies. The returned cookies are ordered by longest path, then by
// earliest creation date. Returns false (0) if cookies cannot be accessed.
///
CEF_EXPORT int cef_visit_all_cookies(struct _cef_cookie_visitor_t* visitor);
///
// Visit a subset of cookies. The results are filtered by the given url scheme,
// host, domain and path. If |includeHttpOnly| is true (1) HTTP-only cookies
// will also be included in the results. The returned cookies are ordered by
// longest path, then by earliest creation date. Returns false (0) if cookies
// cannot be accessed.
///
CEF_EXPORT int cef_visit_url_cookies(const cef_string_t* url,
int includeHttpOnly, struct _cef_cookie_visitor_t* visitor);
///
// Sets a cookie given a valid URL and explicit user-provided cookie attributes.
// This function expects each attribute to be well-formed. It will check for
// disallowed characters (e.g. the ';' character is disallowed within the cookie
// value attribute) and will return false (0) without setting the cookie if such
// characters are found. This function must be called on the IO thread.
///
CEF_EXPORT int cef_set_cookie(const cef_string_t* url,
const struct _cef_cookie_t* cookie);
///
// Delete all cookies that match the specified parameters. If both |url| and
// |cookie_name| are specified all host and domain cookies matching both values
// will be deleted. If only |url| is specified all host cookies (but not domain
// cookies) irrespective of path will be deleted. If |url| is NULL all cookies
// for all hosts and domains will be deleted. Returns false (0) if a non-NULL
// invalid URL is specified or if cookies cannot be accessed. This function must
// be called on the IO thread.
///
CEF_EXPORT int cef_delete_cookies(const cef_string_t* url,
const cef_string_t* cookie_name);
///
// Sets the directory path that will be used for storing cookie data. If |path|
// is NULL data will be stored in memory only. By default the cookie path is the
// same as the cache path. Returns false (0) if cookies cannot be accessed.
///
CEF_EXPORT int cef_set_cookie_path(const cef_string_t* path);
///
// Visit storage of the specified type. If |origin| is non-NULL only data
// matching that origin will be visited. If |key| is non-NULL only data matching
@@ -395,6 +350,25 @@ CEF_EXPORT int cef_delete_storage(enum cef_storage_type_t type,
CEF_EXPORT int cef_set_storage_path(enum cef_storage_type_t type,
const cef_string_t* path);
///
// Returns the number of installed web plugins. This function must be called on
// the UI thread.
///
CEF_EXPORT size_t cef_get_web_plugin_count();
///
// Returns information for web plugin at the specified zero-based index. This
// function must be called on the UI thread.
///
CEF_EXPORT struct _cef_web_plugin_info_t* cef_get_web_plugin_info(int index);
///
// Returns information for web plugin with the specified name. This function
// must be called on the UI thread.
///
CEF_EXPORT struct _cef_web_plugin_info_t* cef_get_web_plugin_info_byname(
const cef_string_t* name);
typedef struct _cef_base_t
{
// Size of the data structure.
@@ -437,6 +411,89 @@ typedef struct _cef_task_t
} cef_task_t;
///
// Structure used for managing cookies. The functions of this structure may be
// called on any thread unless otherwise indicated.
///
typedef struct _cef_cookie_manager_t
{
// Base structure.
cef_base_t base;
///
// Set the schemes supported by this manager. By default only "http" and
// "https" schemes are supported. Must be called before any cookies are
// accessed.
///
void (CEF_CALLBACK *set_supported_schemes)(struct _cef_cookie_manager_t* self,
cef_string_list_t schemes);
///
// Visit all cookies. The returned cookies are ordered by longest path, then
// by earliest creation date. Returns false (0) if cookies cannot be accessed.
///
int (CEF_CALLBACK *visit_all_cookies)(struct _cef_cookie_manager_t* self,
struct _cef_cookie_visitor_t* visitor);
///
// Visit a subset of cookies. The results are filtered by the given url
// scheme, host, domain and path. If |includeHttpOnly| is true (1) HTTP-only
// cookies will also be included in the results. The returned cookies are
// ordered by longest path, then by earliest creation date. Returns false (0)
// if cookies cannot be accessed.
///
int (CEF_CALLBACK *visit_url_cookies)(struct _cef_cookie_manager_t* self,
const cef_string_t* url, int includeHttpOnly,
struct _cef_cookie_visitor_t* visitor);
///
// Sets a cookie given a valid URL and explicit user-provided cookie
// attributes. This function expects each attribute to be well-formed. It will
// check for disallowed characters (e.g. the ';' character is disallowed
// within the cookie value attribute) and will return false (0) without
// setting the cookie if such characters are found. This function must be
// called on the IO thread.
///
int (CEF_CALLBACK *set_cookie)(struct _cef_cookie_manager_t* self,
const cef_string_t* url, const struct _cef_cookie_t* cookie);
///
// Delete all cookies that match the specified parameters. If both |url| and
// values |cookie_name| are specified all host and domain cookies matching
// both will be deleted. If only |url| is specified all host cookies (but not
// domain cookies) irrespective of path will be deleted. If |url| is NULL all
// cookies for all hosts and domains will be deleted. Returns false (0) if a
// non- NULL invalid URL is specified or if cookies cannot be accessed. This
// function must be called on the IO thread.
///
int (CEF_CALLBACK *delete_cookies)(struct _cef_cookie_manager_t* self,
const cef_string_t* url, const cef_string_t* cookie_name);
///
// Sets the directory path that will be used for storing cookie data. If
// |path| is NULL data will be stored in memory only. Returns false (0) if
// cookies cannot be accessed.
///
int (CEF_CALLBACK *set_storage_path)(struct _cef_cookie_manager_t* self,
const cef_string_t* path);
} cef_cookie_manager_t;
///
// Returns the global cookie manager. By default data will be stored at
// CefSettings.cache_path if specified or in memory otherwise.
///
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_get_global_manager();
///
// Creates a new cookie manager. If |path| is NULL data will be stored in memory
// only. Returns NULL if creation fails.
///
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_create_manager(
const cef_string_t* path);
///
// Structure to implement for visiting cookie values. The functions of this
// structure will always be called on the IO thread.
@@ -697,8 +754,8 @@ typedef struct _cef_browser_t
// Send a key event to the browser.
///
void (CEF_CALLBACK *send_key_event)(struct _cef_browser_t* self,
enum cef_key_type_t type, int key, int modifiers, int sysChar,
int imeChar);
enum cef_key_type_t type, const struct _cef_key_info_t* keyInfo,
int modifiers);
///
// Send a mouse click event to the browser. The |x| and |y| coordinates are
@@ -720,7 +777,7 @@ typedef struct _cef_browser_t
// relative to the upper-left corner of the view.
///
void (CEF_CALLBACK *send_mouse_wheel_event)(struct _cef_browser_t* self,
int x, int y, int delta);
int x, int y, int deltaX, int deltaY);
///
// Send a focus event to the browser.
@@ -882,10 +939,9 @@ typedef struct _cef_frame_t
cef_string_userfree_t (CEF_CALLBACK *get_name)(struct _cef_frame_t* self);
///
// Returns the globally unique identifier for this frame. This function should
// only be called on the UI thread.
// Returns the globally unique identifier for this frame.
///
long long (CEF_CALLBACK *get_identifier)(struct _cef_frame_t* self);
int64 (CEF_CALLBACK *get_identifier)(struct _cef_frame_t* self);
///
// Returns the parent of this frame or NULL if this is the main (top-level)
@@ -894,8 +950,7 @@ typedef struct _cef_frame_t
struct _cef_frame_t* (CEF_CALLBACK *get_parent)(struct _cef_frame_t* self);
///
// Returns the URL currently loaded in this frame. This function should only
// be called on the UI thread.
// Returns the URL currently loaded in this frame.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_url)(struct _cef_frame_t* self);
@@ -1159,6 +1214,16 @@ typedef struct _cef_request_handler_t
int port, const cef_string_t* realm, const cef_string_t* scheme,
cef_string_t* username, cef_string_t* password);
///
// Called on the IO thread to retrieve the cookie manager. |main_url| is the
// URL of the top-level frame. Cookies managers can be unique per browser or
// shared across multiple browsers. The global cookie manager will be used if
// this function returns NULL.
///
struct _cef_cookie_manager_t* (CEF_CALLBACK *get_cookie_manager)(
struct _cef_request_handler_t* self, struct _cef_browser_t* browser,
const cef_string_t* main_url);
} cef_request_handler_t;
@@ -1334,6 +1399,26 @@ typedef struct _cef_menu_handler_t
} cef_menu_handler_t;
///
// Implement this structure to handle events related to browser permissions. The
// functions of this structure will be called on the UI thread.
///
typedef struct _cef_permission_handler_t
{
// Base structure.
cef_base_t base;
///
// Called on the UI thread before a script extension is loaded. Return false
// (0) to let the extension load normally.
///
int (CEF_CALLBACK *on_before_script_extension_load)(
struct _cef_permission_handler_t* self, struct _cef_browser_t* browser,
struct _cef_frame_t* frame, const cef_string_t* extensionName);
} cef_permission_handler_t;
///
// Implement this structure to handle events related to printing. The functions
// of this structure will be called on the UI thread.
@@ -1522,7 +1607,9 @@ typedef struct _cef_render_handler_t
// element is the view or the popup widget. |buffer| contains the pixel data
// for the whole image. |dirtyRects| contains the set of rectangles that need
// to be repainted. On Windows |buffer| will be width*height*4 bytes in size
// and represents a BGRA image with an upper-left origin.
// and represents a BGRA image with an upper-left origin. The
// cef_browser_tSettings.animation_frame_rate value controls the rate at which
// this function is called.
///
void (CEF_CALLBACK *on_paint)(struct _cef_render_handler_t* self,
struct _cef_browser_t* browser, enum cef_paint_element_type_t type,
@@ -1570,6 +1657,57 @@ typedef struct _cef_drag_handler_t
} cef_drag_handler_t;
///
// Callback structure used for asynchronous continuation of geolocation
// permission requests.
///
typedef struct _cef_geolocation_callback_t
{
// Base structure.
cef_base_t base;
///
// Call to allow or deny geolocation access.
///
void (CEF_CALLBACK *cont)(struct _cef_geolocation_callback_t* self,
int allow);
} cef_geolocation_callback_t;
///
// Implement this structure to handle events related to geolocation permission
// requests. The functions of this structure will be called on the UI thread.
///
typedef struct _cef_geolocation_handler_t
{
// Base structure.
cef_base_t base;
///
// Called when a page requests permission to access geolocation information.
// |requesting_url| is the URL requesting permission and |request_id| is the
// unique ID for the permission request. Call
// cef_geolocation_callback_t::Continue to allow or deny the permission
// request.
///
void (CEF_CALLBACK *on_request_geolocation_permission)(
struct _cef_geolocation_handler_t* self, struct _cef_browser_t* browser,
const cef_string_t* requesting_url, int request_id,
struct _cef_geolocation_callback_t* callback);
///
// Called when a geolocation access request is canceled. |requesting_url| is
// the URL that originally requested permission and |request_id| is the unique
// ID for the permission request.
///
void (CEF_CALLBACK *on_cancel_geolocation_permission)(
struct _cef_geolocation_handler_t* self, struct _cef_browser_t* browser,
const cef_string_t* requesting_url, int request_id);
} cef_geolocation_handler_t;
///
// Implement this structure to provide handler implementations.
///
@@ -1620,6 +1758,12 @@ typedef struct _cef_client_t
struct _cef_menu_handler_t* (CEF_CALLBACK *get_menu_handler)(
struct _cef_client_t* self);
///
// Return the handler for browser permission events.
///
struct _cef_permission_handler_t* (CEF_CALLBACK *get_permission_handler)(
struct _cef_client_t* self);
///
// Return the handler for printing events.
///
@@ -1656,6 +1800,13 @@ typedef struct _cef_client_t
struct _cef_drag_handler_t* (CEF_CALLBACK *get_drag_handler)(
struct _cef_client_t* self);
///
// Return the handler for geolocation permissions requests. If no handler is
// provided geolocation access will be denied by default.
///
struct _cef_geolocation_handler_t* (CEF_CALLBACK *get_geolocation_handler)(
struct _cef_client_t* self);
} cef_client_t;
@@ -2154,6 +2305,16 @@ typedef struct _cef_v8context_t
int (CEF_CALLBACK *is_same)(struct _cef_v8context_t* self,
struct _cef_v8context_t* that);
///
// Evaluates the specified JavaScript code using this context's global object.
// On success |retval| will be set to the return value, if any, and the
// function will return true (1). On failure |exception| will be set to the
// exception, if any, and the function will return false (0).
///
int (CEF_CALLBACK *eval)(struct _cef_v8context_t* self,
const cef_string_t* code, struct _cef_v8value_t** retval,
struct _cef_v8exception_t** exception);
} cef_v8context_t;
@@ -2598,6 +2759,92 @@ CEF_EXPORT cef_v8value_t* cef_v8value_create_function(const cef_string_t* name,
cef_v8handler_t* handler);
///
// Structure representing a V8 stack trace. The functions of this structure may
// only be called on the UI thread.
///
typedef struct _cef_v8stack_trace_t
{
// Base structure.
cef_base_t base;
///
// Returns the number of stack frames.
///
int (CEF_CALLBACK *get_frame_count)(struct _cef_v8stack_trace_t* self);
///
// Returns the stack frame at the specified 0-based index.
///
struct _cef_v8stack_frame_t* (CEF_CALLBACK *get_frame)(
struct _cef_v8stack_trace_t* self, int index);
} cef_v8stack_trace_t;
///
// Returns the stack trace for the currently active context. |frame_limit| is
// the maximum number of frames that will be captured.
///
CEF_EXPORT cef_v8stack_trace_t* cef_v8stack_trace_get_current(int frame_limit);
///
// Structure representing a V8 stack frame. The functions of this structure may
// only be called on the UI thread.
///
typedef struct _cef_v8stack_frame_t
{
// Base structure.
cef_base_t base;
///
// Returns the name of the resource script that contains the function.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_script_name)(
struct _cef_v8stack_frame_t* self);
///
// Returns the name of the resource script that contains the function or the
// sourceURL value if the script name is undefined and its source ends with a
// "//@ sourceURL=..." string.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_script_name_or_source_url)(
struct _cef_v8stack_frame_t* self);
///
// Returns the name of the function.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_function_name)(
struct _cef_v8stack_frame_t* self);
///
// Returns the 1-based line number for the function call or 0 if unknown.
///
int (CEF_CALLBACK *get_line_number)(struct _cef_v8stack_frame_t* self);
///
// Returns the 1-based column offset on the line for the function call or 0 if
// unknown.
///
int (CEF_CALLBACK *get_column)(struct _cef_v8stack_frame_t* self);
///
// Returns true (1) if the function was compiled using eval().
///
int (CEF_CALLBACK *is_eval)(struct _cef_v8stack_frame_t* self);
///
// Returns true (1) if the function was called as a constructor via "new".
///
int (CEF_CALLBACK *is_constructor)(struct _cef_v8stack_frame_t* self);
} cef_v8stack_frame_t;
///
// Structure that creates cef_scheme_handler_t instances. The functions of this
// structure will always be called on the IO thread.
@@ -2610,7 +2857,8 @@ typedef struct _cef_scheme_handler_factory_t
///
// Return a new scheme handler instance to handle the request. |browser| will
// be the browser window that initiated the request. If the request was
// initiated using the cef_web_urlrequest_t API |browser| will be NULL.
// initiated using the cef_web_urlrequest_t API |browser| will be NULL. The
// |request| object passed to this function will not contain cookie data.
///
struct _cef_scheme_handler_t* (CEF_CALLBACK *create)(
struct _cef_scheme_handler_factory_t* self,
@@ -3762,6 +4010,45 @@ typedef struct _cef_command_line_t
CEF_EXPORT cef_command_line_t* cef_command_line_create();
///
// Information about a specific web plugin.
///
typedef struct _cef_web_plugin_info_t
{
// Base structure.
cef_base_t base;
///
// Returns the plugin name (i.e. Flash).
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_name)(
struct _cef_web_plugin_info_t* self);
///
// Returns the plugin file path (DLL/bundle/library).
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_path)(
struct _cef_web_plugin_info_t* self);
///
// Returns the version of the plugin (may be OS-specific).
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_version)(
struct _cef_web_plugin_info_t* self);
///
// Returns a description of the plugin from the version information.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_description)(
struct _cef_web_plugin_info_t* self);
} cef_web_plugin_info_t;
#ifdef __cplusplus
}
#endif

View File

@@ -38,11 +38,17 @@
#else // !BUILDING_CEF_SHARED
#if defined(_WIN32)
#ifndef OS_WIN
#define OS_WIN 1
#endif
#elif defined(__APPLE__)
#ifndef OS_MACOSX
#define OS_MACOSX 1
#endif
#elif defined(__linux__)
#ifndef OS_LINUX
#define OS_LINUX 1
#endif
#else
#error Please add support for your platform in cef_build.h
#endif
@@ -50,14 +56,20 @@
// For access to standard POSIXish features, use OS_POSIX instead of a
// more specific macro.
#if defined(OS_MACOSX) || defined(OS_LINUX)
#ifndef OS_POSIX
#define OS_POSIX 1
#endif
#endif
// Compiler detection.
#if defined(__GNUC__)
#ifndef COMPILER_GCC
#define COMPILER_GCC 1
#endif
#elif defined(_MSC_VER)
#ifndef COMPILER_MSVC
#define COMPILER_MSVC 1
#endif
#else
#error Please add support for your compiler in cef_build.h
#endif
@@ -66,6 +78,7 @@
// method in the parent class.
// Use like:
// virtual void foo() OVERRIDE;
#ifndef OVERRIDE
#if defined(COMPILER_MSVC)
#define OVERRIDE override
#elif defined(__clang__)
@@ -73,7 +86,9 @@
#else
#define OVERRIDE
#endif
#endif
#ifndef ALLOW_THIS_IN_INITIALIZER_LIST
#if defined(COMPILER_MSVC)
// MSVC_PUSH_DISABLE_WARNING pushes |n| onto a stack of warnings to be disabled.
@@ -106,6 +121,7 @@
#define ALLOW_THIS_IN_INITIALIZER_LIST(code) code
#endif // !COMPILER_MSVC
#endif
#endif // !BUILDING_CEF_SHARED

View File

@@ -28,45 +28,43 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _CEF_LINUX_H
#define _CEF_LINUX_H
#ifndef CEF_INCLUDE_INTERNAL_CEF_LINUX_H_
#define CEF_INCLUDE_INTERNAL_CEF_LINUX_H_
#pragma once
#if defined(OS_LINUX)
#include <pthread.h>
#include "cef_types_linux.h"
#include "cef_types_wrappers.h"
#include "include/internal/cef_types_linux.h"
#include "include/internal/cef_types_wrappers.h"
///
// Atomic increment and decrement.
inline long CefAtomicIncrement(long volatile *pDest)
{
///
inline long CefAtomicIncrement(long volatile *pDest) { // NOLINT(runtime/int)
return __sync_add_and_fetch(pDest, 1);
}
inline long CefAtomicDecrement(long volatile *pDest)
{
inline long CefAtomicDecrement(long volatile *pDest) { // NOLINT(runtime/int)
return __sync_sub_and_fetch(pDest, 1);
}
///
// Critical section wrapper.
class CefCriticalSection
{
public:
CefCriticalSection()
{
///
class CefCriticalSection {
public:
CefCriticalSection() {
pthread_mutexattr_init(&attr_);
pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&lock_, &attr_);
}
virtual ~CefCriticalSection()
{
virtual ~CefCriticalSection() {
pthread_mutex_destroy(&lock_);
pthread_mutexattr_destroy(&attr_);
}
void Lock()
{
void Lock() {
pthread_mutex_lock(&lock_);
}
void Unlock()
{
void Unlock() {
pthread_mutex_unlock(&lock_);
}
@@ -74,54 +72,78 @@ public:
pthread_mutexattr_t attr_;
};
///
// Handle types.
///
#define CefWindowHandle cef_window_handle_t
#define CefCursorHandle cef_cursor_handle_t
struct CefWindowInfoTraits {
typedef cef_window_info_t struct_type;
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s) {}
static inline void set(const struct_type* src, struct_type* target, bool copy)
{
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->m_Widget = src->m_Widget;
target->m_ParentWidget = src->m_ParentWidget;
}
};
///
// Class representing window information.
class CefWindowInfo : public CefStructBase<CefWindowInfoTraits>
{
public:
///
class CefWindowInfo : public CefStructBase<CefWindowInfoTraits> {
public:
typedef CefStructBase<CefWindowInfoTraits> parent;
CefWindowInfo() : parent() {}
CefWindowInfo(const cef_window_info_t& r) : parent(r) {}
CefWindowInfo(const CefWindowInfo& r) : parent(r) {}
void SetAsChild(CefWindowHandle ParentWidget)
{
explicit CefWindowInfo(const cef_window_info_t& r) : parent(r) {}
explicit CefWindowInfo(const CefWindowInfo& r) : parent(r) {}
void SetAsChild(CefWindowHandle ParentWidget) {
m_ParentWidget = ParentWidget;
}
};
struct CefPrintInfoTraits {
typedef cef_print_info_t struct_type;
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s) {}
static inline void set(const struct_type* src, struct_type* target, bool copy)
{
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->m_Scale = src->m_Scale;
}
};
///
// Class representing print context information.
///
typedef CefStructBase<CefPrintInfoTraits> CefPrintInfo;
#endif // OS_LINUX
#endif // _CEF_LINUX_H
struct CefKeyInfoTraits {
typedef cef_key_info_t struct_type;
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s) {}
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->key = src->key;
}
};
///
// Class representing key information.
///
typedef CefStructBase<CefKeyInfoTraits> CefKeyInfo;
#endif // OS_LINUX
#endif // CEF_INCLUDE_INTERNAL_CEF_LINUX_H_

View File

@@ -28,49 +28,49 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _CEF_MAC_H
#define _CEF_MAC_H
#ifndef CEF_INCLUDE_INTERNAL_CEF_MAC_H_
#define CEF_INCLUDE_INTERNAL_CEF_MAC_H_
#pragma once
#if defined(OS_MACOSX)
#include <pthread.h>
#include "cef_types_mac.h"
#include "cef_types_wrappers.h"
#include "include/internal/cef_types_mac.h"
#include "include/internal/cef_types_wrappers.h"
///
// Atomic increment and decrement.
inline long CefAtomicIncrement(long volatile *pDest)
{
///
inline long CefAtomicIncrement(long volatile *pDest) { // NOLINT(runtime/int)
return __sync_add_and_fetch(pDest, 1);
}
inline long CefAtomicDecrement(long volatile *pDest)
{
inline long CefAtomicDecrement(long volatile *pDest) { // NOLINT(runtime/int)
return __sync_sub_and_fetch(pDest, 1);
}
///
// Handle types.
///
#define CefWindowHandle cef_window_handle_t
#define CefCursorHandle cef_cursor_handle_t
///
// Critical section wrapper.
class CefCriticalSection
{
public:
CefCriticalSection()
{
///
class CefCriticalSection {
public:
CefCriticalSection() {
pthread_mutexattr_init(&attr_);
pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&lock_, &attr_);
}
virtual ~CefCriticalSection()
{
virtual ~CefCriticalSection() {
pthread_mutex_destroy(&lock_);
pthread_mutexattr_destroy(&attr_);
}
void Lock()
{
void Lock() {
pthread_mutex_lock(&lock_);
}
void Unlock()
{
void Unlock() {
pthread_mutex_unlock(&lock_);
}
@@ -78,18 +78,18 @@ public:
pthread_mutexattr_t attr_;
};
struct CefWindowInfoTraits {
typedef cef_window_info_t struct_type;
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s)
{
static inline void clear(struct_type* s) {
cef_string_clear(&s->m_windowName);
}
static inline void set(const struct_type* src, struct_type* target, bool copy)
{
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->m_View = src->m_View;
target->m_ParentView = src->m_ParentView;
cef_string_set(src->m_windowName.str, src->m_windowName.length,
@@ -99,22 +99,24 @@ struct CefWindowInfoTraits {
target->m_nWidth = src->m_nWidth;
target->m_nHeight = src->m_nHeight;
target->m_bHidden = src->m_bHidden;
target->m_bWindowRenderingDisabled = src->m_bWindowRenderingDisabled;
target->m_bTransparentPainting = src->m_bTransparentPainting;
}
};
///
// Class representing window information.
class CefWindowInfo : public CefStructBase<CefWindowInfoTraits>
{
public:
///
class CefWindowInfo : public CefStructBase<CefWindowInfoTraits> {
public:
typedef CefStructBase<CefWindowInfoTraits> parent;
CefWindowInfo() : parent() {}
CefWindowInfo(const cef_window_info_t& r) : parent(r) {}
CefWindowInfo(const CefWindowInfo& r) : parent(r) {}
explicit CefWindowInfo(const cef_window_info_t& r) : parent(r) {}
explicit CefWindowInfo(const CefWindowInfo& r) : parent(r) {}
void SetAsChild(CefWindowHandle ParentView, int x, int y, int width,
int height)
{
int height) {
m_ParentView = ParentView;
m_x = x;
m_y = y;
@@ -122,23 +124,55 @@ public:
m_nHeight = height;
m_bHidden = false;
}
void SetAsOffScreen(NSView* parent) {
m_bWindowRenderingDisabled = true;
m_ParentView = parent;
}
void SetTransparentPainting(int transparentPainting) {
m_bTransparentPainting = transparentPainting;
}
};
struct CefPrintInfoTraits {
typedef cef_print_info_t struct_type;
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s) {}
static inline void set(const struct_type* src, struct_type* target, bool copy)
{
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->m_Scale = src->m_Scale;
}
};
///
// Class representing print context information.
///
typedef CefStructBase<CefPrintInfoTraits> CefPrintInfo;
#endif // OS_MACOSX
struct CefKeyInfoTraits {
typedef cef_key_info_t struct_type;
#endif // _CEF_MAC_H
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s) {}
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->keyCode = src->keyCode;
target->character = src->character;
target->characterNoModifiers = src->characterNoModifiers;
}
};
///
// Class representing key information.
///
typedef CefStructBase<CefKeyInfoTraits> CefKeyInfo;
#endif // OS_MACOSX
#endif // CEF_INCLUDE_INTERNAL_CEF_MAC_H_

View File

@@ -411,7 +411,7 @@ public:
///
void clear()
{
if (!empty())
if (string_)
traits::clear(string_);
}

View File

@@ -44,7 +44,9 @@ typedef struct _cef_time_t
{
int year; // Four digit year "2007"
int month; // 1-based month (values 1 = January, etc.)
#if !defined(OS_MACOSX)
int day_of_week; // 0-based day of week (0 = Sunday, etc.)
#endif
int day_of_month; // 1-based day of month (1-31)
int hour; // Hour within the current day (0-23)
int minute; // Minute within the current hour (0-59)

View File

@@ -28,31 +28,37 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _CEF_TYPES_H
#define _CEF_TYPES_H
#ifndef CEF_INCLUDE_INTERNAL_CEF_TYPES_H_
#define CEF_INCLUDE_INTERNAL_CEF_TYPES_H_
#pragma once
#include "cef_build.h"
#include "cef_string.h"
#include "cef_string_list.h"
#include "cef_time.h"
#include "include/internal/cef_build.h"
#include "include/internal/cef_string.h"
#include "include/internal/cef_string_list.h"
#include "include/internal/cef_time.h"
// Bring in platform-specific definitions.
#if defined(OS_WIN)
#include "cef_types_win.h"
#include "include/internal/cef_types_win.h"
#elif defined(OS_MACOSX)
#include "cef_types_mac.h"
#include "include/internal/cef_types_mac.h"
#elif defined(OS_LINUX)
#include "cef_types_linux.h"
#include "include/internal/cef_types_linux.h"
#endif
// The NSPR system headers define 64-bit as |long| when possible. In order to
// not have typedef mismatches, we do the same on LP64.
#if __LP64__
typedef long int64;
typedef unsigned long uint64;
#include <stddef.h> // For size_t
// The NSPR system headers define 64-bit as |long| when possible, except on
// Mac OS X. In order to not have typedef mismatches, we do the same on LP64.
//
// On Mac OS X, |long long| is used for 64-bit types for compatibility with
// <inttypes.h> format macros even in the LP64 model.
#if defined(__LP64__) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
typedef long int64; // NOLINT(runtime/int)
typedef unsigned long uint64; // NOLINT(runtime/int)
#else
typedef long long int64;
typedef unsigned long long uint64;
typedef long long int64; // NOLINT(runtime/int)
typedef unsigned long long uint64; // NOLINT(runtime/int)
#endif
#ifdef __cplusplus
@@ -62,8 +68,7 @@ extern "C" {
///
// Log severity levels.
///
enum cef_log_severity_t
{
enum cef_log_severity_t {
LOGSEVERITY_VERBOSE = -1,
LOGSEVERITY_INFO,
LOGSEVERITY_WARNING,
@@ -77,8 +82,7 @@ enum cef_log_severity_t
// Initialization settings. Specify NULL or 0 to get the recommended default
// values.
///
typedef struct _cef_settings_t
{
typedef struct _cef_settings_t {
///
// Size of this structure.
///
@@ -90,14 +94,14 @@ typedef struct _cef_settings_t
// your application message loop.
///
bool multi_threaded_message_loop;
///
// The location where cache data will be stored on disk. If empty an
// in-memory cache will be used. HTML5 databases such as localStorage will
// only persist across sessions if a cache path is specified.
///
cef_string_t cache_path;
///
// Value that will be returned as the User-Agent HTTP header. If empty the
// default User-Agent string will be used.
@@ -113,7 +117,9 @@ typedef struct _cef_settings_t
///
// The locale string that will be passed to WebKit. If empty the default
// locale of "en-US" will be used.
// locale of "en-US" will be used. This value is ignored on Linux where locale
// is determined using environment variable parsing with the precedence order:
// LANGUAGE, LC_ALL, LC_MESSAGES and LANG.
///
cef_string_t locale;
@@ -160,7 +166,7 @@ typedef struct _cef_settings_t
#if defined(OS_WIN)
///
// Set to true (1) to use the system proxy resolver on Windows when
// Set to true (1) to use the system proxy resolver on Windows when
// "Automatically detect settings" is checked. This setting is disabled
// by default for performance reasons.
///
@@ -173,8 +179,7 @@ typedef struct _cef_settings_t
// default values. The consequences of using custom values may not be well
// tested.
///
typedef struct _cef_browser_settings_t
{
typedef struct _cef_browser_settings_t {
///
// Size of this structure.
///
@@ -195,6 +200,18 @@ typedef struct _cef_browser_settings_t
///
bool history_disabled;
///
// The number of frames per second (fps) for animation and windowless
// rendering. When window rendering is enabled and the JavaScript
// requestAnimationFrame method is used the browser client area will be
// invalidated at the rate specified. When window rendering is disabled the
// CefRenderHandler::OnPaint() method will be called at the rate specified.
// This value must be between 0 and 90. Specify a value of zero for the
// default frame rate of 30 fps. Changing this value may affect display
// performance and/or CPU usage.
///
int animation_frame_rate;
// The below values map to WebPreferences settings.
///
@@ -328,7 +345,7 @@ typedef struct _cef_browser_settings_t
// Set to true (1) to enable the user style sheet for all pages.
///
bool user_style_sheet_enabled;
///
// Location of the user style sheet. This must be a data URL of the form
// "data:text/css;charset=utf-8;base64,csscontent" where "csscontent" is the
@@ -414,8 +431,7 @@ typedef struct _cef_browser_settings_t
///
// URL component parts.
///
typedef struct _cef_urlparts_t
{
typedef struct _cef_urlparts_t {
///
// The complete URL specification.
///
@@ -461,8 +477,7 @@ typedef struct _cef_urlparts_t
///
// Cookie information.
///
typedef struct _cef_cookie_t
{
typedef struct _cef_cookie_t {
///
// The cookie name.
///
@@ -501,7 +516,7 @@ typedef struct _cef_cookie_t
// cookie creation.
///
cef_time_t creation;
///
// The cookie last access date. This is automatically populated by the system
// on access.
@@ -518,8 +533,7 @@ typedef struct _cef_cookie_t
///
// Storage types.
///
enum cef_storage_type_t
{
enum cef_storage_type_t {
ST_LOCALSTORAGE = 0,
ST_SESSIONSTORAGE,
};
@@ -527,8 +541,7 @@ enum cef_storage_type_t
///
// Mouse button types.
///
enum cef_mouse_button_type_t
{
enum cef_mouse_button_type_t {
MBT_LEFT = 0,
MBT_MIDDLE,
MBT_RIGHT,
@@ -537,8 +550,7 @@ enum cef_mouse_button_type_t
///
// Key types.
///
enum cef_key_type_t
{
enum cef_key_type_t {
KT_KEYUP = 0,
KT_KEYDOWN,
KT_CHAR,
@@ -547,8 +559,7 @@ enum cef_key_type_t
///
// Various browser navigation types supported by chrome.
///
enum cef_handler_navtype_t
{
enum cef_handler_navtype_t {
NAVTYPE_LINKCLICKED = 0,
NAVTYPE_FORMSUBMITTED,
NAVTYPE_BACKFORWARD,
@@ -562,8 +573,7 @@ enum cef_handler_navtype_t
// Supported error code values. See net\base\net_error_list.h for complete
// descriptions of the error codes.
///
enum cef_handler_errorcode_t
{
enum cef_handler_errorcode_t {
ERR_FAILED = -2,
ERR_ABORTED = -3,
ERR_INVALID_ARGUMENT = -4,
@@ -619,8 +629,7 @@ enum cef_handler_errorcode_t
// destination. These constants match their equivalents in WebCore's
// DragActions.h and should not be renumbered.
///
enum cef_drag_operations_mask_t
{
enum cef_drag_operations_mask_t {
DRAG_OPERATION_NONE = 0,
DRAG_OPERATION_COPY = 1,
DRAG_OPERATION_LINK = 2,
@@ -634,8 +643,7 @@ enum cef_drag_operations_mask_t
///
// V8 access control values.
///
enum cef_v8_accesscontrol_t
{
enum cef_v8_accesscontrol_t {
V8_ACCESS_CONTROL_DEFAULT = 0,
V8_ACCESS_CONTROL_ALL_CAN_READ = 1,
V8_ACCESS_CONTROL_ALL_CAN_WRITE = 1 << 1,
@@ -645,9 +653,8 @@ enum cef_v8_accesscontrol_t
///
// V8 property attribute values.
///
enum cef_v8_propertyattribute_t
{
V8_PROPERTY_ATTRIBUTE_NONE = 0, // Writeable, Enumerable,
enum cef_v8_propertyattribute_t {
V8_PROPERTY_ATTRIBUTE_NONE = 0, // Writeable, Enumerable,
// Configurable
V8_PROPERTY_ATTRIBUTE_READONLY = 1 << 0, // Not writeable
V8_PROPERTY_ATTRIBUTE_DONTENUM = 1 << 1, // Not enumerable
@@ -657,8 +664,7 @@ enum cef_v8_propertyattribute_t
///
// Structure representing menu information.
///
typedef struct _cef_menu_info_t
{
typedef struct _cef_menu_info_t {
///
// Values from the cef_handler_menutypebits_t enumeration.
///
@@ -690,8 +696,7 @@ typedef struct _cef_menu_info_t
// The cef_menu_info_t typeFlags value will be a combination of the
// following values.
///
enum cef_menu_typebits_t
{
enum cef_menu_typebits_t {
///
// No node is selected
///
@@ -738,8 +743,7 @@ enum cef_menu_typebits_t
// The cef_menu_info_t editFlags value will be a combination of the
// following values.
///
enum cef_menu_capabilitybits_t
{
enum cef_menu_capabilitybits_t {
// Values from WebContextMenuData::EditFlags in WebContextMenuData.h
MENU_CAN_DO_NONE = 0x0,
MENU_CAN_UNDO = 0x1,
@@ -758,8 +762,7 @@ enum cef_menu_capabilitybits_t
///
// Supported menu ID values.
///
enum cef_menu_id_t
{
enum cef_menu_id_t {
MENU_ID_NAV_BACK = 10,
MENU_ID_NAV_FORWARD = 11,
MENU_ID_NAV_RELOAD = 12,
@@ -776,8 +779,7 @@ enum cef_menu_id_t
MENU_ID_VIEWSOURCE = 31,
};
enum cef_paint_element_type_t
{
enum cef_paint_element_type_t {
PET_VIEW = 0,
PET_POPUP,
};
@@ -785,15 +787,13 @@ enum cef_paint_element_type_t
///
// Post data elements may represent either bytes or files.
///
enum cef_postdataelement_type_t
{
enum cef_postdataelement_type_t {
PDE_TYPE_EMPTY = 0,
PDE_TYPE_BYTES,
PDE_TYPE_FILE,
};
enum cef_weburlrequest_flags_t
{
enum cef_weburlrequest_flags_t {
WUR_FLAG_NONE = 0,
WUR_FLAG_SKIP_CACHE = 0x1,
WUR_FLAG_ALLOW_CACHED_CREDENTIALS = 0x2,
@@ -803,8 +803,7 @@ enum cef_weburlrequest_flags_t
WUR_FLAG_REPORT_RAW_HEADERS = 0x20
};
enum cef_weburlrequest_state_t
{
enum cef_weburlrequest_state_t {
WUR_STATE_UNSENT = 0,
WUR_STATE_STARTED = 1,
WUR_STATE_HEADERS_RECEIVED = 2,
@@ -817,8 +816,7 @@ enum cef_weburlrequest_state_t
///
// Focus sources.
///
enum cef_handler_focus_source_t
{
enum cef_handler_focus_source_t {
///
// The source is explicit navigation via the API (LoadURL(), etc).
///
@@ -836,8 +834,7 @@ enum cef_handler_focus_source_t
///
// Key event types.
///
enum cef_handler_keyevent_type_t
{
enum cef_handler_keyevent_type_t {
KEYEVENT_RAWKEYDOWN = 0,
KEYEVENT_KEYDOWN,
KEYEVENT_KEYUP,
@@ -847,19 +844,18 @@ enum cef_handler_keyevent_type_t
///
// 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
enum cef_handler_keyevent_modifiers_t {
KEY_SHIFT = 1 << 0,
KEY_CTRL = 1 << 1,
KEY_ALT = 1 << 2,
KEY_META = 1 << 3,
KEY_KEYPAD = 1 << 4, // Only used on Mac OS-X
};
///
// Structure representing a rectangle.
///
typedef struct _cef_rect_t
{
typedef struct _cef_rect_t {
int x;
int y;
int width;
@@ -869,8 +865,7 @@ typedef struct _cef_rect_t
///
// Existing thread IDs.
///
enum cef_thread_id_t
{
enum cef_thread_id_t {
TID_UI = 0,
TID_IO = 1,
TID_FILE = 2,
@@ -879,8 +874,7 @@ enum cef_thread_id_t
///
// Paper type for printing.
///
enum cef_paper_type_t
{
enum cef_paper_type_t {
PT_LETTER = 0,
PT_LEGAL,
PT_EXECUTIVE,
@@ -892,11 +886,10 @@ enum cef_paper_type_t
///
// Paper metric information for printing.
///
struct cef_paper_metrics
{
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.
// Length and width needed if paper_type is custom_size
// Units are in inches.
double length;
double width;
};
@@ -904,14 +897,13 @@ struct cef_paper_metrics
///
// Paper print margins.
///
struct cef_print_margins
{
//Margin size in inches for left/right/top/bottom (this is content 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.
// Margin size (top/bottom) in inches for header/footer.
double header;
double footer;
};
@@ -919,8 +911,7 @@ struct cef_print_margins
///
// Page orientation for printing.
///
enum cef_page_orientation
{
enum cef_page_orientation {
PORTRAIT = 0,
LANDSCAPE
};
@@ -928,8 +919,7 @@ enum cef_page_orientation
///
// Printing options.
///
typedef struct _cef_print_options_t
{
typedef struct _cef_print_options_t {
enum cef_page_orientation page_orientation;
struct cef_paper_metrics paper_metrics;
struct cef_print_margins paper_margins;
@@ -941,8 +931,7 @@ typedef struct _cef_print_options_t
// before being passed to the parser. If a BOM is detected and the correct
// decoder is available then that decoder will be used automatically.
///
enum cef_xml_encoding_type_t
{
enum cef_xml_encoding_type_t {
XML_ENCODING_NONE = 0,
XML_ENCODING_UTF8,
XML_ENCODING_UTF16LE,
@@ -953,8 +942,7 @@ enum cef_xml_encoding_type_t
///
// XML node types.
///
enum cef_xml_node_type_t
{
enum cef_xml_node_type_t {
XML_NODE_UNSUPPORTED = 0,
XML_NODE_PROCESSING_INSTRUCTION,
XML_NODE_DOCUMENT_TYPE,
@@ -971,8 +959,7 @@ enum cef_xml_node_type_t
///
// Status message types.
///
enum cef_handler_statustype_t
{
enum cef_handler_statustype_t {
STATUSTYPE_TEXT = 0,
STATUSTYPE_MOUSEOVER_URL,
STATUSTYPE_KEYBOARD_FOCUS_URL,
@@ -981,8 +968,7 @@ enum cef_handler_statustype_t
///
// Popup window features.
///
typedef struct _cef_popup_features_t
{
typedef struct _cef_popup_features_t {
int x;
bool xSet;
int y;
@@ -1007,8 +993,7 @@ typedef struct _cef_popup_features_t
///
// DOM document types.
///
enum cef_dom_document_type_t
{
enum cef_dom_document_type_t {
DOM_DOCUMENT_TYPE_UNKNOWN = 0,
DOM_DOCUMENT_TYPE_HTML,
DOM_DOCUMENT_TYPE_XHTML,
@@ -1018,8 +1003,7 @@ enum cef_dom_document_type_t
///
// DOM event category flags.
///
enum cef_dom_event_category_t
{
enum cef_dom_event_category_t {
DOM_EVENT_CATEGORY_UNKNOWN = 0x0,
DOM_EVENT_CATEGORY_UI = 0x1,
DOM_EVENT_CATEGORY_MOUSE = 0x2,
@@ -1045,8 +1029,7 @@ enum cef_dom_event_category_t
///
// DOM event processing phases.
///
enum cef_dom_event_phase_t
{
enum cef_dom_event_phase_t {
DOM_EVENT_PHASE_UNKNOWN = 0,
DOM_EVENT_PHASE_CAPTURING,
DOM_EVENT_PHASE_AT_TARGET,
@@ -1056,8 +1039,7 @@ enum cef_dom_event_phase_t
///
// DOM node types.
///
enum cef_dom_node_type_t
{
enum cef_dom_node_type_t {
DOM_NODE_TYPE_UNSUPPORTED = 0,
DOM_NODE_TYPE_ELEMENT,
DOM_NODE_TYPE_ATTRIBUTE,
@@ -1077,18 +1059,16 @@ enum cef_dom_node_type_t
///
// Proxy types.
///
enum cef_proxy_type_t
{
PROXY_TYPE_DIRECT = 0,
PROXY_TYPE_NAMED,
PROXY_TYPE_PAC_STRING,
enum cef_proxy_type_t {
CEF_PROXY_TYPE_DIRECT = 0,
CEF_PROXY_TYPE_NAMED,
CEF_PROXY_TYPE_PAC_STRING,
};
///
// Proxy information.
///
typedef struct _cef_proxy_info_t
{
typedef struct _cef_proxy_info_t {
enum cef_proxy_type_t proxyType;
cef_string_t proxyList;
} cef_proxy_info_t;
@@ -1097,4 +1077,4 @@ typedef struct _cef_proxy_info_t
}
#endif
#endif // _CEF_TYPES_H
#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_H_

View File

@@ -72,6 +72,13 @@ typedef struct _cef_print_info_t
double m_Scale;
} cef_print_info_t;
///
// Class representing key information.
///
typedef struct _cef_key_info_t {
int key;
} cef_key_info_t;
#ifdef __cplusplus
}
#endif

View File

@@ -28,24 +28,30 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _CEF_TYPES_MAC_H
#define _CEF_TYPES_MAC_H
#ifndef CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_
#define CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_
#pragma once
#include "include/internal/cef_build.h"
#if defined(OS_MACOSX)
#include "cef_string.h"
#include "include/internal/cef_string.h"
// Window handle.
#ifdef __cplusplus
#ifdef __OBJC__
@class NSCursor;
@class NSView;
#else
class NSCursor;
class NSView;
#endif
#define cef_window_handle_t NSView*
#define cef_cursor_handle_t NSCursor*
#else
#define cef_window_handle_t void*
#endif
#define cef_cursor_handle_t void*
#endif
#ifdef __cplusplus
extern "C" {
@@ -54,8 +60,7 @@ extern "C" {
///
// Supported graphics implementations.
///
enum cef_graphics_implementation_t
{
enum cef_graphics_implementation_t {
DESKTOP_IN_PROCESS = 0,
DESKTOP_IN_PROCESS_COMMAND_BUFFER,
};
@@ -63,8 +68,7 @@ enum cef_graphics_implementation_t
///
// Class representing window information.
///
typedef struct _cef_window_info_t
{
typedef struct _cef_window_info_t {
cef_string_t m_windowName;
int m_x;
int m_y;
@@ -74,7 +78,15 @@ typedef struct _cef_window_info_t
// NSView pointer for the parent view.
cef_window_handle_t m_ParentView;
// If window rendering is disabled no browser window will be created. Set
// |m_ParentView| to the window that will act as the parent for popup menus,
// dialog boxes, etc.
int m_bWindowRenderingDisabled;
// Set to true to enable transparent painting.
int m_bTransparentPainting;
// NSView pointer for the new browser view.
cef_window_handle_t m_View;
} cef_window_info_t;
@@ -82,15 +94,23 @@ typedef struct _cef_window_info_t
///
// Class representing print context information.
///
typedef struct _cef_print_info_t
{
typedef struct _cef_print_info_t {
double m_Scale;
} cef_print_info_t;
///
// Class representing key information.
///
typedef struct _cef_key_info_t {
int keyCode;
int character;
int characterNoModifiers;
} cef_key_info_t;
#ifdef __cplusplus
}
#endif
#endif // OS_MACOSX
#endif // OS_MACOSX
#endif // _CEF_TYPES_MAC_H
#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_

View File

@@ -92,6 +92,15 @@ typedef struct _cef_print_info_t
double m_Scale;
} cef_print_info_t;
///
// Class representing key information.
///
typedef struct _cef_key_info_t {
int key;
BOOL sysChar;
BOOL imeChar;
} cef_key_info_t;
#ifdef __cplusplus
}
#endif

View File

@@ -344,6 +344,7 @@ struct CefBrowserSettingsTraits {
target->drag_drop_disabled = src->drag_drop_disabled;
target->load_drops_disabled = src->load_drops_disabled;
target->history_disabled = src->history_disabled;
target->animation_frame_rate = src->animation_frame_rate;
cef_string_set(src->standard_font_family.str,
src->standard_font_family.length, &target->standard_font_family, copy);
@@ -624,7 +625,7 @@ public:
///
void UseDirect()
{
proxyType = PROXY_TYPE_DIRECT;
proxyType = CEF_PROXY_TYPE_DIRECT;
}
///
@@ -638,7 +639,7 @@ public:
///
void UseNamedProxy(const CefString& proxy_uri_list)
{
proxyType = PROXY_TYPE_NAMED;
proxyType = CEF_PROXY_TYPE_NAMED;
(CefString(&proxyList)) = proxy_uri_list;
}
@@ -648,13 +649,13 @@ public:
///
void UsePacString(const CefString& pac_string)
{
proxyType = PROXY_TYPE_PAC_STRING;
proxyType = CEF_PROXY_TYPE_PAC_STRING;
(CefString(&proxyList)) = pac_string;
}
bool IsDirect() const { return proxyType == PROXY_TYPE_DIRECT; }
bool IsNamedProxy() const { return proxyType == PROXY_TYPE_NAMED; }
bool IsPacString() const { return proxyType == PROXY_TYPE_PAC_STRING; }
bool IsDirect() const { return proxyType == CEF_PROXY_TYPE_DIRECT; }
bool IsNamedProxy() const { return proxyType == CEF_PROXY_TYPE_NAMED; }
bool IsPacString() const { return proxyType == CEF_PROXY_TYPE_PAC_STRING; }
CefString ProxyList() const { return CefString(&proxyList); }
};

View File

@@ -28,13 +28,14 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _CEF_WIN_H
#define _CEF_WIN_H
#ifndef CEF_INCLUDE_INTERNAL_CEF_WIN_H_
#define CEF_INCLUDE_INTERNAL_CEF_WIN_H_
#pragma once
#if defined(OS_WIN)
#include <windows.h>
#include "cef_types_win.h"
#include "cef_types_wrappers.h"
#include "include/internal/cef_types_win.h"
#include "include/internal/cef_types_wrappers.h"
///
// Atomic increment and decrement.
@@ -45,24 +46,19 @@
///
// Critical section wrapper.
///
class CefCriticalSection
{
public:
CefCriticalSection()
{
class CefCriticalSection {
public:
CefCriticalSection() {
memset(&m_sec, 0, sizeof(CRITICAL_SECTION));
InitializeCriticalSection(&m_sec);
}
virtual ~CefCriticalSection()
{
virtual ~CefCriticalSection() {
DeleteCriticalSection(&m_sec);
}
void Lock()
{
void Lock() {
EnterCriticalSection(&m_sec);
}
void Unlock()
{
void Unlock() {
LeaveCriticalSection(&m_sec);
}
@@ -75,19 +71,17 @@ public:
#define CefWindowHandle cef_window_handle_t
#define CefCursorHandle cef_cursor_handle_t
struct CefWindowInfoTraits {
typedef cef_window_info_t struct_type;
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s)
{
static inline void clear(struct_type* s) {
cef_string_clear(&s->m_windowName);
}
static inline void set(const struct_type* src, struct_type* target, bool copy)
{
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->m_dwExStyle = src->m_dwExStyle;
cef_string_set(src->m_windowName.str, src->m_windowName.length,
&target->m_windowName, copy);
@@ -107,17 +101,15 @@ struct CefWindowInfoTraits {
///
// Class representing window information.
///
class CefWindowInfo : public CefStructBase<CefWindowInfoTraits>
{
public:
class CefWindowInfo : public CefStructBase<CefWindowInfoTraits> {
public:
typedef CefStructBase<CefWindowInfoTraits> parent;
CefWindowInfo() : parent() {}
CefWindowInfo(const cef_window_info_t& r) : parent(r) {}
CefWindowInfo(const CefWindowInfo& r) : parent(r) {}
void SetAsChild(HWND hWndParent, RECT windowRect)
{
explicit CefWindowInfo(const cef_window_info_t& r) : parent(r) {}
explicit CefWindowInfo(const CefWindowInfo& r) : parent(r) {}
void SetAsChild(HWND hWndParent, RECT windowRect) {
m_dwStyle = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_TABSTOP |
WS_VISIBLE;
m_hWndParent = hWndParent;
@@ -127,8 +119,7 @@ public:
m_nHeight = windowRect.bottom - windowRect.top;
}
void SetAsPopup(HWND hWndParent, const CefString& windowName)
{
void SetAsPopup(HWND hWndParent, const CefString& windowName) {
m_dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS |
WS_VISIBLE;
m_hWndParent = hWndParent;
@@ -140,14 +131,12 @@ public:
cef_string_copy(windowName.c_str(), windowName.length(), &m_windowName);
}
void SetAsOffScreen(HWND hWndParent)
{
void SetAsOffScreen(HWND hWndParent) {
m_bWindowRenderingDisabled = TRUE;
m_hWndParent = hWndParent;
}
void SetTransparentPainting(BOOL transparentPainting)
{
void SetTransparentPainting(BOOL transparentPainting) {
m_bTransparentPainting = transparentPainting;
}
};
@@ -159,8 +148,8 @@ struct CefPrintInfoTraits {
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s) {}
static inline void set(const struct_type* src, struct_type* target, bool copy)
{
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->m_hDC = src->m_hDC;
target->m_Rect = src->m_Rect;
target->m_Scale = src->m_Scale;
@@ -172,6 +161,26 @@ struct CefPrintInfoTraits {
///
typedef CefStructBase<CefPrintInfoTraits> CefPrintInfo;
#endif // OS_WIN
#endif // _CEF_WIN_H
struct CefKeyInfoTraits {
typedef cef_key_info_t struct_type;
static inline void init(struct_type* s) {}
static inline void clear(struct_type* s) {}
static inline void set(const struct_type* src, struct_type* target,
bool copy) {
target->key = src->key;
target->sysChar = src->sysChar;
target->imeChar = src->imeChar;
}
};
///
// Class representing key information.
///
typedef CefStructBase<CefKeyInfoTraits> CefKeyInfo;
#endif // OS_WIN
#endif // CEF_INCLUDE_INTERNAL_CEF_WIN_H_

View File

@@ -127,7 +127,9 @@ void BrowserDragDelegate::StartDragging(const WebDropData& drop_data,
// If it is not drag-out, do the drag-and-drop in the current UI thread.
if (drop_data.download_metadata.empty()) {
DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset);
EndDragging(false);
CefThread::PostTask(
CefThread::UI, FROM_HERE,
NewRunnableMethod(this, &BrowserDragDelegate::EndDragging, false));
return;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,29 @@
// Copyright (c) 2008-2009 The Chromium Embedded Framework Authors.
// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef _BROWSER_IMPL_H
#define _BROWSER_IMPL_H
#ifndef CEF_LIBCEF_BROWSER_IMPL_H_
#define CEF_LIBCEF_BROWSER_IMPL_H_
#pragma once
#include <map>
#include <string>
#include <vector>
#include "include/cef.h"
#include "webview_host.h"
#include "browser_devtools_agent.h"
#include "browser_devtools_client.h"
#include "browser_webview_delegate.h"
#include "browser_navigation_controller.h"
#include "cef_thread.h"
#include "tracker.h"
#include "libcef/webview_host.h"
#include "libcef/browser_devtools_agent.h"
#include "libcef/browser_devtools_client.h"
#include "libcef/browser_webview_delegate.h"
#include "libcef/browser_navigation_controller.h"
#include "libcef/browser_request_context_proxy.h"
#include "libcef/cef_thread.h"
#include "libcef/geolocation_client.h"
#include "libcef/tracker.h"
#if defined(OS_WIN)
#include "printing/win_printing_context.h"
#include "libcef/printing/win_printing_context.h"
#endif
#include "base/scoped_temp_dir.h"
@@ -29,23 +36,23 @@ namespace WebKit {
class WebView;
}
class CefFrameImpl;
#define BUFFER_SIZE 32768
// Implementation of CefBrowser.
class CefBrowserImpl : public CefBrowser
{
public:
class PaintDelegate : public WebWidgetHost::PaintDelegate
{
public:
PaintDelegate(CefBrowserImpl* browser);
class CefBrowserImpl : public CefBrowser {
public:
class PaintDelegate : public WebWidgetHost::PaintDelegate {
public:
explicit PaintDelegate(CefBrowserImpl* browser);
virtual ~PaintDelegate();
virtual void Paint(bool popup, const std::vector<CefRect>& dirtyRects,
const void* buffer) OVERRIDE;
protected:
protected:
CefBrowserImpl* browser_;
};
@@ -78,8 +85,7 @@ public:
virtual bool IsPopup() OVERRIDE { return is_popup(); }
virtual bool HasDocument() OVERRIDE { return has_document(); }
virtual CefRefPtr<CefClient> GetClient() OVERRIDE { return client_; }
virtual CefRefPtr<CefFrame> GetMainFrame() OVERRIDE
{ return GetMainCefFrame(); }
virtual CefRefPtr<CefFrame> GetMainFrame() OVERRIDE;
virtual CefRefPtr<CefFrame> GetFocusedFrame() OVERRIDE;
virtual CefRefPtr<CefFrame> GetFrame(const CefString& name) OVERRIDE;
virtual void GetFrameNames(std::vector<CefString>& names) OVERRIDE;
@@ -99,12 +105,13 @@ public:
virtual void Invalidate(const CefRect& dirtyRect) OVERRIDE;
virtual bool GetImage(PaintElementType type, int width, int height,
void* buffer) OVERRIDE;
virtual void SendKeyEvent(KeyType type, int key, int modifiers, bool sysChar,
bool imeChar) OVERRIDE;
virtual void SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo,
int modifiers) OVERRIDE;
virtual void SendMouseClickEvent(int x, int y, MouseButtonType type,
bool mouseUp, int clickCount) OVERRIDE;
virtual void SendMouseMoveEvent(int x, int y, bool mouseLeave) OVERRIDE;
virtual void SendMouseWheelEvent(int x, int y, int delta) OVERRIDE;
virtual void SendMouseWheelEvent(int x, int y, int deltaX, int deltaY)
OVERRIDE;
virtual void SendFocusEvent(bool setFocus) OVERRIDE;
virtual void SendCaptureLostEvent() OVERRIDE;
@@ -131,28 +138,29 @@ public:
CefRefPtr<CefStreamReader> stream,
const CefString& url);
void ExecuteJavaScript(CefRefPtr<CefFrame> frame,
const CefString& jsCode,
const CefString& jsCode,
const CefString& scriptUrl,
int startLine);
long long GetIdentifier(CefRefPtr<CefFrame> frame);
CefRefPtr<CefFrame> GetParent(CefRefPtr<CefFrame> frame);
CefString GetURL(CefRefPtr<CefFrame> frame);
// 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 name one will be created. There is no
// guarantee that the same CefFrame object will be returned across different
// calls to this function.
CefRefPtr<CefFrame> GetCefFrame(const CefString& name);
void RemoveCefFrame(const CefString& name);
CefRefPtr<CefFrame> GetMainCefFrame();
// coupled to a WebFrame object by id. If a CefFrame object does not already
// exist for the specified id one will be created. There is no guarantee that
// the same CefFrame object will be returned across different calls to this
// function.
CefRefPtr<CefFrameImpl> GetCefFrame(int64 id);
CefRefPtr<CefFrameImpl> GetOrCreateCefFrame(int64 id, const CefString& name,
const GURL& url);
void RemoveCefFrame(int64 id);
CefRefPtr<CefFrameImpl> GetMainCefFrame(int64 id, const GURL& url);
////////////////////////////////////////////////////////////
// ALL UIT_* METHODS MUST ONLY BE CALLED ON THE UI THREAD //
////////////////////////////////////////////////////////////
CefRefPtr<CefFrame> UIT_GetCefFrame(WebKit::WebFrame* frame);
void UIT_UpdateCefFrame(WebKit::WebFrame* frame);
// Return the main WebFrame object.
WebKit::WebFrame* UIT_GetMainWebFrame();
@@ -195,12 +203,13 @@ public:
return popuphost_->view_handle();
}
gfx::NativeView UIT_GetMainWndHandle();
void UIT_ClearMainWndHandle();
BrowserNavigationController* UIT_GetNavigationController() {
REQUIRE_UIT();
return nav_controller_.get();
}
// Return true to allow user editing such as entering text in form elements
bool UIT_AllowEditing() { return true; }
@@ -249,7 +258,7 @@ public:
CefRefPtr<CefStreamReader> stream,
const CefString& url);
void UIT_ExecuteJavaScript(CefRefPtr<CefFrame> frame,
const CefString& js_code,
const CefString& js_code,
const CefString& script_url,
int start_line);
void UIT_GoBackOrForward(int offset);
@@ -260,12 +269,11 @@ public:
void UIT_SetFocus(WebWidgetHost* host, bool enable);
void UIT_SetSize(PaintElementType type, int width, int height);
void UIT_Invalidate(const CefRect& dirtyRect);
void UIT_SendKeyEvent(KeyType type, int key, int modifiers, bool sysChar,
bool imeChar);
void UIT_SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, int modifiers);
void UIT_SendMouseClickEvent(int x, int y, MouseButtonType type,
bool mouseUp, int clickCount);
void UIT_SendMouseMoveEvent(int x, int y, bool mouseLeave);
void UIT_SendMouseWheelEvent(int x, int y, int delta);
void UIT_SendMouseWheelEvent(int x, int y, int deltaX, int deltaY);
void UIT_SendFocusEvent(bool setFocus);
void UIT_SendCaptureLostEvent();
@@ -275,7 +283,7 @@ public:
void UIT_ClosePopupWidget();
void UIT_Show(WebKit::WebNavigationPolicy policy);
// Handles most simple browser actions
void UIT_HandleActionView(cef_menu_id_t menuId);
void UIT_HandleAction(cef_menu_id_t menuId, CefRefPtr<CefFrame> frame);
@@ -305,13 +313,14 @@ public:
void UIT_SetZoomLevel(double zoomLevel);
void UIT_ShowDevTools();
void UIT_CloseDevTools();
WebKit::WebGeolocationClient* UIT_GetGeolocationClient();
void UIT_VisitDOM(CefRefPtr<CefFrame> frame,
CefRefPtr<CefDOMVisitor> visitor);
// Frame objects will be deleted immediately before the frame is closed.
void UIT_AddFrameObject(WebKit::WebFrame* frame,
CefTrackObject* tracked_object);
CefTrackObject* tracked_object);
void UIT_BeforeFrameClosed(WebKit::WebFrame* frame);
// These variables are read-only.
@@ -319,7 +328,7 @@ public:
const FilePath& file_system_root() const { return file_system_root_.path(); }
gfx::NativeView opener_window() { return opener_; }
bool is_popup() { return (opener_ != NULL); }
// These variables may be read/written from multiple threads.
void set_zoom_level(double zoomLevel);
double zoom_level();
@@ -329,32 +338,35 @@ public:
void set_has_document(bool has_document);
bool has_document();
// URL currently being loaded in the main frame.
void set_pending_url(const GURL& url);
GURL pending_url();
void set_is_dropping(bool is_dropping) { is_dropping_ = is_dropping; }
bool is_dropping() { return is_dropping_; }
#if defined(OS_WIN)
void set_opener_was_disabled_by_modal_loop(bool disabled)
{
void set_opener_was_disabled_by_modal_loop(bool disabled) {
opener_was_disabled_by_modal_loop_ = disabled;
}
void set_internal_modal_message_loop_is_active(bool active)
{
void set_internal_modal_message_loop_is_active(bool active) {
internal_modal_message_loop_is_active_ = active;
}
#endif
void set_popup_rect(const gfx::Rect& rect) { popup_rect_ = rect; }
net::URLRequestContext* request_context_proxy();
static bool ImplementsThreadSafeReferenceCounting() { return true; }
protected:
protected:
static void UIT_CloseView(gfx::NativeView view);
static bool UIT_IsViewVisible(gfx::NativeView view);
void UIT_CreateDevToolsClient(BrowserDevToolsAgent* agent);
void UIT_DestroyDevToolsClient();
protected:
CefWindowInfo window_info_;
CefBrowserSettings settings_;
// Handle of the browser window that opened this window.
@@ -372,16 +384,26 @@ protected:
scoped_ptr<BrowserDevToolsAgent> dev_tools_agent_;
scoped_ptr<BrowserDevToolsClient> dev_tools_client_;
scoped_refptr<BrowserRequestContextProxy> request_context_proxy_;
// The geolocation client attached to this view, lazily initialized.
scoped_refptr<CefGeolocationClient> geolocation_client_;
CefString title_;
double zoom_level_;
bool can_go_back_;
bool can_go_forward_;
bool has_document_;
GURL pending_url_;
// True if a drop action is occuring.
bool is_dropping_;
// True if currently in the OnSetFocus callback. Only accessed on the UI
// thread.
bool is_in_onsetfocus_;
#if defined(OS_WIN)
// Context object used to manage printing.
printing::PrintingContext print_context_;
@@ -391,9 +413,12 @@ protected:
bool internal_modal_message_loop_is_active_;
#endif
typedef std::map<CefString, CefFrame*> FrameMap;
// Map of frame id to reference.
typedef std::map<int64, CefFrameImpl*> FrameMap;
FrameMap frames_;
CefFrame* main_frame_;
// Singleton main frame reference.
CefRefPtr<CefFrameImpl> main_frame_;
typedef std::map<WebKit::WebFrame*, CefRefPtr<CefTrackManager> >
FrameObjectMap;
@@ -401,7 +426,7 @@ protected:
// Unique browser ID assigned by the context.
int unique_id_;
// A temporary directory for FileSystem API.
ScopedTempDir file_system_root_;
@@ -411,10 +436,12 @@ protected:
// Implementation of CefFrame.
class CefFrameImpl : public CefFrame
{
public:
CefFrameImpl(CefBrowserImpl* browser, const CefString& name);
class CefFrameImpl : public CefFrame {
public:
CefFrameImpl(CefBrowserImpl* browser,
int64 frame_id,
const CefString& name,
const CefString& url);
virtual ~CefFrameImpl();
// CefFrame methods
@@ -429,37 +456,50 @@ public:
virtual void ViewSource() OVERRIDE { browser_->ViewSource(this); }
virtual CefString GetSource() OVERRIDE { return browser_->GetSource(this); }
virtual CefString GetText() OVERRIDE { return browser_->GetText(this); }
virtual void LoadRequest(CefRefPtr<CefRequest> request) OVERRIDE
{ return browser_->LoadRequest(this, request); }
virtual void LoadURL(const CefString& url) OVERRIDE
{ return browser_->LoadURL(this, url); }
virtual void LoadRequest(CefRefPtr<CefRequest> request) OVERRIDE {
return browser_->LoadRequest(this, request);
}
virtual void LoadURL(const CefString& url) OVERRIDE {
return browser_->LoadURL(this, url);
}
virtual void LoadString(const CefString& string,
const CefString& url) OVERRIDE
{ return browser_->LoadString(this, string, url); }
const CefString& url) OVERRIDE {
return browser_->LoadString(this, string, url);
}
virtual void LoadStream(CefRefPtr<CefStreamReader> stream,
const CefString& url) OVERRIDE
{ return browser_->LoadStream(this, stream, url); }
virtual void ExecuteJavaScript(const CefString& jsCode,
const CefString& url) OVERRIDE {
return browser_->LoadStream(this, stream, url);
}
virtual void ExecuteJavaScript(const CefString& jsCode,
const CefString& scriptUrl,
int startLine) OVERRIDE
{ return browser_->ExecuteJavaScript(this, jsCode, scriptUrl, startLine); }
int startLine) OVERRIDE {
return browser_->ExecuteJavaScript(this, jsCode, scriptUrl, startLine);
}
virtual bool IsMain() OVERRIDE { return name_.empty(); }
virtual bool IsFocused() OVERRIDE;
virtual CefString GetName() OVERRIDE { return name_; }
virtual long long GetIdentifier() OVERRIDE
{ return browser_->GetIdentifier(this); }
virtual CefRefPtr<CefFrame> GetParent() OVERRIDE
{ return browser_->GetParent(this); }
virtual CefString GetURL() OVERRIDE { return browser_->GetURL(this); }
virtual int64 GetIdentifier() OVERRIDE;
virtual CefRefPtr<CefFrame> GetParent() OVERRIDE {
return browser_->GetParent(this);
}
virtual CefString GetURL() OVERRIDE;
virtual CefRefPtr<CefBrowser> GetBrowser() OVERRIDE { return browser_.get(); }
virtual void VisitDOM(CefRefPtr<CefDOMVisitor> visitor) OVERRIDE;
virtual CefRefPtr<CefV8Context> GetV8Context() OVERRIDE;
private:
void set_id(int64 id);
void set_url(const CefString& url);
private:
CefRefPtr<CefBrowserImpl> browser_;
CefString name_;
// The below values must be protected by the lock.
base::Lock lock_;
int64 id_;
CefString url_;
IMPLEMENT_REFCOUNTING(CefFrameImpl);
};
#endif // _BROWSER_IMPL_H
#endif // CEF_LIBCEF_BROWSER_IMPL_H_

View File

@@ -18,6 +18,14 @@
using WebKit::WebRect;
using WebKit::WebSize;
namespace {
void window_destroyed(GtkWidget* widget, CefBrowserImpl* browser) {
browser->UIT_DestroyBrowser();
}
} // namespace
void CefBrowserImpl::ParentWindowWillClose()
{
// TODO(port): Implement this method if necessary.
@@ -40,6 +48,11 @@ gfx::NativeView CefBrowserImpl::UIT_GetMainWndHandle() {
return window_info_.m_Widget;
}
void CefBrowserImpl::UIT_ClearMainWndHandle() {
REQUIRE_UIT();
window_info_.m_Widget = NULL;
}
bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
{
REQUIRE_UIT();
@@ -83,7 +96,11 @@ bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
if (!settings_.developer_tools_disabled)
dev_tools_agent_->SetWebView(webviewhost_->webview());
webviewhost_->SetFrameRate(settings_.animation_frame_rate);
window_info_.m_Widget = webviewhost_->view_handle();
g_signal_connect(G_OBJECT(window_info_.m_Widget), "destroy",
G_CALLBACK(window_destroyed), this);
Unlock();
@@ -176,11 +193,8 @@ int CefBrowserImpl::UIT_GetPagesCount(WebKit::WebFrame* frame)
// static
void CefBrowserImpl::UIT_CloseView(gfx::NativeView view)
{
GtkWidget* window =
gtk_widget_get_parent(gtk_widget_get_parent(GTK_WIDGET(view)));
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(
&gtk_widget_destroy, GTK_WIDGET(window)));
GtkWidget* window = gtk_widget_get_toplevel(GTK_WIDGET(view));
gtk_widget_destroy(window);
}
// static

View File

@@ -3,13 +3,13 @@
// 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_settings.h"
#include "browser_webview_mac.h"
#import <Cocoa/Cocoa.h>
#include "libcef/cef_context.h"
#include "libcef/browser_impl.h"
#include "libcef/browser_settings.h"
#include "libcef/browser_webview_mac.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSize.h"
@@ -19,30 +19,32 @@
using WebKit::WebRect;
using WebKit::WebSize;
void CefBrowserImpl::ParentWindowWillClose()
{
void CefBrowserImpl::ParentWindowWillClose() {
// TODO(port): Implement this method if necessary.
}
CefWindowHandle CefBrowserImpl::GetWindowHandle()
{
CefWindowHandle CefBrowserImpl::GetWindowHandle() {
AutoLock lock_scope(this);
return window_info_.m_View;
}
bool CefBrowserImpl::IsWindowRenderingDisabled()
{
// TODO(port): Add support for off-screen rendering.
return false;
bool CefBrowserImpl::IsWindowRenderingDisabled() {
return (window_info_.m_bWindowRenderingDisabled ? true : false);
}
gfx::NativeView CefBrowserImpl::UIT_GetMainWndHandle() {
REQUIRE_UIT();
return window_info_.m_View;
return window_info_.m_bWindowRenderingDisabled ?
window_info_.m_ParentView : window_info_.m_View;
}
bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
{
void CefBrowserImpl::UIT_ClearMainWndHandle() {
REQUIRE_UIT();
if (!window_info_.m_bWindowRenderingDisabled)
window_info_.m_View = NULL;
}
bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url) {
REQUIRE_UIT();
Lock();
@@ -60,29 +62,35 @@ bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
NSView* parentView = window_info_.m_ParentView;
gfx::Rect contentRect(window_info_.m_x, window_info_.m_y,
window_info_.m_nWidth, window_info_.m_nHeight);
if (parentView == nil) {
// Create a new window.
NSRect screen_rect = [[NSScreen mainScreen] visibleFrame];
NSRect window_rect = {{window_info_.m_x,
screen_rect.size.height - window_info_.m_y},
{window_info_.m_nWidth, window_info_.m_nHeight}};
if (window_rect.size.width == 0)
window_rect.size.width = 750;
if (window_rect.size.height == 0)
window_rect.size.height = 750;
contentRect.SetRect(0, 0, window_rect.size.width, window_rect.size.height);
if (!window_info_.m_bWindowRenderingDisabled) {
if (parentView == nil) {
// Create a new window.
NSRect screen_rect = [[NSScreen mainScreen] visibleFrame];
NSRect window_rect = {{window_info_.m_x,
screen_rect.size.height - window_info_.m_y},
{window_info_.m_nWidth, window_info_.m_nHeight}};
if (window_rect.size.width == 0)
window_rect.size.width = 750;
if (window_rect.size.height == 0)
window_rect.size.height = 750;
contentRect.SetRect(0, 0, window_rect.size.width,
window_rect.size.height);
newWnd = [[NSWindow alloc]
initWithContentRect:window_rect
styleMask:(NSTitledWindowMask |
NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask |
NSUnifiedTitleAndToolbarWindowMask )
backing:NSBackingStoreBuffered
defer:NO];
parentView = [newWnd contentView];
window_info_.m_ParentView = parentView;
newWnd = [[NSWindow alloc]
initWithContentRect:window_rect
styleMask:(NSTitledWindowMask |
NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask |
NSUnifiedTitleAndToolbarWindowMask )
backing:NSBackingStoreBuffered
defer:NO];
parentView = [newWnd contentView];
window_info_.m_ParentView = parentView;
}
} else {
// Create a new paint delegate.
paint_delegate_.reset(new PaintDelegate(this));
}
WebPreferences prefs;
@@ -91,17 +99,25 @@ bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
// Create the webview host object
webviewhost_.reset(
WebViewHost::Create(parentView, contentRect, delegate_.get(),
NULL, dev_tools_agent_.get(), prefs));
paint_delegate_.get(), dev_tools_agent_.get(),
prefs));
if (window_info_.m_bTransparentPainting)
webviewhost_->webview()->setIsTransparent(true);
if (!settings_.developer_tools_disabled)
dev_tools_agent_->SetWebView(webviewhost_->webview());
webviewhost_->SetFrameRate(settings_.animation_frame_rate);
BrowserWebView* browserView = (BrowserWebView*)webviewhost_->view_handle();
browserView.browser = this;
window_info_.m_View = browserView;
if (!settings_.drag_drop_disabled)
[browserView registerDragDrop];
if (!window_info_.m_bWindowRenderingDisabled) {
if (!settings_.drag_drop_disabled)
[browserView registerDragDrop];
}
Unlock();
@@ -124,26 +140,41 @@ bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
return true;
}
void CefBrowserImpl::UIT_SetFocus(WebWidgetHost* host, bool enable)
{
void CefBrowserImpl::UIT_SetFocus(WebWidgetHost* host, bool enable) {
REQUIRE_UIT();
if (!host)
return;
NSView* view = host->view_handle();
if (!view)
BrowserWebView* browserView = (BrowserWebView*)host->view_handle();
if (!browserView)
return;
if (enable)
[[view window] makeFirstResponder:view];
if (enable) {
// Guard against calling OnSetFocus twice.
browserView.in_setfocus = true;
[[browserView window] makeFirstResponder:browserView];
browserView.in_setfocus = false;
}
}
bool CefBrowserImpl::UIT_ViewDocumentString(WebKit::WebFrame *frame)
{
bool CefBrowserImpl::UIT_ViewDocumentString(WebKit::WebFrame* frame) {
REQUIRE_UIT();
// TODO(port): Add implementation.
NOTIMPLEMENTED();
char sztmp[L_tmpnam+4];
if (tmpnam(sztmp)) {
strcat(sztmp, ".txt");
FILE* fp = fopen(sztmp, "wb");
if (fp) {
std::string markup = frame->contentAsMarkup().utf8();
fwrite(markup.c_str(), 1, markup.size(), fp);
fclose(fp);
char szopen[L_tmpnam + 14];
snprintf(szopen, sizeof(szopen), "open -t \"%s\"", sztmp);
return (system(szopen) >= 0);
}
}
return false;
}
@@ -163,8 +194,7 @@ void CefBrowserImpl::UIT_PrintPages(WebKit::WebFrame* frame) {
NOTIMPLEMENTED();
}
int CefBrowserImpl::UIT_GetPagesCount(WebKit::WebFrame* frame)
{
int CefBrowserImpl::UIT_GetPagesCount(WebKit::WebFrame* frame) {
REQUIRE_UIT();
// TODO(port): Add implementation.
@@ -173,15 +203,13 @@ int CefBrowserImpl::UIT_GetPagesCount(WebKit::WebFrame* frame)
}
// static
void CefBrowserImpl::UIT_CloseView(gfx::NativeView view)
{
void CefBrowserImpl::UIT_CloseView(gfx::NativeView view) {
[[view window] performSelector:@selector(performClose:)
withObject:nil
afterDelay:0];
}
// static
bool CefBrowserImpl::UIT_IsViewVisible(gfx::NativeView view)
{
bool CefBrowserImpl::UIT_IsViewVisible(gfx::NativeView view) {
return [[view window] isVisible];
}

View File

@@ -89,8 +89,15 @@ LRESULT CALLBACK CefBrowserImpl::WndProc(HWND hwnd, UINT message,
// Clear the user data pointer.
ui::SetWindowUserData(hwnd, NULL);
// Destroy the browser.
browser->UIT_DestroyBrowser();
BrowserWebViewDelegate* delegate = browser->UIT_GetWebViewDelegate();
if (delegate && delegate->drag_delegate()) {
// Don't destroy the browser while a drag operation is pending. Instead,
// destroy the browser once the drag operation completes.
delegate->set_destroy_on_drag_end(true);
} else {
// Destroy the browser.
browser->UIT_DestroyBrowser();
}
}
return 0;
@@ -105,21 +112,8 @@ LRESULT CALLBACK CefBrowserImpl::WndProc(HWND hwnd, UINT message,
return 0;
case WM_SETFOCUS:
if (browser) {
WebViewHost* host = browser->UIT_GetWebViewHost();
if (host) {
bool handled = false;
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
CefRefPtr<CefFocusHandler> handler = client->GetFocusHandler();
if (handler.get())
handled = handler->OnSetFocus(browser, FOCUS_SOURCE_SYSTEM);
}
if (!handled)
browser->UIT_SetFocus(host, true);
}
}
if (browser)
browser->SetFocus(true);
return 0;
case WM_ERASEBKGND:
@@ -163,6 +157,12 @@ gfx::NativeWindow CefBrowserImpl::UIT_GetMainWndHandle() {
window_info_.m_hWndParent : window_info_.m_hWnd;
}
void CefBrowserImpl::UIT_ClearMainWndHandle() {
REQUIRE_UIT();
if (!window_info_.m_bWindowRenderingDisabled)
window_info_.m_hWnd = NULL;
}
bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
{
REQUIRE_UIT();
@@ -224,6 +224,8 @@ bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url)
if (!settings_.developer_tools_disabled)
dev_tools_agent_->SetWebView(webviewhost_->webview());
webviewhost_->SetFrameRate(settings_.animation_frame_rate);
Unlock();
if (!window_info_.m_bWindowRenderingDisabled) {

View File

@@ -3,8 +3,8 @@
// 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 "libcef/browser_navigation_controller.h"
#include "libcef/browser_impl.h"
#include "base/logging.h"
#include "net/base/upload_data.h"
@@ -29,7 +29,7 @@ BrowserNavigationEntry::BrowserNavigationEntry(int page_id,
method_(method),
headers_(headers),
target_frame_(target_frame) {
if(!upload.isNull())
if (!upload.isNull())
upload_ = upload;
}
@@ -57,7 +57,7 @@ BrowserNavigationController::~BrowserNavigationController() {
}
void BrowserNavigationController::Reset() {
entries_.clear();
entries_.reset();
DiscardPendingEntry();
last_committed_entry_index_ = -1;
@@ -88,8 +88,8 @@ void BrowserNavigationController::GoToOffset(int offset) {
}
void BrowserNavigationController::GoToIndex(int index) {
DCHECK(index >= 0);
DCHECK(index < static_cast<int>(entries_.size()));
DCHECK_GE(index, 0);
DCHECK_LT(index, static_cast<int>(entries_.size()));
DiscardPendingEntry();
@@ -111,7 +111,8 @@ BrowserNavigationEntry* BrowserNavigationController::GetLastCommittedEntry()
const {
if (last_committed_entry_index_ == -1)
return NULL;
return entries_[last_committed_entry_index_].get();
return const_cast<BrowserNavigationEntry*>(
entries_[last_committed_entry_index_]);
}
BrowserNavigationEntry* BrowserNavigationController::GetActiveEntry() const {
@@ -133,13 +134,14 @@ BrowserNavigationEntry* BrowserNavigationController::GetEntryAtIndex(
if (index < 0 || index >= GetEntryCount())
return NULL;
return entries_[index].get();
return const_cast<BrowserNavigationEntry*>(entries_[index]);
}
BrowserNavigationEntry* BrowserNavigationController::GetEntryWithPageID(
int32 page_id) const {
int index = GetEntryIndexWithPageID(page_id);
return (index != -1) ? entries_[index].get() : NULL;
return (index != -1) ?
const_cast<BrowserNavigationEntry*>(entries_[index]) : NULL;
}
void BrowserNavigationController::DidNavigateToEntry(
@@ -158,7 +160,7 @@ void BrowserNavigationController::DidNavigateToEntry(
int existing_entry_index = GetEntryIndexWithPageID(entry->GetPageID());
BrowserNavigationEntry* existing_entry = (existing_entry_index != -1) ?
entries_[existing_entry_index].get() : NULL;
entries_[existing_entry_index] : NULL;
if (!existing_entry) {
// No existing entry, then simply ignore this navigation!
DLOG(WARNING) << "ignoring navigation for page: " << entry->GetPageID();
@@ -191,7 +193,7 @@ void BrowserNavigationController::DidNavigateToEntry(
}
void BrowserNavigationController::DiscardPendingEntry() {
if (pending_entry_index_ == -1)
if (pending_entry_index_ == -1 && pending_entry_)
delete pending_entry_;
pending_entry_ = NULL;
pending_entry_index_ = -1;
@@ -204,19 +206,19 @@ void BrowserNavigationController::InsertEntry(BrowserNavigationEntry* entry) {
if (settings.history_disabled) {
// History is disabled. Remove any existing entries.
if (entries_.size() > 0)
entries_.clear();
entries_.reset();
} else {
// Prune any entry which are in front of the current entry.
int current_size = static_cast<int>(entries_.size());
if (current_size > 0) {
while (last_committed_entry_index_ < (current_size - 1)) {
entries_.pop_back();
entries_.erase(entries_.end() - 1);
current_size--;
}
}
}
entries_.push_back(linked_ptr<BrowserNavigationEntry>(entry));
entries_.push_back(entry);
last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
UpdateMaxPageID();
}
@@ -233,8 +235,8 @@ 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();
DCHECK_NE(pending_entry_index_, -1);
pending_entry_ = entries_[pending_entry_index_];
}
if (browser_->UIT_Navigate(*pending_entry_, reload, ignoreCache)) {

View File

@@ -3,15 +3,16 @@
// 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
#ifndef CEF_LIBCEF_BROWSER_NAVIGATION_CONTROLLER_H_
#define CEF_LIBCEF_BROWSER_NAVIGATION_CONTROLLER_H_
#pragma once
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/memory/linked_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_vector.h"
#include "googleurl/src/gurl.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebHTTPBody.h"
@@ -24,7 +25,7 @@ class CefBrowserImpl;
// Associated with browser-initated navigations to hold tracking data.
class BrowserExtraData : public WebKit::WebDataSource::ExtraData {
public:
BrowserExtraData(int32 pending_page_id)
explicit BrowserExtraData(int32 pending_page_id)
: pending_page_id(pending_page_id),
request_committed(false) {
}
@@ -76,7 +77,7 @@ class BrowserNavigationEntry {
const WebKit::WebHTTPBody& GetUploadData() const { return upload_; }
const CefRequest::HeaderMap& GetHeaders() const { return headers_; }
private:
private:
// Describes the current page that the tab represents. This is not relevant
// for all tab contents types.
int32 page_id_;
@@ -97,7 +98,7 @@ private:
// version as possible.
class BrowserNavigationController {
public:
BrowserNavigationController(CefBrowserImpl* browser);
explicit BrowserNavigationController(CefBrowserImpl* browser);
~BrowserNavigationController();
void Reset();
@@ -186,8 +187,7 @@ class BrowserNavigationController {
void UpdateMaxPageID();
// List of NavigationEntry for this tab
typedef std::vector< linked_ptr<BrowserNavigationEntry> > NavigationEntryList;
typedef NavigationEntryList::iterator NavigationEntryListIterator;
typedef ScopedVector<BrowserNavigationEntry> NavigationEntryList;
NavigationEntryList entries_;
// An entry we haven't gotten a response for yet. This will be discarded
@@ -208,5 +208,4 @@ class BrowserNavigationController {
DISALLOW_EVIL_CONSTRUCTORS(BrowserNavigationController);
};
#endif // _BROWSER_NAVIGATION_CONTROLLER_H
#endif // CEF_LIBCEF_BROWSER_NAVIGATION_CONTROLLER_H_

View File

@@ -31,7 +31,7 @@ class BrowserRequestContext : public net::URLRequestContext {
net::HttpCache::Mode cache_mode,
bool no_proxy);
virtual const std::string& GetUserAgent(const GURL& url) const;
virtual const std::string& GetUserAgent(const GURL& url) const OVERRIDE;
void SetAcceptAllCookies(bool accept_all_cookies);
bool AcceptAllCookies();

View File

@@ -0,0 +1,45 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/browser_request_context_proxy.h"
#include "libcef/browser_impl.h"
#include "libcef/browser_request_context.h"
#include "libcef/cookie_store_proxy.h"
BrowserRequestContextProxy::BrowserRequestContextProxy(
BrowserRequestContext* context,
CefBrowserImpl* browser)
: context_(context),
browser_(browser) {
DCHECK(context_);
DCHECK(browser_);
// Cookie store that proxies to the browser implementation.
set_cookie_store(new CefCookieStoreProxy(browser_));
// All other values refer to the global request context.
set_net_log(context->net_log());
set_host_resolver(context->host_resolver());
set_cert_verifier(context->cert_verifier());
set_origin_bound_cert_service(context->origin_bound_cert_service());
set_fraudulent_certificate_reporter(
context->fraudulent_certificate_reporter());
set_proxy_service(context->proxy_service());
set_ssl_config_service(context->ssl_config_service());
set_http_auth_handler_factory(context->http_auth_handler_factory());
set_http_transaction_factory(context->http_transaction_factory());
set_ftp_transaction_factory(context->ftp_transaction_factory());
set_network_delegate(context->network_delegate());
set_http_server_properties(context->http_server_properties());
set_transport_security_state(context->transport_security_state());
set_accept_charset(context->accept_charset());
set_accept_language(context->accept_language());
set_referrer_charset(context->referrer_charset());
set_job_factory(context->job_factory());
}
const std::string&
BrowserRequestContextProxy::GetUserAgent(const GURL& url) const {
return context_->GetUserAgent(url);
}

View File

@@ -0,0 +1,30 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_
#define CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_
#pragma once
#include <string>
#include "include/cef.h"
#include "net/url_request/url_request_context.h"
class BrowserRequestContext;
class CefBrowserImpl;
// A basic URLRequestContext that only provides an in-memory cookie store.
class BrowserRequestContextProxy : public net::URLRequestContext {
public:
// Use an in-memory cache
BrowserRequestContextProxy(BrowserRequestContext* context,
CefBrowserImpl* browser);
virtual const std::string& GetUserAgent(const GURL& url) const OVERRIDE;
private:
BrowserRequestContext* context_;
CefRefPtr<CefBrowserImpl> browser_;
};
#endif // CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_

View File

@@ -20,10 +20,6 @@
// \ -> net::URLRequest
// o-------> SyncRequestProxy (synchronous case)
// -> net::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-
@@ -31,19 +27,19 @@
// 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_webkit_glue.h"
#include "browser_impl.h"
#include "cef_context.h"
#include "cef_process.h"
#include "cef_process_io_thread.h"
#include "external_protocol_handler.h"
#include "request_impl.h"
#include "response_impl.h"
#include "http_header_utils.h"
#include "libcef/browser_resource_loader_bridge.h"
#include "libcef/browser_appcache_system.h"
#include "libcef/browser_request_context.h"
#include "libcef/browser_socket_stream_bridge.h"
#include "libcef/browser_webkit_glue.h"
#include "libcef/browser_impl.h"
#include "libcef/cef_context.h"
#include "libcef/cef_process.h"
#include "libcef/cef_process_io_thread.h"
#include "libcef/external_protocol_handler.h"
#include "libcef/request_impl.h"
#include "libcef/response_impl.h"
#include "libcef/http_header_utils.h"
#include "base/bind.h"
#include "base/file_path.h"
@@ -51,13 +47,11 @@
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/synchronization/waitable_event.h"
#include "base/time.h"
#include "base/timer.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "net/base/auth.h"
#include "net/base/cookie_store.h"
#include "net/base/file_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
@@ -114,40 +108,40 @@ struct RequestParams {
static const int kUpdateUploadProgressIntervalMsec = 100;
class ExtraRequestInfo : public net::URLRequest::UserData {
public:
ExtraRequestInfo(CefBrowser* browser, ResourceType::Type resource_type)
public:
ExtraRequestInfo(CefBrowserImpl* browser, ResourceType::Type resource_type)
: browser_(browser),
resource_type_(resource_type),
allow_download_(resource_type == ResourceType::MAIN_FRAME ||
resource_type == ResourceType::SUB_FRAME)
{ }
allow_download_(resource_type == ResourceType::MAIN_FRAME ||
resource_type == ResourceType::SUB_FRAME) {
}
// The browser pointer is guaranteed to be valid for the lifespan of the
// request. The pointer will be NULL in cases where the request was
// initiated via the CefWebURLRequest API instead of by a browser window.
CefBrowser* browser() const { return browser_; }
CefBrowserImpl* browser() const { return browser_; }
// Identifies the type of resource, such as subframe, media, etc.
ResourceType::Type resource_type() const { return resource_type_; }
bool allow_download() const { return allow_download_; }
private:
CefBrowser* browser_;
private:
CefBrowserImpl* browser_;
ResourceType::Type resource_type_;
bool allow_download_;
};
// Used to intercept redirect requests.
class RequestInterceptor : public net::URLRequest::Interceptor
{
public:
class RequestInterceptor : public net::URLRequest::Interceptor {
public:
RequestInterceptor() {
REQUIRE_IOT();
net::URLRequestJobManager::GetInstance()->RegisterRequestInterceptor(this);
}
~RequestInterceptor() {
REQUIRE_IOT();
net::URLRequestJobManager::GetInstance()->UnregisterRequestInterceptor(this);
net::URLRequestJobManager::GetInstance()->
UnregisterRequestInterceptor(this);
}
virtual net::URLRequestJob* MaybeIntercept(net::URLRequest* request)
@@ -195,14 +189,13 @@ class RequestProxy : public net::URLRequest::Delegate,
public base::RefCountedThreadSafe<RequestProxy> {
public:
// Takes ownership of the params.
RequestProxy(CefRefPtr<CefBrowser> browser)
explicit RequestProxy(CefRefPtr<CefBrowserImpl> browser)
: download_to_file_(false),
buf_(new net::IOBuffer(kDataSize)),
browser_(browser),
last_upload_position_(0),
defers_loading_(false),
defers_loading_want_read_(false)
{
defers_loading_want_read_(false) {
}
void DropPeer() {
@@ -221,7 +214,7 @@ class RequestProxy : public net::URLRequest::Delegate,
}
void Cancel() {
if(download_handler_.get()) {
if (download_handler_.get()) {
// WebKit will try to cancel the download but we won't allow it.
return;
}
@@ -270,13 +263,12 @@ class RequestProxy : public net::URLRequest::Delegate,
void NotifyReceivedResponse(const ResourceResponseInfo& info,
const GURL& url, bool allow_download) {
if (browser_.get() && info.headers.get()) {
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefRequestHandler> handler;
if (client.get())
handler = client->GetRequestHandler();
if (handler.get()) {
CefRefPtr<CefResponse> response = new CefResponseImpl();
// Transfer response headers
@@ -294,7 +286,7 @@ class RequestProxy : public net::URLRequest::Delegate,
response->SetStatus(info.headers->response_code());
}
response->SetMimeType(info.mime_type);
handler->OnResourceResponse(browser_, url.spec(), response,
handler->OnResourceResponse(browser_.get(), url.spec(), response,
content_filter_);
std::string content_disposition;
@@ -307,7 +299,7 @@ class RequestProxy : public net::URLRequest::Delegate,
content_disposition, info.charset, "", info.mime_type,
"download");
CefRefPtr<CefDownloadHandler> dl_handler;
if (handler->GetDownloadHandler(browser_, info.mime_type,
if (handler->GetDownloadHandler(browser_.get(), info.mime_type,
filename, info.content_length,
dl_handler)) {
download_handler_ = dl_handler;
@@ -340,9 +332,9 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefStreamReader> resourceStream;
if(content_filter_.get())
if (content_filter_.get())
content_filter_->ProcessData(buf_copy.get(), bytes_read, resourceStream);
if (resourceStream.get()) {
// The filter made some changes to the data in the buffer.
resourceStream->Seek(0, SEEK_END);
@@ -377,13 +369,12 @@ class RequestProxy : public net::URLRequest::Delegate,
void NotifyCompletedRequest(const net::URLRequestStatus& status,
const std::string& security_info,
const base::Time& complete_time) {
// Drain the content filter of all remaining data
// Drain the content filter of all remaining data
if (content_filter_.get()) {
CefRefPtr<CefStreamReader> remainder;
content_filter_->Drain(remainder);
if(remainder.get()) {
if (remainder.get()) {
remainder->Seek(0, SEEK_END);
long size = remainder->Tell();
if (size) {
@@ -433,8 +424,8 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefRequestHandler> handler;
if (client.get())
handler = client->GetRequestHandler();
if(handler.get()) {
if (handler.get()) {
// Build the request object for passing to the handler
CefRefPtr<CefRequest> request(new CefRequestImpl());
CefRequestImpl* requestimpl =
@@ -443,16 +434,16 @@ class RequestProxy : public net::URLRequest::Delegate,
std::string originalUrl(params->url.spec());
requestimpl->SetURL(originalUrl);
requestimpl->SetMethod(params->method);
// Transfer request headers
CefRequest::HeaderMap headerMap;
HttpHeaderUtils::ParseHeaders(params->headers, headerMap);
headerMap.insert(std::make_pair("Referrer", params->referrer.spec()));
headerMap.insert(std::make_pair("Referer", params->referrer.spec()));
requestimpl->SetHeaderMap(headerMap);
// Transfer post data, if any
scoped_refptr<net::UploadData> upload = params->upload;
if(upload.get()) {
if (upload.get()) {
CefRefPtr<CefPostData> postdata(new CefPostDataImpl());
static_cast<CefPostDataImpl*>(postdata.get())->Set(*upload.get());
requestimpl->SetPostData(postdata);
@@ -465,15 +456,15 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefStreamReader> resourceStream;
CefRefPtr<CefResponse> response(new CefResponseImpl());
handled = handler->OnBeforeResourceLoad(browser_, request, redirectUrl,
resourceStream, response, loadFlags);
handled = handler->OnBeforeResourceLoad(browser_.get(), request,
redirectUrl, resourceStream, response, loadFlags);
if (!handled) {
// Observe URL from request.
const std::string requestUrl(request->GetURL());
if(requestUrl != originalUrl) {
if (requestUrl != originalUrl)
params->url = GURL(requestUrl);
redirectUrl.clear(); // Request URL trumps redirect URL
}
else if (!redirectUrl.empty())
params->url = GURL(std::string(redirectUrl));
// Observe method from request.
params->method = request->GetMethod();
@@ -481,9 +472,10 @@ class RequestProxy : public net::URLRequest::Delegate,
// Observe headers from request.
request->GetHeaderMap(headerMap);
CefString referrerStr;
referrerStr.FromASCII("Referrer");
CefRequest::HeaderMap::iterator referrer = headerMap.find(referrerStr);
if(referrer == headerMap.end()) {
referrerStr.FromASCII("Referer");
CefRequest::HeaderMap::iterator referrer =
headerMap.find(referrerStr);
if (referrer == headerMap.end()) {
params->referrer = GURL();
} else {
params->referrer = GURL(std::string(referrer->second));
@@ -493,7 +485,7 @@ class RequestProxy : public net::URLRequest::Delegate,
// Observe post data from request.
CefRefPtr<CefPostData> postData = request->GetPostData();
if(postData.get()) {
if (postData.get()) {
params->upload = new net::UploadData();
static_cast<CefPostDataImpl*>(postData.get())->Get(*params->upload);
}
@@ -504,14 +496,6 @@ class RequestProxy : public net::URLRequest::Delegate,
OnCompletedRequest(
URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED),
std::string(), base::Time());
} else if (!redirectUrl.empty()) {
// redirect to the specified URL
handled = true;
params->url = GURL(std::string(redirectUrl));
ResourceResponseInfo info;
bool defer_redirect;
OnReceivedRedirect(params->url, info, &defer_redirect);
} else if (resourceStream.get()) {
// load from the provided resource stream
handled = true;
@@ -549,8 +533,8 @@ class RequestProxy : public net::URLRequest::Delegate,
if (!handled && ResourceType::IsFrame(params->request_type) &&
!net::URLRequest::IsHandledProtocol(params->url.scheme())) {
bool allow_os_execution = false;
handled = handler->OnProtocolExecution(browser_, params->url.spec(),
allow_os_execution);
handled = handler->OnProtocolExecution(browser_.get(),
params->url.spec(), allow_os_execution);
if (!handled && allow_os_execution &&
ExternalProtocolHandler::HandleExternalProtocol(params->url)) {
handled = true;
@@ -559,13 +543,13 @@ class RequestProxy : public net::URLRequest::Delegate,
if (handled) {
OnCompletedRequest(
URLRequestStatus(URLRequestStatus::HANDLED_EXTERNALLY, net::OK),
std::string(), base::Time());
std::string(), base::Time());
}
}
}
}
if(!handled) {
if (!handled) {
// Might need to resolve the blob references in the upload data.
if (params->upload) {
_Context->request_context()->blob_storage_controller()->
@@ -582,7 +566,8 @@ class RequestProxy : public net::URLRequest::Delegate,
request_->SetExtraRequestHeaders(headers);
request_->set_load_flags(params->load_flags);
request_->set_upload(params->upload.get());
request_->set_context(_Context->request_context());
request_->set_context(browser_.get() ? browser_->request_context_proxy() :
_Context->request_context());
request_->SetUserData(kCefUserData,
new ExtraRequestInfo(browser_.get(), params->request_type));
BrowserAppCacheSystem::SetExtraRequestInfo(
@@ -652,10 +637,10 @@ class RequestProxy : public net::URLRequest::Delegate,
return;
}
if(resource_stream_.get()) {
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) {
if (bytes_read > 0) {
OnReceivedData(bytes_read);
} else {
Done();
@@ -699,7 +684,7 @@ class RequestProxy : public net::URLRequest::Delegate,
const GURL& simulated_url) {
GURL url;
bool allow_download(false);
if (request_.get()){
if (request_.get()) {
url = request_->url();
ExtraRequestInfo* info =
static_cast<ExtraRequestInfo*>(request_->GetUserData(kCefUserData));
@@ -721,7 +706,7 @@ class RequestProxy : public net::URLRequest::Delegate,
&RequestProxy::NotifyDownloadedData, this, bytes_read));
return;
}
owner_loop_->PostTask(FROM_HERE, base::Bind(
&RequestProxy::NotifyReceivedData, this, bytes_read));
}
@@ -766,9 +751,9 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
if(handler.get()) {
if (handler.get()) {
CefString username, password;
if (handler->GetAuthCredentials(browser_,
if (handler->GetAuthCredentials(browser_.get(),
auth_info->is_proxy,
auth_info->challenger.host(),
auth_info->challenger.port(),
@@ -833,12 +818,12 @@ class RequestProxy : public net::URLRequest::Delegate,
// Helpers and data:
void Done() {
if(resource_stream_.get()) {
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()) {
} else if (request_.get()) {
if (upload_progress_timer_.IsRunning()) {
MaybeUpdateUploadProgress();
upload_progress_timer_.Stop();
@@ -915,7 +900,7 @@ class RequestProxy : public net::URLRequest::Delegate,
// read buffer for async IO
scoped_refptr<net::IOBuffer> buf_;
CefRefPtr<CefBrowser> browser_;
CefRefPtr<CefBrowserImpl> browser_;
MessageLoop* owner_loop_;
@@ -945,7 +930,7 @@ class RequestProxy : public net::URLRequest::Delegate,
class SyncRequestProxy : public RequestProxy {
public:
explicit SyncRequestProxy(CefRefPtr<CefBrowser> browser,
explicit SyncRequestProxy(CefRefPtr<CefBrowserImpl> browser,
ResourceLoaderBridge::SyncLoadResponse* result)
: RequestProxy(browser), result_(result), event_(true, false) {
}
@@ -990,7 +975,7 @@ class SyncRequestProxy : public RequestProxy {
const base::Time& complete_time) {
if (download_to_file_)
file_stream_.Close();
result_->status = status;
event_.Signal();
}
@@ -1012,7 +997,7 @@ class SyncRequestProxy : public RequestProxy {
class ResourceLoaderBridgeImpl : public ResourceLoaderBridge {
public:
ResourceLoaderBridgeImpl(CefRefPtr<CefBrowser> browser,
ResourceLoaderBridgeImpl(CefRefPtr<CefBrowserImpl> browser,
const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info)
: browser_(browser),
params_(new RequestParams),
@@ -1110,7 +1095,7 @@ class ResourceLoaderBridgeImpl : public ResourceLoaderBridge {
virtual void UpdateRoutingId(int new_routing_id) OVERRIDE {}
private:
CefRefPtr<CefBrowser> browser_;
CefRefPtr<CefBrowserImpl> browser_;
// Ownership of params_ is transfered to the proxy when the proxy is created.
scoped_ptr<RequestParams> params_;
@@ -1120,61 +1105,6 @@ class ResourceLoaderBridgeImpl : public ResourceLoaderBridge {
RequestProxy* proxy_;
};
//-----------------------------------------------------------------------------
class CookieSetter : public base::RefCountedThreadSafe<CookieSetter> {
public:
void Set(const GURL& url, const std::string& cookie) {
REQUIRE_IOT();
net::CookieStore* cookie_store =
_Context->request_context()->cookie_store();
if (cookie_store) {
cookie_store->SetCookieWithOptionsAsync(
url, cookie, net::CookieOptions(),
net::CookieStore::SetCookiesCallback());
}
}
private:
friend class base::RefCountedThreadSafe<CookieSetter>;
~CookieSetter() {}
};
class CookieGetter : public base::RefCountedThreadSafe<CookieGetter> {
public:
CookieGetter() : event_(false, false) {
}
void Get(const GURL& url) {
REQUIRE_IOT();
net::CookieStore* cookie_store =
_Context->request_context()->cookie_store();
if (cookie_store) {
cookie_store->GetCookiesWithOptionsAsync(
url, net::CookieOptions(),
base::Bind(&CookieGetter::OnGetCookies, this));
}
}
std::string GetResult() {
event_.Wait();
return result_;
}
private:
void OnGetCookies(const std::string& cookie_line) {
result_ = cookie_line;
event_.Signal();
}
friend class base::RefCountedThreadSafe<CookieGetter>;
~CookieGetter() {}
base::WaitableEvent event_;
std::string result_;
};
} // anonymous namespace
//-----------------------------------------------------------------------------
@@ -1190,37 +1120,7 @@ webkit_glue::ResourceLoaderBridge* BrowserResourceLoaderBridge::Create(
//-----------------------------------------------------------------------------
// 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<CookieSetter> cookie_setter = new CookieSetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieSetter::Set, cookie_setter.get(), 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<CookieGetter> cookie_getter = new CookieGetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieGetter::Get, cookie_getter.get(), url));
// Blocks until the result is available.
return cookie_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, base::Bind(
&BrowserRequestContext::SetAcceptAllCookies,
_Context->request_context().get(), accept_all_cookies));
}
// static
CefRefPtr<CefBrowser> BrowserResourceLoaderBridge::GetBrowserForRequest(
CefRefPtr<CefBrowserImpl> BrowserResourceLoaderBridge::GetBrowserForRequest(
net::URLRequest* request) {
REQUIRE_IOT();
ExtraRequestInfo* extra_info =
@@ -1230,13 +1130,13 @@ CefRefPtr<CefBrowser> BrowserResourceLoaderBridge::GetBrowserForRequest(
return NULL;
}
//static
// static
scoped_refptr<base::MessageLoopProxy>
BrowserResourceLoaderBridge::GetCacheThread() {
return CefThread::GetMessageLoopProxyForThread(CefThread::FILE);
}
//static
// static
net::URLRequest::Interceptor*
BrowserResourceLoaderBridge::CreateRequestInterceptor() {
return new RequestInterceptor();

View File

@@ -3,31 +3,27 @@
// 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
#ifndef CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_
#define CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_
#pragma once
#include <string>
#include "include/cef.h"
#include "base/message_loop_proxy.h"
#include "net/url_request/url_request.h"
#include "webkit/glue/resource_loader_bridge.h"
#include <string>
class CefBrowserImpl;
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);
// Return the CefBrowser associated with the specified request. The browser
// will be NULL in cases where the request was initiated using the
// CefWebURLRequest API.
static CefRefPtr<CefBrowser> GetBrowserForRequest(net::URLRequest* request);
static CefRefPtr<CefBrowserImpl> GetBrowserForRequest(
net::URLRequest* request);
// Creates a ResourceLoaderBridge instance.
static webkit_glue::ResourceLoaderBridge* Create(
@@ -40,5 +36,5 @@ class BrowserResourceLoaderBridge {
static net::URLRequest::Interceptor* CreateRequestInterceptor();
};
#endif // _BROWSER_RESOURCE_LOADER_BRIDGE_H
#endif // CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_

View File

@@ -0,0 +1,54 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "content/public/browser/browser_thread.h"
#include "libcef/cef_thread.h"
// Stub implementations to convert BrowserThread calls to CefThread.
namespace content {
namespace {
int GetCefId(BrowserThread::ID browser_id) {
switch (browser_id) {
case BrowserThread::UI:
return CefThread::UI;
case BrowserThread::IO:
return CefThread::IO;
case BrowserThread::FILE:
return CefThread::FILE;
default:
break;
}
// The specified BrowserThread ID is not supported.
NOTREACHED();
return -1;
}
} // namespace
// static
bool BrowserThread::PostTask(ID identifier,
const tracked_objects::Location& from_here,
const base::Closure& task) {
int cef_id = GetCefId(identifier);
if (cef_id < 0)
return false;
return CefThread::PostTask(static_cast<CefThread::ID>(cef_id), from_here,
task);
}
// static
bool BrowserThread::CurrentlyOn(ID identifier) {
int cef_id = GetCefId(identifier);
if (cef_id < 0)
return false;
return CefThread::CurrentlyOn(static_cast<CefThread::ID>(cef_id));
}
} // namespace content

View File

@@ -1,25 +1,139 @@
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Copyright (c) 2012 the Chromium Embedded Framework authors.
// Portions copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser_webcookiejar_impl.h"
#include "browser_resource_loader_bridge.h"
#include "libcef/browser_webcookiejar_impl.h"
#include <string>
#include "libcef/browser_resource_loader_bridge.h"
#include "libcef/browser_impl.h"
#include "libcef/cookie_manager_impl.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "base/synchronization/waitable_event.h"
#include "net/base/cookie_store.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h"
using WebKit::WebString;
using WebKit::WebURL;
namespace {
net::CookieStore* GetCookieStore(CefRefPtr<CefBrowserImpl> browser) {
scoped_refptr<net::CookieStore> cookie_store;
if (browser) {
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
if (handler.get()) {
// Get the manager from the handler.
CefRefPtr<CefCookieManager> manager =
handler->GetCookieManager(browser.get(),
browser->pending_url().spec());
if (manager.get()) {
cookie_store =
reinterpret_cast<CefCookieManagerImpl*>(
manager.get())->cookie_monster();
}
}
}
}
if (!cookie_store) {
// Use the global cookie store.
cookie_store = _Context->request_context()->cookie_store();
}
DCHECK(cookie_store);
return cookie_store;
}
class CookieSetter : public base::RefCountedThreadSafe<CookieSetter> {
public:
void Set(CefRefPtr<CefBrowserImpl> browser,
const GURL& url,
const std::string& cookie) {
REQUIRE_IOT();
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore(browser);
cookie_store->SetCookieWithOptionsAsync(
url, cookie, net::CookieOptions(),
net::CookieStore::SetCookiesCallback());
}
private:
friend class base::RefCountedThreadSafe<CookieSetter>;
~CookieSetter() {}
};
class CookieGetter : public base::RefCountedThreadSafe<CookieGetter> {
public:
CookieGetter() : event_(false, false) {
}
void Get(CefRefPtr<CefBrowserImpl> browser, const GURL& url) {
REQUIRE_IOT();
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore(browser);
cookie_store->GetCookiesWithOptionsAsync(
url, net::CookieOptions(),
base::Bind(&CookieGetter::OnGetCookies, this));
}
std::string GetResult() {
event_.Wait();
return result_;
}
private:
void OnGetCookies(const std::string& cookie_line) {
result_ = cookie_line;
event_.Signal();
}
friend class base::RefCountedThreadSafe<CookieGetter>;
~CookieGetter() {}
base::WaitableEvent event_;
std::string result_;
};
} // namespace
BrowserWebCookieJarImpl::BrowserWebCookieJarImpl()
: browser_(NULL) {
}
BrowserWebCookieJarImpl::BrowserWebCookieJarImpl(CefBrowserImpl* browser)
: browser_(browser) {
}
void BrowserWebCookieJarImpl::setCookie(const WebURL& url,
const WebURL& first_party_for_cookies,
const WebString& value) {
BrowserResourceLoaderBridge::SetCookie(
url, first_party_for_cookies, value.utf8());
const WebURL& first_party_for_cookies,
const WebString& value) {
GURL gurl = url;
std::string cookie = value.utf8();
// Proxy to IO thread to synchronize w/ network loading.
scoped_refptr<CookieSetter> cookie_setter = new CookieSetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieSetter::Set, cookie_setter.get(), browser_, gurl, cookie));
}
WebString BrowserWebCookieJarImpl::cookies(
const WebURL& url,
const WebURL& first_party_for_cookies) {
return WebString::fromUTF8(
BrowserResourceLoaderBridge::GetCookies(url, first_party_for_cookies));
GURL gurl = url;
// Proxy to IO thread to synchronize w/ network loading.
scoped_refptr<CookieGetter> cookie_getter = new CookieGetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieGetter::Get, cookie_getter.get(), browser_, gurl));
// Blocks until the result is available.
return WebString::fromUTF8(cookie_getter->GetResult());
}

View File

@@ -1,22 +1,36 @@
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Copyright (c) 2012 the Chromium Embedded Framework authors.
// Portions copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef _BROWSER_SIMPLE_WEBCOOKIEJAR_IMPL_H
#define _BROWSER_SIMPLE_WEBCOOKIEJAR_IMPL_H
#ifndef CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_
#define CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_
#pragma once
// TODO(darin): WebCookieJar.h is missing a WebString.h include!
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCookieJar.h"
namespace net {
class CookieStore;
}
class CefBrowserImpl;
// Handles cookie requests from the renderer.
class BrowserWebCookieJarImpl : public WebKit::WebCookieJar {
public:
// WebKit::WebCookieJar methods:
BrowserWebCookieJarImpl();
explicit BrowserWebCookieJarImpl(CefBrowserImpl* browser);
// WebKit::WebCookieJar methods.
virtual void setCookie(
const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies,
const WebKit::WebString& cookie);
virtual WebKit::WebString cookies(
const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies);
private:
// May be NULL for the global implementation.
CefBrowserImpl* browser_;
};
#endif // _BROWSER_SIMPLE_WEBCOOKIEJAR_IMPL_H
#endif // CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_

View File

@@ -40,23 +40,25 @@ using WebKit::WebFrameImpl;
namespace webkit_glue {
#if !defined(OS_MACOSX)
FilePath GetResourcesFilePath() {
FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
return pak_dir;
}
#endif // !defined(OS_MACOSX)
void InitializeResourceBundle(const std::string& locale) {
// Load chrome.pak (on Mac) and the appropiate locale pack.
const std::string loaded_locale =
ResourceBundle::InitSharedInstance(locale);
CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
#if defined(OS_WIN)
// Explicitly load chrome.pak on Windows. Use the module (libcef.dll)
// directory to match the location of the locale folder.
FilePath chrome_pack_path;
PathService::Get(base::DIR_MODULE, &chrome_pack_path);
chrome_pack_path = chrome_pack_path.AppendASCII("chrome.pak");
if (file_util::PathExists(chrome_pack_path))
ResourceBundle::AddDataPackToSharedInstance(chrome_pack_path);
else
NOTREACHED() << "Could not load chrome.pak";
#endif
// Load devtools_resources.pak if it exists.
FilePath pack_path =
GetResourcesFilePath().AppendASCII("devtools_resources.pak");
if (file_util::PathExists(pack_path))
ResourceBundle::AddDataPackToSharedInstance(pack_path);
}
void CleanupResourceBundle() {

View File

@@ -20,9 +20,7 @@ namespace webkit {
struct WebPluginInfo;
}
#if defined(OS_MACOSX)
class FilePath;
#endif
namespace webkit_glue {
@@ -34,14 +32,11 @@ void CaptureWebViewBitmap(HWND mainWnd, WebKit::WebView* webview,
// Save a bitmap image to file, providing optional alternative data in |lpBits|
BOOL SaveBitmapToFile(HBITMAP hBmp, HDC hDC, LPCTSTR file, LPBYTE lpBits);
#endif
FilePath GetResourcesFilePath();
void InitializeResourceBundle(const std::string& locale);
void CleanupResourceBundle();
#if defined(OS_MACOSX)
FilePath GetResourcesFilePath();
#endif
string16 GetLocalizedString(int message_id);
base::StringPiece GetDataResource(int resource_id);

View File

@@ -12,6 +12,7 @@
#undef LOG
#include "base/file_util.h"
#include "base/logging.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
@@ -21,24 +22,17 @@
namespace webkit_glue {
// Helper method for getting the path to the CEF resources directory.
FilePath GetResourcesFilePath() {
FilePath path;
// We need to know if we're bundled or not to know which path to use.
if (base::mac::AmIBundled()) {
PathService::Get(base::DIR_EXE, &path);
path = path.Append(FilePath::kParentDirectory);
return path.AppendASCII("Resources");
} else {
// TODO(port): Allow the embedder to customize the resource path.
PathService::Get(base::DIR_SOURCE_ROOT, &path);
path = path.AppendASCII("src");
path = path.AppendASCII("cef");
path = path.AppendASCII("tests");
path = path.AppendASCII("cefclient");
return path.AppendASCII("res");
}
// Start out with the path to the running executable.
FilePath execPath;
PathService::Get(base::FILE_EXE, &execPath);
// Get the main bundle path.
FilePath bundlePath = base::mac::GetAppBundlePath(execPath);
return bundlePath.Append(FILE_PATH_LITERAL("Contents"))
.Append(FILE_PATH_LITERAL("Resources"));
}
base::StringPiece GetDataResource(int resource_id) {

View File

@@ -38,10 +38,10 @@ BrowserWebKitInit::BrowserWebKitInit()
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableIndexedDatabase(true);
WebKit::WebRuntimeFeatures::enableFileSystem(true);
WebKit::WebRuntimeFeatures::enableGeolocation(true);
// TODO: Enable these once the implementation supports it.
WebKit::WebRuntimeFeatures::enableNotifications(false);
WebKit::WebRuntimeFeatures::enableGeolocation(false);
WebKit::WebRuntimeFeatures::enableSpeechInput(false);
WebKit::WebRuntimeFeatures::enableTouch(false);
WebKit::WebRuntimeFeatures::enableDeviceMotion(false);

View File

@@ -7,18 +7,22 @@
// 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_file_system.h"
#include "browser_impl.h"
#include "browser_navigation_controller.h"
#include "browser_webkit_glue.h"
#include "browser_webstoragenamespace_impl.h"
#include "browser_zoom_map.h"
#include "cef_context.h"
#include "dom_document_impl.h"
#include "request_impl.h"
#include "v8_impl.h"
#include "libcef/browser_webview_delegate.h"
#include <algorithm>
#include "libcef/browser_appcache_system.h"
#include "libcef/browser_file_system.h"
#include "libcef/browser_impl.h"
#include "libcef/browser_navigation_controller.h"
#include "libcef/browser_webkit_glue.h"
#include "libcef/browser_webstoragenamespace_impl.h"
#include "libcef/browser_zoom_map.h"
#include "libcef/cef_context.h"
#include "libcef/cef_process_ui_thread.h"
#include "libcef/dom_document_impl.h"
#include "libcef/request_impl.h"
#include "libcef/v8_impl.h"
#include "base/debug/trace_event.h"
#include "base/file_util.h"
@@ -72,8 +76,8 @@
#include "webkit/plugins/npapi/webplugin_impl.h"
#if defined(OS_WIN)
#include "browser_drag_delegate_win.h"
#include "web_drop_target_win.h"
#include "libcef/browser_drag_delegate_win.h"
#include "libcef/web_drop_target_win.h"
#endif
using appcache::WebApplicationCacheHostImpl;
@@ -124,8 +128,7 @@ namespace {
int next_page_id_ = 1;
void TranslatePopupFeatures(const WebWindowFeatures& webKitFeatures,
CefPopupFeatures& features)
{
CefPopupFeatures& features) {
features.x = static_cast<int>(webKitFeatures.x);
features.xSet = webKitFeatures.xSet;
features.y = static_cast<int>(webKitFeatures.y);
@@ -143,13 +146,13 @@ void TranslatePopupFeatures(const WebWindowFeatures& webKitFeatures,
features.resizable = webKitFeatures.resizable;
features.fullscreen = webKitFeatures.fullscreen;
features.dialog = webKitFeatures.dialog;
features.dialog = webKitFeatures.dialog;
features.additionalFeatures = NULL;
if (webKitFeatures.additionalFeatures.size() > 0)
if (webKitFeatures.additionalFeatures.size() > 0)
features.additionalFeatures = cef_string_list_alloc();
CefString str;
for(unsigned int i = 0; i < webKitFeatures.additionalFeatures.size(); ++i) {
for (unsigned int i = 0; i < webKitFeatures.additionalFeatures.size(); ++i) {
str = string16(webKitFeatures.additionalFeatures[i]);
cef_string_list_append(features.additionalFeatures, str.GetStruct());
}
@@ -201,7 +204,7 @@ void BrowserWebViewDelegate::didAddMessageToConsole(
}
}
if(!handled) {
if (!handled) {
logging::LogMessage("CONSOLE", 0).stream() << "\""
<< messageStr
<< ",\" source: "
@@ -289,8 +292,8 @@ bool BrowserWebViewDelegate::runFileChooser(
WebKit::WebFileChooserCompletion* chooser_completion) {
// Support file open dialog.
std::vector<FilePath> file_names;
if(!ShowFileChooser(file_names, params.multiSelect, params.title,
if (!ShowFileChooser(file_names, params.multiSelect, params.title,
webkit_glue::WebStringToFilePath(params.initialValue))) {
return false;
}
@@ -309,7 +312,7 @@ void BrowserWebViewDelegate::runModalAlertDialog(
WebFrame* frame, const WebString& message) {
CefString messageStr = string16(message);
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefJSDialogHandler> handler;
if (client.get())
@@ -328,7 +331,7 @@ bool BrowserWebViewDelegate::runModalConfirmDialog(
CefString messageStr = string16(message);
bool retval = false;
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefJSDialogHandler> handler;
if (client.get())
@@ -349,12 +352,12 @@ bool BrowserWebViewDelegate::runModalPromptDialog(
CefString messageStr = string16(message);
CefString defaultValueStr = string16(default_value);
CefString actualValueStr;
if(actual_value)
if (actual_value)
actualValueStr = string16(*actual_value);
bool retval = false;
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefJSDialogHandler> handler;
if (client.get())
@@ -370,7 +373,7 @@ bool BrowserWebViewDelegate::runModalPromptDialog(
}
if (actual_value)
*actual_value = string16(actualValueStr);
return retval;
}
@@ -392,8 +395,7 @@ void BrowserWebViewDelegate::setKeyboardFocusURL(const WebKit::WebURL& url) {
}
void BrowserWebViewDelegate::setToolTipText(
const WebString& text, WebTextDirection hint)
{
const WebString& text, WebTextDirection hint) {
CefString tooltipStr = string16(text);
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
@@ -474,23 +476,46 @@ int BrowserWebViewDelegate::historyForwardListCount() {
- current_index - 1;
}
WebKit::WebGeolocationClient* BrowserWebViewDelegate::geolocationClient() {
return browser_->UIT_GetGeolocationClient();
}
// WebPermissionClient -------------------------------------------------------
bool BrowserWebViewDelegate::allowScriptExtension(
WebKit::WebFrame* frame,
const WebKit::WebString& extensionName,
int extensionGroup) {
bool allowExtension = true;
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefPermissionHandler> handler = client->GetPermissionHandler();
if (handler.get()) {
CefString extensionNameStr = string16(extensionName);
allowExtension = !handler->OnBeforeScriptExtensionLoad(
browser_, browser_->UIT_GetCefFrame(frame), extensionNameStr);
}
}
return allowExtension;
}
// WebPluginPageDelegate -----------------------------------------------------
WebCookieJar* BrowserWebViewDelegate::GetCookieJar() {
return WebKit::webKitPlatformSupport()->cookieJar();
return &cookie_jar_;
}
// WebWidgetClient -----------------------------------------------------------
void BrowserWebViewDelegate::didInvalidateRect(const WebRect& rect) {
if (WebWidgetHost* host = GetWidgetHost())
host->DidInvalidateRect(rect);
host->InvalidateRect(rect);
}
void BrowserWebViewDelegate::didScrollRect(int dx, int dy,
const WebRect& clip_rect) {
if (WebWidgetHost* host = GetWidgetHost())
host->DidScrollRect(dx, dy, clip_rect);
host->ScrollRect(dx, dy, clip_rect);
}
void BrowserWebViewDelegate::scheduleComposite() {
@@ -577,7 +602,7 @@ WebPlugin* BrowserWebViewDelegate::createPlugin(
NULL, &plugins, &mime_types);
if (plugins.empty())
return NULL;
#if defined(OS_MACOSX)
// Mac does not supported windowed plugins.
bool force_windowless = true;
@@ -656,6 +681,10 @@ WebApplicationCacheHost* BrowserWebViewDelegate::createApplicationCacheHost(
return BrowserAppCacheSystem::CreateApplicationCacheHost(client);
}
WebKit::WebCookieJar* BrowserWebViewDelegate::cookieJar(WebFrame* frame) {
return &cookie_jar_;
}
void BrowserWebViewDelegate::willClose(WebFrame* frame) {
browser_->UIT_BeforeFrameClosed(frame);
}
@@ -690,7 +719,7 @@ WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation(
req->SetMethod(string16(request.httpMethod()));
const WebKit::WebHTTPBody& httpBody = request.httpBody();
if(!httpBody.isNull()) {
if (!httpBody.isNull()) {
CefRefPtr<CefPostData> postdata(CefPostData::CreatePostData());
static_cast<CefPostDataImpl*>(postdata.get())->Set(httpBody);
req->SetPostData(postdata);
@@ -698,7 +727,7 @@ WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation(
CefRequest::HeaderMap map;
CefRequestImpl::GetHeaderMap(request, map);
if(map.size() > 0)
if (map.size() > 0)
static_cast<CefRequestImpl*>(req.get())->SetHeaderMap(map);
cef_handler_navtype_t navType;
@@ -711,7 +740,7 @@ WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation(
bool handled = handler->OnBeforeBrowse(browser_,
browser_->UIT_GetCefFrame(frame), req, navType,
is_redirect);
if(handled)
if (handled)
return WebKit::WebNavigationPolicyIgnore;
}
}
@@ -750,6 +779,12 @@ WebURLError BrowserWebViewDelegate::cancelledError(
void BrowserWebViewDelegate::didCreateDataSource(
WebFrame* frame, WebDataSource* ds) {
ds->setExtraData(pending_extra_data_.release());
if (frame->parent() == 0) {
GURL url = ds->request().url();
if (!url.is_empty())
browser_->set_pending_url(url);
}
}
void BrowserWebViewDelegate::didStartProvisionalLoad(WebFrame* frame) {
@@ -771,7 +806,7 @@ void BrowserWebViewDelegate::didFailProvisionalLoad(
const WebDataSource* failed_ds = frame->provisionalDataSource();
BrowserExtraData* extra_data =
static_cast<BrowserExtraData*>(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.
@@ -782,7 +817,7 @@ void BrowserWebViewDelegate::didFailProvisionalLoad(
CefString errorStr;
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefLoadHandler> handler = client->GetLoadHandler();
@@ -794,8 +829,8 @@ void BrowserWebViewDelegate::didFailProvisionalLoad(
std::string(failed_ds->request().url().spec().data()), errorStr);
}
}
if(handled && !errorStr.empty()) {
if (handled && !errorStr.empty()) {
error_text = errorStr;
} else {
error_text = base::StringPrintf("Error %d when loading url %s",
@@ -938,22 +973,22 @@ void BrowserWebViewDelegate::didChangeContentsSize(
}
void BrowserWebViewDelegate::reportFindInPageMatchCount(
int request_id, int count, bool final_update)
{
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)
{
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, bool create,
WebFrame* frame, WebFileSystem::Type type,
long long size, // NOLINT(runtime/int)
bool create,
WebFileSystemCallbacks* callbacks) {
BrowserFileSystem* fileSystem = static_cast<BrowserFileSystem*>(
WebKit::webKitPlatformSupport()->fileSystem());
@@ -969,13 +1004,17 @@ BrowserWebViewDelegate::BrowserWebViewDelegate(CefBrowserImpl* browser)
browser_(browser),
page_id_(-1),
last_page_id_updated_(-1),
#if defined(OS_WIN)
destroy_on_drag_end_(false),
#endif
smart_insert_delete_enabled_(true),
#if defined(OS_WIN)
select_trailing_whitespace_enabled_(true),
#else
select_trailing_whitespace_enabled_(false),
#endif
block_redirects_(false) {
block_redirects_(false),
cookie_jar_(browser) {
}
BrowserWebViewDelegate::~BrowserWebViewDelegate() {
@@ -985,7 +1024,7 @@ void BrowserWebViewDelegate::Reset() {
// Do a little placement new dance...
CefBrowserImpl* browser = browser_;
this->~BrowserWebViewDelegate();
new (this) BrowserWebViewDelegate(browser);
new (this)BrowserWebViewDelegate(browser); // NOLINT(whitespace/parens)
}
void BrowserWebViewDelegate::SetSmartInsertDeleteEnabled(bool enabled) {
@@ -1016,8 +1055,7 @@ void BrowserWebViewDelegate::WaitForPolicyDelegate() {
// Private methods -----------------------------------------------------------
bool BrowserWebViewDelegate::OnKeyboardEvent(
const WebKit::WebKeyboardEvent& event, bool isAfterJavaScript)
{
const WebKit::WebKeyboardEvent& event, bool isAfterJavaScript) {
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefKeyboardHandler> handler;
if (client.get())
@@ -1027,10 +1065,10 @@ bool BrowserWebViewDelegate::OnKeyboardEvent(
CefKeyboardHandler::KeyEventType eventType;
switch (event.type) {
case WebKeyboardEvent::RawKeyDown:
case WebKeyboardEvent::RawKeyDown:
eventType = KEYEVENT_RAWKEYDOWN;
break;
case WebKeyboardEvent::KeyDown:
case WebKeyboardEvent::KeyDown:
eventType = KEYEVENT_KEYDOWN;
break;
case WebKeyboardEvent::KeyUp:
@@ -1048,8 +1086,7 @@ bool BrowserWebViewDelegate::OnKeyboardEvent(
}
void BrowserWebViewDelegate::ShowStatus(const WebString& text,
cef_handler_statustype_t type)
{
cef_handler_statustype_t type) {
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefDisplayHandler> handler = client->GetDisplayHandler();
@@ -1064,7 +1101,7 @@ void BrowserWebViewDelegate::LocationChangeDone(WebFrame* frame) {
CefRefPtr<CefClient> client = browser_->GetClient();
if (!client.get())
return;
bool is_main_frame = (frame->parent() == 0);
if (is_main_frame) {
CefString title = browser_->UIT_GetTitle();
@@ -1144,6 +1181,9 @@ void BrowserWebViewDelegate::UpdateURL(WebFrame* frame) {
entry->SetURL(request.url());
}
// Update attributes of the CefFrame if it currently exists.
browser_->UIT_UpdateCefFrame(frame);
bool is_main_frame = (frame->parent() == 0);
CefRefPtr<CefClient> client = browser_->GetClient();
@@ -1186,13 +1226,13 @@ void BrowserWebViewDelegate::UpdateSessionHistory(WebFrame* frame) {
if (page_id_ == -1)
return;
BrowserNavigationEntry* entry = static_cast<BrowserNavigationEntry*>(
browser_->UIT_GetNavigationController()->GetEntryWithPageID(page_id_));
BrowserNavigationEntry* entry =
browser_->UIT_GetNavigationController()->GetEntryWithPageID(page_id_);
if (!entry)
return;
WebView* view = browser_->UIT_GetWebView();
if (!view)
if (!view)
return;
const WebHistoryItem& history_item = view->mainFrame()->previousHistoryItem();
@@ -1207,30 +1247,30 @@ bool BrowserWebViewDelegate::OnBeforeMenu(
int& edit_flags, int& type_flags) {
// Populate the edit flags values.
edit_flags = data.editFlags;
if(browser_->UIT_CanGoBack())
if (browser_->UIT_CanGoBack())
edit_flags |= MENU_CAN_GO_BACK;
if(browser_->UIT_CanGoForward())
if (browser_->UIT_CanGoForward())
edit_flags |= MENU_CAN_GO_FORWARD;
// Populate the type flags values.
type_flags = MENUTYPE_NONE;
if(!data.pageURL.isEmpty())
if (!data.pageURL.isEmpty())
type_flags |= MENUTYPE_PAGE;
if(!data.frameURL.isEmpty())
if (!data.frameURL.isEmpty())
type_flags |= MENUTYPE_FRAME;
if(!data.linkURL.isEmpty())
if (!data.linkURL.isEmpty())
type_flags |= MENUTYPE_LINK;
if(data.mediaType == WebContextMenuData::MediaTypeImage)
if (data.mediaType == WebContextMenuData::MediaTypeImage)
type_flags |= MENUTYPE_IMAGE;
if(!data.selectedText.isEmpty())
if (!data.selectedText.isEmpty())
type_flags |= MENUTYPE_SELECTION;
if(data.isEditable)
if (data.isEditable)
type_flags |= MENUTYPE_EDITABLE;
if(data.isSpellCheckingEnabled && !data.misspelledWord.isEmpty())
if (data.isSpellCheckingEnabled && !data.misspelledWord.isEmpty())
type_flags |= MENUTYPE_MISSPELLED_WORD;
if(data.mediaType == WebContextMenuData::MediaTypeVideo)
if (data.mediaType == WebContextMenuData::MediaTypeVideo)
type_flags |= MENUTYPE_VIDEO;
if(data.mediaType == WebContextMenuData::MediaTypeAudio)
if (data.mediaType == WebContextMenuData::MediaTypeAudio)
type_flags |= MENUTYPE_AUDIO;
CefRefPtr<CefClient> client = browser_->GetClient();
@@ -1271,6 +1311,6 @@ bool BrowserWebViewDelegate::OnBeforeMenu(
if (handler->OnBeforeMenu(browser_, menuInfo))
return true;
}
return false;
}

View File

@@ -3,17 +3,23 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// BrowserWebViewDelegate class:
// 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
#ifndef CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_
#define CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_
#pragma once
#include <map>
#include <string>
#include <vector>
#include "libcef/browser_navigation_controller.h"
#include "libcef/browser_webcookiejar_impl.h"
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
@@ -21,15 +27,19 @@
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileChooserParams.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebFileSystem.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrameClient.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPermissionClient.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebViewClient.h"
#include "webkit/glue/webcursor.h"
#include "webkit/plugins/npapi/webplugin_page_delegate.h"
#include "browser_navigation_controller.h"
#if defined(TOOLKIT_USES_GTK)
#include <gdk/gdk.h> // NOLINT(build/include_order)
#endif
#if defined(OS_MACOSX)
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenuInfo.h"
#include "external_popup_menu_mac.h"
#include "libcef/external_popup_menu_mac.h"
#endif
#if defined(OS_WIN)
@@ -37,10 +47,6 @@ class BrowserDragDelegate;
class WebDropTarget;
#endif
#if defined(TOOLKIT_USES_GTK)
#include <gdk/gdk.h>
#endif
class CefBrowserImpl;
class GURL;
class WebWidgetHost;
@@ -48,6 +54,7 @@ class FilePath;
class BrowserWebViewDelegate : public WebKit::WebViewClient,
public WebKit::WebFrameClient,
public WebKit::WebPermissionClient,
public webkit::npapi::WebPluginPageDelegate,
public base::SupportsWeakPtr<BrowserWebViewDelegate> {
public:
@@ -116,6 +123,7 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
virtual void navigateBackForwardSoon(int offset) OVERRIDE;
virtual int historyBackListCount() OVERRIDE;
virtual int historyForwardListCount() OVERRIDE;
virtual WebKit::WebGeolocationClient* geolocationClient() OVERRIDE;
// WebKit::WebWidgetClient
virtual void didInvalidateRect(const WebKit::WebRect& rect) OVERRIDE;
@@ -143,6 +151,7 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
virtual WebKit::WebApplicationCacheHost* createApplicationCacheHost(
WebKit::WebFrame* frame, WebKit::WebApplicationCacheHostClient* client)
OVERRIDE;
virtual WebKit::WebCookieJar* cookieJar(WebKit::WebFrame*) OVERRIDE;
virtual void willClose(WebKit::WebFrame*) OVERRIDE;
virtual void loadURLExternally(
WebKit::WebFrame*, const WebKit::WebURLRequest&,
@@ -191,10 +200,16 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
virtual void openFileSystem(
WebKit::WebFrame* frame,
WebKit::WebFileSystem::Type type,
long long size,
long long size, // NOLINT(runtime/int)
bool create,
WebKit::WebFileSystemCallbacks* callbacks) OVERRIDE;
// WebKit::WebPermissionClient
virtual bool allowScriptExtension(
WebKit::WebFrame*,
const WebKit::WebString& extensionName,
int extensionGroup) OVERRIDE;
// webkit_glue::WebPluginPageDelegate
virtual webkit::npapi::WebPluginDelegate* CreatePluginDelegate(
const FilePath& file_path,
@@ -227,7 +242,9 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
BrowserDragDelegate* drag_delegate() { return drag_delegate_.get(); }
WebDropTarget* drop_target() { return drop_target_.get(); }
#endif
void set_destroy_on_drag_end(bool val) { destroy_on_drag_end_ = val; }
#endif // defined(OS_WIN)
void set_pending_extra_data(BrowserExtraData* extra_data) {
pending_extra_data_.reset(extra_data);
@@ -279,9 +296,9 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
CefString* result);
// Called to show the file chooser dialog.
bool ShowFileChooser(std::vector<FilePath>& file_names,
const bool multi_select,
const WebKit::WebString& title,
bool ShowFileChooser(std::vector<FilePath>& file_names,
const bool multi_select,
const WebKit::WebString& title,
const FilePath& default_file);
// Called to show status messages.
@@ -306,7 +323,7 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
int& type_flags);
private:
// Causes navigation actions just printout the intended navigation instead
// 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_;
@@ -332,6 +349,7 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
// Classes needed by drag and drop.
scoped_refptr<BrowserDragDelegate> drag_delegate_;
scoped_refptr<WebDropTarget> drop_target_;
bool destroy_on_drag_end_;
#endif
#if defined(OS_LINUX)
@@ -359,7 +377,9 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
std::string edit_command_name_;
std::string edit_command_value_;
BrowserWebCookieJarImpl cookie_jar_;
DISALLOW_COPY_AND_ASSIGN(BrowserWebViewDelegate);
};
#endif // _BROWSER_WEBVIEW_DELEGATE_H
#endif // CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_

View File

@@ -2,10 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser_webview_delegate.h"
#import "browser_webview_mac.h"
#include "browser_impl.h"
#include "drag_data_impl.h"
#include "libcef/browser_webview_delegate.h"
#import "libcef/browser_webview_mac.h"
#include "libcef/browser_impl.h"
#include "libcef/drag_data_impl.h"
#import "include/cef_application_mac.h"
#import <Cocoa/Cocoa.h>
@@ -48,6 +48,7 @@ namespace {
void AddMenuItem(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefMenuHandler> handler,
NSMenu* menu,
id target,
cef_menu_id_t menuId,
const std::string& label,
bool enabled) {
@@ -65,7 +66,8 @@ void AddMenuItem(CefRefPtr<CefBrowser> browser,
NSMenuItem* item =
[[[NSMenuItem alloc] initWithTitle:str
action:enabled?@selector(menuItemSelected:):nil
keyEquivalent:@""] autorelease];
keyEquivalent:@""] autorelease];
[item setTarget:target];
[item setTag:menuId];
[menu addItem:item];
}
@@ -77,6 +79,46 @@ void AddMenuSeparator(NSMenu* menu) {
} // namespace
@interface BrowserMenuDelegate : NSObject <NSMenuDelegate> {
@private
CefRefPtr<CefBrowserImpl> browser_;
}
- (id)initWithBrowser:(CefBrowserImpl*)browser;
- (void)menuItemSelected:(id)sender;
@end
@implementation BrowserMenuDelegate
- (id)initWithBrowser:(CefBrowserImpl*)browser {
self = [super init];
if (self)
browser_ = browser;
return self;
}
// Called when a context menu item is selected by the user.
- (void)menuItemSelected:(id)sender {
cef_menu_id_t menuId = static_cast<cef_menu_id_t>([sender tag]);
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefMenuHandler> handler = client->GetMenuHandler();
if (handler.get()) {
// Ask the handler if it wants to handle the action.
handled = handler->OnMenuAction(browser_.get(), menuId);
}
}
if(!handled) {
// Execute the action.
browser_->UIT_HandleAction(menuId, browser_->GetFocusedFrame());
}
}
@end
// WebViewClient --------------------------------------------------------------
@@ -102,12 +144,21 @@ void BrowserWebViewDelegate::showContextMenu(
if (!host)
return;
BrowserWebView *view = static_cast<BrowserWebView*>(host->view_handle());
NSView *view = browser_->UIT_GetMainWndHandle();
if (!view)
return;
NSWindow* window = [view window];
NSPoint position = [window mouseLocationOutsideOfEventStream];
int screenX = -1;
int screenY = -1;
NSPoint mouse_pt = {data.mousePosition.x, data.mousePosition.y};
if (!browser_->IsWindowRenderingDisabled()) {
mouse_pt = [window mouseLocationOutsideOfEventStream];
NSPoint screen_pt = [window convertBaseToScreen:mouse_pt];
screenX = screen_pt.x;
screenY = screen_pt.y;
}
int edit_flags = 0;
int type_flags = 0;
@@ -117,7 +168,7 @@ void BrowserWebViewDelegate::showContextMenu(
MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
// Give the client a chance to handle the menu.
if (OnBeforeMenu(data, position.x, position.y, edit_flags, type_flags))
if (OnBeforeMenu(data, mouse_pt.x, mouse_pt.y, edit_flags, type_flags))
return;
CefRefPtr<CefClient> client = browser_->GetClient();
@@ -125,43 +176,57 @@ void BrowserWebViewDelegate::showContextMenu(
if (client.get())
handler = client->GetMenuHandler();
if (client.get() && browser_->IsWindowRenderingDisabled()) {
// Retrieve the screen coordinates.
CefRefPtr<CefRenderHandler> render_handler = client->GetRenderHandler();
if (!render_handler.get() ||
!render_handler->GetScreenPoint(browser_, mouse_pt.x, mouse_pt.y,
screenX, screenY)) {
return;
}
}
BrowserMenuDelegate* delegate =
[[[BrowserMenuDelegate alloc] initWithBrowser:browser_] autorelease];
// Build the correct default context menu
if (type_flags & MENUTYPE_EDITABLE) {
menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
AddMenuItem(browser_, handler, menu, MENU_ID_UNDO, "Undo",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_UNDO, "Undo",
!!(edit_flags & MENU_CAN_UNDO));
AddMenuItem(browser_, handler, menu, MENU_ID_REDO, "Redo",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_REDO, "Redo",
!!(edit_flags & MENU_CAN_REDO));
AddMenuSeparator(menu);
AddMenuItem(browser_, handler, menu, MENU_ID_CUT, "Cut",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_CUT, "Cut",
!!(edit_flags & MENU_CAN_CUT));
AddMenuItem(browser_, handler, menu, MENU_ID_COPY, "Copy",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_COPY, "Copy",
!!(edit_flags & MENU_CAN_COPY));
AddMenuItem(browser_, handler, menu, MENU_ID_PASTE, "Paste",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_PASTE, "Paste",
!!(edit_flags & MENU_CAN_PASTE));
AddMenuItem(browser_, handler, menu, MENU_ID_DELETE, "Delete",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_DELETE, "Delete",
!!(edit_flags & MENU_CAN_DELETE));
AddMenuSeparator(menu);
AddMenuItem(browser_, handler, menu, MENU_ID_SELECTALL, "Select All",
!!(edit_flags & MENU_CAN_SELECT_ALL));
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_SELECTALL,
"Select All", !!(edit_flags & MENU_CAN_SELECT_ALL));
} else if(type_flags & MENUTYPE_SELECTION) {
menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
AddMenuItem(browser_, handler, menu, MENU_ID_COPY, "Copy",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_COPY, "Copy",
!!(edit_flags & MENU_CAN_COPY));
} else if(type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) {
menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
AddMenuItem(browser_, handler, menu, MENU_ID_NAV_BACK, "Back",
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_NAV_BACK, "Back",
!!(edit_flags & MENU_CAN_GO_BACK));
AddMenuItem(browser_, handler, menu, MENU_ID_NAV_FORWARD, "Forward",
!!(edit_flags & MENU_CAN_GO_FORWARD));
AddMenuItem(browser_, handler, menu, delegate, MENU_ID_NAV_FORWARD,
"Forward", !!(edit_flags & MENU_CAN_GO_FORWARD));
// TODO(port): Enable the below menu items when supported.
//AddMenuSeparator(menu);
//AddMenuItem(browser_, handler, menu, MENU_ID_PRINT, "Print", true);
//AddMenuItem(browser_, handler, menu, MENU_ID_VIEWSOURCE, "View Source",
// true);
//AddMenuItem(browser_, handler, menu, delegate, MENU_ID_PRINT, "Print",
// true);
//AddMenuItem(browser_, handler, menu, delegate, MENU_ID_VIEWSOURCE,
// "View Source", true);
}
if (!menu)
@@ -169,21 +234,24 @@ void BrowserWebViewDelegate::showContextMenu(
// Synthesize an event for the click, as there is no certainty that
// [NSApp currentEvent] will return a valid event.
NSPoint screen_pt = {screenX, screenY};
NSPoint window_pt = [window convertScreenToBase:screen_pt];
NSEvent* currentEvent = [NSApp currentEvent];
NSTimeInterval eventTime = [currentEvent timestamp];
NSEvent* clickEvent = [NSEvent mouseEventWithType:NSRightMouseDown
location:position
modifierFlags:NSRightMouseDownMask
timestamp:eventTime
windowNumber:[window windowNumber]
context:nil
eventNumber:0
clickCount:1
pressure:1.0];
location:window_pt
modifierFlags:NSRightMouseDownMask
timestamp:eventTime
windowNumber:[window windowNumber]
context:nil
eventNumber:0
clickCount:1
pressure:1.0];
// Menu selection events go to the BrowserWebView.
[menu setDelegate:view];
// Menu selection events go to the BrowserMenuDelegate.
[menu setDelegate:delegate];
// Show the menu.
[NSMenu popUpContextMenu:menu
@@ -194,18 +262,43 @@ void BrowserWebViewDelegate::showContextMenu(
// WebWidgetClient ------------------------------------------------------------
void BrowserWebViewDelegate::show(WebNavigationPolicy policy) {
DCHECK(this != browser_->UIT_GetPopupDelegate());
}
void BrowserWebViewDelegate::didChangeCursor(const WebCursorInfo& cursor_info) {
NSCursor* ns_cursor = WebCursor(cursor_info).GetCursor();
[ns_cursor set];
if (!browser_->IsWindowRenderingDisabled()) {
[ns_cursor set];
} else {
// Notify the handler of cursor change.
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefRenderHandler> handler = client->GetRenderHandler();
if (handler.get())
handler->OnCursorChange(browser_, ns_cursor);
}
}
}
WebRect BrowserWebViewDelegate::windowRect() {
if (WebWidgetHost* host = GetWidgetHost()) {
NSView *view = host->view_handle();
NSRect rect = [view frame];
return gfx::Rect(NSRectToCGRect(rect));
if (!browser_->IsWindowRenderingDisabled()) {
NSView *view = host->view_handle();
NSRect rect = [view frame];
return gfx::Rect(NSRectToCGRect(rect));
} else {
// Retrieve the view rectangle from the handler.
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefRenderHandler> handler = client->GetRenderHandler();
if (handler.get()) {
CefRect rect(0, 0, 0, 0);
if (handler->GetViewRect(browser_, rect))
return WebRect(rect.x, rect.y, rect.width, rect.height);
}
}
}
}
return WebRect();
}
@@ -213,6 +306,8 @@ WebRect BrowserWebViewDelegate::windowRect() {
void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) {
if (this == browser_->UIT_GetWebViewDelegate()) {
// TODO(port): Set the window rectangle.
} else if (this == browser_->UIT_GetPopupDelegate()) {
NOTREACHED();
}
}
@@ -257,7 +352,8 @@ void BrowserWebViewDelegate::startDragging(const WebDragData& data,
WebDragOperationsMask mask,
const WebImage& image,
const WebPoint& image_offset) {
if (browser_->settings().drag_drop_disabled) {
if (browser_->settings().drag_drop_disabled ||
browser_->IsWindowRenderingDisabled()) {
browser_->UIT_GetWebView()->dragSourceSystemDragEnded();
return;
}
@@ -303,10 +399,17 @@ void BrowserWebViewDelegate::startDragging(const WebDragData& data,
ns_image = gfx::SkBitmapToNSImageWithColorSpace(bitmap, color_space);
}
NSPoint offset = NSPointFromCGPoint(gfx::Point(image_offset).ToCGPoint());
// Keep a reference to the NSView so that it won't be destroyed until after
// the drag operation has completed.
[view retain];
[view startDragWithDropData:drop_data
dragOperationMask:static_cast<NSDragOperation>(mask)
image:ns_image
offset:offset];
[view release];
}
void BrowserWebViewDelegate::runModal() {
@@ -332,15 +435,30 @@ webkit::npapi::WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate(
void BrowserWebViewDelegate::CreatedPluginWindow(
gfx::PluginWindowHandle handle) {
if (browser_->IsWindowRenderingDisabled()) {
WebViewHost* host = browser_->UIT_GetWebViewHost();
if (host)
host->AddWindowedPlugin(handle);
}
}
void BrowserWebViewDelegate::WillDestroyPluginWindow(
gfx::PluginWindowHandle handle) {
if (browser_->IsWindowRenderingDisabled()) {
WebViewHost* host = browser_->UIT_GetWebViewHost();
if (host)
host->RemoveWindowedPlugin(handle);
}
}
void BrowserWebViewDelegate::DidMovePlugin(
const webkit::npapi::WebPluginGeometry& move) {
// TODO(port): add me once plugins work.
if (browser_->IsWindowRenderingDisabled()) {
WebViewHost* host = browser_->UIT_GetWebViewHost();
if (host) {
host->MoveWindowedPlugin(move);
}
}
}
// Protected methods ----------------------------------------------------------

View File

@@ -7,18 +7,19 @@
// as the WebViewDelegate for the BrowserWebHost. The host is expected to
// have initialized a MessageLoop before these methods are called.
#include "browser_drag_delegate_win.h"
#include "browser_navigation_controller.h"
#include "browser_impl.h"
#include "browser_webview_delegate.h"
#include "cef_context.h"
#include "drag_data_impl.h"
#include "web_drop_target_win.h"
#include "libcef/browser_webview_delegate.h"
#include <objidl.h>
#include <shlobj.h>
#include <shlwapi.h>
#include "libcef/browser_drag_delegate_win.h"
#include "libcef/browser_navigation_controller.h"
#include "libcef/browser_impl.h"
#include "libcef/cef_context.h"
#include "libcef/drag_data_impl.h"
#include "libcef/web_drop_target_win.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "net/base/net_errors.h"
@@ -66,8 +67,7 @@ void AddMenuItem(CefRefPtr<CefBrowser> browser,
cef_menu_id_t menuId,
const wchar_t* label,
bool enabled,
std::list<std::wstring>& label_list)
{
std::list<std::wstring>& label_list) {
CefString actual_label(label);
if (handler.get()) {
// Let the handler change the label if desired,
@@ -91,8 +91,7 @@ void AddMenuItem(CefRefPtr<CefBrowser> browser,
InsertMenuItem(menu, -1, TRUE, &mii);
}
void AddMenuSeparator(HMENU menu)
{
void AddMenuSeparator(HMENU menu) {
MENUITEMINFO mii;
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_FTYPE;
@@ -101,7 +100,7 @@ void AddMenuSeparator(HMENU menu)
InsertMenuItem(menu, -1, TRUE, &mii);
}
} // namespace
} // namespace
// WebViewClient --------------------------------------------------------------
@@ -120,7 +119,7 @@ void BrowserWebViewDelegate::show(WebNavigationPolicy) {
// Restore the window and bring it to the top if the window is currently
// visible.
HWND root = GetAncestor(browser_->UIT_GetMainWndHandle(), GA_ROOT);
if(IsWindowVisible(root)) {
if (IsWindowVisible(root)) {
ShowWindow(root, SW_SHOWNORMAL);
SetWindowPos(root, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
@@ -145,7 +144,7 @@ void BrowserWebViewDelegate::didChangeCursor(const WebCursorInfo& cursor_info) {
if (WebWidgetHost* host = GetWidgetHost()) {
current_cursor_.InitFromCursorInfo(cursor_info);
HMODULE hModule = ::GetModuleHandle(L"libcef.dll");
if(!hModule)
if (!hModule)
hModule = ::GetModuleHandle(NULL);
HCURSOR hCursor = current_cursor_.GetCursor(hModule);
@@ -195,7 +194,7 @@ void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) {
} else {
browser_->set_popup_rect(rect);
browser_->UIT_GetPopupHost()->SetSize(rect.width, rect.height);
// Notify the handler of popup size change.
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
@@ -268,9 +267,9 @@ void BrowserWebViewDelegate::runModal() {
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefLifeSpanHandler> handler;
if( client.get())
if (client.get())
handler = client->GetLifeSpanHandler();
bool handled(false);
if (handler.get()) {
@@ -293,7 +292,7 @@ void BrowserWebViewDelegate::runModal() {
}
DWORD dwStyle = ::GetWindowLong(child, GWL_STYLE);
DWORD dwNewStyle = dwStyle | WS_POPUP;
if(dwStyle != dwNewStyle)
if (dwStyle != dwNewStyle)
::SetWindowLong(child, GWL_STYLE, dwNewStyle);
}
@@ -313,8 +312,7 @@ void BrowserWebViewDelegate::runModal() {
webkit::npapi::WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate(
const FilePath& file_path,
const std::string& mime_type)
{
const std::string& mime_type) {
WebViewHost* host = browser_->UIT_GetWebViewHost();
if (!host)
return NULL;
@@ -379,7 +377,7 @@ void BrowserWebViewDelegate::WillDestroyPluginWindow(
void BrowserWebViewDelegate::DidMovePlugin(
const webkit::npapi::WebPluginGeometry& move) {
unsigned long flags = 0;
UINT flags = 0;
if (move.rects_valid) {
HRGN hrgn = ::CreateRectRgn(move.clip_rect.x(),
@@ -417,10 +415,9 @@ void BrowserWebViewDelegate::DidMovePlugin(
}
void BrowserWebViewDelegate::showContextMenu(
WebFrame* frame, const WebContextMenuData& data)
{
WebFrame* frame, const WebContextMenuData& data) {
int screenX = -1, screenY = -1;
POINT mouse_pt = {data.mousePosition.x, data.mousePosition.y};
if (!browser_->IsWindowRenderingDisabled()) {
// Perform the conversion to screen coordinates only if window rendering is
@@ -451,7 +448,7 @@ void BrowserWebViewDelegate::showContextMenu(
if (client.get() && browser_->IsWindowRenderingDisabled()) {
// Retrieve the screen coordinates.
CefRefPtr<CefRenderHandler> render_handler = client->GetRenderHandler();
if (render_handler.get() &&
if (!render_handler.get() ||
!render_handler->GetScreenPoint(browser_, mouse_pt.x, mouse_pt.y,
screenX, screenY)) {
return;
@@ -477,11 +474,11 @@ void BrowserWebViewDelegate::showContextMenu(
AddMenuSeparator(menu);
AddMenuItem(browser_, handler, menu, MENU_ID_SELECTALL, L"Select All",
!!(edit_flags & MENU_CAN_SELECT_ALL), label_list);
} else if(type_flags & MENUTYPE_SELECTION) {
} else if (type_flags & MENUTYPE_SELECTION) {
menu = CreatePopupMenu();
AddMenuItem(browser_, handler, menu, MENU_ID_COPY, L"Copy",
!!(edit_flags & MENU_CAN_COPY), label_list);
} else if(type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) {
} else if (type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) {
menu = CreatePopupMenu();
AddMenuItem(browser_, handler, menu, MENU_ID_NAV_BACK, L"Back",
!!(edit_flags & MENU_CAN_GO_BACK), label_list);
@@ -511,7 +508,7 @@ void BrowserWebViewDelegate::showContextMenu(
handled = handler->OnMenuAction(browser_, menuId);
}
if(!handled) {
if (!handled) {
// Execute the action
browser_->UIT_HandleAction(menuId, browser_->GetFocusedFrame());
}
@@ -536,11 +533,13 @@ void BrowserWebViewDelegate::EndDragging() {
if (browser_->UIT_GetWebView())
browser_->UIT_GetWebView()->dragSourceSystemDragEnded();
drag_delegate_ = NULL;
if (destroy_on_drag_end_)
browser_->UIT_DestroyBrowser();
}
void BrowserWebViewDelegate::ShowJavaScriptAlert(WebFrame* webframe,
const CefString& message)
{
const CefString& message) {
// TODO(cef): Think about what we should be showing as the prompt caption
std::wstring messageStr = message;
std::wstring titleStr = browser_->UIT_GetTitle();
@@ -549,8 +548,7 @@ void BrowserWebViewDelegate::ShowJavaScriptAlert(WebFrame* webframe,
}
bool BrowserWebViewDelegate::ShowJavaScriptConfirm(WebFrame* webframe,
const CefString& message)
{
const CefString& message) {
// TODO(cef): Think about what we should be showing as the prompt caption
std::wstring messageStr = message;
std::wstring titleStr = browser_->UIT_GetTitle();
@@ -562,19 +560,16 @@ bool BrowserWebViewDelegate::ShowJavaScriptConfirm(WebFrame* webframe,
bool BrowserWebViewDelegate::ShowJavaScriptPrompt(WebFrame* webframe,
const CefString& message,
const CefString& default_value,
CefString* result)
{
CefString* result) {
// TODO(cef): Implement a default prompt dialog
return false;
}
namespace
{
namespace {
// from chrome/browser/views/shell_dialogs_win.cc
bool RunOpenFileDialog(const std::wstring& filter, HWND owner, FilePath* path)
{
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
@@ -603,8 +598,7 @@ bool RunOpenFileDialog(const std::wstring& filter, HWND owner, FilePath* path)
}
bool RunOpenMultiFileDialog(const std::wstring& filter, HWND owner,
std::vector<FilePath>* paths)
{
std::vector<FilePath>* paths) {
OPENFILENAME ofn;
// We must do this otherwise the ofn's FlagsEx may be initialized to random
@@ -655,15 +649,14 @@ bool RunOpenMultiFileDialog(const std::wstring& filter, HWND owner,
return success;
}
}
} // namespace
bool BrowserWebViewDelegate::ShowFileChooser(std::vector<FilePath>& file_names,
const bool multi_select,
const WebKit::WebString& title,
const FilePath& default_file)
{
bool BrowserWebViewDelegate::ShowFileChooser(std::vector<FilePath>& file_names,
const bool multi_select,
const WebKit::WebString& title,
const FilePath& default_file) {
bool result = false;
if (multi_select) {
result = RunOpenMultiFileDialog(L"", browser_->UIT_GetMainWndHandle(),
&file_names);

View File

@@ -2,9 +2,16 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CEF_LIBCEF_BROWSER_WEBVIEW_MAC_H_
#define CEF_LIBCEF_BROWSER_WEBVIEW_MAC_H_
#pragma once
#import <Cocoa/Cocoa.h>
#import "base/mac/cocoa_protocols.h"
#include "base/string16.h"
#include "base/memory/scoped_nsobject.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCompositionUnderline.h"
#include <Vector>
class CefBrowserImpl;
@class WebDragSource;
@@ -14,13 +21,45 @@ struct WebDropData;
// A view to wrap the WebCore view and help it live in a Cocoa world. The
// (rough) equivalent of Apple's WebView.
@interface BrowserWebView : NSView <NSMenuDelegate> {
@interface BrowserWebView : NSView<NSTextInputClient> {
@private
CefBrowserImpl *browser_; // weak
NSTrackingArea *trackingArea_;
CefBrowserImpl* browser_; // weak
NSTrackingArea* trackingArea_;
bool is_in_setfocus_;
scoped_nsobject<WebDragSource> dragSource_;
scoped_nsobject<WebDropTarget> dropTarget_;
// Represents the input-method attributes supported by this object.
scoped_nsobject<NSArray> validAttributesForMarkedText_;
// Indicates if we are currently handling a key down event.
BOOL handlingKeyDown_;
// Indicates if there is any marked text.
BOOL hasMarkedText_;
// Indicates if unmarkText is called or not when handling a keyboard
// event.
BOOL unmarkTextCalled_;
// The range of current marked text inside the whole content of the DOM node
// being edited.
// TODO(suzhe): This is currently a fake value, as we do not support accessing
// the whole content yet.
NSRange markedRange_;
// The selected range, cached from a message sent by the renderer.
NSRange selectedRange_;
// Text to be inserted which was generated by handling a key down event.
string16 textToBeInserted_;
// Marked text which was generated by handling a key down event.
string16 markedText_;
// Underline information of the |markedText_|.
std::vector<WebKit::WebCompositionUnderline> underlines_;
}
- (void)mouseDown:(NSEvent *)theEvent;
@@ -41,9 +80,6 @@ struct WebDropData;
- (BOOL)isOpaque;
- (void)setFrame:(NSRect)frameRect;
// Called when a context menu item is selected by the user.
- (void)menuItemSelected:(id)sender;
// Register this WebView as a drag/drop target.
- (void)registerDragDrop;
@@ -53,6 +89,9 @@ struct WebDropData;
image:(NSImage*)image
offset:(NSPoint)offset;
@property (nonatomic, assign) CefBrowserImpl *browser;
@property (nonatomic, assign) CefBrowserImpl* browser;
@property (nonatomic, assign) bool in_setfocus;
@end
#endif // CEF_LIBCEF_BROWSER_WEBVIEW_MAC_H_

View File

@@ -12,15 +12,71 @@
#import "webwidget_host.h"
#import "base/memory/scoped_ptr.h"
#import "base/string_util.h"
#import "base/sys_string_conversions.h"
#import "third_party/WebKit/Source/WebKit/chromium/public/mac/WebInputEventFactory.h"
#import "third_party/WebKit/Source/WebKit/chromium/public/mac/WebSubstringUtil.h"
#import "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#import "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#import "third_party/mozilla/NSPasteboard+Utils.h"
#import "third_party/skia/include/core/SkRegion.h"
#import "ui/gfx/rect.h"
using WebKit::WebColor;
using WebKit::WebCompositionUnderline;
using WebKit::WebInputEvent;
using WebKit::WebInputEventFactory;
using WebKit::WebKeyboardEvent;
using WebKit::WebPoint;
using WebKit::WebRect;
using WebKit::WebString;
using WebKit::WebSubstringUtil;
// This code is copied from
// content/browser/renderer_host/render_widget_host_mac
namespace {
WebColor WebColorFromNSColor(NSColor *color) {
CGFloat r, g, b, a;
[color getRed:&r green:&g blue:&b alpha:&a];
return
std::max(0, std::min(static_cast<int>(lroundf(255.0f * a)), 255)) << 24 |
std::max(0, std::min(static_cast<int>(lroundf(255.0f * r)), 255)) << 16 |
std::max(0, std::min(static_cast<int>(lroundf(255.0f * g)), 255)) << 8 |
std::max(0, std::min(static_cast<int>(lroundf(255.0f * b)), 255));
}
// Extract underline information from an attributed string. Mostly copied from
// third_party/WebKit/Source/WebKit/mac/WebView/WebHTMLView.mm
void ExtractUnderlines(
NSAttributedString* string,
std::vector<WebCompositionUnderline>* underlines) {
int length = [[string string] length];
int i = 0;
while (i < length) {
NSRange range;
NSDictionary* attrs = [string attributesAtIndex:i
longestEffectiveRange:&range
inRange:NSMakeRange(i, length - i)];
if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) {
WebColor color = SK_ColorBLACK;
if (NSColor *colorAttr =
[attrs objectForKey:NSUnderlineColorAttributeName]) {
color = WebColorFromNSColor(
[colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]);
}
underlines->push_back(WebCompositionUnderline(
range.location, NSMaxRange(range), color, [style intValue] > 1));
}
i = range.location + range.length;
}
}
} // namespace
@implementation BrowserWebView
@synthesize browser = browser_;
@synthesize in_setfocus = is_in_setfocus_;
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
@@ -139,12 +195,83 @@
browser_->UIT_GetWebViewHost()->MouseEvent(theEvent);
}
// This code is mostly copied and adapted from
// content/browser/renderer_host/render_widget_host_mac
- (void)keyDown:(NSEvent *)theEvent {
// Records the current marked text state, so that we can know if the marked
// text was deleted or not after handling the key down event.
BOOL oldHasMarkedText = hasMarkedText_;
// We check if the marked text has one or less characters and a delete key is
// pressed. In such cases, we want to cancel IME composition and delete the
// marked character, so we dispatch the event directly to WebKit.
if (hasMarkedText_ && underlines_.size() <= 1) {
// Check for backspace or delete.
if ([theEvent keyCode] == 0x33 || [theEvent keyCode] == 0x75)
browser_->UIT_GetWebViewHost()->KeyEvent(theEvent);
}
textToBeInserted_.clear();
markedText_.clear();
underlines_.clear();
unmarkTextCalled_ = NO;
handlingKeyDown_ = YES;
[self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
handlingKeyDown_ = NO;
// Only send a corresponding key press event if there is no marked text.
// We also handle keys like backspace or delete, where the length
// of the text to be inserted is 0.
if (!hasMarkedText_ && !oldHasMarkedText &&
!textToBeInserted_.length() <= 1) {
if (textToBeInserted_.length() == 1) {
// If a single character was inserted, then we just send it as a keypress
// event.
WebKeyboardEvent keyboard_event(
WebInputEventFactory::keyboardEvent(theEvent));
keyboard_event.type = WebInputEvent::Char;
keyboard_event.text[0] = textToBeInserted_[0];
keyboard_event.text[1] = 0;
browser_->UIT_GetWebView()->handleInputEvent(keyboard_event);
} else {
browser_->UIT_GetWebViewHost()->KeyEvent(theEvent);
}
}
// Calling KeyEvent() could have destroyed the widget.
// We perform a sanity check and return if the widget is NULL.
if (!browser_ || !browser_->UIT_GetWebView())
return;
BOOL textInserted = NO;
if (textToBeInserted_.length() >
((hasMarkedText_ || oldHasMarkedText) ? 0u : 1u)) {
browser_->UIT_GetWebView()->confirmComposition(textToBeInserted_);
textInserted = YES;
}
if (hasMarkedText_ && markedText_.length()) {
browser_->UIT_GetWebView()->setComposition(markedText_, underlines_,
selectedRange_.location,
NSMaxRange(selectedRange_));
} else if (oldHasMarkedText && !hasMarkedText_ && !textInserted) {
if (unmarkTextCalled_) {
browser_->UIT_GetWebView()->confirmComposition();
} else {
// Simulating a cancelComposition
browser_->UIT_GetWebView()->setComposition(EmptyString16(), underlines_,
0, 0);
}
}
}
- (void)keyUp:(NSEvent *)theEvent {
if (browser_ && browser_->UIT_GetWebView())
browser_->UIT_GetWebViewHost()->KeyEvent(theEvent);
}
- (void)keyUp:(NSEvent *)theEvent {
- (void)flagsChanged:(NSEvent *)theEvent {
if (browser_ && browser_->UIT_GetWebView())
browser_->UIT_GetWebViewHost()->KeyEvent(theEvent);
}
@@ -163,12 +290,14 @@
- (BOOL)becomeFirstResponder {
if (browser_ && browser_->UIT_GetWebView()) {
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefFocusHandler> handler = client->GetFocusHandler();
if (handler.get() &&
handler->OnSetFocus(browser_, FOCUS_SOURCE_SYSTEM)) {
return NO;
if (!is_in_setfocus_) {
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefFocusHandler> handler = client->GetFocusHandler();
if (handler.get() &&
handler->OnSetFocus(browser_, FOCUS_SOURCE_SYSTEM)) {
return NO;
}
}
}
@@ -192,7 +321,8 @@
[super setFrame:frameRect];
if (browser_ && browser_->UIT_GetWebView()) {
const NSRect bounds = [self bounds];
browser_->UIT_GetWebViewHost()->Resize(gfx::Rect(NSRectToCGRect(bounds)));
browser_->UIT_GetWebViewHost()->SetSize(bounds.size.width,
bounds.size.height);
}
}
@@ -231,25 +361,6 @@
browser_->GetFocusedFrame()->SelectAll();
}
- (void)menuItemSelected:(id)sender {
cef_menu_id_t menuId = static_cast<cef_menu_id_t>([sender tag]);
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefMenuHandler> handler = client->GetMenuHandler();
if (handler.get()) {
// Ask the handler if it wants to handle the action.
handled = handler->OnMenuAction(browser_, menuId);
}
}
if(!handled) {
// Execute the action.
browser_->UIT_HandleAction(menuId, browser_->GetFocusedFrame());
}
}
- (void)registerDragDrop {
dropTarget_.reset([[WebDropTarget alloc] initWithWebView:self]);
@@ -264,12 +375,12 @@
image:(NSImage*)image
offset:(NSPoint)offset {
dragSource_.reset([[WebDragSource alloc]
initWithWebView:self
dropData:&dropData
image:image
offset:offset
pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
dragOperationMask:operationMask]);
initWithWebView:self
dropData:&dropData
image:image
offset:offset
pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]
dragOperationMask:operationMask]);
[dragSource_ startDrag];
}
@@ -339,4 +450,167 @@
return [dropTarget_ performDragOperation:sender view:self];
}
// NSTextInputClient methods
// This code is mostly copied and adapted from
// content/browser/renderer_host/render_widget_host_mac
extern "C" {
extern NSString *NSTextInputReplacementRangeAttributeName;
}
- (NSArray *)validAttributesForMarkedText {
if (!validAttributesForMarkedText_) {
validAttributesForMarkedText_.reset([[NSArray alloc] initWithObjects:
NSUnderlineStyleAttributeName,
NSUnderlineColorAttributeName,
NSMarkedClauseSegmentAttributeName,
NSTextInputReplacementRangeAttributeName,
nil]);
}
return validAttributesForMarkedText_.get();
}
- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint {
DCHECK([self window]);
// |thePoint| is in screen coordinates, but needs to be converted to WebKit
// coordinates (upper left origin). Scroll offsets will be taken care of in
// the renderer.
thePoint = [[self window] convertScreenToBase:thePoint];
thePoint = [self convertPoint:thePoint fromView:nil];
thePoint.y = NSHeight([self frame]) - thePoint.y;
WebPoint point(thePoint.x, thePoint.y);
return (NSUInteger)browser_->UIT_GetWebView()->focusedFrame()->
characterIndexForPoint(point);
}
- (NSRect)firstRectForCharacterRange:(NSRange)theRange
actualRange:(NSRangePointer) actualRange {
if (actualRange)
*actualRange = theRange;
if (!browser_ || !browser_->UIT_GetWebView() ||
!browser_->UIT_GetWebView()->focusedFrame()) {
return NSMakeRect(0, 0, 0, 0);
}
WebRect webRect;
browser_->UIT_GetWebView()->focusedFrame()->firstRectForCharacterRange(
theRange.location, theRange.length, webRect);
NSRect rect = NSMakeRect(webRect.x, webRect.y, webRect.width, webRect.height);
// The returned rectangle is in WebKit coordinates (upper left origin), so
// flip the coordinate system and then convert it into screen coordinates for
// return.
NSRect viewFrame = [self frame];
rect.origin.y = NSHeight(viewFrame) - rect.origin.y;
rect.origin.y -= rect.size.height;
rect = [self convertRectToBase:rect];
rect.origin = [[self window] convertBaseToScreen:rect.origin];
return rect;
}
- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)theRange
actualRange:(NSRangePointer) actualRange {
if (actualRange)
*actualRange = theRange;
if (!browser_ || !browser_->UIT_GetWebView() ||
!browser_->UIT_GetWebView()->focusedFrame()) {
return nil;
}
return WebSubstringUtil::attributedSubstringInRange(
browser_->UIT_GetWebView()->focusedFrame(),
theRange.location,
theRange.length);
}
- (void)doCommandBySelector:(SEL)selector {
}
- (NSRange)markedRange {
return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0);
}
- (NSRange)selectedRange {
return selectedRange_;
}
- (NSInteger)conversationIdentifier {
return reinterpret_cast<NSInteger>(self);
}
- (BOOL)hasMarkedText {
return hasMarkedText_;
}
- (void)unmarkText {
hasMarkedText_ = NO;
markedText_.clear();
underlines_.clear();
if (!handlingKeyDown_) {
if (browser_ && browser_->UIT_GetWebView())
browser_->UIT_GetWebView()->confirmComposition();
} else {
unmarkTextCalled_ = YES;
}
}
- (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange
replacementRange: (NSRange) replacementRange {
// An input method updates the composition string.
// We send the given text and range to the renderer so it can update the
// composition node of WebKit.
BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
NSString* im_text = isAttributedString ? [string string] : string;
int length = [im_text length];
// |markedRange_| will get set on a callback from ImeSetComposition().
selectedRange_ = newSelRange;
markedText_ = base::SysNSStringToUTF16(im_text);
hasMarkedText_ = (length > 0);
underlines_.clear();
if (isAttributedString) {
ExtractUnderlines(string, &underlines_);
} else {
// Use a thin black underline by default.
underlines_.push_back(
WebCompositionUnderline(0, length, SK_ColorBLACK, false));
}
// If we are handling a key down event, then SetComposition() will be
// called in keyEvent: method.
// Input methods of Mac use setMarkedText calls with an empty text to cancel
// an ongoing composition. So, we should check whether or not the given text
// is empty to update the input method state. (Our input method backend can
// automatically cancels an ongoing composition when we send an empty text.
// So, it is OK to send an empty text to the renderer.)
if (!handlingKeyDown_) {
if (browser_ && browser_->UIT_GetWebView()) {
const WebString markedText(markedText_);
browser_->UIT_GetWebView()->setComposition(markedText,
underlines_,
newSelRange.location,
NSMaxRange(newSelRange));
}
}
}
- (void)insertText:(id)string replacementRange: (NSRange) replacementRange {
BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
NSString* im_text = isAttributedString ? [string string] : string;
if (handlingKeyDown_) {
textToBeInserted_.append(base::SysNSStringToUTF16(im_text));
} else {
browser_->UIT_GetWebViewHost()->webwidget()->confirmComposition(
base::SysNSStringToUTF16(im_text));
}
// Inserting text will delete all marked text automatically.
hasMarkedText_ = NO;
}
@end

View File

@@ -61,8 +61,7 @@ public:
// The BrowserRequestContext object is managed by CefProcessIOThread.
void set_request_context(BrowserRequestContext* request_context)
{ request_context_ = request_context; }
scoped_refptr<BrowserRequestContext> request_context()
{ return request_context_; }
BrowserRequestContext* request_context() { return request_context_; }
// The DOMStorageContext object is managed by CefProcessUIThread.
void set_storage_context(DOMStorageContext* storage_context)

View File

@@ -31,10 +31,7 @@ CefProcessIOThread::~CefProcessIOThread() {
}
void CefProcessIOThread::Init() {
#if defined(OS_WIN)
// Initializes the COM library on the current thread.
CoInitialize(NULL);
#endif
CefThread::Init();
FilePath cache_path(_Context->cache_path());
request_context_ = new BrowserRequestContext(cache_path,
@@ -63,9 +60,5 @@ void CefProcessIOThread::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
CefThread::Cleanup();
}

View File

@@ -25,12 +25,13 @@ class CefProcessIOThread : public CefThread {
CefProcessIOThread(MessageLoop* message_loop);
virtual ~CefProcessIOThread();
virtual void Init();
virtual void CleanUp();
scoped_refptr<BrowserRequestContext> request_context()
{ return request_context_; }
protected:
virtual void Init();
virtual void CleanUp();
private:
scoped_refptr<BrowserRequestContext> request_context_;

View File

@@ -6,10 +6,6 @@
#include "cef_process_sub_thread.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include <Objbase.h>
#endif
CefProcessSubThread::CefProcessSubThread(CefThread::ID identifier)
: CefThread(identifier) {}
@@ -23,22 +19,11 @@ CefProcessSubThread::~CefProcessSubThread() {
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
CefThread::Cleanup();
}

View File

@@ -25,7 +25,6 @@ class CefProcessSubThread : public CefThread {
virtual ~CefProcessSubThread();
protected:
virtual void Init();
virtual void CleanUp();
private:

View File

@@ -22,7 +22,6 @@
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptController.h"
#include "ui/base/ui_base_paths.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/glue/user_agent.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/npapi/plugin_list.h"
@@ -107,15 +106,10 @@ void CefProcessUIThread::Init() {
kStatsFileCounters);
base::StatsTable::set_current(statstable_);
// CEF always exposes the GC.
std::string javascript_flags = "--expose-gc";
if (settings.javascript_flags.length > 0)
javascript_flags += " " + CefString(&settings.javascript_flags).ToString();
webkit_glue::SetJavaScriptFlags(javascript_flags);
// Expose GCController to JavaScript.
WebKit::WebScriptController::registerExtension(
extensions_v8::GCExtension::Get());
if (settings.javascript_flags.length > 0) {
// Pass the JavaScript flags to V8.
webkit_glue::SetJavaScriptFlags(CefString(&settings.javascript_flags));
}
#if defined(OS_WIN)
if (settings.graphics_implementation == ANGLE_IN_PROCESS ||

View File

@@ -9,6 +9,10 @@
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#if defined(OS_WIN)
#include <Objbase.h> // NOLINT(build/include_order)
#endif
using base::MessageLoopProxy;
// Friendly names for the well-known threads.
@@ -102,6 +106,29 @@ CefThread::CefThread(ID identifier, MessageLoop* message_loop)
Initialize();
}
void CefThread::Init() {
#if defined(OS_WIN)
// Initializes the COM library on the current thread.
CoInitialize(NULL);
#endif
#if defined(OS_MACOSX)
autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool);
#endif
}
void CefThread::Cleanup() {
#if defined(OS_WIN)
// Closes the COM library on the current thread. CoInitialize must
// be balanced by a corresponding call to CoUninitialize.
CoUninitialize();
#endif
#if defined(OS_MACOSX)
autorelease_pool_.reset(NULL);
#endif
}
void CefThread::Initialize() {
base::AutoLock lock(lock_);
DCHECK(identifier_ >= 0 && identifier_ < ID_COUNT);

View File

@@ -6,10 +6,15 @@
#ifndef _CEF_THREAD_H
#define _CEF_THREAD_H
#include "base/memory/scoped_ptr.h"
#include "base/synchronization/lock.h"
#include "base/task.h"
#include "base/threading/thread.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
namespace base {
class MessageLoopProxy;
}
@@ -179,6 +184,10 @@ class CefThread : public base::Thread {
struct DeleteOnIOThread : public DeleteOnThread<IO> { };
struct DeleteOnFileThread : public DeleteOnThread<FILE> { };
protected:
virtual void Init();
virtual void Cleanup();
private:
// Common initialization code for the constructors.
void Initialize();
@@ -210,6 +219,10 @@ class CefThread : public base::Thread {
// on the UI thread by the g_browser_process object. CefThreads remove
// themselves from this array upon destruction.
static CefThread* cef_threads_[ID_COUNT];
#if defined(OS_MACOSX)
scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
#endif
};
#define REQUIRE_UIT() DCHECK(CefThread::CurrentlyOn(CefThread::UI))

View File

@@ -9,7 +9,9 @@ void cef_time_to_basetime(const cef_time_t& cef_time, base::Time& time)
base::Time::Exploded exploded;
exploded.year = cef_time.year;
exploded.month = cef_time.month;
#if !defined(OS_MACOSX)
exploded.day_of_week = cef_time.day_of_week;
#endif
exploded.day_of_month = cef_time.day_of_month;
exploded.hour = cef_time.hour;
exploded.minute = cef_time.minute;
@@ -24,7 +26,9 @@ void cef_time_from_basetime(const base::Time& time, cef_time_t& cef_time)
time.UTCExplode(&exploded);
cef_time.year = exploded.year;
cef_time.month = exploded.month;
#if !defined(OS_MACOSX)
cef_time.day_of_week = exploded.day_of_week;
#endif
cef_time.day_of_month = exploded.day_of_month;
cef_time.hour = exploded.hour;
cef_time.minute = exploded.minute;

View File

@@ -0,0 +1,280 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/cookie_manager_impl.h"
#include <string>
#include "libcef/browser_persistent_cookie_store.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "libcef/cef_time_util.h"
#include "base/bind.h"
#include "base/logging.h"
namespace {
// Callback class for visiting cookies.
class VisitCookiesCallback : public base::RefCounted<VisitCookiesCallback> {
public:
explicit VisitCookiesCallback(net::CookieMonster* cookie_monster,
CefRefPtr<CefCookieVisitor> visitor)
: cookie_monster_(cookie_monster),
visitor_(visitor) {
}
void Run(const net::CookieList& list) {
REQUIRE_IOT();
int total = list.size(), count = 0;
net::CookieList::const_iterator it = list.begin();
for (; it != list.end(); ++it, ++count) {
CefCookie cookie;
const net::CookieMonster::CanonicalCookie& cc = *(it);
CefString(&cookie.name).FromString(cc.Name());
CefString(&cookie.value).FromString(cc.Value());
CefString(&cookie.domain).FromString(cc.Domain());
CefString(&cookie.path).FromString(cc.Path());
cookie.secure = cc.IsSecure();
cookie.httponly = cc.IsHttpOnly();
cef_time_from_basetime(cc.CreationDate(), cookie.creation);
cef_time_from_basetime(cc.LastAccessDate(), cookie.last_access);
cookie.has_expires = cc.DoesExpire();
if (cookie.has_expires)
cef_time_from_basetime(cc.ExpiryDate(), cookie.expires);
bool deleteCookie = false;
bool keepLooping = visitor_->Visit(cookie, count, total, deleteCookie);
if (deleteCookie) {
cookie_monster_->DeleteCanonicalCookieAsync(cc,
net::CookieMonster::DeleteCookieCallback());
}
if (!keepLooping)
break;
}
}
private:
scoped_refptr<net::CookieMonster> cookie_monster_;
CefRefPtr<CefCookieVisitor> visitor_;
};
} // namespace
CefCookieManagerImpl::CefCookieManagerImpl(bool is_global)
: is_global_(is_global) {
if (is_global) {
cookie_monster_ =
static_cast<net::CookieMonster*>(
_Context->request_context()->cookie_store());
DCHECK(cookie_monster_);
}
}
CefCookieManagerImpl::~CefCookieManagerImpl() {
}
void CefCookieManagerImpl::SetSupportedSchemes(
const std::vector<CefString>& schemes) {
if (CefThread::CurrentlyOn(CefThread::IO)) {
if (schemes.empty())
return;
std::set<std::string> scheme_set;
std::vector<CefString>::const_iterator it = schemes.begin();
for (; it != schemes.end(); ++it)
scheme_set.insert(*it);
const char** arr = new const char*[scheme_set.size()];
std::set<std::string>::const_iterator it2 = scheme_set.begin();
for (int i = 0; it2 != scheme_set.end(); ++it2, ++i)
arr[i] = it2->c_str();
cookie_monster_->SetCookieableSchemes(arr, scheme_set.size());
delete [] arr;
} else {
// Execute on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(&CefCookieManagerImpl::SetSupportedSchemes,
this, schemes));
}
}
bool CefCookieManagerImpl::VisitAllCookies(
CefRefPtr<CefCookieVisitor> visitor) {
if (CefThread::CurrentlyOn(CefThread::IO)) {
scoped_refptr<VisitCookiesCallback> callback(
new VisitCookiesCallback(cookie_monster_, visitor));
cookie_monster_->GetAllCookiesAsync(
base::Bind(&VisitCookiesCallback::Run, callback.get()));
} else {
// Execute on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitAllCookies),
this, visitor));
}
return true;
}
bool CefCookieManagerImpl::VisitUrlCookies(
const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor) {
if (CefThread::CurrentlyOn(CefThread::IO)) {
net::CookieOptions options;
if (includeHttpOnly)
options.set_include_httponly();
scoped_refptr<VisitCookiesCallback> callback(
new VisitCookiesCallback(cookie_monster_, visitor));
GURL gurl = GURL(url.ToString());
cookie_monster_->GetAllCookiesForURLWithOptionsAsync(gurl, options,
base::Bind(&VisitCookiesCallback::Run, callback.get()));
} else {
// Execute on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitUrlCookies),
this, url, includeHttpOnly, visitor));
}
return true;
}
bool CefCookieManagerImpl::SetCookie(const CefString& url,
const CefCookie& cookie) {
// Verify that this function is being called on the IO thread.
if (!CefThread::CurrentlyOn(CefThread::IO)) {
NOTREACHED() << "called on invalid thread";
return false;
}
GURL gurl = GURL(url.ToString());
if (!gurl.is_valid())
return false;
std::string name = CefString(&cookie.name).ToString();
std::string value = CefString(&cookie.value).ToString();
std::string domain = CefString(&cookie.domain).ToString();
std::string path = CefString(&cookie.path).ToString();
base::Time expiration_time;
if (cookie.has_expires)
cef_time_to_basetime(cookie.expires, expiration_time);
cookie_monster_->SetCookieWithDetailsAsync(gurl, name, value, domain, path,
expiration_time, cookie.secure, cookie.httponly,
net::CookieStore::SetCookiesCallback());
return true;
}
bool CefCookieManagerImpl::DeleteCookies(const CefString& url,
const CefString& cookie_name) {
// Verify that this function is being called on the IO thread.
if (!CefThread::CurrentlyOn(CefThread::IO)) {
NOTREACHED() << "called on invalid thread";
return false;
}
if (url.empty()) {
// Delete all cookies.
cookie_monster_->DeleteAllAsync(net::CookieMonster::DeleteCallback());
return true;
}
GURL gurl = GURL(url.ToString());
if (!gurl.is_valid())
return false;
if (cookie_name.empty()) {
// Delete all matching host cookies.
cookie_monster_->DeleteAllForHostAsync(gurl,
net::CookieMonster::DeleteCallback());
} else {
// Delete all matching host and domain cookies.
cookie_monster_->DeleteCookieAsync(gurl, cookie_name, base::Closure());
}
return true;
}
bool CefCookieManagerImpl::SetStoragePath(const CefString& path) {
if (CefThread::CurrentlyOn(CefThread::IO)) {
FilePath new_path;
if (!path.empty())
new_path = FilePath(path);
if (is_global_) {
// Global path changes are handled by the request context.
_Context->request_context()->SetCookieStoragePath(new_path);
cookie_monster_ =
static_cast<net::CookieMonster*>(
_Context->request_context()->cookie_store());
return true;
}
if (cookie_monster_ && ((storage_path_.empty() && path.empty()) ||
storage_path_ == new_path)) {
// The path has not changed so don't do anything.
return true;
}
scoped_refptr<BrowserPersistentCookieStore> persistent_store;
if (!new_path.empty()) {
if (file_util::CreateDirectory(new_path)) {
const FilePath& cookie_path = new_path.AppendASCII("Cookies");
persistent_store = new BrowserPersistentCookieStore(cookie_path, false);
} else {
NOTREACHED() << "The cookie storage directory could not be created";
storage_path_.clear();
}
}
// Set the new cookie store that will be used for all new requests. The old
// cookie store, if any, will be automatically flushed and closed when no
// longer referenced.
cookie_monster_ = new net::CookieMonster(persistent_store.get(), NULL);
storage_path_ = new_path;
} else {
// Execute on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(base::IgnoreResult(&CefCookieManagerImpl::SetStoragePath),
this, path));
}
return true;
}
// CefCookieManager methods ----------------------------------------------------
// static
CefRefPtr<CefCookieManager> CefCookieManager::GetGlobalManager() {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
return NULL;
}
return new CefCookieManagerImpl(true);
}
// static
CefRefPtr<CefCookieManager> CefCookieManager::CreateManager(
const CefString& path) {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
return NULL;
}
CefRefPtr<CefCookieManager> manager(new CefCookieManagerImpl(false));
manager->SetStoragePath(path);
return manager;
}

View File

@@ -0,0 +1,41 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef CEF_LIBCEF_COOKIE_IMPL_H_
#define CEF_LIBCEF_COOKIE_IMPL_H_
#include "include/cef.h"
#include "base/file_path.h"
#include "net/base/cookie_monster.h"
// Implementation of the CefCookieManager interface.
class CefCookieManagerImpl : public CefCookieManager {
public:
CefCookieManagerImpl(bool is_global);
~CefCookieManagerImpl();
// CefCookieManager methods.
virtual void SetSupportedSchemes(const std::vector<CefString>& schemes)
OVERRIDE;
virtual bool VisitAllCookies(CefRefPtr<CefCookieVisitor> visitor) OVERRIDE;
virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor) OVERRIDE;
virtual bool SetCookie(const CefString& url,
const CefCookie& cookie) OVERRIDE;
virtual bool DeleteCookies(const CefString& url,
const CefString& cookie_name) OVERRIDE;
virtual bool SetStoragePath(const CefString& path) OVERRIDE;
net::CookieMonster* cookie_monster() { return cookie_monster_; }
private:
scoped_refptr<net::CookieMonster> cookie_monster_;
bool is_global_;
FilePath storage_path_;
IMPLEMENT_REFCOUNTING(CefCookieManagerImpl);
};
#endif // CEF_LIBCEF_COOKIE_IMPL_H_

View File

@@ -0,0 +1,83 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/cookie_store_proxy.h"
#include <string>
#include "libcef/browser_impl.h"
#include "libcef/cef_context.h"
#include "libcef/cookie_manager_impl.h"
#include "base/logging.h"
CefCookieStoreProxy::CefCookieStoreProxy(CefBrowserImpl* browser)
: browser_(browser) {
DCHECK(browser_);
}
void CefCookieStoreProxy::SetCookieWithOptionsAsync(
const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options,
const SetCookiesCallback& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->SetCookieWithOptionsAsync(url, cookie_line, options, callback);
}
void CefCookieStoreProxy::GetCookiesWithOptionsAsync(
const GURL& url, const net::CookieOptions& options,
const GetCookiesCallback& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->GetCookiesWithOptionsAsync(url, options, callback);
}
void CefCookieStoreProxy::GetCookiesWithInfoAsync(
const GURL& url,
const net::CookieOptions& options,
const GetCookieInfoCallback& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->GetCookiesWithInfoAsync(url, options, callback);
}
void CefCookieStoreProxy::DeleteCookieAsync(
const GURL& url,
const std::string& cookie_name,
const base::Closure& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->DeleteCookieAsync(url, cookie_name, callback);
}
net::CookieMonster* CefCookieStoreProxy::GetCookieMonster() {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
return cookie_store->GetCookieMonster();
}
net::CookieStore* CefCookieStoreProxy::GetCookieStore() {
scoped_refptr<net::CookieStore> cookie_store;
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
if (handler.get()) {
// Get the manager from the handler.
CefRefPtr<CefCookieManager> manager =
handler->GetCookieManager(browser_, browser_->pending_url().spec());
if (manager.get()) {
cookie_store =
reinterpret_cast<CefCookieManagerImpl*>(
manager.get())->cookie_monster();
}
}
}
if (!cookie_store) {
// Use the global cookie store.
cookie_store = _Context->request_context()->cookie_store();
}
DCHECK(cookie_store);
return cookie_store;
}

View File

@@ -0,0 +1,42 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef CEF_LIBCEF_COOKIE_STORE_PROXY_H_
#define CEF_LIBCEF_COOKIE_STORE_PROXY_H_
#pragma once
#include "net/base/cookie_store.h"
class CefBrowserImpl;
// Handles cookie requests from the network stack.
class CefCookieStoreProxy : public net::CookieStore {
public:
explicit CefCookieStoreProxy(CefBrowserImpl* browser);
// net::CookieStore methods.
virtual void SetCookieWithOptionsAsync(
const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options,
const SetCookiesCallback& callback) OVERRIDE;
virtual void GetCookiesWithOptionsAsync(
const GURL& url, const net::CookieOptions& options,
const GetCookiesCallback& callback) OVERRIDE;
void GetCookiesWithInfoAsync(
const GURL& url,
const net::CookieOptions& options,
const GetCookieInfoCallback& callback) OVERRIDE;
virtual void DeleteCookieAsync(const GURL& url,
const std::string& cookie_name,
const base::Closure& callback) OVERRIDE;
virtual net::CookieMonster* GetCookieMonster() OVERRIDE;
private:
net::CookieStore* GetCookieStore();
CefBrowserImpl* browser_;
};
#endif // CEF_LIBCEF_COOKIE_STORE_PROXY_H_

View File

@@ -1,16 +1,17 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "dom_node_impl.h"
#include "browser_impl.h"
#include "cef_thread.h"
#include "dom_document_impl.h"
#include "dom_event_impl.h"
#include "tracker.h"
#include "libcef/dom_node_impl.h"
#include "libcef/browser_impl.h"
#include "libcef/cef_thread.h"
#include "libcef/dom_document_impl.h"
#include "libcef/dom_event_impl.h"
#include "libcef/tracker.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/threading/non_thread_safe.h"
#include "base/utf_string_conversions.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebAttribute.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
@@ -38,31 +39,28 @@ using WebKit::WebNode;
using WebKit::WebSelectElement;
using WebKit::WebString;
namespace {
// Wrapper implementation for WebDOMEventListener.
class CefDOMEventListenerWrapper : public WebDOMEventListener,
public CefTrackObject
{
public:
public CefTrackObject,
public base::NonThreadSafe {
public:
CefDOMEventListenerWrapper(CefBrowserImpl* browser, WebFrame* frame,
CefRefPtr<CefDOMEventListener> listener)
: browser_(browser), frame_(frame), listener_(listener)
{
: browser_(browser),
frame_(frame),
listener_(listener) {
// Cause this object to be deleted immediately before the frame is closed.
browser->UIT_AddFrameObject(frame, this);
}
virtual ~CefDOMEventListenerWrapper()
{
REQUIRE_UIT();
virtual ~CefDOMEventListenerWrapper() {
}
virtual void handleEvent(const WebDOMEvent& event)
{
virtual void handleEvent(const WebDOMEvent& event) {
CefRefPtr<CefDOMDocumentImpl> documentImpl;
CefRefPtr<CefDOMEventImpl> eventImpl;
if (!event.isNull()) {
// Create CefDOMDocumentImpl and CefDOMEventImpl objects that are valid
// only for the scope of this method.
@@ -72,32 +70,31 @@ public:
eventImpl = new CefDOMEventImpl(documentImpl, event);
}
}
listener_->HandleEvent(eventImpl.get());
if(eventImpl.get())
if (eventImpl.get())
eventImpl->Detach();
if (documentImpl.get())
documentImpl->Detach();
}
protected:
protected:
CefBrowserImpl* browser_;
WebFrame* frame_;
CefRefPtr<CefDOMEventListener> listener_;
};
} // namespace
} // namespace
CefDOMNodeImpl::CefDOMNodeImpl(CefRefPtr<CefDOMDocumentImpl> document,
const WebKit::WebNode& node)
: document_(document), node_(node)
{
: document_(document),
node_(node) {
}
CefDOMNodeImpl::~CefDOMNodeImpl()
{
CefDOMNodeImpl::~CefDOMNodeImpl() {
REQUIRE_UIT();
if (document_.get() && !node_.isNull()) {
@@ -106,8 +103,7 @@ CefDOMNodeImpl::~CefDOMNodeImpl()
}
}
CefDOMNodeImpl::Type CefDOMNodeImpl::GetType()
{
CefDOMNodeImpl::Type CefDOMNodeImpl::GetType() {
if (!VerifyContext())
return DOM_NODE_TYPE_UNSUPPORTED;
@@ -143,24 +139,21 @@ CefDOMNodeImpl::Type CefDOMNodeImpl::GetType()
}
}
bool CefDOMNodeImpl::IsText()
{
bool CefDOMNodeImpl::IsText() {
if (!VerifyContext())
return false;
return node_.isTextNode();
}
bool CefDOMNodeImpl::IsElement()
{
bool CefDOMNodeImpl::IsElement() {
if (!VerifyContext())
return false;
return node_.isElementNode();
}
bool CefDOMNodeImpl::IsFormControlElement()
{
bool CefDOMNodeImpl::IsFormControlElement() {
if (!VerifyContext())
return false;
@@ -172,8 +165,7 @@ bool CefDOMNodeImpl::IsFormControlElement()
return false;
}
CefString CefDOMNodeImpl::GetFormControlElementType()
{
CefString CefDOMNodeImpl::GetFormControlElementType() {
CefString str;
if (!VerifyContext())
return str;
@@ -193,8 +185,7 @@ CefString CefDOMNodeImpl::GetFormControlElementType()
return str;
}
bool CefDOMNodeImpl::IsSame(CefRefPtr<CefDOMNode> that)
{
bool CefDOMNodeImpl::IsSame(CefRefPtr<CefDOMNode> that) {
if (!VerifyContext())
return false;
@@ -205,8 +196,7 @@ bool CefDOMNodeImpl::IsSame(CefRefPtr<CefDOMNode> that)
return node_.equals(impl->node_);
}
CefString CefDOMNodeImpl::GetName()
{
CefString CefDOMNodeImpl::GetName() {
CefString str;
if (!VerifyContext())
return str;
@@ -218,8 +208,7 @@ CefString CefDOMNodeImpl::GetName()
return str;
}
CefString CefDOMNodeImpl::GetValue()
{
CefString CefDOMNodeImpl::GetValue() {
CefString str;
if (!VerifyContext())
return str;
@@ -257,8 +246,7 @@ CefString CefDOMNodeImpl::GetValue()
return str;
}
bool CefDOMNodeImpl::SetValue(const CefString& value)
{
bool CefDOMNodeImpl::SetValue(const CefString& value) {
if (!VerifyContext())
return false;
@@ -268,8 +256,7 @@ bool CefDOMNodeImpl::SetValue(const CefString& value)
return node_.setNodeValue(string16(value));
}
CefString CefDOMNodeImpl::GetAsMarkup()
{
CefString CefDOMNodeImpl::GetAsMarkup() {
CefString str;
if (!VerifyContext())
return str;
@@ -281,56 +268,49 @@ CefString CefDOMNodeImpl::GetAsMarkup()
return str;
}
CefRefPtr<CefDOMDocument> CefDOMNodeImpl::GetDocument()
{
CefRefPtr<CefDOMDocument> CefDOMNodeImpl::GetDocument() {
if (!VerifyContext())
return NULL;
return document_.get();
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetParent()
{
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetParent() {
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.parentNode());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetPreviousSibling()
{
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetPreviousSibling() {
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.previousSibling());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetNextSibling()
{
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetNextSibling() {
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.nextSibling());
}
bool CefDOMNodeImpl::HasChildren()
{
bool CefDOMNodeImpl::HasChildren() {
if (!VerifyContext())
return false;
return node_.hasChildNodes();
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetFirstChild()
{
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetFirstChild() {
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.firstChild());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetLastChild()
{
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetLastChild() {
if (!VerifyContext())
return NULL;
@@ -339,8 +319,7 @@ CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetLastChild()
void CefDOMNodeImpl::AddEventListener(const CefString& eventType,
CefRefPtr<CefDOMEventListener> listener,
bool useCapture)
{
bool useCapture) {
if (!VerifyContext())
return;
@@ -350,8 +329,7 @@ void CefDOMNodeImpl::AddEventListener(const CefString& eventType,
useCapture);
}
CefString CefDOMNodeImpl::GetElementTagName()
{
CefString CefDOMNodeImpl::GetElementTagName() {
CefString str;
if (!VerifyContext())
return str;
@@ -369,8 +347,7 @@ CefString CefDOMNodeImpl::GetElementTagName()
return str;
}
bool CefDOMNodeImpl::HasElementAttributes()
{
bool CefDOMNodeImpl::HasElementAttributes() {
if (!VerifyContext())
return false;
@@ -383,8 +360,7 @@ bool CefDOMNodeImpl::HasElementAttributes()
return (element.attributes().length() > 0);
}
bool CefDOMNodeImpl::HasElementAttribute(const CefString& attrName)
{
bool CefDOMNodeImpl::HasElementAttribute(const CefString& attrName) {
if (!VerifyContext())
return false;
@@ -397,8 +373,7 @@ bool CefDOMNodeImpl::HasElementAttribute(const CefString& attrName)
return element.hasAttribute(string16(attrName));
}
CefString CefDOMNodeImpl::GetElementAttribute(const CefString& attrName)
{
CefString CefDOMNodeImpl::GetElementAttribute(const CefString& attrName) {
CefString str;
if (!VerifyContext())
return str;
@@ -416,8 +391,7 @@ CefString CefDOMNodeImpl::GetElementAttribute(const CefString& attrName)
return str;
}
void CefDOMNodeImpl::GetElementAttributes(AttributeMap& attrMap)
{
void CefDOMNodeImpl::GetElementAttributes(AttributeMap& attrMap) {
if (!VerifyContext())
return;
@@ -449,8 +423,7 @@ void CefDOMNodeImpl::GetElementAttributes(AttributeMap& attrMap)
}
bool CefDOMNodeImpl::SetElementAttribute(const CefString& attrName,
const CefString& value)
{
const CefString& value) {
if (!VerifyContext())
return false;
@@ -463,8 +436,7 @@ bool CefDOMNodeImpl::SetElementAttribute(const CefString& attrName,
return element.setAttribute(string16(attrName), string16(value));
}
CefString CefDOMNodeImpl::GetElementInnerText()
{
CefString CefDOMNodeImpl::GetElementInnerText() {
CefString str;
if (!VerifyContext())
return str;
@@ -482,21 +454,19 @@ CefString CefDOMNodeImpl::GetElementInnerText()
return str;
}
void CefDOMNodeImpl::Detach()
{
void CefDOMNodeImpl::Detach() {
document_ = NULL;
node_.assign(WebNode());
}
bool CefDOMNodeImpl::VerifyContext()
{
bool CefDOMNodeImpl::VerifyContext() {
if (!document_.get()) {
NOTREACHED();
return false;
}
if (!document_->VerifyContext())
return false;
if(node_.isNull()) {
if (node_.isNull()) {
NOTREACHED();
return false;
}

View File

@@ -33,9 +33,35 @@ void ExternalPopupMenu::show(const WebKit::WebRect& bounds) {
CefBrowserImpl* browser = delegate_->GetBrowser();
NSView* view = nil;
NSRect view_rect;
if (!browser->IsWindowRenderingDisabled()) {
view = browser->UIT_GetWebViewWndHandle();
view_rect = [view bounds];
} else {
view = browser->UIT_GetMainWndHandle();
if (view != nil) {
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
// Retrieve the view rect.
CefRect rect;
CefRefPtr<CefRenderHandler> render_handler = client->GetRenderHandler();
if (render_handler.get() &&
render_handler->GetViewRect(browser, rect)) {
view_rect = NSMakeRect(rect.x, rect.y, rect.width, rect.height);
}
}
}
}
if (view == nil || view_rect.size.width == 0 || view_rect.size.height == 0) {
popup_menu_client_->didCancel();
delegate_->ClosePopupMenu();
return;
}
// Set up the menu position.
NSView* web_view = browser->UIT_GetWebViewWndHandle();
NSRect view_rect = [web_view bounds];
int y_offset = bounds.y + bounds.height;
NSRect position = NSMakeRect(bounds.x, view_rect.size.height - y_offset,
bounds.width, bounds.height);
@@ -46,7 +72,7 @@ void ExternalPopupMenu::show(const WebKit::WebRect& bounds) {
fontSize:font_size
rightAligned:right_aligned]);
[menu_runner runMenuInView:browser->UIT_GetWebViewWndHandle()
[menu_runner runMenuInView:view
withBounds:position
initialIndex:selected_index];

View File

@@ -0,0 +1,347 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/geolocation_client.h"
#include "libcef/browser_impl.h"
#include "include/cef.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "base/bind.h"
#include "base/logging.h"
#include "content/browser/geolocation/access_token_store.h"
#include "content/browser/geolocation/arbitrator_dependency_factory.h"
#include "content/browser/geolocation/geolocation_observer.h"
#include "content/browser/geolocation/geolocation_provider.h"
#include "content/browser/geolocation/location_provider.h"
#include "content/common/geoposition.h"
#include "content/public/common/content_switches.h"
#include "net/url_request/url_request_context_getter.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebGeolocationPermissionRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebGeolocationPermissionRequestManager.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebGeolocationClient.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebGeolocationPosition.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebGeolocationError.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
using WebKit::WebGeolocationController;
using WebKit::WebGeolocationError;
using WebKit::WebGeolocationPermissionRequest;
using WebKit::WebGeolocationPermissionRequestManager;
using WebKit::WebGeolocationPosition;
namespace {
class CefURLRequestContextGetter : public net::URLRequestContextGetter {
public:
CefURLRequestContextGetter() {}
virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE {
return _Context->request_context();
}
virtual scoped_refptr<base::MessageLoopProxy>
GetIOMessageLoopProxy() const OVERRIDE {
return CefThread::GetMessageLoopProxyForThread(CefThread::IO);
}
private:
DISALLOW_COPY_AND_ASSIGN(CefURLRequestContextGetter);
};
// In-memory store for access tokens used by geolocation.
class CefAccessTokenStore : public AccessTokenStore {
public:
CefAccessTokenStore() {}
virtual void DoLoadAccessTokens(
scoped_refptr<CancelableRequest<LoadAccessTokensCallbackType> > req)
OVERRIDE {
if (!request_context_getter_)
request_context_getter_ = new CefURLRequestContextGetter;
req->ForwardResultAsync(access_token_set_, request_context_getter_);
}
virtual void SaveAccessToken(
const GURL& server_url, const string16& access_token) OVERRIDE {
access_token_set_[server_url] = access_token;
}
private:
AccessTokenSet access_token_set_;
scoped_refptr<CefURLRequestContextGetter> request_context_getter_;
DISALLOW_COPY_AND_ASSIGN(CefAccessTokenStore);
};
void NotifyArbitratorPermissionGranted(const GURL& requesting_frame) {
DCHECK(CefThread::CurrentlyOn(CefThread::IO));
GeolocationProvider::GetInstance()->OnPermissionGranted(requesting_frame);
}
} // namespace
// CefGeolocationCallback implementation.
class CefGeolocationCallbackImpl : public CefGeolocationCallback {
public:
CefGeolocationCallbackImpl(CefGeolocationClient* client, int bridge_id)
: client_(client),
bridge_id_(bridge_id) {}
virtual void Continue(bool allow) OVERRIDE {
if (CefThread::CurrentlyOn(CefThread::UI)) {
if (client_) {
client_->OnPermissionSet(bridge_id_, allow);
client_ = NULL;
}
} else {
CefThread::PostTask(CefThread::UI, FROM_HERE,
base::Bind(&CefGeolocationCallbackImpl::Continue, this, allow));
}
}
private:
scoped_refptr<CefGeolocationClient> client_;
int bridge_id_;
IMPLEMENT_REFCOUNTING(CefGeolocationCallbackImpl);
};
CefGeolocationClient::CefGeolocationClient(CefBrowserImpl* browser)
: browser_(browser),
pending_permissions_(new WebGeolocationPermissionRequestManager()),
enable_high_accuracy_(false),
updating_(false),
location_provider_(NULL) {
}
CefGeolocationClient::~CefGeolocationClient() {}
void CefGeolocationClient::geolocationDestroyed() {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
controller_.reset();
DCHECK(!updating_);
}
void CefGeolocationClient::startUpdating() {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(&CefGeolocationClient::OnStartUpdating, this,
enable_high_accuracy_));
updating_ = true;
}
void CefGeolocationClient::stopUpdating() {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(&CefGeolocationClient::OnStopUpdating, this));
updating_ = false;
}
void CefGeolocationClient::setEnableHighAccuracy(bool enable_high_accuracy) {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
// GeolocationController calls setEnableHighAccuracy(true) before
// startUpdating in response to the first high-accuracy Geolocation
// subscription. When the last high-accuracy Geolocation unsubscribes
// it calls setEnableHighAccuracy(false) after stopUpdating.
bool has_changed = enable_high_accuracy_ != enable_high_accuracy;
enable_high_accuracy_ = enable_high_accuracy;
// We have a different accuracy requirement. Request browser to update.
if (updating_ && has_changed)
startUpdating();
}
void CefGeolocationClient::setController(
WebGeolocationController* controller) {
controller_.reset(controller);
}
bool CefGeolocationClient::lastPosition(WebGeolocationPosition&) {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
// The latest position is stored in the browser, not the renderer, so we
// would have to fetch it synchronously to give a good value here. The
// WebCore::GeolocationController already caches the last position it
// receives, so there is not much benefit to more position caching here.
return false;
}
void CefGeolocationClient::requestPermission(
const WebGeolocationPermissionRequest& permissionRequest) {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
int bridge_id = pending_permissions_->add(permissionRequest);
string16 origin = permissionRequest.securityOrigin().toString();
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefGeolocationHandler> handler =
client->GetGeolocationHandler();
if (handler.get()) {
CefRefPtr<CefGeolocationCallbackImpl> callbackPtr(
new CefGeolocationCallbackImpl(this, bridge_id));
handler->OnRequestGeolocationPermission(browser_, origin, bridge_id,
callbackPtr.get());
return;
}
}
// Disallow geolocation access by default.
OnPermissionSet(bridge_id, false);
}
void CefGeolocationClient::cancelPermissionRequest(
const WebGeolocationPermissionRequest& permissionRequest) {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
int bridge_id;
if (!pending_permissions_->remove(permissionRequest, bridge_id))
return;
string16 origin = permissionRequest.securityOrigin().toString();
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefGeolocationHandler> handler =
client->GetGeolocationHandler();
if (handler.get())
handler->OnCancelGeolocationPermission(browser_, origin, bridge_id);
}
}
void CefGeolocationClient::OnStartUpdating(bool enable_high_accuracy) {
DCHECK(CefThread::CurrentlyOn(CefThread::IO));
if (!location_provider_)
location_provider_ = GeolocationProvider::GetInstance();
// Re-add to re-establish our options, in case they changed.
location_provider_->AddObserver(
this, GeolocationObserverOptions(enable_high_accuracy));
}
void CefGeolocationClient::OnStopUpdating() {
DCHECK(CefThread::CurrentlyOn(CefThread::IO));
if (location_provider_) {
location_provider_->RemoveObserver(this);
location_provider_ = NULL;
}
}
void CefGeolocationClient::OnLocationUpdate(const Geoposition& position) {
DCHECK(CefThread::CurrentlyOn(CefThread::IO));
CefThread::PostTask(CefThread::UI, FROM_HERE,
base::Bind(&CefGeolocationClient::OnPositionUpdated, this, position));
}
// Permission for using geolocation has been set.
void CefGeolocationClient::OnPermissionSet(int bridge_id, bool is_allowed) {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
WebGeolocationPermissionRequest permissionRequest;
if (!pending_permissions_->remove(bridge_id, permissionRequest))
return;
permissionRequest.setIsAllowed(is_allowed);
if (is_allowed) {
string16 origin = permissionRequest.securityOrigin().toString();
CefThread::PostTask(
CefThread::IO, FROM_HERE,
base::Bind(&NotifyArbitratorPermissionGranted, GURL(origin)));
}
}
// We have an updated geolocation position or error code.
void CefGeolocationClient::OnPositionUpdated(const Geoposition& geoposition) {
DCHECK(CefThread::CurrentlyOn(CefThread::UI));
// It is possible for the browser process to have queued an update message
// before receiving the stop updating message.
if (!updating_)
return;
DCHECK(geoposition.IsInitialized());
if (geoposition.IsValidFix()) {
controller_->positionChanged(
WebGeolocationPosition(
geoposition.timestamp.ToDoubleT(),
geoposition.latitude, geoposition.longitude,
geoposition.accuracy,
geoposition.is_valid_altitude(), geoposition.altitude,
geoposition.is_valid_altitude_accuracy(),
geoposition.altitude_accuracy,
geoposition.is_valid_heading(), geoposition.heading,
geoposition.is_valid_speed(), geoposition.speed));
} else {
WebGeolocationError::Error code;
switch (geoposition.error_code) {
case Geoposition::ERROR_CODE_PERMISSION_DENIED:
code = WebGeolocationError::ErrorPermissionDenied;
break;
case Geoposition::ERROR_CODE_POSITION_UNAVAILABLE:
code = WebGeolocationError::ErrorPositionUnavailable;
break;
default:
DCHECK(false);
NOTREACHED() << geoposition.error_code;
return;
}
controller_->errorOccurred(
WebGeolocationError(
code, WebKit::WebString::fromUTF8(geoposition.error_message)));
}
}
// Replacement for content/browser/geolocation/arbitrator_dependency_factory.cc
// GeolocationArbitratorDependencyFactory
GeolocationArbitratorDependencyFactory::
~GeolocationArbitratorDependencyFactory() {
}
// DefaultGeolocationArbitratorDependencyFactory
DefaultGeolocationArbitratorDependencyFactory::GetTimeNow
DefaultGeolocationArbitratorDependencyFactory::GetTimeFunction() {
return base::Time::Now;
}
AccessTokenStore*
DefaultGeolocationArbitratorDependencyFactory::NewAccessTokenStore() {
return new CefAccessTokenStore;
}
LocationProviderBase*
DefaultGeolocationArbitratorDependencyFactory::NewNetworkLocationProvider(
AccessTokenStore* access_token_store,
net::URLRequestContextGetter* context,
const GURL& url,
const string16& access_token) {
return ::NewNetworkLocationProvider(access_token_store, context,
url, access_token);
}
LocationProviderBase*
DefaultGeolocationArbitratorDependencyFactory::NewSystemLocationProvider() {
return ::NewSystemLocationProvider();
}
// Extract from content/public/common/content_switches.cc.
namespace switches {
const char kExperimentalLocationFeatures[] = "experimental-location-features";
} // namespace switches

View File

@@ -0,0 +1,88 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CEF_LIBCEF_GEOLOCATION_CLIENT_H_
#define CEF_LIBCEF_GEOLOCATION_CLIENT_H_
#pragma once
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "content/browser/geolocation/geolocation_observer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebGeolocationClient.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebGeolocationController.h"
class CefBrowserImpl;
class CefGeolocationCallbackImpl;
class GeolocationProvider;
struct Geoposition;
namespace WebKit {
class WebGeolocationController;
class WebGeolocationPermissionRequest;
class WebGeolocationPermissionRequestManager;
class WebGeolocationPosition;
}
// Delegate for Geolocation messages used by WebKit.
class CefGeolocationClient
: public WebKit::WebGeolocationClient,
public GeolocationObserver,
public base::RefCountedThreadSafe<CefGeolocationClient> {
public:
explicit CefGeolocationClient(CefBrowserImpl* browser);
virtual ~CefGeolocationClient();
private:
friend class CefGeolocationCallbackImpl;
// WebGeolocationClient methods.
virtual void geolocationDestroyed();
virtual void startUpdating();
virtual void stopUpdating();
virtual void setEnableHighAccuracy(bool enable_high_accuracy);
virtual void setController(WebKit::WebGeolocationController* controller);
virtual bool lastPosition(WebKit::WebGeolocationPosition& position);
virtual void requestPermission(
const WebKit::WebGeolocationPermissionRequest& permissionRequest);
virtual void cancelPermissionRequest(
const WebKit::WebGeolocationPermissionRequest& permissionRequest);
// Called to continue processing on the IO thread.
void OnStartUpdating(bool enable_high_accuracy);
void OnStopUpdating();
// GeolocationObserver methods.
virtual void OnLocationUpdate(const Geoposition& position);
// Permission for using geolocation has been set.
void OnPermissionSet(int bridge_id, bool is_allowed);
// We have an updated geolocation position or error code.
void OnPositionUpdated(const Geoposition& geoposition);
// The following members are only accessed on the UI thread.
// The |browser_| pointer is guaranteed to outlive this object.
CefBrowserImpl* browser_;
// The controller_ is valid for the lifetime of the underlying
// WebCore::GeolocationController. geolocationDestroyed() is
// invoked when the underlying object is destroyed.
scoped_ptr<WebKit::WebGeolocationController> controller_;
scoped_ptr<WebKit::WebGeolocationPermissionRequestManager>
pending_permissions_;
bool enable_high_accuracy_;
bool updating_;
// The following members are only accessed on the IO thread.
// Only set whilst we are registered with the arbitrator.
GeolocationProvider* location_provider_;
DISALLOW_COPY_AND_ASSIGN(CefGeolocationClient);
};
#endif // CEF_LIBCEF_GEOLOCATION_CLIENT_H_

View File

@@ -2,73 +2,67 @@
// 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 "libcef/request_impl.h"
#include <string>
#include <vector>
#include "libcef/http_header_utils.h"
#include "base/logging.h"
#include "net/url_request/url_request.h"
#include "http_header_utils.h"
using WebKit::WebHTTPBody;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebURLRequest;
CefRefPtr<CefRequest> CefRequest::CreateRequest()
{
CefRefPtr<CefRequest> CefRequest::CreateRequest() {
CefRefPtr<CefRequest> request(new CefRequestImpl());
return request;
}
CefRequestImpl::CefRequestImpl()
: method_("GET"), flags_(WUR_FLAG_NONE)
{
: method_("GET"),
flags_(WUR_FLAG_NONE) {
}
CefString CefRequestImpl::GetURL()
{
CefString CefRequestImpl::GetURL() {
AutoLock lock_scope(this);
return url_;
}
void CefRequestImpl::SetURL(const CefString& url)
{
void CefRequestImpl::SetURL(const CefString& url) {
AutoLock lock_scope(this);
url_ = url;
}
CefString CefRequestImpl::GetMethod()
{
CefString CefRequestImpl::GetMethod() {
AutoLock lock_scope(this);
return method_;
}
void CefRequestImpl::SetMethod(const CefString& method)
{
void CefRequestImpl::SetMethod(const CefString& method) {
AutoLock lock_scope(this);
method_ = method;
}
CefRefPtr<CefPostData> CefRequestImpl::GetPostData()
{
CefRefPtr<CefPostData> CefRequestImpl::GetPostData() {
AutoLock lock_scope(this);
return postdata_;
}
void CefRequestImpl::SetPostData(CefRefPtr<CefPostData> postData)
{
void CefRequestImpl::SetPostData(CefRefPtr<CefPostData> postData) {
AutoLock lock_scope(this);
postdata_ = postData;
}
void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap)
{
void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap) {
AutoLock lock_scope(this);
headerMap = headermap_;
}
void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap)
{
void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap) {
AutoLock lock_scope(this);
headermap_ = headerMap;
}
@@ -76,8 +70,7 @@ void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap)
void CefRequestImpl::Set(const CefString& url,
const CefString& method,
CefRefPtr<CefPostData> postData,
const HeaderMap& headerMap)
{
const HeaderMap& headerMap) {
AutoLock lock_scope(this);
url_ = url;
method_ = method;
@@ -85,17 +78,30 @@ void CefRequestImpl::Set(const CefString& url,
headermap_ = headerMap;
}
void CefRequestImpl::Set(net::URLRequest* request)
{
void CefRequestImpl::Set(net::URLRequest* request) {
AutoLock lock_scope(this);
url_ = request->url().spec();
method_ = request->method();
net::HttpRequestHeaders headers = request->extra_request_headers();
// Ensure that we do not send username and password fields in the referrer.
GURL referrer(request->GetSanitizedReferrer());
// Strip Referer from request_info_.extra_headers to prevent, e.g., plugins
// from overriding headers that are controlled using other means. Otherwise a
// plugin could set a referrer although sending the referrer is inhibited.
headers.RemoveHeader(net::HttpRequestHeaders::kReferer);
// Our consumer should have made sure that this is a safe referrer. See for
// instance WebCore::FrameLoader::HideReferrer.
if (referrer.is_valid())
headers.SetHeader(net::HttpRequestHeaders::kReferer, referrer.spec());
// Transfer request headers
GetHeaderMap(request->extra_request_headers(), headermap_);
headermap_.insert(std::make_pair(L"Referrer", request->referrer()));
GetHeaderMap(headers, headermap_);
// Transfer post data, if any
net::UploadData* data = request->get_upload();
if (data) {
@@ -104,8 +110,7 @@ void CefRequestImpl::Set(net::URLRequest* request)
}
}
void CefRequestImpl::Set(const WebKit::WebURLRequest& request)
{
void CefRequestImpl::Set(const WebKit::WebURLRequest& request) {
DCHECK(!request.isNull());
AutoLock lock_scope(this);
@@ -116,7 +121,7 @@ void CefRequestImpl::Set(const WebKit::WebURLRequest& request)
if (!body.isNull()) {
postdata_ = new CefPostDataImpl();
static_cast<CefPostDataImpl*>(postdata_.get())->Set(body);
} else if(postdata_.get()) {
} else if (postdata_.get()) {
postdata_ = NULL;
}
@@ -144,8 +149,7 @@ void CefRequestImpl::Set(const WebKit::WebURLRequest& request)
#define SETBOOLFLAG(obj, flags, method, FLAG) \
obj.method((flags & (FLAG)) == (FLAG))
void CefRequestImpl::Get(WebKit::WebURLRequest& request)
{
void CefRequestImpl::Get(WebKit::WebURLRequest& request) {
request.initialize();
AutoLock lock_scope(this);
@@ -170,13 +174,13 @@ void CefRequestImpl::Get(WebKit::WebURLRequest& request)
WebURLRequest::ReloadIgnoringCacheData :
WebURLRequest::UseProtocolCachePolicy);
SETBOOLFLAG(request, flags_, setAllowStoredCredentials,
SETBOOLFLAG(request, flags_, setAllowStoredCredentials,
WUR_FLAG_ALLOW_CACHED_CREDENTIALS);
SETBOOLFLAG(request, flags_, setAllowCookies,
SETBOOLFLAG(request, flags_, setAllowCookies,
WUR_FLAG_ALLOW_COOKIES);
SETBOOLFLAG(request, flags_, setReportUploadProgress,
SETBOOLFLAG(request, flags_, setReportUploadProgress,
WUR_FLAG_REPORT_UPLOAD_PROGRESS);
SETBOOLFLAG(request, flags_, setReportLoadTiming,
SETBOOLFLAG(request, flags_, setReportLoadTiming,
WUR_FLAG_REPORT_LOAD_TIMING);
SETBOOLFLAG(request, flags_, setReportRawHeaders,
WUR_FLAG_REPORT_RAW_HEADERS);
@@ -188,32 +192,27 @@ void CefRequestImpl::Get(WebKit::WebURLRequest& request)
}
}
CefRequest::RequestFlags CefRequestImpl::GetFlags()
{
CefRequest::RequestFlags CefRequestImpl::GetFlags() {
AutoLock lock_scope(this);
return flags_;
}
void CefRequestImpl::SetFlags(RequestFlags flags)
{
void CefRequestImpl::SetFlags(RequestFlags flags) {
AutoLock lock_scope(this);
flags_ = flags;
}
CefString CefRequestImpl::GetFirstPartyForCookies()
{
CefString CefRequestImpl::GetFirstPartyForCookies() {
AutoLock lock_scope(this);
return first_party_for_cookies_;
}
void CefRequestImpl::SetFirstPartyForCookies(const CefString& url)
{
void CefRequestImpl::SetFirstPartyForCookies(const CefString& url) {
AutoLock lock_scope(this);
first_party_for_cookies_ = url;
}
// static
void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers,
HeaderMap& map)
{
void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers,
HeaderMap& map) {
net::HttpRequestHeaders::Iterator it(headers);
do {
map.insert(std::make_pair(it.name(), it.value()));
@@ -222,50 +221,43 @@ void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers,
// static
void CefRequestImpl::GetHeaderMap(const WebKit::WebURLRequest& request,
HeaderMap& map)
{
HeaderMap& map) {
HttpHeaderUtils::HeaderVisitor visitor(&map);
request.visitHTTPHeaderFields(&visitor);
}
// static
void CefRequestImpl::SetHeaderMap(const HeaderMap& map,
WebKit::WebURLRequest& request)
{
WebKit::WebURLRequest& request) {
HeaderMap::const_iterator it = map.begin();
for(; it != map.end(); ++it)
for (; it != map.end(); ++it)
request.setHTTPHeaderField(string16(it->first), string16(it->second));
}
CefRefPtr<CefPostData> CefPostData::CreatePostData()
{
CefRefPtr<CefPostData> CefPostData::CreatePostData() {
CefRefPtr<CefPostData> postdata(new CefPostDataImpl());
return postdata;
}
CefPostDataImpl::CefPostDataImpl()
{
CefPostDataImpl::CefPostDataImpl() {
}
size_t CefPostDataImpl::GetElementCount()
{
size_t CefPostDataImpl::GetElementCount() {
AutoLock lock_scope(this);
return elements_.size();
}
void CefPostDataImpl::GetElements(ElementVector& elements)
{
void CefPostDataImpl::GetElements(ElementVector& elements) {
AutoLock lock_scope(this);
elements = elements_;
}
bool CefPostDataImpl::RemoveElement(CefRefPtr<CefPostDataElement> element)
{
bool CefPostDataImpl::RemoveElement(CefRefPtr<CefPostDataElement> element) {
AutoLock lock_scope(this);
ElementVector::iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
if(it->get() == element.get()) {
for (; it != elements_.end(); ++it) {
if (it->get() == element.get()) {
elements_.erase(it);
return true;
}
@@ -274,35 +266,32 @@ bool CefPostDataImpl::RemoveElement(CefRefPtr<CefPostDataElement> element)
return false;
}
bool CefPostDataImpl::AddElement(CefRefPtr<CefPostDataElement> element)
{
bool CefPostDataImpl::AddElement(CefRefPtr<CefPostDataElement> element) {
bool found = false;
AutoLock lock_scope(this);
// check that the element isn't already in the list before adding
ElementVector::const_iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
if(it->get() == element.get()) {
for (; it != elements_.end(); ++it) {
if (it->get() == element.get()) {
found = true;
break;
}
}
if(!found)
if (!found)
elements_.push_back(element);
return !found;
}
void CefPostDataImpl::RemoveElements()
{
void CefPostDataImpl::RemoveElements() {
AutoLock lock_scope(this);
elements_.clear();
}
void CefPostDataImpl::Set(net::UploadData& data)
{
void CefPostDataImpl::Set(net::UploadData& data) {
AutoLock lock_scope(this);
CefRefPtr<CefPostDataElement> postelem;
@@ -316,22 +305,20 @@ void CefPostDataImpl::Set(net::UploadData& data)
}
}
void CefPostDataImpl::Get(net::UploadData& data)
{
void CefPostDataImpl::Get(net::UploadData& data) {
AutoLock lock_scope(this);
net::UploadData::Element element;
std::vector<net::UploadData::Element> data_elements;
ElementVector::iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
for (; it != elements_.end(); ++it) {
static_cast<CefPostDataElementImpl*>(it->get())->Get(element);
data_elements.push_back(element);
}
data.SetElements(data_elements);
}
void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data)
{
void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data) {
AutoLock lock_scope(this);
CefRefPtr<CefPostDataElement> postelem;
@@ -346,17 +333,16 @@ void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data)
}
}
void CefPostDataImpl::Get(WebKit::WebHTTPBody& data)
{
void CefPostDataImpl::Get(WebKit::WebHTTPBody& data) {
AutoLock lock_scope(this);
WebKit::WebHTTPBody::Element element;
ElementVector::iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
for (; it != elements_.end(); ++it) {
static_cast<CefPostDataElementImpl*>(it->get())->Get(element);
if(element.type == WebKit::WebHTTPBody::Element::TypeData) {
if (element.type == WebKit::WebHTTPBody::Element::TypeData) {
data.appendData(element.data);
} else if(element.type == WebKit::WebHTTPBody::Element::TypeFile) {
} else if (element.type == WebKit::WebHTTPBody::Element::TypeFile) {
data.appendFile(element.filePath);
} else {
NOTREACHED();
@@ -364,36 +350,31 @@ void CefPostDataImpl::Get(WebKit::WebHTTPBody& data)
}
}
CefRefPtr<CefPostDataElement> CefPostDataElement::CreatePostDataElement()
{
CefRefPtr<CefPostDataElement> CefPostDataElement::CreatePostDataElement() {
CefRefPtr<CefPostDataElement> element(new CefPostDataElementImpl());
return element;
}
CefPostDataElementImpl::CefPostDataElementImpl()
{
CefPostDataElementImpl::CefPostDataElementImpl() {
type_ = PDE_TYPE_EMPTY;
memset(&data_, 0, sizeof(data_));
}
CefPostDataElementImpl::~CefPostDataElementImpl()
{
CefPostDataElementImpl::~CefPostDataElementImpl() {
SetToEmpty();
}
void CefPostDataElementImpl::SetToEmpty()
{
void CefPostDataElementImpl::SetToEmpty() {
AutoLock lock_scope(this);
if(type_ == PDE_TYPE_BYTES)
if (type_ == PDE_TYPE_BYTES)
free(data_.bytes.bytes);
else if(type_ == PDE_TYPE_FILE)
else if (type_ == PDE_TYPE_FILE)
cef_string_clear(&data_.filename);
type_ = PDE_TYPE_EMPTY;
memset(&data_, 0, sizeof(data_));
}
void CefPostDataElementImpl::SetToFile(const CefString& fileName)
{
void CefPostDataElementImpl::SetToFile(const CefString& fileName) {
AutoLock lock_scope(this);
// Clear any data currently in the element
SetToEmpty();
@@ -403,8 +384,7 @@ void CefPostDataElementImpl::SetToFile(const CefString& fileName)
cef_string_copy(fileName.c_str(), fileName.length(), &data_.filename);
}
void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes)
{
void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes) {
AutoLock lock_scope(this);
// Clear any data currently in the element
SetToEmpty();
@@ -412,56 +392,51 @@ void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes)
// Assign the new data
void* data = malloc(size);
DCHECK(data != NULL);
if(data == NULL)
if (data == NULL)
return;
memcpy(data, bytes, size);
type_ = PDE_TYPE_BYTES;
data_.bytes.bytes = data;
data_.bytes.size = size;
}
CefPostDataElement::Type CefPostDataElementImpl::GetType()
{
CefPostDataElement::Type CefPostDataElementImpl::GetType() {
AutoLock lock_scope(this);
return type_;
}
CefString CefPostDataElementImpl::GetFile()
{
CefString CefPostDataElementImpl::GetFile() {
AutoLock lock_scope(this);
DCHECK(type_ == PDE_TYPE_FILE);
CefString filename;
if(type_ == PDE_TYPE_FILE)
if (type_ == PDE_TYPE_FILE)
filename.FromString(data_.filename.str, data_.filename.length, false);
return filename;
}
size_t CefPostDataElementImpl::GetBytesCount()
{
size_t CefPostDataElementImpl::GetBytesCount() {
AutoLock lock_scope(this);
DCHECK(type_ == PDE_TYPE_BYTES);
size_t size = 0;
if(type_ == PDE_TYPE_BYTES)
if (type_ == PDE_TYPE_BYTES)
size = data_.bytes.size;
return size;
}
size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes)
{
size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes) {
AutoLock lock_scope(this);
DCHECK(type_ == PDE_TYPE_BYTES);
size_t rv = 0;
if(type_ == PDE_TYPE_BYTES) {
if (type_ == PDE_TYPE_BYTES) {
rv = (size < data_.bytes.size ? size : data_.bytes.size);
memcpy(bytes, data_.bytes.bytes, rv);
}
return rv;
}
void CefPostDataElementImpl::Set(const net::UploadData::Element& element)
{
void CefPostDataElementImpl::Set(const net::UploadData::Element& element) {
AutoLock lock_scope(this);
if (element.type() == net::UploadData::TYPE_BYTES) {
@@ -476,13 +451,12 @@ void CefPostDataElementImpl::Set(const net::UploadData::Element& element)
}
}
void CefPostDataElementImpl::Get(net::UploadData::Element& element)
{
void CefPostDataElementImpl::Get(net::UploadData::Element& element) {
AutoLock lock_scope(this);
if(type_ == PDE_TYPE_BYTES) {
if (type_ == PDE_TYPE_BYTES) {
element.SetToBytes(static_cast<char*>(data_.bytes.bytes), data_.bytes.size);
} else if(type_ == PDE_TYPE_FILE) {
} else if (type_ == PDE_TYPE_FILE) {
FilePath path = FilePath(CefString(&data_.filename));
element.SetToFilePath(path);
} else {
@@ -490,29 +464,27 @@ void CefPostDataElementImpl::Get(net::UploadData::Element& element)
}
}
void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element)
{
void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element) {
AutoLock lock_scope(this);
if(element.type == WebKit::WebHTTPBody::Element::TypeData) {
if (element.type == WebKit::WebHTTPBody::Element::TypeData) {
SetToBytes(element.data.size(),
static_cast<const void*>(element.data.data()));
} else if(element.type == WebKit::WebHTTPBody::Element::TypeFile) {
} else if (element.type == WebKit::WebHTTPBody::Element::TypeFile) {
SetToFile(string16(element.filePath));
} else {
NOTREACHED();
}
}
void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element)
{
void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element) {
AutoLock lock_scope(this);
if(type_ == PDE_TYPE_BYTES) {
if (type_ == PDE_TYPE_BYTES) {
element.type = WebKit::WebHTTPBody::Element::TypeData;
element.data.assign(
static_cast<char*>(data_.bytes.bytes), data_.bytes.size);
} else if(type_ == PDE_TYPE_FILE) {
} else if (type_ == PDE_TYPE_FILE) {
element.type = WebKit::WebHTTPBody::Element::TypeFile;
element.filePath.assign(string16(CefString(&data_.filename)));
} else {

View File

@@ -3,14 +3,18 @@
// 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 "browser_devtools_scheme_handler.h"
#include "browser_resource_loader_bridge.h"
#include "cef_context.h"
#include "cef_thread.h"
#include "request_impl.h"
#include "response_impl.h"
#include <map>
#include "include/cef.h"
#include "libcef/browser_devtools_scheme_handler.h"
#include "libcef/browser_impl.h"
#include "libcef/browser_resource_loader_bridge.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "libcef/request_impl.h"
#include "libcef/response_impl.h"
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/message_loop.h"
@@ -18,6 +22,7 @@
#include "base/synchronization/lock.h"
#include "googleurl/src/url_util.h"
#include "net/base/completion_callback.h"
#include "net/base/cookie_monster.h"
#include "net/base/io_buffer.h"
#include "net/base/upload_data.h"
#include "net/http/http_response_headers.h"
@@ -35,22 +40,18 @@
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include <map>
using net::URLRequestStatus;
using WebKit::WebSecurityPolicy;
using WebKit::WebString;
namespace {
bool IsStandardScheme(const std::string& scheme)
{
bool IsStandardScheme(const std::string& scheme) {
url_parse::Component scheme_comp(0, scheme.length());
return url_util::IsStandard(scheme.c_str(), scheme_comp);
}
void RegisterStandardScheme(const std::string& scheme)
{
void RegisterStandardScheme(const std::string& scheme) {
REQUIRE_UIT();
url_parse::Component scheme_comp(0, scheme.length());
if (!url_util::IsStandard(scheme.c_str(), scheme_comp))
@@ -71,8 +72,7 @@ static const SchemeToFactory kBuiltinFactories[] = {
{ "data", net::URLRequestDataJob::Factory },
};
bool IsBuiltinScheme(const std::string& scheme)
{
bool IsBuiltinScheme(const std::string& scheme) {
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i)
if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme))
return true;
@@ -80,8 +80,7 @@ bool IsBuiltinScheme(const std::string& scheme)
}
net::URLRequestJob* GetBuiltinSchemeRequestJob(net::URLRequest* request,
const std::string& scheme)
{
const std::string& scheme) {
// See if the request should be handled by a built-in protocol factory.
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) {
if (scheme == kBuiltinFactories[i].scheme) {
@@ -94,8 +93,7 @@ net::URLRequestJob* GetBuiltinSchemeRequestJob(net::URLRequest* request,
return NULL;
}
std::string ToLower(const std::string& str)
{
std::string ToLower(const std::string& str) {
std::string str_lower = str;
std::transform(str_lower.begin(), str_lower.end(), str_lower.begin(),
towlower);
@@ -105,43 +103,155 @@ std::string ToLower(const std::string& str)
// net::URLRequestJob implementation.
class CefUrlRequestJob : public net::URLRequestJob {
public:
public:
CefUrlRequestJob(net::URLRequest* request,
CefRefPtr<CefSchemeHandler> handler)
: net::URLRequestJob(request),
handler_(handler),
remaining_bytes_(0)
{
remaining_bytes_(0),
response_cookies_save_index_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}
virtual ~CefUrlRequestJob()
{
virtual ~CefUrlRequestJob() {
}
virtual void Start() OVERRIDE
{
virtual void Start() OVERRIDE {
REQUIRE_IOT();
cef_request_ = CefRequest::CreateRequest();
// Populate the request data.
static_cast<CefRequestImpl*>(cef_request_.get())->Set(request_);
// Add default headers if not already specified.
const net::URLRequestContext* context = request_->context();
if (context) {
CefRequest::HeaderMap::const_iterator it;
CefRequest::HeaderMap headerMap;
cef_request_->GetHeaderMap(headerMap);
bool changed = false;
if (!context->accept_language().empty()) {
it = headerMap.find(net::HttpRequestHeaders::kAcceptLanguage);
if (it == headerMap.end()) {
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kAcceptLanguage,
context->accept_language()));
}
changed = true;
}
if (!context->accept_charset().empty()) {
it = headerMap.find(net::HttpRequestHeaders::kAcceptCharset);
if (it == headerMap.end()) {
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kAcceptCharset,
context->accept_charset()));
}
changed = true;
}
it = headerMap.find(net::HttpRequestHeaders::kUserAgent);
if (it == headerMap.end()) {
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kUserAgent,
context->GetUserAgent(request_->url())));
changed = true;
}
if (changed)
cef_request_->SetHeaderMap(headerMap);
}
AddCookieHeaderAndStart();
}
void AddCookieHeaderAndStart() {
// No matter what, we want to report our status as IO pending since we will
// be notifying our consumer asynchronously via OnStartCompleted.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
// If the request was destroyed, then there is no more work to do.
if (!request_)
return;
scoped_refptr<net::CookieStore> cookie_store =
request_->context()->cookie_store();
if (cookie_store) {
net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();
if (cookie_monster) {
cookie_monster->GetAllCookiesForURLAsync(
request_->url(),
base::Bind(&CefUrlRequestJob::CheckCookiePolicyAndLoad,
weak_factory_.GetWeakPtr()));
} else {
DoLoadCookies();
}
} else {
DoStartTransaction();
}
}
void DoLoadCookies() {
net::CookieOptions options;
options.set_include_httponly();
scoped_refptr<net::CookieStore> cookie_store =
request_->context()->cookie_store();
if (cookie_store) {
cookie_store->GetCookiesWithInfoAsync(
request_->url(), options,
base::Bind(&CefUrlRequestJob::OnCookiesLoaded,
weak_factory_.GetWeakPtr()));
}
}
void CheckCookiePolicyAndLoad(
const net::CookieList& cookie_list) {
if (CanGetCookies(cookie_list))
DoLoadCookies();
else
DoStartTransaction();
}
void OnCookiesLoaded(
const std::string& cookie_line,
const std::vector<net::CookieStore::CookieInfo>& cookie_infos) {
if (!cookie_line.empty()) {
CefRequest::HeaderMap headerMap;
cef_request_->GetHeaderMap(headerMap);
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kCookie, cookie_line));
cef_request_->SetHeaderMap(headerMap);
}
DoStartTransaction();
}
void DoStartTransaction() {
// We may have been canceled while retrieving cookies.
if (GetStatus().is_success()) {
StartTransaction();
} else {
NotifyCanceled();
}
}
void StartTransaction() {
if (!callback_)
callback_ = new Callback(this);
CefRefPtr<CefRequest> req(CefRequest::CreateRequest());
// Populate the request data.
static_cast<CefRequestImpl*>(req.get())->Set(request());
// Protect against deletion of this object.
base::WeakPtr<CefUrlRequestJob> weak_ptr(weak_factory_.GetWeakPtr());
// Handler can decide whether to process the request.
bool rv = handler_->ProcessRequest(req, callback_.get());
if (!rv) {
bool rv = handler_->ProcessRequest(cef_request_, callback_.get());
if (weak_ptr.get() && !rv) {
// Cancel the request.
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, ERR_ABORTED));
NotifyCanceled();
}
return;
}
virtual void Kill() OVERRIDE
{
virtual void Kill() OVERRIDE {
REQUIRE_IOT();
// Notify the handler that the request has been canceled.
@@ -156,8 +266,7 @@ public:
}
virtual bool ReadRawData(net::IOBuffer* dest, int dest_size, int *bytes_read)
OVERRIDE
{
OVERRIDE {
REQUIRE_IOT();
DCHECK_NE(dest_size, 0);
@@ -179,39 +288,33 @@ public:
// The handler has indicated completion of the request.
*bytes_read = 0;
return true;
} else if(*bytes_read == 0) {
} else if (*bytes_read == 0) {
if (!GetStatus().is_io_pending()) {
// Report our status as IO pending.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
callback_->SetDestination(dest, dest_size);
}
return false;
} else if(*bytes_read > dest_size) {
} else if (*bytes_read > dest_size) {
// Normalize the return value.
*bytes_read = dest_size;
}
if(remaining_bytes_ > 0)
if (remaining_bytes_ > 0)
remaining_bytes_ -= *bytes_read;
// Continue calling this method.
return true;
}
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE
{
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
REQUIRE_IOT();
if (response_.get()) {
CefResponseImpl* responseImpl =
static_cast<CefResponseImpl*>(response_.get());
info->headers = responseImpl->GetResponseHeaders();
}
info->headers = GetResponseHeaders();
}
virtual bool IsRedirectResponse(GURL* location, int* http_status_code)
OVERRIDE
{
OVERRIDE {
REQUIRE_IOT();
if (redirect_url_.is_valid()) {
@@ -228,7 +331,7 @@ public:
CefResponse::HeaderMap headerMap;
response_->GetHeaderMap(headerMap);
CefRequest::HeaderMap::iterator iter = headerMap.find("Location");
if(iter != headerMap.end()) {
if (iter != headerMap.end()) {
GURL new_url = GURL(std::string(iter->second));
*http_status_code = status;
location->Swap(&new_url);
@@ -240,8 +343,7 @@ public:
return false;
}
virtual bool GetMimeType(std::string* mime_type) const OVERRIDE
{
virtual bool GetMimeType(std::string* mime_type) const OVERRIDE {
REQUIRE_IOT();
if (response_.get())
@@ -252,9 +354,8 @@ public:
CefRefPtr<CefSchemeHandler> handler_;
CefRefPtr<CefResponse> response_;
private:
void SendHeaders()
{
private:
void SendHeaders() {
REQUIRE_IOT();
// We may have been orphaned...
@@ -277,20 +378,96 @@ private:
set_expected_content_size(remaining_bytes_);
// Continue processing the request.
NotifyHeadersComplete();
SaveCookiesAndNotifyHeadersComplete();
}
net::HttpResponseHeaders* GetResponseHeaders() {
DCHECK(response_);
if (!response_headers_.get()) {
CefResponseImpl* responseImpl =
static_cast<CefResponseImpl*>(response_.get());
response_headers_ = responseImpl->GetResponseHeaders();
}
return response_headers_;
}
void SaveCookiesAndNotifyHeadersComplete() {
response_cookies_.clear();
response_cookies_save_index_ = 0;
FetchResponseCookies(&response_cookies_);
// Now, loop over the response cookies, and attempt to persist each.
SaveNextCookie();
}
void SaveNextCookie() {
if (response_cookies_save_index_ == response_cookies_.size()) {
response_cookies_.clear();
response_cookies_save_index_ = 0;
SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
NotifyHeadersComplete();
return;
}
// No matter what, we want to report our status as IO pending since we will
// be notifying our consumer asynchronously via OnStartCompleted.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
net::CookieOptions options;
options.set_include_httponly();
if (CanSetCookie(
response_cookies_[response_cookies_save_index_], &options)) {
scoped_refptr<net::CookieStore> cookie_store =
request_->context()->cookie_store();
if (cookie_store) {
cookie_store->SetCookieWithOptionsAsync(
request_->url(), response_cookies_[response_cookies_save_index_],
options, base::Bind(&CefUrlRequestJob::OnCookieSaved,
weak_factory_.GetWeakPtr()));
}
return;
}
CookieHandled();
}
void OnCookieSaved(bool cookie_status) {
CookieHandled();
}
void CookieHandled() {
response_cookies_save_index_++;
// We may have been canceled within OnSetCookie.
if (GetStatus().is_success()) {
SaveNextCookie();
} else {
NotifyCanceled();
}
}
void FetchResponseCookies(
std::vector<std::string>* cookies) {
const std::string name = "Set-Cookie";
std::string value;
void* iter = NULL;
net::HttpResponseHeaders* headers = GetResponseHeaders();
while (headers->EnumerateHeader(&iter, name, &value)) {
if (!value.empty())
cookies->push_back(value);
}
}
// Client callback for asynchronous response continuation.
class Callback : public CefSchemeHandlerCallback
{
public:
Callback(CefUrlRequestJob* job)
class Callback : public CefSchemeHandlerCallback {
public:
explicit Callback(CefUrlRequestJob* job)
: job_(job),
dest_(NULL),
dest_size_() {}
virtual void HeadersAvailable() OVERRIDE
{
virtual void HeadersAvailable() OVERRIDE {
if (CefThread::CurrentlyOn(CefThread::IO)) {
// Currently on IO thread.
if (job_ && !job_->has_response_started()) {
@@ -300,12 +477,11 @@ private:
} else {
// Execute this method on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableMethod(this, &Callback::HeadersAvailable));
base::Bind(&Callback::HeadersAvailable, this));
}
}
virtual void BytesAvailable() OVERRIDE
{
virtual void BytesAvailable() OVERRIDE {
if (CefThread::CurrentlyOn(CefThread::IO)) {
// Currently on IO thread.
if (job_ && job_->has_response_started() &&
@@ -322,21 +498,25 @@ private:
dest_ = NULL;
dest_size_ = 0;
} else {
// All done.
job_->NotifyDone(URLRequestStatus());
}
} else {
// All done.
} else if (!job_->GetStatus().is_io_pending()) {
// Failed due to an error.
NOTREACHED() <<
"ReadRawData returned false without setting IO as pending";
job_->NotifyDone(URLRequestStatus());
}
}
} else {
// Execute this method on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableMethod(this, &Callback::BytesAvailable));
base::Bind(&Callback::BytesAvailable, this));
}
}
virtual void Cancel() OVERRIDE
{
virtual void Cancel() OVERRIDE {
if (CefThread::CurrentlyOn(CefThread::IO)) {
// Currently on IO thread.
if (job_)
@@ -344,25 +524,23 @@ private:
} else {
// Execute this method on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableMethod(this, &Callback::Cancel));
base::Bind(&Callback::Cancel, this));
}
}
void Detach()
{
void Detach() {
REQUIRE_IOT();
job_ = NULL;
}
void SetDestination(net::IOBuffer* dest, int dest_size)
{
void SetDestination(net::IOBuffer* dest, int dest_size) {
dest_ = dest;
dest_size_ = dest_size;
}
static bool ImplementsThreadSafeReferenceCounting() { return true; }
private:
private:
CefUrlRequestJob* job_;
net::IOBuffer* dest_;
@@ -373,7 +551,12 @@ private:
GURL redirect_url_;
int64 remaining_bytes_;
CefRefPtr<CefRequest> cef_request_;
CefRefPtr<Callback> callback_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
std::vector<std::string> response_cookies_;
size_t response_cookies_save_index_;
base::WeakPtrFactory<CefUrlRequestJob> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(CefUrlRequestJob);
};
@@ -381,28 +564,27 @@ private:
// Class that manages the CefSchemeHandlerFactory instances.
class CefUrlRequestManager {
protected:
protected:
// Class used for creating URLRequestJob instances. The lifespan of this
// object is managed by URLRequestJobFactory.
class ProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
public:
ProtocolHandler(const std::string& scheme)
public:
explicit ProtocolHandler(const std::string& scheme)
: scheme_(scheme) {}
// From net::URLRequestJobFactory::ProtocolHandler
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request) const OVERRIDE
{
net::URLRequest* request) const OVERRIDE {
REQUIRE_IOT();
return CefUrlRequestManager::GetInstance()->GetRequestJob(request,
scheme_);
}
private:
private:
std::string scheme_;
};
public:
public:
CefUrlRequestManager() {}
// Retrieve the singleton instance.
@@ -410,8 +592,7 @@ public:
bool AddFactory(const std::string& scheme,
const std::string& domain,
CefRefPtr<CefSchemeHandlerFactory> factory)
{
CefRefPtr<CefSchemeHandlerFactory> factory) {
if (!factory.get()) {
RemoveFactory(scheme, domain);
return true;
@@ -439,8 +620,7 @@ public:
}
void RemoveFactory(const std::string& scheme,
const std::string& domain)
{
const std::string& domain) {
REQUIRE_IOT();
std::string scheme_lower = ToLower(scheme);
@@ -457,8 +637,7 @@ public:
}
// Clear all the existing URL handlers and unregister the ProtocolFactory.
void ClearFactories()
{
void ClearFactories() {
REQUIRE_IOT();
net::URLRequestJobFactory* job_factory =
@@ -480,8 +659,7 @@ public:
}
// Check if a scheme has already been registered.
bool HasRegisteredScheme(const std::string& scheme)
{
bool HasRegisteredScheme(const std::string& scheme) {
std::string scheme_lower = ToLower(scheme);
// Don't register builtin schemes.
@@ -498,8 +676,7 @@ public:
bool RegisterScheme(const std::string& scheme,
bool is_standard,
bool is_local,
bool is_display_isolated)
{
bool is_display_isolated) {
if (HasRegisteredScheme(scheme)) {
NOTREACHED() << "Scheme already registered: " << scheme;
return false;
@@ -525,12 +702,11 @@ public:
return true;
}
private:
private:
// Retrieve the matching handler factory, if any. |scheme| will already be in
// lower case.
CefRefPtr<CefSchemeHandlerFactory> GetHandlerFactory(
net::URLRequest* request, const std::string& scheme)
{
net::URLRequest* request, const std::string& scheme) {
CefRefPtr<CefSchemeHandlerFactory> factory;
if (request->url().is_valid() && IsStandardScheme(scheme)) {
@@ -556,8 +732,7 @@ private:
// Create the job that will handle the request. |scheme| will already be in
// lower case.
net::URLRequestJob* GetRequestJob(net::URLRequest* request,
const std::string& scheme)
{
const std::string& scheme) {
net::URLRequestJob* job = NULL;
CefRefPtr<CefSchemeHandlerFactory> factory =
GetHandlerFactory(request, scheme);
@@ -565,10 +740,10 @@ private:
// Call the handler factory to create the handler for the request.
CefRefPtr<CefRequest> requestPtr(new CefRequestImpl());
static_cast<CefRequestImpl*>(requestPtr.get())->Set(request);
CefRefPtr<CefBrowser> browser =
CefRefPtr<CefBrowserImpl> browser =
BrowserResourceLoaderBridge::GetBrowserForRequest(request);
CefRefPtr<CefSchemeHandler> handler =
factory->Create(browser, scheme, requestPtr);
factory->Create(browser.get(), scheme, requestPtr);
if (handler.get())
job = new CefUrlRequestJob(request, handler);
}
@@ -582,7 +757,7 @@ private:
if (job)
DLOG(INFO) << "CefUrlRequestManager hit for " << request->url().spec();
#endif
return job;
}
@@ -602,19 +777,17 @@ private:
base::LazyInstance<CefUrlRequestManager> g_manager = LAZY_INSTANCE_INITIALIZER;
CefUrlRequestManager* CefUrlRequestManager::GetInstance()
{
CefUrlRequestManager* CefUrlRequestManager::GetInstance() {
return g_manager.Pointer();
}
} // anonymous
} // namespace
bool CefRegisterCustomScheme(const CefString& scheme_name,
bool is_standard,
bool is_local,
bool is_display_isolated)
{
bool is_display_isolated) {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
@@ -631,18 +804,18 @@ bool CefRegisterCustomScheme(const CefString& scheme_name,
NOTREACHED() << "Scheme already registered: " << scheme_name;
return false;
}
CefThread::PostTask(CefThread::UI, FROM_HERE,
NewRunnableFunction(&CefRegisterCustomScheme, scheme_name, is_standard,
is_local, is_display_isolated));
base::Bind(base::IgnoreResult(&CefRegisterCustomScheme), scheme_name,
is_standard, is_local, is_display_isolated));
return true;
}
}
bool CefRegisterSchemeHandlerFactory(const CefString& scheme_name,
const CefString& domain_name,
CefRefPtr<CefSchemeHandlerFactory> factory)
{
bool CefRegisterSchemeHandlerFactory(
const CefString& scheme_name,
const CefString& domain_name,
CefRefPtr<CefSchemeHandlerFactory> factory) {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
@@ -655,14 +828,13 @@ bool CefRegisterSchemeHandlerFactory(const CefString& scheme_name,
factory);
} else {
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableFunction(&CefRegisterSchemeHandlerFactory, scheme_name,
domain_name, factory));
base::Bind(base::IgnoreResult(&CefRegisterSchemeHandlerFactory),
scheme_name, domain_name, factory));
return true;
}
}
bool CefClearSchemeHandlerFactories()
{
bool CefClearSchemeHandlerFactories() {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
@@ -676,7 +848,7 @@ bool CefClearSchemeHandlerFactories()
RegisterDevToolsSchemeHandler(false);
} else {
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableFunction(&CefClearSchemeHandlerFactories));
base::Bind(base::IgnoreResult(&CefClearSchemeHandlerFactories)));
}
return true;

View File

@@ -2,10 +2,23 @@
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "browser_impl.h"
#include "v8_impl.h"
#include "cef_context.h"
#include "tracker.h"
#include <string>
#include "base/compiler_specific.h"
#include "third_party/WebKit/Source/WebCore/config.h"
MSVC_PUSH_WARNING_LEVEL(0);
#include "V8Proxy.h" // NOLINT(build/include)
MSVC_POP_WARNING();
#undef LOG
#include "libcef/v8_impl.h"
#include "libcef/browser_impl.h"
#include "libcef/cef_context.h"
#include "libcef/tracker.h"
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
@@ -135,9 +148,14 @@ void v8impl_string_dtor(char* str)
// Convert a v8::String to CefString.
void GetCefString(v8::Handle<v8::String> str, CefString& out)
{
if (str.IsEmpty())
return;
#if defined(CEF_STRING_TYPE_WIDE)
// Allocate enough space for a worst-case conversion.
int len = str->Utf8Length();
if (len == 0)
return;
char* buf = new char[len + 1];
str->WriteUtf8(buf, len + 1);
@@ -149,11 +167,15 @@ void GetCefString(v8::Handle<v8::String> str, CefString& out)
#else // !defined(CEF_STRING_TYPE_WIDE)
#if defined(CEF_STRING_TYPE_UTF16)
int len = str->Length();
if (len == 0)
return;
char16* buf = new char16[len + 1];
str->Write(reinterpret_cast<uint16_t*>(buf), 0, len + 1);
#else
// Allocate enough space for a worst-case conversion.
int len = str->Utf8Length();
if (len == 0)
return;
char* buf = new char[len + 1];
str->WriteUtf8(buf, len + 1);
#endif
@@ -400,11 +422,11 @@ bool CefV8Context::InContext()
// CefV8ContextImpl
CefV8ContextImpl::CefV8ContextImpl(v8::Handle<v8::Context> context)
: handle_(new Handle(context))
#ifndef NDEBUG
: enter_count_(0)
, enter_count_(0)
#endif
{
v8_context_ = new CefV8ContextHandle(context);
}
CefV8ContextImpl::~CefV8ContextImpl()
@@ -445,14 +467,14 @@ CefRefPtr<CefV8Value> CefV8ContextImpl::GetGlobal()
CEF_REQUIRE_UI_THREAD(NULL);
v8::HandleScope handle_scope;
v8::Context::Scope context_scope(v8_context_->GetHandle());
return new CefV8ValueImpl(v8_context_->GetHandle()->Global());
v8::Context::Scope context_scope(GetHandle());
return new CefV8ValueImpl(GetHandle()->Global());
}
bool CefV8ContextImpl::Enter()
{
CEF_REQUIRE_UI_THREAD(false);
v8_context_->GetHandle()->Enter();
GetHandle()->Enter();
#ifndef NDEBUG
++enter_count_;
#endif
@@ -463,7 +485,7 @@ bool CefV8ContextImpl::Exit()
{
CEF_REQUIRE_UI_THREAD(false);
DLOG_ASSERT(enter_count_ > 0);
v8_context_->GetHandle()->Exit();
GetHandle()->Exit();
#ifndef NDEBUG
--enter_count_;
#endif
@@ -486,32 +508,77 @@ bool CefV8ContextImpl::IsSame(CefRefPtr<CefV8Context> that)
return (thisHandle == thatHandle);
}
bool CefV8ContextImpl::Eval(const CefString& code,
CefRefPtr<CefV8Value>& retval,
CefRefPtr<CefV8Exception>& exception) {
CEF_REQUIRE_UI_THREAD(NULL);
if (code.empty()) {
NOTREACHED() << "invalid input parameter";
return false;
}
v8::HandleScope handle_scope;
v8::Context::Scope context_scope(GetHandle());
v8::Local<v8::Object> obj = GetHandle()->Global();
// Retrieve the eval function.
v8::Local<v8::Value> val = obj->Get(v8::String::New("eval"));
if (val.IsEmpty() || !val->IsFunction())
return false;
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(val);
v8::Handle<v8::Value> code_val = GetV8String(code);
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
v8::Local<v8::Value> func_rv;
retval = NULL;
exception = NULL;
// Execute the function call using the V8Proxy so that inspector
// instrumentation works.
WebCore::V8Proxy* proxy = WebCore::V8Proxy::retrieve();
DCHECK(proxy);
if (proxy)
func_rv = proxy->callFunction(func, obj, 1, &code_val);
if (try_catch.HasCaught()) {
exception = new CefV8ExceptionImpl(try_catch.Message());
return false;
} else if (!func_rv.IsEmpty()) {
retval = new CefV8ValueImpl(func_rv);
}
return true;
}
v8::Local<v8::Context> CefV8ContextImpl::GetContext()
{
return v8::Local<v8::Context>::New(v8_context_->GetHandle());
return v8::Local<v8::Context>::New(GetHandle());
}
WebKit::WebFrame* CefV8ContextImpl::GetWebFrame()
{
v8::HandleScope handle_scope;
v8::Context::Scope context_scope(v8_context_->GetHandle());
v8::Context::Scope context_scope(GetHandle());
WebKit::WebFrame* frame = WebKit::WebFrame::frameForCurrentContext();
return frame;
}
// CefV8ValueHandle
// CefV8ValueImpl::Handle
// Custom destructor for a v8 value handle which gets called only on the UI
// thread.
CefV8ValueHandle::~CefV8ValueHandle()
CefV8ValueImpl::Handle::~Handle()
{
if(tracker_) {
TrackAdd(tracker_);
v8_handle_.MakeWeak(tracker_, TrackDestructor);
handle_.MakeWeak(tracker_, TrackDestructor);
} else {
v8_handle_.Dispose();
v8_handle_.Clear();
handle_.Dispose();
handle_.Clear();
}
tracker_ = NULL;
}
@@ -700,8 +767,7 @@ CefRefPtr<CefV8Value> CefV8Value::CreateFunction(const CefString& name,
CefV8ValueImpl::CefV8ValueImpl(v8::Handle<v8::Value> value,
CefTrackObject* tracker)
{
v8_value_ = new CefV8ValueHandle(value, tracker);
: handle_(new Handle(value, tracker)) {
}
CefV8ValueImpl::~CefV8ValueImpl()
@@ -1173,6 +1239,9 @@ bool CefV8ValueImpl::ExecuteFunctionWithContext(
retval = new CefV8ValueImpl(func_rv);
}
if (argv)
delete [] argv;
return true;
}
@@ -1186,3 +1255,105 @@ CefV8Accessor* CefV8ValueImpl::GetAccessor(v8::Handle<v8::Object> object)
return NULL;
}
// CefV8StackTrace
// static
CefRefPtr<CefV8StackTrace> CefV8StackTrace::GetCurrent(int frame_limit) {
CEF_REQUIRE_VALID_CONTEXT(NULL);
CEF_REQUIRE_UI_THREAD(NULL);
v8::Handle<v8::StackTrace> stackTrace =
v8::StackTrace::CurrentStackTrace(
frame_limit, v8::StackTrace::kDetailed);
if (stackTrace.IsEmpty())
return NULL;
return new CefV8StackTraceImpl(stackTrace);
}
// CefV8StackTraceImpl
CefV8StackTraceImpl::CefV8StackTraceImpl(v8::Handle<v8::StackTrace> handle)
: handle_(new Handle(handle)) {
}
CefV8StackTraceImpl::~CefV8StackTraceImpl() {
}
int CefV8StackTraceImpl::GetFrameCount() {
CEF_REQUIRE_UI_THREAD(0);
v8::HandleScope handle_scope;
return GetHandle()->GetFrameCount();
}
CefRefPtr<CefV8StackFrame> CefV8StackTraceImpl::GetFrame(int index) {
CEF_REQUIRE_UI_THREAD(NULL);
v8::HandleScope handle_scope;
v8::Handle<v8::StackFrame> stackFrame = GetHandle()->GetFrame(index);
if (stackFrame.IsEmpty())
return NULL;
return new CefV8StackFrameImpl(stackFrame);
}
// CefV8StackFrameImpl
CefV8StackFrameImpl::CefV8StackFrameImpl(v8::Handle<v8::StackFrame> handle)
: handle_(new Handle(handle)) {
}
CefV8StackFrameImpl::~CefV8StackFrameImpl() {
}
CefString CefV8StackFrameImpl::GetScriptName() {
CefString rv;
CEF_REQUIRE_UI_THREAD(rv);
v8::HandleScope handle_scope;
GetCefString(v8::Handle<v8::String>::Cast(GetHandle()->GetScriptName()), rv);
return rv;
}
CefString CefV8StackFrameImpl::GetScriptNameOrSourceURL() {
CefString rv;
CEF_REQUIRE_UI_THREAD(rv);
v8::HandleScope handle_scope;
GetCefString(
v8::Handle<v8::String>::Cast(GetHandle()->GetScriptNameOrSourceURL()),
rv);
return rv;
}
CefString CefV8StackFrameImpl::GetFunctionName() {
CefString rv;
CEF_REQUIRE_UI_THREAD(rv);
v8::HandleScope handle_scope;
GetCefString(
v8::Handle<v8::String>::Cast(GetHandle()->GetFunctionName()), rv);
return rv;
}
int CefV8StackFrameImpl::GetLineNumber() {
CEF_REQUIRE_UI_THREAD(0);
v8::HandleScope handle_scope;
return GetHandle()->GetLineNumber();
}
int CefV8StackFrameImpl::GetColumn() {
CEF_REQUIRE_UI_THREAD(0);
v8::HandleScope handle_scope;
return GetHandle()->GetColumn();
}
bool CefV8StackFrameImpl::IsEval() {
CEF_REQUIRE_UI_THREAD(false);
v8::HandleScope handle_scope;
return GetHandle()->IsEval();
}
bool CefV8StackFrameImpl::IsConstructor() {
CEF_REQUIRE_UI_THREAD(false);
v8::HandleScope handle_scope;
return GetHandle()->IsConstructor();
}

View File

@@ -5,8 +5,12 @@
#ifndef _V8_IMPL_H
#define _V8_IMPL_H
#include <vector>
#include "include/cef.h"
#include "v8/include/v8.h"
#include "libcef/cef_thread.h"
#include "base/memory/ref_counted.h"
class CefTrackObject;
@@ -16,53 +20,40 @@ class WebFrame;
// Template for V8 Handle types. This class is used to ensure that V8 objects
// are only released on the UI thread.
template <class v8class>
class CefReleaseV8HandleOnUIThread:
public base::RefCountedThreadSafe<CefReleaseV8HandleOnUIThread<v8class>,
CefThread::DeleteOnUIThread>
{
public:
template <typename v8class>
class CefV8Handle :
public base::RefCountedThreadSafe<CefV8Handle<v8class>,
CefThread::DeleteOnUIThread> {
public:
typedef v8::Handle<v8class> handleType;
typedef v8::Persistent<v8class> persistentType;
typedef CefReleaseV8HandleOnUIThread<v8class> superType;
CefReleaseV8HandleOnUIThread(handleType v)
{
v8_handle_ = persistentType::New(v);
CefV8Handle(handleType v)
: handle_(persistentType::New(v)) {
}
virtual ~CefReleaseV8HandleOnUIThread()
{
~CefV8Handle() {
handle_.Dispose();
handle_.Clear();
}
handleType GetHandle()
{
return v8_handle_;
}
handleType GetHandle() { return handle_; }
persistentType v8_handle_;
protected:
persistentType handle_;
DISALLOW_COPY_AND_ASSIGN(CefV8Handle);
};
// Special class for a v8::Context to ensure that it is deleted from the UI
// thread.
class CefV8ContextHandle : public CefReleaseV8HandleOnUIThread<v8::Context>
{
public:
CefV8ContextHandle(handleType context): superType(context)
{
}
// Context handles are disposed rather than makeweak.
~CefV8ContextHandle()
{
v8_handle_.Dispose();
v8_handle_.Clear();
}
// Specialization for v8::Value with empty implementation to avoid incorrect
// usage.
template <>
class CefV8Handle<v8::Value> {
};
class CefV8ContextImpl : public CefV8Context
{
public:
CefV8ContextImpl(v8::Handle<v8::Context> context);
class CefV8ContextImpl : public CefV8Context {
public:
explicit CefV8ContextImpl(v8::Handle<v8::Context> context);
virtual ~CefV8ContextImpl();
virtual CefRefPtr<CefBrowser> GetBrowser() OVERRIDE;
@@ -71,12 +62,18 @@ public:
virtual bool Enter() OVERRIDE;
virtual bool Exit() OVERRIDE;
virtual bool IsSame(CefRefPtr<CefV8Context> that) OVERRIDE;
virtual bool Eval(const CefString& code,
CefRefPtr<CefV8Value>& retval,
CefRefPtr<CefV8Exception>& exception) OVERRIDE;
v8::Local<v8::Context> GetContext();
WebKit::WebFrame* GetWebFrame();
v8::Handle<v8::Context> GetHandle() { return handle_->GetHandle(); }
protected:
scoped_refptr<CefV8ContextHandle> v8_context_;
typedef CefV8Handle<v8::Context> Handle;
scoped_refptr<Handle> handle_;
#ifndef NDEBUG
// Used in debug builds to catch missing Exits in destructor.
@@ -86,27 +83,8 @@ protected:
IMPLEMENT_REFCOUNTING(CefV8ContextImpl);
};
// Special class for a v8::Value to ensure that it is deleted from the UI
// thread.
class CefV8ValueHandle: public CefReleaseV8HandleOnUIThread<v8::Value>
{
public:
CefV8ValueHandle(handleType value, CefTrackObject* tracker)
: superType(value), tracker_(tracker)
{
}
// Destructor implementation is provided in v8_impl.cc.
~CefV8ValueHandle();
private:
// For Object and Function types, we need to hold on to a reference to their
// internal data or function handler objects that are reference counted.
CefTrackObject *tracker_;
};
class CefV8ValueImpl : public CefV8Value
{
public:
class CefV8ValueImpl : public CefV8Value {
public:
CefV8ValueImpl(v8::Handle<v8::Value> value, CefTrackObject* tracker = NULL);
virtual ~CefV8ValueImpl();
@@ -155,19 +133,79 @@ public:
CefRefPtr<CefV8Exception>& exception,
bool rethrow_exception) OVERRIDE;
inline v8::Handle<v8::Value> GetHandle()
{
DCHECK(v8_value_.get());
return v8_value_->GetHandle();
}
v8::Handle<v8::Value> GetHandle() { return handle_->GetHandle(); }
// Returns the accessor assigned for the specified object, if any.
static CefV8Accessor* GetAccessor(v8::Handle<v8::Object> object);
protected:
scoped_refptr<CefV8ValueHandle> v8_value_;
protected:
class Handle :
public base::RefCountedThreadSafe<Handle, CefThread::DeleteOnUIThread> {
public:
typedef v8::Handle<v8::Value> handleType;
typedef v8::Persistent<v8::Value> persistentType;
Handle(handleType v, CefTrackObject* tracker)
: handle_(persistentType::New(v)),
tracker_(tracker) {
}
~Handle();
handleType GetHandle() { return handle_; }
private:
persistentType handle_;
// For Object and Function types, we need to hold on to a reference to their
// internal data or function handler objects that are reference counted.
CefTrackObject* tracker_;
DISALLOW_COPY_AND_ASSIGN(Handle);
};
scoped_refptr<Handle> handle_;
IMPLEMENT_REFCOUNTING(CefV8ValueImpl);
};
class CefV8StackTraceImpl : public CefV8StackTrace {
public:
explicit CefV8StackTraceImpl(v8::Handle<v8::StackTrace> handle);
virtual ~CefV8StackTraceImpl();
virtual int GetFrameCount() OVERRIDE;
virtual CefRefPtr<CefV8StackFrame> GetFrame(int index) OVERRIDE;
v8::Handle<v8::StackTrace> GetHandle() { return handle_->GetHandle(); }
protected:
typedef CefV8Handle<v8::StackTrace> Handle;
scoped_refptr<Handle> handle_;
IMPLEMENT_REFCOUNTING(CefV8StackTraceImpl);
DISALLOW_COPY_AND_ASSIGN(CefV8StackTraceImpl);
};
class CefV8StackFrameImpl : public CefV8StackFrame {
public:
explicit CefV8StackFrameImpl(v8::Handle<v8::StackFrame> handle);
virtual ~CefV8StackFrameImpl();
virtual CefString GetScriptName() OVERRIDE;
virtual CefString GetScriptNameOrSourceURL() OVERRIDE;
virtual CefString GetFunctionName() OVERRIDE;
virtual int GetLineNumber() OVERRIDE;
virtual int GetColumn() OVERRIDE;
virtual bool IsEval() OVERRIDE;
virtual bool IsConstructor() OVERRIDE;
v8::Handle<v8::StackFrame> GetHandle() { return handle_->GetHandle(); }
protected:
typedef CefV8Handle<v8::StackFrame> Handle;
scoped_refptr<Handle> handle_;
IMPLEMENT_REFCOUNTING(CefV8StackFrameImpl);
DISALLOW_COPY_AND_ASSIGN(CefV8StackFrameImpl);
};
#endif //_V8_IMPL_H

105
libcef/web_plugin_impl.cc Normal file
View File

@@ -0,0 +1,105 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "webkit/plugins/npapi/plugin_list.h"
namespace {
class CefWebPluginInfoImpl : public CefWebPluginInfo {
public:
explicit CefWebPluginInfoImpl(const webkit::WebPluginInfo& plugin_info)
: plugin_info_(plugin_info) {
}
virtual CefString GetName() OVERRIDE {
return plugin_info_.name;
}
virtual CefString GetPath() OVERRIDE {
return plugin_info_.path.value();
}
virtual CefString GetVersion() OVERRIDE {
return plugin_info_.version;
}
virtual CefString GetDescription() OVERRIDE {
return plugin_info_.desc;
}
private:
webkit::WebPluginInfo plugin_info_;
IMPLEMENT_REFCOUNTING(CefWebPluginInfoImpl);
};
} // namespace
size_t CefGetWebPluginCount() {
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
return 0;
}
if (!CefThread::CurrentlyOn(CefThread::UI)) {
NOTREACHED() << "called on invalid thread";
return 0;
}
std::vector<webkit::WebPluginInfo> plugins;
webkit::npapi::PluginList::Singleton()->GetPlugins(&plugins);
return plugins.size();
}
CefRefPtr<CefWebPluginInfo> CefGetWebPluginInfo(int index) {
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
return 0;
}
if (!CefThread::CurrentlyOn(CefThread::UI)) {
NOTREACHED() << "called on invalid thread";
return 0;
}
std::vector<webkit::WebPluginInfo> plugins;
webkit::npapi::PluginList::Singleton()->GetPlugins(&plugins);
if (index < 0 || index >= static_cast<int>(plugins.size()))
return NULL;
return new CefWebPluginInfoImpl(plugins[index]);
}
CefRefPtr<CefWebPluginInfo> CefGetWebPluginInfo(const CefString& name) {
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
return 0;
}
if (!CefThread::CurrentlyOn(CefThread::UI)) {
NOTREACHED() << "called on invalid thread";
return 0;
}
std::vector<webkit::WebPluginInfo> plugins;
webkit::npapi::PluginList::Singleton()->GetPlugins(&plugins);
std::string nameStr = name;
StringToLowerASCII(&nameStr);
std::vector<webkit::WebPluginInfo>::const_iterator it = plugins.begin();
for (; it != plugins.end(); ++it) {
if (LowerCaseEqualsASCII(it->name, nameStr.c_str()))
return new CefWebPluginInfoImpl(*it);
}
return NULL;
}

View File

@@ -3,6 +3,7 @@
// can be found in the LICENSE file.
#include "webview_host.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
WebViewHost::WebViewHost(BrowserWebViewDelegate* delegate)
: delegate_(delegate)
@@ -14,3 +15,7 @@ WebViewHost::~WebViewHost()
{
}
#endif
bool WebViewHost::IsTransparent() {
return static_cast<WebKit::WebView*>(webwidget_)->isTransparent();
}

View File

@@ -57,6 +57,8 @@ class WebViewHost : public WebWidgetHost {
virtual void SetFocus(bool enable);
#endif
virtual bool IsTransparent();
protected:
WebViewHost(BrowserWebViewDelegate* delegate);

View File

@@ -40,6 +40,7 @@ WebViewHost* WebViewHost::Create(GtkWidget* parent_view,
host->webwidget_ = WebView::create(delegate);
#endif
host->webview()->setDevToolsAgentClient(dev_tools_client);
host->webview()->setPermissionClient(delegate);
prefs.Apply(host->webview());
host->webview()->initializeMainFrame(delegate);
host->webwidget_->layout();

View File

@@ -35,10 +35,15 @@ WebViewHost* WebViewHost::Create(NSView* parent_view,
WebViewHost* host = new WebViewHost(delegate);
NSRect content_rect = {{rect.x(), rect.y()}, {rect.width(), rect.height()}};
host->view_ = [[BrowserWebView alloc] initWithFrame:content_rect];
[host->view_ setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[parent_view addSubview:host->view_];
[host->view_ release];
if (!paint_delegate) {
host->view_ = [[BrowserWebView alloc] initWithFrame:content_rect];
[host->view_ setAutoresizingMask:(NSViewWidthSizable |
NSViewHeightSizable)];
[parent_view addSubview:host->view_];
[host->view_ release];
} else {
host->paint_delegate_ = paint_delegate;
}
#if defined(WEBKIT_HAS_WEB_AUTO_FILL_CLIENT)
host->webwidget_ = WebView::create(delegate, NULL);
@@ -46,6 +51,7 @@ WebViewHost* WebViewHost::Create(NSView* parent_view,
host->webwidget_ = WebView::create(delegate);
#endif
host->webview()->setDevToolsAgentClient(dev_tools_client);
host->webview()->setPermissionClient(delegate);
prefs.Apply(host->webview());
host->webview()->initializeMainFrame(delegate);
host->webwidget_->resize(WebSize(content_rect.size.width,

View File

@@ -60,6 +60,7 @@ WebViewHost* WebViewHost::Create(HWND parent_view,
host->webwidget_ = WebView::create(delegate);
#endif
host->webview()->setDevToolsAgentClient(dev_tools_client);
host->webview()->setPermissionClient(delegate);
prefs.Apply(host->webview());
host->webview()->initializeMainFrame(delegate);

View File

@@ -2,63 +2,83 @@
// 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 "cef_thread.h"
#include "libcef/webwidget_host.h"
#include "libcef/cef_thread.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebWidget.h"
#include "webkit/glue/webkit_glue.h"
using webkit::npapi::WebPluginGeometry;
using WebKit::WebSize;
const int WebWidgetHost::kDefaultFrameRate = 30;
const int WebWidgetHost::kMaxFrameRate = 90;
void WebWidgetHost::ScheduleComposite() {
if (has_invalidate_task_)
void WebWidgetHost::InvalidateRect(const gfx::Rect& rect) {
if (rect.IsEmpty())
return;
has_invalidate_task_ = true;
int width, height;
GetSize(width, height);
const gfx::Rect client_rect(width, height);
// Try to paint at 60fps.
static int64 kDesiredRate = 16;
const gfx::Rect rect_in_client = client_rect.Intersect(rect);
if (rect_in_client.IsEmpty())
return;
base::TimeDelta delta = base::TimeTicks::Now() - paint_last_call_;
int64 actualRate = delta.InMilliseconds();
if (actualRate >= kDesiredRate) {
// Can't keep up so run as fast as possible.
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(&WebWidgetHost::Invalidate, weak_factory_.GetWeakPtr()));
} else {
// Maintain the desired rate.
MessageLoop::current()->PostDelayedTask(FROM_HERE,
base::Bind(&WebWidgetHost::Invalidate, weak_factory_.GetWeakPtr()),
kDesiredRate - actualRate);
}
UpdatePaintRect(rect_in_client);
if (view_)
InvalidateWindowRect(rect_in_client);
else
ScheduleTimer();
}
void WebWidgetHost::ScheduleComposite() {
ScheduleTimer();
}
void WebWidgetHost::ScheduleAnimation() {
ScheduleComposite();
ScheduleTimer();
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
#if defined(OS_WIN) || defined(OS_MACOSX)
paint_rgn_.op(rect.x(), rect.y(), rect.right(), rect.bottom(),
SkRegion::kUnion_Op);
#else
// TODO: Update all ports to use regions instead of rectangles.
paint_rect_ = paint_rect_.Union(rect);
#endif
}
bool WebWidgetHost::GetImage(int width, int height, void* rgba_buffer) {
if (!canvas_.get())
return false;
void WebWidgetHost::UpdateRedrawRect(const gfx::Rect& rect) {
if (!view_)
redraw_rect_ = redraw_rect_.Union(rect);
const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false);
DCHECK(bitmap.config() == SkBitmap::kARGB_8888_Config);
if (width == canvas_->getDevice()->width() &&
height == canvas_->getDevice()->height()) {
// The specified width and height values are the same as the canvas size.
// Return the existing canvas contents.
const void* pixels = bitmap.getPixels();
memcpy(rgba_buffer, pixels, width * height * 4);
return true;
}
// Create a new canvas of the requested size.
scoped_ptr<skia::PlatformCanvas> new_canvas(
new skia::PlatformCanvas(width, height, true));
new_canvas->writePixels(bitmap, 0, 0);
const SkBitmap& new_bitmap = new_canvas->getDevice()->accessBitmap(false);
DCHECK(new_bitmap.config() == SkBitmap::kARGB_8888_Config);
// Return the new canvas contents.
const void* pixels = new_bitmap.getPixels();
memcpy(rgba_buffer, pixels, width * height * 4);
return true;
}
void WebWidgetHost::SetSize(int width, int height) {
webwidget_->resize(WebSize(width, height));
DidInvalidateRect(gfx::Rect(0, 0, width, height));
InvalidateRect(gfx::Rect(0, 0, width, height));
EnsureTooltip();
}
@@ -68,21 +88,18 @@ void WebWidgetHost::GetSize(int& width, int& height) {
height = size.height;
}
void WebWidgetHost::AddWindowedPlugin(gfx::PluginWindowHandle handle)
{
void WebWidgetHost::AddWindowedPlugin(gfx::PluginWindowHandle handle) {
WebPluginGeometry geometry;
plugin_map_.insert(std::make_pair(handle, geometry));
}
void WebWidgetHost::RemoveWindowedPlugin(gfx::PluginWindowHandle handle)
{
void WebWidgetHost::RemoveWindowedPlugin(gfx::PluginWindowHandle handle) {
PluginMap::iterator it = plugin_map_.find(handle);
DCHECK(it != plugin_map_.end());
plugin_map_.erase(it);
}
void WebWidgetHost::MoveWindowedPlugin(const WebPluginGeometry& move)
{
void WebWidgetHost::MoveWindowedPlugin(const WebPluginGeometry& move) {
PluginMap::iterator it = plugin_map_.find(move.window);
DCHECK(it != plugin_map_.end());
@@ -96,11 +113,10 @@ void WebWidgetHost::MoveWindowedPlugin(const WebPluginGeometry& move)
it->second.visible = move.visible;
}
gfx::PluginWindowHandle WebWidgetHost::GetWindowedPluginAt(int x, int y)
{
gfx::PluginWindowHandle WebWidgetHost::GetWindowedPluginAt(int x, int y) {
if (!plugin_map_.empty()) {
PluginMap::const_iterator it = plugin_map_.begin();
for(; it != plugin_map_.end(); ++it) {
for (; it != plugin_map_.end(); ++it) {
if (it->second.visible && it->second.window_rect.Contains(x, y))
return it->second.window;
}
@@ -109,22 +125,103 @@ gfx::PluginWindowHandle WebWidgetHost::GetWindowedPluginAt(int x, int y)
return gfx::kNullPluginWindow;
}
void WebWidgetHost::DoPaint() {
// TODO(cef): The below code is cross-platform but the IsIdle() method
// currently requires patches to Chromium. Since this code is only executed
// on Windows it's been stuck behind an #ifdef for now to avoid having to
// patch Chromium code on other platforms.
#if defined(OS_WIN)
if (MessageLoop::current()->IsIdle()) {
has_update_task_ = false;
// Paint to the delegate.
Paint();
} else {
// Try again later.
CefThread::PostTask(CefThread::UI, FROM_HERE,
base::Bind(&WebWidgetHost::DoPaint, weak_factory_.GetWeakPtr()));
}
void WebWidgetHost::SetFrameRate(int frames_per_second) {
if (frames_per_second <= 0)
frames_per_second = kDefaultFrameRate;
if (frames_per_second > kMaxFrameRate)
frames_per_second = kMaxFrameRate;
frame_delay_ = 1000 / frames_per_second;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
#if defined(OS_WIN) || defined(OS_MACOSX)
paint_rgn_.op(rect.x(), rect.y(), rect.right(), rect.bottom(),
SkRegion::kUnion_Op);
#else
NOTIMPLEMENTED();
// TODO(cef): Update all ports to use regions instead of rectangles.
paint_rect_ = paint_rect_.Union(rect);
#endif
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
#ifndef NDEBUG
DCHECK(!painting_);
#endif
DCHECK(canvas_.get());
if (rect.IsEmpty())
return;
if (IsTransparent()) {
// When using transparency mode clear the rectangle before painting.
SkPaint clearpaint;
clearpaint.setARGB(0, 0, 0, 0);
clearpaint.setXfermodeMode(SkXfermode::kClear_Mode);
SkRect skrc;
skrc.set(rect.x(), rect.y(), rect.right(), rect.bottom());
canvas_->drawRect(skrc, clearpaint);
}
set_painting(true);
webwidget_->paint(webkit_glue::ToWebCanvas(canvas_.get()), rect);
set_painting(false);
}
void WebWidgetHost::ScheduleTimer() {
if (timer_.IsRunning())
return;
// This method may be called multiple times while the timer callback is
// executing. If so re-execute this method a single time after the callback
// has completed.
if (timer_executing_) {
if (!timer_wanted_)
timer_wanted_ = true;
return;
}
// Maintain the desired rate.
base::TimeDelta delta = base::TimeTicks::Now() - timer_last_;
int64 actualRate = delta.InMilliseconds();
if (actualRate >= frame_delay_)
delta = base::TimeDelta::FromMilliseconds(1);
else
delta = base::TimeDelta::FromMilliseconds(frame_delay_ - actualRate);
timer_.Start(
FROM_HERE,
delta,
this,
&WebWidgetHost::DoTimer);
}
void WebWidgetHost::DoTimer() {
timer_executing_ = true;
if (view_) {
// Window rendering is enabled and we've received a requestAnimationFrame
// or similar call. Trigger the OS to invalidate/repaint the client area at
// the requested frequency.
InvalidateWindow();
} else {
// Window rendering is disabled. Generate OnPaint() calls at the requested
// frequency.
#if defined(OS_MACOSX)
SkRegion region;
Paint(region);
#else
Paint();
#endif
}
timer_executing_ = false;
timer_last_ = base::TimeTicks::Now();
if (timer_wanted_) {
timer_wanted_ = false;
ScheduleTimer();
}
}

View File

@@ -2,17 +2,21 @@
// 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
#ifndef CEF_LIBCEF_WEBWIDGET_HOST_H_
#define CEF_LIBCEF_WEBWIDGET_HOST_H_
#pragma once
#include <map>
#include <vector>
#include "include/internal/cef_string.h"
#include "include/internal/cef_types.h"
#include "include/internal/cef_types_wrappers.h"
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/task.h"
#include "base/time.h"
#include "base/timer.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h"
@@ -21,14 +25,13 @@
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/rect.h"
#include "webkit/plugins/npapi/webplugin.h"
#include <map>
#if defined(OS_WIN)
#include "ui/base/win/ime_input.h"
#endif
#if defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#if defined(TOOLKIT_GTK)
#include <gtk/gtk.h> // NOLINT(build/include_order)
#endif
namespace gfx {
@@ -56,6 +59,7 @@ class WebWidgetHost {
public:
class PaintDelegate {
public:
virtual ~PaintDelegate() {}
virtual void Paint(bool popup, const std::vector<CefRect>& dirtyRects,
const void* buffer) =0;
};
@@ -72,8 +76,9 @@ class WebWidgetHost {
gfx::NativeView view_handle() const { return view_; }
WebKit::WebWidget* webwidget() const { return webwidget_; }
void DidInvalidateRect(const gfx::Rect& rect);
void DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect);
void InvalidateRect(const gfx::Rect& rect);
void ScrollRect(int dx, int dy, const gfx::Rect& clip_rect);
// Called for accelerated content like WebGL.
void ScheduleComposite();
@@ -81,28 +86,15 @@ class WebWidgetHost {
// Called for requestAnimationFrame animations.
void ScheduleAnimation();
// Invalidate the complete client area. This is called at a reasonable frame
// rate by the Schedule*() methods.
void Invalidate();
#if defined(OS_WIN)
void SetCursor(HCURSOR cursor);
#endif
// Update the region that will be painted to the canvas by WebKit the next
// time that Paint() is called.
void UpdatePaintRect(const gfx::Rect& rect);
// Update the region that will be drawn to the device the next time Paint()
// is called. This is only used when window rendering is disabled.
void UpdateRedrawRect(const gfx::Rect& rect);
#if defined(OS_MACOSX)
void Paint(SkRegion& update_rgn);
#else
void Paint();
#endif
void InvalidateRect(const gfx::Rect& rect);
bool GetImage(int width, int height, void* buffer);
@@ -115,16 +107,14 @@ class WebWidgetHost {
WebKit::WebKeyboardEvent GetLastKeyEvent() const { return last_key_event_; }
void PaintRect(const gfx::Rect& rect);
void SetTooltipText(const CefString& tooltip_text);
void SendKeyEvent(cef_key_type_t type, int key, int modifiers, bool sysChar,
bool imeChar);
void SendKeyEvent(cef_key_type_t type, const cef_key_info_t& keyInfo,
int modifiers);
void SendMouseClickEvent(int x, int y, cef_mouse_button_type_t type,
bool mouseUp, int clickCount);
void SendMouseMoveEvent(int x, int y, bool mouseLeave);
void SendMouseWheelEvent(int x, int y, int delta);
void SendMouseWheelEvent(int x, int y, int deltaX, int deltaY);
void SendFocusEvent(bool setFocus);
void SendCaptureLostEvent();
@@ -135,9 +125,9 @@ class WebWidgetHost {
void MoveWindowedPlugin(const webkit::npapi::WebPluginGeometry& geometry);
gfx::PluginWindowHandle GetWindowedPluginAt(int x, int y);
// If window rendering is disabled paint messages are generated after all
// other pending messages have been processed.
void DoPaint();
void SetFrameRate(int frames_per_second);
virtual bool IsTransparent() { return false; }
void set_popup(bool popup) { popup_ = popup; }
bool popup() { return popup_; }
@@ -147,11 +137,26 @@ class WebWidgetHost {
protected:
WebWidgetHost();
// Update the region that will be painted to the canvas by WebKit the next
// time that Paint() is called.
void UpdatePaintRect(const gfx::Rect& rect);
void PaintRect(const gfx::Rect& rect);
// Trigger the OS to invalidate/repaint the window.
void InvalidateWindow();
void InvalidateWindowRect(const gfx::Rect& rect);
// When window rendering is enabled this method invalidates the client area to
// trigger repaint via the OS. When window rendering is disabled this method
// is used to generate CefRenderHandler::OnPaint() calls.
void ScheduleTimer();
void DoTimer();
#if defined(OS_WIN)
// Per-class wndproc. Returns true if the event should be swallowed.
virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam);
void Resize(LPARAM lparam);
virtual void MouseEvent(UINT message, WPARAM wparam, LPARAM lparam);
void WheelEvent(WPARAM wparam, LPARAM lparam);
virtual void KeyEvent(UINT message, WPARAM wparam, LPARAM lparam);
@@ -169,19 +174,19 @@ class WebWidgetHost {
LRESULT OnImeEndComposition(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled);
void OnInputLangChange(DWORD character_set, HKL input_language_id);
void ImeUpdateTextInputState(WebKit::WebTextInputType type,
const gfx::Rect& caret_rect);
void UpdateInputMethod();
void UpdateImeInputState();
void ToggleImeTimer();
#elif defined(OS_MACOSX)
// These need to be called from a non-subclass, so they need to be public.
public:
void Resize(const gfx::Rect& rect);
virtual void MouseEvent(NSEvent *);
void WheelEvent(NSEvent *);
virtual void KeyEvent(NSEvent *);
virtual void MouseEvent(NSEvent* event);
void WheelEvent(NSEvent* event);
virtual void KeyEvent(NSEvent* event);
virtual void SetFocus(bool enable);
protected:
#elif defined(TOOLKIT_USES_GTK)
#elif defined(TOOLKIT_GTK)
public:
// ---------------------------------------------------------------------------
// This is needed on Linux because the GtkWidget creation is the same between
@@ -194,8 +199,6 @@ class WebWidgetHost {
// ---------------------------------------------------------------------------
static gfx::NativeView CreateWidget(gfx::NativeView parent_view,
WebWidgetHost* host);
void WindowDestroyed();
void Resize(const gfx::Size& size);
virtual void KeyEvent(GdkEventKey* event);
#endif
@@ -232,26 +235,21 @@ class WebWidgetHost {
gfx::Rect paint_rect_;
#endif
// True if an update task is pending when window rendering is disabled.
bool has_update_task_;
base::OneShotTimer<WebWidgetHost> timer_;
base::TimeTicks timer_last_;
bool timer_executing_;
bool timer_wanted_;
// True if an invalidate task is pending due to the Schedule*() methods.
bool has_invalidate_task_;
int64 frame_delay_;
#if defined(OS_WIN)
// True if an update input method task is pending due to DidInvalidateRect().
bool has_update_input_method_task_;
// Used to call UpdateImeInputState() while IME is active.
base::RepeatingTimer<WebWidgetHost> ime_timer_;
#endif
// When the Paint() method last completed.
base::TimeTicks paint_last_call_;
// Redraw rectangle requested by an explicit call to CefBrowser::Invalidate().
gfx::Rect redraw_rect_;
// The map of windowed plugins that need to be drawn when window rendering is
// disabled.
typedef std::map<gfx::PluginWindowHandle,webkit::npapi::WebPluginGeometry>
typedef std::map<gfx::PluginWindowHandle, webkit::npapi::WebPluginGeometry>
PluginMap;
PluginMap plugin_map_;
@@ -264,25 +262,20 @@ class WebWidgetHost {
// Wrapper class for IME input.
ui::ImeInput ime_input_;
// Represents whether or not this browser process is receiving status
// messages about the focused edit control from a renderer process.
// Represents whether or not this browser process is receiving status messages
// about the focused edit control from a renderer process.
bool ime_notification_;
// Represents whether or not the IME of a browser process is active.
bool input_method_is_active_;
// Stores the current text input type received by ImeUpdateTextInputState()
// method.
// Stores the current text input type.
WebKit::WebTextInputType text_input_type_;
// Stores the current caret bounds of input focus.
WebKit::WebRect caret_bounds_;
#endif
#endif // OS_WIN
#if defined(TOOLKIT_USES_GTK)
// Since GtkWindow resize is asynchronous, we have to stash the dimensions,
// so that the backing store doesn't have to wait for sizing to take place.
gfx::Size logical_size_;
#if defined(OS_MACOSX)
int mouse_modifiers_;
WebKit::WebMouseEvent::Button mouse_button_down_;
#endif
WebKit::WebKeyboardEvent last_key_event_;
@@ -290,8 +283,8 @@ class WebWidgetHost {
bool painting_;
bool layouting_;
private:
base::WeakPtrFactory<WebWidgetHost> weak_factory_;
static const int kDefaultFrameRate;
static const int kMaxFrameRate;
};
#endif // _WEBWIDGET_HOST_H
#endif // CEF_LIBCEF_WEBWIDGET_HOST_H_

View File

@@ -2,7 +2,7 @@
// 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 "libcef/webwidget_host.h"
#include <cairo/cairo.h>
#include <gdk/gdkx.h>
@@ -84,8 +84,6 @@ class WebWidgetHostGtkWidget {
G_CALLBACK(&HandleConfigure), host);
g_signal_connect(widget, "expose-event",
G_CALLBACK(&HandleExpose), host);
g_signal_connect(widget, "destroy",
G_CALLBACK(&HandleDestroy), host);
g_signal_connect(widget, "key-press-event",
G_CALLBACK(&HandleKeyPress), host);
g_signal_connect(widget, "key-release-event",
@@ -130,14 +128,14 @@ class WebWidgetHostGtkWidget {
static void HandleSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation,
WebWidgetHost* host) {
host->Resize(WebSize(allocation->width, allocation->height));
host->SetSize(allocation->width, allocation->height);
}
// Size, position, or stacking of the GdkWindow changed.
static gboolean HandleConfigure(GtkWidget* widget,
GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(WebSize(config->width, config->height));
host->SetSize(config->width, config->height);
return FALSE;
}
@@ -148,22 +146,12 @@ class WebWidgetHostGtkWidget {
// See comments above about what g_handling_expose is for.
g_handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->InvalidateRect(rect);
host->Paint();
g_handling_expose = false;
return FALSE;
}
// The GdkWindow was destroyed.
static gboolean HandleDestroy(GtkWidget* widget, void* unused) {
// The associated WebWidgetHost instance may have already been destroyed.
WebWidgetHost* host = static_cast<WebWidgetHost*>(
g_object_get_data(G_OBJECT(widget), kWebWidgetHostKey));
if (host)
host->WindowDestroyed();
return FALSE;
}
// Keyboard key pressed.
static gboolean HandleKeyPress(GtkWidget* widget,
GdkEventKey* event,
@@ -285,34 +273,10 @@ WebWidgetHost* WebWidgetHost::Create(GtkWidget* parent_view,
return host;
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!g_handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
void WebWidgetHost::ScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
void WebWidgetHost::Invalidate() {
int width = logical_size_.width();
int height = logical_size_.height();
GdkRectangle grect = {
0,
0,
width,
height
};
GdkWindow* window = view_->window;
gdk_window_invalidate_rect(window, &grect, 0);
InvalidateRect(clip_rect);
}
WebWidgetHost::WebWidgetHost()
@@ -322,9 +286,9 @@ WebWidgetHost::WebWidgetHost()
canvas_w_(0),
canvas_h_(0),
popup_(false),
has_update_task_(false),
has_invalidate_task_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
timer_executing_(false),
timer_wanted_(false),
frame_delay_(1000 / kDefaultFrameRate) {
set_painting(false);
}
@@ -338,14 +302,24 @@ WebWidgetHost::~WebWidgetHost() {
// webwidget_->close();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
logical_size_ = newsize;
SetSize(newsize.width(), newsize.height());
void WebWidgetHost::InvalidateWindow() {
int width, height;
GetSize(width, height);
const gfx::Rect client_rect(width, height);
InvalidateWindowRect(client_rect);
}
void WebWidgetHost::InvalidateWindowRect(const gfx::Rect& rect) {
DCHECK(view_);
if (!g_handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), rect.x(),
rect.y(), rect.width(), rect.height());
}
}
void WebWidgetHost::Paint() {
int width = logical_size_.width();
int height = logical_size_.height();
int width, height;
GetSize(width, height);
gfx::Rect client_rect(width, height);
// Number of pixels that the canvas is allowed to differ from the client area.
@@ -391,7 +365,7 @@ void WebWidgetHost::Paint() {
total_paint = total_paint.Union(rect);
}
}
//DCHECK(paint_rect_.IsEmpty());
// DCHECK(paint_rect_.IsEmpty());
// Invalidate the paint region on the widget's underlying gdk window. Note
// that gdk_window_invalidate_* will generate extra expose events, which
@@ -415,101 +389,61 @@ void WebWidgetHost::Paint() {
cairo_destroy(cairo_drawable);
gdk_window_end_paint(window);
// Used with scheduled invalidation to maintain a consistent frame rate.
paint_last_call_ = base::TimeTicks::Now();
if (has_invalidate_task_)
has_invalidate_task_ = false;
}
void WebWidgetHost::SetTooltipText(const CefString& tooltip_text)
{
void WebWidgetHost::SetTooltipText(const CefString& tooltip_text) {
// TODO(port): Implement this method as part of tooltip support.
}
void WebWidgetHost::InvalidateRect(const gfx::Rect& rect)
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
bool WebWidgetHost::GetImage(int width, int height, void* rgba_buffer)
{
if (!canvas_.get())
return false;
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
return false;
}
WebScreenInfo WebWidgetHost::GetScreenInfo() {
Display* display = GtkWidgetGetDisplay(view_);
int screen_num = GtkWidgetGetScreenNum(view_);
return WebScreenInfoFactory::screenInfo(display, screen_num);
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->paint(canvas_.get(), rect);
set_painting(false);
}
void WebWidgetHost::WindowDestroyed() {
delete this;
}
void WebWidgetHost::SendKeyEvent(cef_key_type_t type, int key, int modifiers,
bool sysChar, bool imeChar)
{
void WebWidgetHost::SendKeyEvent(cef_key_type_t type,
const cef_key_info_t& keyInfo,
int modifiers) {
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
void WebWidgetHost::SendMouseClickEvent(int x, int y,
cef_mouse_button_type_t type,
bool mouseUp, int clickCount)
{
bool mouseUp, int clickCount) {
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave)
{
void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave) {
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
void WebWidgetHost::SendMouseWheelEvent(int x, int y, int delta)
{
void WebWidgetHost::SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) {
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
void WebWidgetHost::SendFocusEvent(bool setFocus)
{
void WebWidgetHost::SendFocusEvent(bool setFocus) {
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
void WebWidgetHost::SendCaptureLostEvent()
{
void WebWidgetHost::SendCaptureLostEvent() {
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
void WebWidgetHost::EnsureTooltip()
{
void WebWidgetHost::EnsureTooltip() {
// TODO(port): Implement this method as part of tooltip support.
}
void WebWidgetHost::ResetTooltip()
{
void WebWidgetHost::ResetTooltip() {
// TODO(port): Implement this method as part of tooltip support.
}
void WebWidgetHost::KeyEvent(GdkEventKey* event)
{
void WebWidgetHost::KeyEvent(GdkEventKey* event) {
WebKeyboardEvent keyboard_event(WebInputEventFactory::keyboardEvent(event));
last_key_event_ = keyboard_event;
webwidget()->handleInputEvent(keyboard_event);

View File

@@ -3,7 +3,18 @@
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import "webwidget_host.h"
#include "base/compiler_specific.h"
#include "third_party/WebKit/Source/WebCore/config.h"
MSVC_PUSH_WARNING_LEVEL(0);
#include "KeyEventCocoa.h" // NOLINT(build/include)
MSVC_POP_WARNING();
#undef LOG
#import "libcef/webwidget_host.h"
#include "libcef/cef_thread.h"
#include "base/bind.h"
#import "base/logging.h"
#import "skia/ext/platform_canvas.h"
#import "third_party/WebKit/Source/WebKit/chromium/public/mac/WebInputEventFactory.h"
@@ -15,8 +26,8 @@
#import "third_party/skia/include/core/SkRegion.h"
#import "ui/gfx/rect.h"
#import "ui/gfx/size.h"
#import "webkit/glue/webkit_glue.h"
using webkit::npapi::WebPluginGeometry;
using WebKit::WebInputEvent;
using WebKit::WebInputEventFactory;
using WebKit::WebKeyboardEvent;
@@ -30,17 +41,15 @@ using WebKit::WebWidgetClient;
namespace {
inline SkIRect convertToSkiaRect(const gfx::Rect& r)
{
inline SkIRect convertToSkiaRect(const gfx::Rect& r) {
return SkIRect::MakeLTRB(r.x(), r.y(), r.right(), r.bottom());
}
inline gfx::Rect convertFromSkiaRect(const SkIRect& r)
{
inline gfx::Rect convertFromSkiaRect(const SkIRect& r) {
return gfx::Rect(r.x(), r.y(), r.width(), r.height());
}
} // namespace
} // namespace
/*static*/
WebWidgetHost* WebWidgetHost::Create(NSView* parent_view,
@@ -48,14 +57,19 @@ WebWidgetHost* WebWidgetHost::Create(NSView* parent_view,
PaintDelegate* paint_delegate) {
WebWidgetHost* host = new WebWidgetHost();
const NSRect bounds = [parent_view bounds];
host->view_ = [[NSView alloc] initWithFrame:bounds];
[parent_view addSubview:host->view_];
if (!paint_delegate) {
const NSRect bounds = [parent_view bounds];
host->view_ = [[NSView alloc] initWithFrame:bounds];
[parent_view addSubview:host->view_];
host->webwidget_ = WebPopupMenu::create(client);
host->webwidget_->resize(WebSize(NSWidth(bounds), NSHeight(bounds)));
} else {
host->paint_delegate_ = paint_delegate;
host->view_ = nil;
host->webwidget_ = WebPopupMenu::create(client);
}
host->painting_ = false;
host->layouting_ = false;
host->webwidget_ = WebPopupMenu::create(client);
host->webwidget_->resize(WebSize(NSWidth(bounds), NSHeight(bounds)));
return host;
}
@@ -66,31 +80,24 @@ WebWidgetHost::WebWidgetHost()
canvas_w_(0),
canvas_h_(0),
popup_(false),
has_update_task_(false),
has_invalidate_task_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
timer_executing_(false),
timer_wanted_(false),
frame_delay_(1000 / kDefaultFrameRate),
mouse_modifiers_(0),
painting_(false),
layouting_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
const gfx::Rect client_rect(NSRectToCGRect([view_ bounds]));
const gfx::Rect damaged_rect_in_client = client_rect.Intersect(damaged_rect);
if (!damaged_rect_in_client.IsEmpty()) {
UpdatePaintRect(damaged_rect_in_client);
NSRect cocoa_rect = NSRectFromCGRect(damaged_rect_in_client.ToCGRect());
cocoa_rect.origin.y = client_rect.height() - NSMaxY(cocoa_rect);
[view_ setNeedsDisplayInRect:cocoa_rect];
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
void WebWidgetHost::ScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
DCHECK(dx || dy);
const gfx::Rect client_rect(NSRectToCGRect([view_ bounds]));
int width, height;
GetSize(width, height);
const gfx::Rect client_rect(width, height);
gfx::Rect rect = clip_rect.Intersect(client_rect);
const int x = rect.x();
@@ -108,8 +115,9 @@ void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// needs to be laid out; calling scrollRect:by: in this situation leads to
// unwanted behavior. Finally, scrolling the rectangle by more than the size
// of the view means we can just invalidate the entire scroll rect.
if (![view_ canDraw] || painting_ || layouting_ || Dx >= w || Dy >= h) {
DidInvalidateRect(clip_rect);
if (!view_ || [view_ canDraw] || painting_ || layouting_ || Dx >= w ||
Dy >= h) {
InvalidateRect(clip_rect);
return;
}
@@ -133,7 +141,7 @@ void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// to the screen buffer.
rect = gfx::Rect(dx>=0? x: r - Dx, dy>=0? y: b - Dy,
dx>0? Dx: w, dy>0? Dy: h);
DidInvalidateRect(rect);
InvalidateRect(rect);
// If any part of the scrolled rect was marked as dirty make sure to redraw
// it in the new scrolled-to location. Otherwise we can end up with artifacts
@@ -142,40 +150,54 @@ void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
SkRegion moved_paint_rgn(paint_rgn_);
moved_paint_rgn.translate(dx, dy);
moved_paint_rgn.op(convertToSkiaRect(client_rect), SkRegion::kIntersect_Op);
DidInvalidateRect(convertFromSkiaRect(moved_paint_rgn.getBounds()));
InvalidateRect(convertFromSkiaRect(moved_paint_rgn.getBounds()));
}
void WebWidgetHost::Paint(SkRegion& update_rgn) {
gfx::Rect client_rect(NSRectToCGRect([view_ bounds]));
int width, height;
GetSize(width, height);
gfx::Rect client_rect(width, height);
// Union the rectangle that WebKit think needs repainting with the rectangle
// of the view that must be painted now. In most situations this will not
// affect the painted rectangle. In some situations we could end up re-
// painting areas that are already in the canvas and only dirty in the view
// itself. However, if we don't do this we can get artifacts when scrolling
// because contents of the canvas are no longer correct after scrolling only
// in the view.
paint_rgn_.op(update_rgn, SkRegion::kUnion_Op);
SkRegion damaged_rgn;
// When we are not using accelerated compositing the canvas area is allowed
// to differ in size from the client by a certain number of pixels (128 in
// this case). When accelerated compositing is in effect the size must match
// exactly.
const int extra_w = (webwidget_->isAcceleratedCompositingActive()? 0: 128);
const int extra_h = (webwidget_->isAcceleratedCompositingActive()? 0: 128);
const int min_w = client_rect.width();
const int min_h = client_rect.height();
const int max_w = client_rect.width() + extra_w * 2;
const int max_h = client_rect.height() + extra_h * 2;
if (view_) {
// Union the rectangle that WebKit think needs repainting with the rectangle
// of the view that must be painted now. In most situations this will not
// affect the painted rectangle. In some situations we could end up re-
// painting areas that are already in the canvas and only dirty in the view
// itself. However, if we don't do this we can get artifacts when scrolling
// because contents of the canvas are no longer correct after scrolling only
// in the view.
paint_rgn_.op(update_rgn, SkRegion::kUnion_Op);
const bool too_small = (canvas_w_ < min_w || canvas_h_ < min_h);
const bool too_large = (canvas_w_ > max_w || canvas_h_ > max_h);
// When we are not using accelerated compositing the canvas area is allowed
// to differ in size from the client by a certain number of pixels (128 in
// this case). When accelerated compositing is in effect the size must match
// exactly.
const int extra_w = (webwidget_->isAcceleratedCompositingActive()? 0: 128);
const int extra_h = (webwidget_->isAcceleratedCompositingActive()? 0: 128);
const int min_w = client_rect.width();
const int min_h = client_rect.height();
const int max_w = client_rect.width() + extra_w * 2;
const int max_h = client_rect.height() + extra_h * 2;
if (!canvas_.get() || too_small || too_large) {
canvas_w_ = client_rect.width() + extra_w;
canvas_h_ = client_rect.height() + extra_h;
canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true));
const bool too_small = (canvas_w_ < min_w || canvas_h_ < min_h);
const bool too_large = (canvas_w_ > max_w || canvas_h_ > max_h);
if (!canvas_.get() || too_small || too_large) {
canvas_w_ = client_rect.width() + extra_w;
canvas_h_ = client_rect.height() + extra_h;
canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true));
paint_rgn_.setRect(convertToSkiaRect(client_rect));
}
} else if (!canvas_.get() || canvas_w_ != client_rect.width() ||
canvas_h_ != client_rect.height()) {
paint_rgn_.setRect(convertToSkiaRect(client_rect));
// The canvas must be the exact size of the client area.
canvas_w_ = client_rect.width();
canvas_h_ = client_rect.height();
canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true));
}
webwidget_->animate(0.0);
@@ -204,69 +226,83 @@ void WebWidgetHost::Paint(SkRegion& update_rgn) {
draw_rgn.swap(paint_rgn_);
SkRegion::Cliperator iterator(draw_rgn, convertToSkiaRect(client_rect));
for (; !iterator.done(); iterator.next())
PaintRect(convertFromSkiaRect(iterator.rect()));
for (; !iterator.done(); iterator.next()) {
const SkIRect& r = iterator.rect();
PaintRect(convertFromSkiaRect(r));
// If any more rectangles were made dirty during the paint operation, make
// sure they are copied to the window buffer, by including the paint region.
// If nothing needs additional painting, this is a no-op.
update_rgn.op(paint_rgn_, SkRegion::kUnion_Op);
if (!view_)
damaged_rgn.op(r, SkRegion::kUnion_Op);
}
if (view_) {
// If any more rectangles were made dirty during the paint operation, make
// sure they are copied to the window buffer, by including the paint
// region. If nothing needs additional painting, this is a no-op.
update_rgn.op(paint_rgn_, SkRegion::kUnion_Op);
}
}
if (!view_ && plugin_map_.size() > 0) {
// Flash seems to stop calling NPN_InvalidateRect, which means we stop
// painting. If we've got a plugin make sure we paint its rect each time.
PluginMap::const_iterator it = plugin_map_.begin();
for (; it != plugin_map_.end(); ++it) {
if (it->second.visible &&
client_rect.Intersects(it->second.window_rect)) {
const WebPluginGeometry* geom = &it->second;
damaged_rgn.op(convertToSkiaRect(geom->window_rect),
SkRegion::kUnion_Op);
}
}
}
// Set the context back to our view and copy the bitmap that we just painted
// into to the view. Only the regions that were updated are copied.
[NSGraphicsContext restoreGraphicsState];
NSGraphicsContext* view_context = [NSGraphicsContext currentContext];
CGContextRef context = static_cast<CGContextRef>([view_context graphicsPort]);
if (view_) {
// Set the context back to our view and copy the bitmap that we just painted
// into to the view. Only the regions that were updated are copied.
[NSGraphicsContext restoreGraphicsState];
NSGraphicsContext* view_context = [NSGraphicsContext currentContext];
CGContextRef context =
static_cast<CGContextRef>([view_context graphicsPort]);
SkRegion::Cliperator iterator(update_rgn, convertToSkiaRect(client_rect));
for (; !iterator.done(); iterator.next()) {
const SkIRect& r = iterator.rect();
CGRect copy_rect = { { r.x(), r.y() }, { r.width(), r.height() } };
const float x = r.x();
const float y = client_rect.height() - r.bottom();
skia::DrawToNativeContext(canvas_.get(), context, x, y, &copy_rect);
SkRegion::Cliperator iterator(update_rgn, convertToSkiaRect(client_rect));
for (; !iterator.done(); iterator.next()) {
const SkIRect& r = iterator.rect();
CGRect copy_rect = { { r.x(), r.y() }, { r.width(), r.height() } };
const float x = r.x();
const float y = client_rect.height() - r.bottom();
skia::DrawToNativeContext(canvas_.get(), context, x, y, &copy_rect);
}
} else {
if (damaged_rgn.isEmpty())
return;
// Paint to the delegate.
DCHECK(paint_delegate_);
const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false);
DCHECK(bitmap.config() == SkBitmap::kARGB_8888_Config);
const void* pixels = bitmap.getPixels();
std::vector<CefRect> damaged_rects;
SkRegion::Cliperator iterator(damaged_rgn, convertToSkiaRect(client_rect));
for (; !iterator.done(); iterator.next()) {
const SkIRect& r = iterator.rect();
damaged_rects.push_back(
CefRect(r.left(), r.top(), r.width(), r.height()));
}
paint_delegate_->Paint(popup_, damaged_rects, pixels);
}
// Used with scheduled invalidation to maintain a consistent frame rate.
paint_last_call_ = base::TimeTicks::Now();
if (has_invalidate_task_)
has_invalidate_task_ = false;
}
void WebWidgetHost::Invalidate() {
[view_ setNeedsDisplay:YES];
}
void WebWidgetHost::SetTooltipText(const CefString& tooltip_text)
{
void WebWidgetHost::SetTooltipText(const CefString& tooltip_text) {
// TODO(port): Implement this method as part of tooltip support.
}
void WebWidgetHost::InvalidateRect(const gfx::Rect& rect)
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
}
bool WebWidgetHost::GetImage(int width, int height, void* rgba_buffer)
{
if (!canvas_.get())
return false;
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
return false;
}
WebScreenInfo WebWidgetHost::GetScreenInfo() {
return WebScreenInfoFactory::screenInfo(view_);
}
void WebWidgetHost::Resize(const gfx::Rect& rect) {
SetSize(rect.width(), rect.height());
}
void WebWidgetHost::MouseEvent(NSEvent *event) {
const WebMouseEvent& web_event = WebInputEventFactory::mouseEvent(
event, view_);
@@ -325,64 +361,217 @@ void WebWidgetHost::SetFocus(bool enable) {
webwidget_->setFocus(enable);
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
#ifndef NDEBUG
DCHECK(!painting_);
#endif
DCHECK(canvas_.get());
void WebWidgetHost::SendKeyEvent(cef_key_type_t type,
const cef_key_info_t& keyInfo,
int modifiers) {
WebKeyboardEvent event;
if (!rect.IsEmpty()) {
set_painting(true);
webwidget_->paint(webkit_glue::ToWebCanvas(canvas_.get()), rect);
set_painting(false);
switch (type) {
case KT_KEYUP:
default:
event.type = WebInputEvent::KeyUp;
break;
case KT_KEYDOWN:
event.type = WebInputEvent::RawKeyDown;
break;
case KT_CHAR:
event.type = WebInputEvent::Char;
break;
}
}
event.timeStampSeconds = TickCount();
void WebWidgetHost::SendKeyEvent(cef_key_type_t type, int key, int modifiers,
bool sysChar, bool imeChar)
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
if (modifiers & KEY_SHIFT)
event.modifiers |= WebInputEvent::ShiftKey;
if (modifiers & KEY_ALT)
event.modifiers |= WebInputEvent::AltKey;
if (modifiers & KEY_CTRL)
event.modifiers |= WebInputEvent::ControlKey;
if (modifiers & KEY_META)
event.modifiers |= WebInputEvent::MetaKey;
if (modifiers & KEY_KEYPAD)
event.modifiers |= WebInputEvent::IsKeyPad;
// There are several kinds of characters for which we produce key code from
// char code:
// 1. Roman letters. Windows keyboard layouts affect both virtual key codes
// and character codes for these, so e.g. 'A' gets the same keyCode on
// QWERTY, AZERTY or Dvorak layouts.
// 2. Keys for which there is no known Mac virtual key codes, like
// PrintScreen.
// 3. Certain punctuation keys. On Windows, these are also remapped depending
// on current keyboard layout, but see comment in
// windowsKeyCodeForCharCode().
if (type == KT_KEYUP || type == KT_KEYDOWN) {
if (keyInfo.character != 0) {
// Cmd switches Roman letters for Dvorak-QWERTY layout, so try modified
// characters first.
event.windowsKeyCode =
WebCore::windowsKeyCodeForCharCode(keyInfo.character);
}
if (event.windowsKeyCode == 0 && keyInfo.characterNoModifiers != 0) {
// Ctrl+A on an AZERTY keyboard would get VK_Q keyCode if we relied on
// keyInfo.keyCode below.
event.windowsKeyCode =
WebCore::windowsKeyCodeForCharCode(keyInfo.characterNoModifiers);
}
}
if (event.windowsKeyCode == 0) {
// Map Mac virtual key code directly to Windows one for any keys not handled
// above. E.g. the key next to Caps Lock has the same Event.keyCode on U.S.
// keyboard ('A') and on Russian keyboard (CYRILLIC LETTER EF).
event.windowsKeyCode = WebCore::windowsKeyCodeForKeyCode(keyInfo.keyCode);
}
event.nativeKeyCode = keyInfo.keyCode;
int textChar = keyInfo.character;
int unmodifiedChar = keyInfo.characterNoModifiers;
// Always use 13 for Enter/Return -- we don't want to use AppKit's
// different character for Enter.
if (event.windowsKeyCode == '\r') {
textChar = '\r';
unmodifiedChar = '\r';
}
// The adjustments below are only needed in backward compatibility mode,
// but we cannot tell what mode we are in from here.
// Turn 0x7F into 8, because backspace needs to always be 8.
if (textChar == '\x7F')
textChar = '\x8';
if (unmodifiedChar == '\x7F')
unmodifiedChar = '\x8';
// Always use 9 for tab -- we don't want to use AppKit's different character
// for shift-tab.
if (event.windowsKeyCode == 9) {
textChar = '\x9';
unmodifiedChar = '\x9';
}
event.text[0] = textChar;
event.unmodifiedText[0] = unmodifiedChar;
event.setKeyIdentifierFromWindowsKeyCode();
event.isSystemKey = !!(modifiers & KEY_META);
last_key_event_ = event;
webwidget_->handleInputEvent(event);
}
void WebWidgetHost::SendMouseClickEvent(int x, int y,
cef_mouse_button_type_t type,
bool mouseUp, int clickCount)
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
bool mouseUp, int clickCount) {
WebMouseEvent event;
switch(type) {
case MBT_LEFT:
event.button = WebMouseEvent::ButtonLeft;
event.modifiers |= WebInputEvent::LeftButtonDown;
break;
case MBT_MIDDLE:
event.button = WebMouseEvent::ButtonMiddle;
event.modifiers |= WebInputEvent::MiddleButtonDown;
break;
case MBT_RIGHT:
event.button = WebMouseEvent::ButtonRight;
event.modifiers |= WebInputEvent::RightButtonDown;
break;
}
if (mouseUp)
event.type = WebInputEvent::MouseUp;
else
event.type = WebInputEvent::MouseDown;
event.clickCount = clickCount;
event.timeStampSeconds = TickCount();
event.x = x;
event.y = y;
event.windowX = event.x;
event.windowY = event.y;
if (mouseUp) {
mouse_button_down_ = WebMouseEvent::ButtonNone;
mouse_modifiers_ &= ~event.modifiers;
} else {
mouse_modifiers_ |= event.modifiers;
mouse_button_down_ = event.button;
}
event.modifiers = mouse_modifiers_;
webwidget_->handleInputEvent(event);
}
void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave)
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave) {
WebMouseEvent event;
event.type = WebInputEvent::MouseMove;
event.timeStampSeconds = TickCount();
event.button = mouse_button_down_;
event.x = x;
event.y = y;
event.windowX = event.x;
event.windowY = event.y;
event.modifiers = mouse_modifiers_;
webwidget_->handleInputEvent(event);
}
void WebWidgetHost::SendMouseWheelEvent(int x, int y, int delta)
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
void WebWidgetHost::SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) {
WebMouseWheelEvent event;
// Conversion between wheel delta amounts and number of pixels to scroll.
static const double scrollbarPixelsPerCocoaTick = 40.0;
event.type = WebInputEvent::MouseWheel;
event.timeStampSeconds = TickCount();
event.button = WebMouseEvent::ButtonNone;
event.deltaX = static_cast<float>(deltaX);
event.deltaY = static_cast<float>(deltaY);
event.wheelTicksX = static_cast<float>(deltaX/scrollbarPixelsPerCocoaTick);
event.wheelTicksY = static_cast<float>(deltaY/scrollbarPixelsPerCocoaTick);
event.hasPreciseScrollingDeltas = true;
event.x = x;
event.y = y;
event.windowX = event.x;
event.windowY = event.y;
webwidget_->handleInputEvent(event);
}
void WebWidgetHost::SendFocusEvent(bool setFocus)
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
void WebWidgetHost::SendFocusEvent(bool setFocus) {
SetFocus(setFocus);
}
void WebWidgetHost::SendCaptureLostEvent()
{
// TODO(port): Implement this method as part of off-screen rendering support.
NOTIMPLEMENTED();
void WebWidgetHost::SendCaptureLostEvent() {
}
void WebWidgetHost::EnsureTooltip()
{
void WebWidgetHost::InvalidateWindow() {
DCHECK(view_);
[view_ setNeedsDisplay:YES];
}
void WebWidgetHost::InvalidateWindowRect(const gfx::Rect& rect) {
DCHECK(view_);
int width, height;
GetSize(width, height);
const gfx::Rect client_rect(width, height);
NSRect cocoa_rect = NSRectFromCGRect(rect.ToCGRect());
cocoa_rect.origin.y = client_rect.height() - NSMaxY(cocoa_rect);
[view_ setNeedsDisplayInRect:cocoa_rect];
}
void WebWidgetHost::EnsureTooltip() {
// TODO(port): Implement this method as part of tooltip support.
}
void WebWidgetHost::ResetTooltip()
{
void WebWidgetHost::ResetTooltip() {
// TODO(port): Implement this method as part of tooltip support.
}

View File

@@ -3,8 +3,12 @@
// 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 "cef_thread.h"
#include <windows.h>
#include <commctrl.h>
#include "libcef/webwidget_host.h"
#include "libcef/browser_impl.h"
#include "libcef/cef_thread.h"
#include "base/bind.h"
#include "base/logging.h"
@@ -16,7 +20,6 @@
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/win/WebInputEventFactory.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/win/WebScreenInfoFactory.h"
#include "third_party/skia/include/core/SkRegion.h"
@@ -26,7 +29,8 @@
#include "ui/gfx/gdi_util.h"
#include "ui/gfx/rect.h"
#include <commctrl.h>
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
using webkit::npapi::WebPluginGeometry;
using WebKit::WebInputEvent;
@@ -51,8 +55,7 @@ struct MessageInfo {
LPARAM lParam;
};
BOOL CALLBACK SendMessageFunc(HWND hwnd, LPARAM lParam)
{
BOOL CALLBACK SendMessageFunc(HWND hwnd, LPARAM lParam) {
MessageInfo* info = reinterpret_cast<MessageInfo*>(lParam);
SendMessage(hwnd, info->message, info->wParam, info->lParam);
return TRUE;
@@ -61,18 +64,16 @@ BOOL CALLBACK SendMessageFunc(HWND hwnd, LPARAM lParam)
// Plugins are hosted in a Chromium-created parent window so it's necessary to
// send messages directly to the child window.
void SendMessageToPlugin(HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
LPARAM lParam) {
MessageInfo info = {message, wParam, lParam};
EnumChildWindows(hwnd, SendMessageFunc, reinterpret_cast<LPARAM>(&info));
}
inline SkIRect convertToSkiaRect(const gfx::Rect& r)
{
inline SkIRect convertToSkiaRect(const gfx::Rect& r) {
return SkIRect::MakeLTRB(r.x(), r.y(), r.right(), r.bottom());
}
} // namespace
} // namespace
/*static*/
WebWidgetHost* WebWidgetHost::Create(HWND parent_view,
@@ -100,7 +101,6 @@ WebWidgetHost* WebWidgetHost::Create(HWND parent_view,
0, 0, 0, 0,
parent_view, NULL, GetModuleHandle(NULL),
NULL);
ui::SetWindowUserData(host->view_, host);
} else {
host->paint_delegate_ = paint_delegate;
@@ -133,9 +133,12 @@ LRESULT CALLBACK WebWidgetHost::WndProc(HWND hwnd, UINT message, WPARAM wparam,
// during painting.
return 0;
case WM_SIZE:
host->Resize(lparam);
case WM_SIZE: {
int width = LOWORD(lparam);
int height = HIWORD(lparam);
host->SetSize(width, height);
return 0;
}
case WM_MOUSEMOVE:
case WM_MOUSELEAVE:
@@ -160,7 +163,7 @@ LRESULT CALLBACK WebWidgetHost::WndProc(HWND hwnd, UINT message, WPARAM wparam,
case WM_MOUSEWHEEL:
{
// Only send mouse wheel events if the cursor is over the window.
POINT mousePt = { LOWORD(lparam), HIWORD(lparam) };
POINT mousePt = { GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam) };
RECT wndRect;
GetWindowRect(hwnd, &wndRect);
if (PtInRect(&wndRect, mousePt))
@@ -254,7 +257,7 @@ LRESULT CALLBACK WebWidgetHost::WndProc(HWND hwnd, UINT message, WPARAM wparam,
break;
case WM_NOTIFY:
host->OnNotify(0, (NMHDR*)lparam);
host->OnNotify(0, reinterpret_cast<NMHDR*>(lparam));
break;
case WM_GETDLGCODE:
@@ -262,40 +265,21 @@ LRESULT CALLBACK WebWidgetHost::WndProc(HWND hwnd, UINT message, WPARAM wparam,
}
}
return DefWindowProc(hwnd, message, wparam, lparam);;
return DefWindowProc(hwnd, message, wparam, lparam);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
// If this invalidate overlaps with a pending scroll then we have to downgrade
// to invalidating the scroll rect.
UpdatePaintRect(damaged_rect);
InvalidateRect(damaged_rect);
if (!popup_ && view_ && webwidget_ && input_method_is_active_ &&
!has_update_input_method_task_) {
has_update_input_method_task_ = true;
// Call UpdateInputMethod() approximately every 100ms.
CefThread::PostDelayedTask(CefThread::UI, FROM_HERE,
base::Bind(&WebWidgetHost::UpdateInputMethod,
weak_factory_.GetWeakPtr()),
100);
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
void WebWidgetHost::ScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
DCHECK(dx || dy);
// Invalidate and re-paint the entire scroll rect if:
// 1. We're in a state where we cannot draw into the view right now, or
// 2. The rect is being scrolled by more than the size of the view, or
// 3. The scroll rect intersects the current paint region.
if (!canvas_.get() || layouting_ || painting_ ||
// 1. Window rendering is disabled, or
// 2. We're in a state where we cannot draw into the view right now, or
// 3. The rect is being scrolled by more than the size of the view, or
// 4. The scroll rect intersects the current paint region.
if (!view_ || !canvas_.get() || layouting_ || painting_ ||
abs(dx) >= clip_rect.width() || abs(dy) >= clip_rect.height() ||
paint_rgn_.intersects(convertToSkiaRect(clip_rect))) {
DidInvalidateRect(clip_rect);
InvalidateRect(clip_rect);
return;
}
@@ -303,7 +287,7 @@ void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
{
skia::ScopedPlatformPaint scoped_platform_paint(canvas_.get());
HDC hdc = scoped_platform_paint.GetPlatformSurface();
RECT clip_rect_win32 = clip_rect.ToRECT(), uncovered_rect = {0,0,0,0};
RECT clip_rect_win32 = clip_rect.ToRECT(), uncovered_rect = {0, 0, 0, 0};
ScrollDC(hdc, dx, dy, NULL, &clip_rect_win32, NULL, &uncovered_rect);
UpdatePaintRect(gfx::Rect(uncovered_rect));
@@ -311,14 +295,8 @@ void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// Invalidate the scroll rect. It will be drawn from the canvas bitmap on the
// next WM_PAINT call.
InvalidateRect(clip_rect);
}
void WebWidgetHost::Invalidate() {
if (!webwidget_)
return;
WebSize size = webwidget_->size();
InvalidateRect(gfx::Rect(0, 0, size.width, size.height));
RECT r = clip_rect.ToRECT();
::InvalidateRect(view_, &r, FALSE);
}
void WebWidgetHost::SetCursor(HCURSOR cursor) {
@@ -335,26 +313,40 @@ WebWidgetHost::WebWidgetHost()
canvas_w_(0),
canvas_h_(0),
popup_(false),
timer_executing_(false),
timer_wanted_(false),
track_mouse_leave_(false),
has_update_task_(false),
has_invalidate_task_(false),
has_update_input_method_task_(false),
frame_delay_(1000 / kDefaultFrameRate),
tooltip_view_(NULL),
tooltip_showing_(false),
ime_notification_(false),
input_method_is_active_(false),
layouting_(false),
text_input_type_(WebKit::WebTextInputTypeNone),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
text_input_type_(WebKit::WebTextInputTypeNone) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
if (view_)
ui::SetWindowUserData(view_, 0);
TrackMouseLeave(false);
ResetTooltip();
if (view_) {
ui::SetWindowUserData(view_, 0);
view_ = NULL;
}
}
void WebWidgetHost::InvalidateWindow() {
int width, height;
GetSize(width, height);
const gfx::Rect client_rect(width, height);
InvalidateWindowRect(client_rect);
}
void WebWidgetHost::InvalidateWindowRect(const gfx::Rect& rect) {
DCHECK(view_);
RECT r = rect.ToRECT();
::InvalidateRect(view_, &r, FALSE);
}
bool WebWidgetHost::WndProc(UINT message, WPARAM wparam, LPARAM lparam) {
@@ -377,12 +369,6 @@ void WebWidgetHost::Paint() {
// Damaged rectangle used for drawing when window rendering is disabled.
SkRegion damaged_rgn;
if (!view_ && !redraw_rect_.IsEmpty()) {
// At a minimum we need to send the delegate the rectangle that was
// requested by calling CefBrowser::InvalidateRect().
damaged_rgn.setRect(convertToSkiaRect(redraw_rect_));
redraw_rect_ = gfx::Rect();
}
if (view_ && !webwidget_->isAcceleratedCompositingActive()) {
// Number of pixels that the canvas is allowed to differ from the client
@@ -401,8 +387,8 @@ void WebWidgetHost::Paint() {
canvas_h_ = client_rect.height() + kCanvasGrowSize;
canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true));
}
} else if(!canvas_.get() || canvas_w_ != client_rect.width() ||
canvas_h_ != client_rect.height()) {
} else if (!canvas_.get() || canvas_w_ != client_rect.width() ||
canvas_h_ != client_rect.height()) {
paint_rgn_.setRect(convertToSkiaRect(client_rect));
// The canvas must be the exact size of the client area.
@@ -446,10 +432,10 @@ void WebWidgetHost::Paint() {
if (!view_ && plugin_map_.size() > 0) {
typedef std::list<const WebPluginGeometry*> PluginList;
PluginList visible_plugins;
// Identify the visible plugins.
PluginMap::const_iterator it = plugin_map_.begin();
for(; it != plugin_map_.end(); ++it) {
for (; it != plugin_map_.end(); ++it) {
if (it->second.visible && client_rect.Intersects(it->second.window_rect))
visible_plugins.push_back(&it->second);
}
@@ -462,10 +448,10 @@ void WebWidgetHost::Paint() {
// Paint the plugin windows.
PluginList::const_iterator it = visible_plugins.begin();
for(; it != visible_plugins.end(); ++it) {
for (; it != visible_plugins.end(); ++it) {
const WebPluginGeometry* geom = *(it);
oldRGN = CreateRectRgn(0,0,1,1);
oldRGN = CreateRectRgn(0, 0, 1, 1);
GetClipRgn(drawDC, oldRGN);
// Only paint inside the clip region.
@@ -484,7 +470,7 @@ void WebWidgetHost::Paint() {
SendMessageToPlugin(geom->window, WM_PRINT,
reinterpret_cast<WPARAM>(drawDC),
PRF_OWNED | PRF_ERASEBKGND | PRF_CLIENT | PRF_NONCLIENT);
SetViewportOrgEx(drawDC, oldViewport.x, oldViewport.y, NULL);
SelectClipRgn(drawDC, oldRGN);
@@ -510,6 +496,9 @@ void WebWidgetHost::Paint() {
// Draw children
UpdateWindow(view_);
} else {
if (damaged_rgn.isEmpty())
return;
// Paint to the delegate.
DCHECK(paint_delegate_);
const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false);
@@ -526,69 +515,12 @@ void WebWidgetHost::Paint() {
paint_delegate_->Paint(popup_, damaged_rects, pixels);
}
// Used with scheduled invalidation to maintain a consistent frame rate.
paint_last_call_ = base::TimeTicks::Now();
if (has_invalidate_task_)
has_invalidate_task_ = false;
}
void WebWidgetHost::InvalidateRect(const gfx::Rect& rect)
{
if (rect.IsEmpty())
return;
if (view_) {
// Let the window handle painting.
RECT r = rect.ToRECT();
::InvalidateRect(view_, &r, FALSE);
} else {
// Don't post a paint task if this invalidation occurred during layout or if
// a paint task is already pending. Paint() will be called by DoPaint().
if (!layouting_ && !has_update_task_) {
has_update_task_ = true;
CefThread::PostTask(CefThread::UI, FROM_HERE,
base::Bind(&WebWidgetHost::DoPaint, weak_factory_.GetWeakPtr()));
}
}
}
bool WebWidgetHost::GetImage(int width, int height, void* buffer)
{
const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false);
DCHECK(bitmap.config() == SkBitmap::kARGB_8888_Config);
if (width == canvas_->getDevice()->width() &&
height == canvas_->getDevice()->height()) {
// The specified width and height values are the same as the canvas size.
// Return the existing canvas contents.
const void* pixels = bitmap.getPixels();
memcpy(buffer, pixels, width * height * 4);
return true;
}
// Create a new canvas of the requested size.
scoped_ptr<skia::PlatformCanvas> new_canvas(
new skia::PlatformCanvas(width, height, true));
new_canvas->writePixels(bitmap, 0, 0);
const SkBitmap& new_bitmap = new_canvas->getDevice()->accessBitmap(false);
DCHECK(new_bitmap.config() == SkBitmap::kARGB_8888_Config);
// Return the new canvas contents.
const void* pixels = new_bitmap.getPixels();
memcpy(buffer, pixels, width * height * 4);
return true;
}
WebScreenInfo WebWidgetHost::GetScreenInfo() {
return WebScreenInfoFactory::screenInfo(view_);
}
void WebWidgetHost::Resize(LPARAM lparam) {
SetSize(LOWORD(lparam), HIWORD(lparam));
}
void WebWidgetHost::MouseEvent(UINT message, WPARAM wparam, LPARAM lparam) {
const WebMouseEvent& event = WebInputEventFactory::mouseEvent(
view_, message, wparam, lparam);
@@ -602,11 +534,24 @@ void WebWidgetHost::MouseEvent(UINT message, WPARAM wparam, LPARAM lparam) {
case WebInputEvent::MouseDown:
if (!popup()) {
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_);
if (::GetFocus() != view_) {
// Set focus to this window.
HWND parent_hwnd = ::GetParent(view_);
if (parent_hwnd) {
CefRefPtr<CefBrowserImpl> browser =
static_cast<CefBrowserImpl*>(
ui::GetWindowUserData(parent_hwnd));
if (browser.get()) {
// This mimics a temporary workaround in RenderWidgetHostViewWin
// for bug 765011 to get focus when the mouse is clicked. This
// happens after the mouse down event is sent to the renderer
// because normally Windows does a WM_SETFOCUS after
// WM_LBUTTONDOWN.
browser->SetFocus(true);
}
}
}
}
break;
case WebInputEvent::MouseUp:
@@ -645,7 +590,7 @@ void WebWidgetHost::OnNotify(WPARAM wparam, NMHDR* header) {
return;
switch (header->code) {
case TTN_GETDISPINFO:
case TTN_GETDISPINFO:
{
NMTTDISPINFOW* tooltip_info = reinterpret_cast<NMTTDISPINFOW*>(header);
tooltip_info->szText[0] = L'\0';
@@ -679,8 +624,7 @@ void WebWidgetHost::SetTooltipText(const CefString& tooltip_text) {
::SendMessage(tooltip_view_, TTM_POP, 0, 0);
::SendMessage(tooltip_view_, TTM_POPUP, 0, 0);
}
}
else {
} 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.
@@ -745,53 +689,31 @@ void WebWidgetHost::TrackMouseLeave(bool track) {
TrackMouseEvent(&tme);
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
#ifndef NDEBUG
DCHECK(!painting_);
#endif
DCHECK(canvas_.get());
if (!popup() && ((WebKit::WebView*)webwidget_)->isTransparent()) {
// When using transparency mode clear the rectangle before painting.
SkPaint clearpaint;
clearpaint.setARGB(0,0,0,0);
clearpaint.setXfermodeMode(SkXfermode::kClear_Mode);
SkRect skrc;
skrc.set(rect.x(), rect.y(), rect.right(), rect.bottom());
canvas_->drawRect(skrc, clearpaint);
}
set_painting(true);
webwidget_->paint(canvas_.get(), rect);
set_painting(false);
}
void WebWidgetHost::SendKeyEvent(cef_key_type_t type, int key, int modifiers,
bool sysChar, bool imeChar)
{
void WebWidgetHost::SendKeyEvent(cef_key_type_t type,
const cef_key_info_t& keyInfo,
int modifiers) {
UINT message = 0;
WPARAM wparam = key;
WPARAM wparam = keyInfo.key;
LPARAM lparam = modifiers;
if (type == KT_KEYUP) {
if (sysChar)
if (keyInfo.sysChar)
message = WM_SYSKEYUP;
else if(imeChar)
else if (keyInfo.imeChar)
message = WM_IME_KEYUP;
else
message = WM_KEYUP;
} else if(type == KT_KEYDOWN) {
if (sysChar)
} else if (type == KT_KEYDOWN) {
if (keyInfo.sysChar)
message = WM_SYSKEYDOWN;
else if(imeChar)
else if (keyInfo.imeChar)
message = WM_IME_KEYDOWN;
else
message = WM_KEYDOWN;
} else if(type == KT_CHAR) {
if (sysChar)
} else if (type == KT_CHAR) {
if (keyInfo.sysChar)
message = WM_SYSCHAR;
else if(imeChar)
else if (keyInfo.imeChar)
message = WM_IME_CHAR;
else
message = WM_CHAR;
@@ -811,27 +733,26 @@ void WebWidgetHost::SendKeyEvent(cef_key_type_t type, int key, int modifiers,
void WebWidgetHost::SendMouseClickEvent(int x, int y,
cef_mouse_button_type_t type,
bool mouseUp, int clickCount)
{
bool mouseUp, int clickCount) {
DCHECK(clickCount >=1 && clickCount <= 2);
UINT message = 0;
WPARAM wparam = 0;
LPARAM lparam = MAKELPARAM(x, y);
if (type == MBT_LEFT) {
if (mouseUp)
message = (clickCount==1?WM_LBUTTONUP:WM_LBUTTONDBLCLK);
message = (clickCount == 1?WM_LBUTTONUP:WM_LBUTTONDBLCLK);
else
message = WM_LBUTTONDOWN;
} else if (type == MBT_MIDDLE) {
if (mouseUp)
message = (clickCount==1?WM_MBUTTONUP:WM_MBUTTONDBLCLK);
message = (clickCount == 1?WM_MBUTTONUP:WM_MBUTTONDBLCLK);
else
message = WM_MBUTTONDOWN;
} else if (type == MBT_RIGHT) {
if (mouseUp)
message = (clickCount==1?WM_RBUTTONUP:WM_RBUTTONDBLCLK);
message = (clickCount == 1?WM_RBUTTONUP:WM_RBUTTONDBLCLK);
else
message = WM_RBUTTONDOWN;
}
@@ -840,7 +761,7 @@ void WebWidgetHost::SendMouseClickEvent(int x, int y,
NOTREACHED();
return;
}
if (GetKeyState(VK_CONTROL) & 0x8000)
wparam |= MK_CONTROL;
if (GetKeyState(VK_SHIFT) & 0x8000)
@@ -862,12 +783,11 @@ void WebWidgetHost::SendMouseClickEvent(int x, int y,
}
}
void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave)
{
void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave) {
UINT message;
WPARAM wparam = 0;
LPARAM lparam = 0;
if (mouseLeave) {
message = WM_MOUSELEAVE;
} else {
@@ -896,11 +816,10 @@ void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave)
}
}
void WebWidgetHost::SendMouseWheelEvent(int x, int y, int delta)
{
WPARAM wparam = MAKEWPARAM(0, delta);
void WebWidgetHost::SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) {
WPARAM wparam = MAKEWPARAM(0, deltaY);
LPARAM lparam = MAKELPARAM(x, y);
if (GetKeyState(VK_CONTROL) & 0x8000)
wparam |= MK_CONTROL;
if (GetKeyState(VK_SHIFT) & 0x8000)
@@ -922,48 +841,40 @@ void WebWidgetHost::SendMouseWheelEvent(int x, int y, int delta)
}
}
void WebWidgetHost::SendFocusEvent(bool setFocus)
{
void WebWidgetHost::SendFocusEvent(bool setFocus) {
SetFocus(setFocus);
}
void WebWidgetHost::SendCaptureLostEvent()
{
void WebWidgetHost::SendCaptureLostEvent() {
CaptureLostEvent();
}
LRESULT WebWidgetHost::OnImeSetContext(UINT message, WPARAM wparam,
LPARAM lparam, BOOL& handled)
{
LPARAM lparam, BOOL& handled) {
if (!webwidget_)
return 0;
// We need status messages about the focused input control from a
// renderer process when:
// We need to start the IME timer when:
// * the current input context has IMEs, and;
// * an application is activated.
// This seems to tell we should also check if the current input context has
// IMEs before sending a request, however, this WM_IME_SETCONTEXT is
// fortunately sent to an application only while the input context has IMEs.
// Therefore, we just start/stop status messages according to the activation
// This seems to indicate that we should also check if the current input
// context has IMEs before starting the timer, however, this WM_IME_SETCONTEXT
// is fortunately sent to an application only while the input context has
// IMEs. Therefore, we just start/stop the timer according to the activation
// status of this application without checks.
bool activated = (wparam == TRUE);
if (webwidget_) {
input_method_is_active_ = activated;
ime_notification_ = activated;
}
ime_notification_ = (wparam == TRUE);
if (ime_notification_)
ime_input_.CreateImeWindow(view_);
ime_input_.CleanupComposition(view_);
ime_input_.SetImeWindowStyle(view_, message, wparam, lparam, &handled);
ToggleImeTimer();
return 0;
}
LRESULT WebWidgetHost::OnImeStartComposition(UINT message, WPARAM wparam,
LPARAM lparam, BOOL& handled)
{
LPARAM lparam, BOOL& handled) {
if (!webwidget_)
return 0;
@@ -978,8 +889,7 @@ LRESULT WebWidgetHost::OnImeStartComposition(UINT message, WPARAM wparam,
}
LRESULT WebWidgetHost::OnImeComposition(UINT message, WPARAM wparam,
LPARAM lparam, BOOL& handled)
{
LPARAM lparam, BOOL& handled) {
if (!webwidget_)
return 0;
@@ -993,7 +903,7 @@ LRESULT WebWidgetHost::OnImeComposition(UINT message, WPARAM wparam,
ui_CompositionUnderline__WebKit_WebCompositionUnderline_diff);
// Retrieve the result string and its attributes of the ongoing composition
// and send it to a renderer process.
// and send to WebKit.
ui::CompositionText composition;
if (ime_input_.GetResult(view_, lparam, &composition.text)) {
webwidget_->setComposition(composition.text,
@@ -1007,14 +917,12 @@ LRESULT WebWidgetHost::OnImeComposition(UINT message, WPARAM wparam,
// by the start of another composition.
}
// Retrieve the composition string and its attributes of the ongoing
// composition and send it to a renderer process.
// composition and send to WebKit.
if (ime_input_.GetComposition(view_, lparam, &composition)) {
// TODO(suzhe): due to a bug of webkit, we can't use selection range with
// composition string. See: https://bugs.webkit.org/show_bug.cgi?id=37788
composition.selection = ui::Range(composition.selection.end());
// TODO(suzhe): convert both renderer_host and renderer to use
// ui::CompositionText.
const std::vector<WebKit::WebCompositionUnderline>& underlines =
reinterpret_cast<const std::vector<WebKit::WebCompositionUnderline>&>(
composition.underlines);
@@ -1029,16 +937,15 @@ LRESULT WebWidgetHost::OnImeComposition(UINT message, WPARAM wparam,
}
LRESULT WebWidgetHost::OnImeEndComposition(UINT message, WPARAM wparam,
LPARAM lparam, BOOL& handled)
{
LPARAM lparam, BOOL& handled) {
if (!webwidget_)
return 0;
if (ime_input_.is_composing()) {
// A composition has been ended while there is an ongoing composition,
// i.e. the ongoing composition has been canceled.
// We need to reset the composition status both of the ImeInput object and
// of the renderer process.
// Reset the composition status of both of the ImeInput object and the
// window.
ime_input_.CancelIME(view_);
ime_input_.ResetComposition(view_);
}
@@ -1049,47 +956,33 @@ LRESULT WebWidgetHost::OnImeEndComposition(UINT message, WPARAM wparam,
}
void WebWidgetHost::OnInputLangChange(DWORD character_set,
HKL input_language_id)
{
HKL input_language_id) {
if (!webwidget_)
return;
// Send the given Locale ID to the ImeInput object and retrieves whether
// or not the current input context has IMEs.
// If the current input context has IMEs, a browser process has to send a
// request to a renderer process that it needs status messages about
// the focused edit control from the renderer process.
// On the other hand, if the current input context does not have IMEs, the
// browser process also has to send a request to the renderer process that
// it does not need the status messages any longer.
// To minimize the number of this notification request, we should check if
// the browser process is actually retrieving the status messages (this
// state is stored in ime_notification_) and send a request only if the
// browser process has to update this status, its details are listed below:
// * If a browser process is not retrieving the status messages,
// (i.e. ime_notification_ == false),
// send this request only if the input context does have IMEs,
// (i.e. ime_status == true);
// When it successfully sends the request, toggle its notification status,
// (i.e.ime_notification_ = !ime_notification_ = true).
// * If a browser process is retrieving the status messages
// (i.e. ime_notification_ == true),
// send this request only if the input context does not have IMEs,
// (i.e. ime_status == false).
// When it successfully sends the request, toggle its notification status,
// (i.e.ime_notification_ = !ime_notification_ = false).
// To analyze the above actions, we can optimize them into the ones
// listed below:
// 1 Sending a request only if ime_status_ != ime_notification_, and;
// 2 Copying ime_status to ime_notification_ if it sends the request
// successfully (because Action 1 shows ime_status = !ime_notification_.)
// or not the current input context has IMEs. Toggle the timer based on
// whether the current input context has IMEs.
bool ime_status = ime_input_.SetInputLanguage();
if (ime_status != ime_notification_ && webwidget_) {
input_method_is_active_ = ime_status;
if (ime_status != ime_notification_) {
ime_notification_ = ime_status;
ToggleImeTimer();
}
}
void WebWidgetHost::ImeUpdateTextInputState(WebKit::WebTextInputType type,
const gfx::Rect& caret_rect)
{
void WebWidgetHost::UpdateImeInputState() {
if (!webwidget_ || !ime_notification_) {
ToggleImeTimer();
return;
}
WebKit::WebTextInputType type = webwidget_->textInputType();
WebKit::WebRect caret_bounds;
WebKit::WebRect startRect, endRect;
if (webwidget_->selectionBounds(startRect, endRect))
caret_bounds = endRect;
if (text_input_type_ != type) {
text_input_type_ = type;
if (type == WebKit::WebTextInputTypeText)
@@ -1098,32 +991,24 @@ void WebWidgetHost::ImeUpdateTextInputState(WebKit::WebTextInputType type,
ime_input_.DisableIME(view_);
}
// Only update caret position if the input method is enabled.
if (type == WebKit::WebTextInputTypeText)
ime_input_.UpdateCaretRect(view_, caret_rect);
}
void WebWidgetHost::UpdateInputMethod()
{
REQUIRE_UIT();
has_update_input_method_task_ = false;
if (!input_method_is_active_ || !webwidget_)
return;
WebKit::WebTextInputType new_type = webwidget_->textInputType();
WebKit::WebRect new_caret_bounds;
WebKit::WebRect startRect, endRect;
if (webwidget_->selectionBounds(startRect, endRect))
new_caret_bounds = endRect;
// Only sends text input type and caret bounds to the browser process if they
// are changed.
if (text_input_type_ != new_type || caret_bounds_ != new_caret_bounds) {
text_input_type_ = new_type;
caret_bounds_ = new_caret_bounds;
ImeUpdateTextInputState(new_type, new_caret_bounds);
// Only update caret position if the input method is enabled and the caret
// position has changed.
if (type == WebKit::WebTextInputTypeText && caret_bounds != caret_bounds_) {
caret_bounds_ = caret_bounds;
ime_input_.UpdateCaretRect(view_, caret_bounds);
}
}
void WebWidgetHost::ToggleImeTimer() {
if (view_ && !popup_ && ime_notification_ && webwidget_) {
if (!ime_timer_.IsRunning()) {
ime_timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(200),
this,
&WebWidgetHost::UpdateImeInputState);
}
} else if (ime_timer_.IsRunning()) {
ime_timer_.Stop();
}
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
@@ -674,22 +674,29 @@ int CEF_CALLBACK browser_get_image(struct _cef_browser_t* self,
void CEF_CALLBACK browser_send_key_event(struct _cef_browser_t* self,
enum cef_key_type_t type, int key, int modifiers, int sysChar,
int imeChar)
enum cef_key_type_t type, const struct _cef_key_info_t* keyInfo,
int modifiers)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: keyInfo; type: struct_byref_const
DCHECK(keyInfo);
if (!keyInfo)
return;
// Translate param: keyInfo; type: struct_byref_const
CefKeyInfo keyInfoObj;
if (keyInfo)
keyInfoObj.Set(*keyInfo, false);
// Execute
CefBrowserCppToC::Get(self)->SendKeyEvent(
type,
key,
modifiers,
sysChar?true:false,
imeChar?true:false);
keyInfoObj,
modifiers);
}
@@ -731,7 +738,7 @@ void CEF_CALLBACK browser_send_mouse_move_event(struct _cef_browser_t* self,
void CEF_CALLBACK browser_send_mouse_wheel_event(struct _cef_browser_t* self,
int x, int y, int delta)
int x, int y, int deltaX, int deltaY)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
@@ -743,7 +750,8 @@ void CEF_CALLBACK browser_send_mouse_wheel_event(struct _cef_browser_t* self,
CefBrowserCppToC::Get(self)->SendMouseWheelEvent(
x,
y,
delta);
deltaX,
deltaY);
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
@@ -15,11 +15,13 @@
#include "libcef_dll/cpptoc/drag_handler_cpptoc.h"
#include "libcef_dll/cpptoc/find_handler_cpptoc.h"
#include "libcef_dll/cpptoc/focus_handler_cpptoc.h"
#include "libcef_dll/cpptoc/geolocation_handler_cpptoc.h"
#include "libcef_dll/cpptoc/jsdialog_handler_cpptoc.h"
#include "libcef_dll/cpptoc/keyboard_handler_cpptoc.h"
#include "libcef_dll/cpptoc/life_span_handler_cpptoc.h"
#include "libcef_dll/cpptoc/load_handler_cpptoc.h"
#include "libcef_dll/cpptoc/menu_handler_cpptoc.h"
#include "libcef_dll/cpptoc/permission_handler_cpptoc.h"
#include "libcef_dll/cpptoc/print_handler_cpptoc.h"
#include "libcef_dll/cpptoc/render_handler_cpptoc.h"
#include "libcef_dll/cpptoc/request_handler_cpptoc.h"
@@ -154,6 +156,24 @@ cef_menu_handler_t* CEF_CALLBACK client_get_menu_handler(
}
cef_permission_handler_t* CEF_CALLBACK client_get_permission_handler(
struct _cef_client_t* self)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefPermissionHandler> _retval = CefClientCppToC::Get(
self)->GetPermissionHandler();
// Return type: refptr_same
return CefPermissionHandlerCppToC::Wrap(_retval);
}
cef_print_handler_t* CEF_CALLBACK client_get_print_handler(
struct _cef_client_t* self)
{
@@ -262,6 +282,24 @@ cef_drag_handler_t* CEF_CALLBACK client_get_drag_handler(
}
cef_geolocation_handler_t* CEF_CALLBACK client_get_geolocation_handler(
struct _cef_client_t* self)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Execute
CefRefPtr<CefGeolocationHandler> _retval = CefClientCppToC::Get(
self)->GetGeolocationHandler();
// Return type: refptr_same
return CefGeolocationHandlerCppToC::Wrap(_retval);
}
// CONSTRUCTOR - Do not edit by hand.
@@ -275,12 +313,14 @@ CefClientCppToC::CefClientCppToC(CefClient* cls)
struct_.struct_.get_focus_handler = client_get_focus_handler;
struct_.struct_.get_keyboard_handler = client_get_keyboard_handler;
struct_.struct_.get_menu_handler = client_get_menu_handler;
struct_.struct_.get_permission_handler = client_get_permission_handler;
struct_.struct_.get_print_handler = client_get_print_handler;
struct_.struct_.get_find_handler = client_get_find_handler;
struct_.struct_.get_jsdialog_handler = client_get_jsdialog_handler;
struct_.struct_.get_v8context_handler = client_get_v8context_handler;
struct_.struct_.get_render_handler = client_get_render_handler;
struct_.struct_.get_drag_handler = client_get_drag_handler;
struct_.struct_.get_geolocation_handler = client_get_geolocation_handler;
}
#ifndef NDEBUG

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -0,0 +1,216 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/cookie_manager_cpptoc.h"
#include "libcef_dll/ctocpp/cookie_visitor_ctocpp.h"
#include "libcef_dll/transfer_util.h"
// GLOBAL FUNCTIONS - Body may be edited by hand.
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_get_global_manager()
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
CefRefPtr<CefCookieManager> _retval = CefCookieManager::GetGlobalManager();
// Return type: refptr_same
return CefCookieManagerCppToC::Wrap(_retval);
}
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_create_manager(
const cef_string_t* path)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: path
// Execute
CefRefPtr<CefCookieManager> _retval = CefCookieManager::CreateManager(
CefString(path));
// Return type: refptr_same
return CefCookieManagerCppToC::Wrap(_retval);
}
// MEMBER FUNCTIONS - Body may be edited by hand.
void CEF_CALLBACK cookie_manager_set_supported_schemes(
struct _cef_cookie_manager_t* self, cef_string_list_t schemes)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Verify param: schemes; type: string_vec_byref_const
DCHECK(schemes);
if (!schemes)
return;
// Translate param: schemes; type: string_vec_byref_const
std::vector<CefString> schemesList;
transfer_string_list_contents(schemes, schemesList);
// Execute
CefCookieManagerCppToC::Get(self)->SetSupportedSchemes(
schemesList);
}
int CEF_CALLBACK cookie_manager_visit_all_cookies(
struct _cef_cookie_manager_t* self, struct _cef_cookie_visitor_t* visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: visitor; type: refptr_diff
DCHECK(visitor);
if (!visitor)
return 0;
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->VisitAllCookies(
CefCookieVisitorCToCpp::Wrap(visitor));
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_visit_url_cookies(
struct _cef_cookie_manager_t* self, const cef_string_t* url,
int includeHttpOnly, struct _cef_cookie_visitor_t* visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: url; type: string_byref_const
DCHECK(url);
if (!url)
return 0;
// Verify param: visitor; type: refptr_diff
DCHECK(visitor);
if (!visitor)
return 0;
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->VisitUrlCookies(
CefString(url),
includeHttpOnly?true:false,
CefCookieVisitorCToCpp::Wrap(visitor));
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_set_cookie(struct _cef_cookie_manager_t* self,
const cef_string_t* url, const struct _cef_cookie_t* cookie)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: url; type: string_byref_const
DCHECK(url);
if (!url)
return 0;
// Verify param: cookie; type: struct_byref_const
DCHECK(cookie);
if (!cookie)
return 0;
// Translate param: cookie; type: struct_byref_const
CefCookie cookieObj;
if (cookie)
cookieObj.Set(*cookie, false);
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->SetCookie(
CefString(url),
cookieObj);
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_delete_cookies(
struct _cef_cookie_manager_t* self, const cef_string_t* url,
const cef_string_t* cookie_name)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Unverified params: url, cookie_name
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->DeleteCookies(
CefString(url),
CefString(cookie_name));
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_set_storage_path(
struct _cef_cookie_manager_t* self, const cef_string_t* path)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Unverified params: path
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->SetStoragePath(
CefString(path));
// Return type: bool
return _retval;
}
// CONSTRUCTOR - Do not edit by hand.
CefCookieManagerCppToC::CefCookieManagerCppToC(CefCookieManager* cls)
: CefCppToC<CefCookieManagerCppToC, CefCookieManager, cef_cookie_manager_t>(
cls)
{
struct_.struct_.set_supported_schemes = cookie_manager_set_supported_schemes;
struct_.struct_.visit_all_cookies = cookie_manager_visit_all_cookies;
struct_.struct_.visit_url_cookies = cookie_manager_visit_url_cookies;
struct_.struct_.set_cookie = cookie_manager_set_cookie;
struct_.struct_.delete_cookies = cookie_manager_delete_cookies;
struct_.struct_.set_storage_path = cookie_manager_set_storage_path;
}
#ifndef NDEBUG
template<> long CefCppToC<CefCookieManagerCppToC, CefCookieManager,
cef_cookie_manager_t>::DebugObjCt = 0;
#endif

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#ifndef _COOKIEMANAGER_CPPTOC_H
#define _COOKIEMANAGER_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 CefCookieManagerCppToC
: public CefCppToC<CefCookieManagerCppToC, CefCookieManager,
cef_cookie_manager_t>
{
public:
CefCookieManagerCppToC(CefCookieManager* cls);
virtual ~CefCookieManagerCppToC() {}
};
#endif // BUILDING_CEF_SHARED
#endif // _COOKIEMANAGER_CPPTOC_H

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//

Some files were not shown because too many files have changed in this diff Show More