diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index dcb75da2e..d2f0143fe 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,7 +1,2 @@ -Please do not create Issues. Issues must first be discussed -and confirmed on the Forum. Report issues on the Forum here: - -https://goo.gl/xz4cEF - -Please do not ask questions in existing issues. Ask questions -on the Forum, link above. +Questions should be asked on the forum: +https://groups.google.com/group/cefpython diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..c5663b055 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: ['https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=V7LU7PD4N4GGG'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 2bf4f13a8..d2f0143fe 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,8 +1,2 @@ -Please do not create Issues using this form. Issues must -first be discussed and confirmed on the Forum. Report issues -on the Forum here: - -https://goo.gl/xz4cEF - -Please do not ask questions in existing issues. Ask questions -on the Forum, link above. +Questions should be asked on the forum: +https://groups.google.com/group/cefpython diff --git a/.gitignore b/.gitignore index 68c99713f..b786188bc 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,10 @@ webcache/ examples/screenshot.png examples/pyinstaller/build/ examples/pyinstaller/dist/ +examples/GPUCache/ +examples/blob_storage/ +examples/webrtc_event_logs/ +unittests/GPUCache/ +unittests/blob_storage/ +unittests/webrtc_event_logs/ +.DS_Store diff --git a/Authors b/Authors index 827d05cc5..b44b24e68 100644 --- a/Authors +++ b/Authors @@ -1,16 +1,22 @@ Core developers: -Czarek Tomczak + Czarek Tomczak Contributors: -老农 cjjer -Richard Rodriguez -Roman Plášil -Rokas Stupuras -Greg Kacy -Thomas Dähling -Dominique Burnand -Greg Farrell -Finn Hughes -Marcelo Fernandez -Simon Hatt <9hatt2@@gmail.com> -Neil Munday + 老农 cjjer + Richard Rodriguez + Roman Plášil + Rokas Stupuras + Greg Kacy + Thomas Dähling + Dominique Burnand + Greg Farrell + Finn Hughes + Marcelo Fernandez + Simon Hatt <9hatt2@@gmail.com> + Neil Munday + Joseph Kogut + Paweł Kierski + Dónal McMullan + nobodyguy + Elliot Woods + Bryan Koroleski diff --git a/README.md b/README.md index 3f96e4a24..b85f34c6b 100644 --- a/README.md +++ b/README.md @@ -2,99 +2,78 @@ Table of contents: * [Introduction](#introduction) -* [Major sponsors](#major-sponsors) -* [Funding for v63.0 release](#funding-for-v630-release) * [Install](#install) -* [Tutorial](#tutorial) * [Examples](#examples) * [Support](#support) * [Support development](#support-development) - * [Thanks](#thanks) -* [Releases](#releases) -* [Other READMEs](#other-readmes) -* [Quick links](#quick-links) +* [Seeking sponsors](#seeking-sponsors) +* [API](#api) ## Introduction -CEF Python is a BSD-licensed open source project founded by Czarek Tomczak (hire me! download my [resume](https://drive.google.com/file/d/17xmoT5Z_zTHkVclqPzrs2aAV64Uiu7fh/view)) in 2012 and is based on Google Chromium and the -[CEF Framework](https://bitbucket.org/chromiumembedded/cef) -projects. The Chromium project focuses mainly on Google Chrome application -development, while CEF focuses on facilitating embedded browser use cases +CEF Python is an open source project founded by +[Czarek Tomczak](https://www.linkedin.com/in/czarektomczak/) +in 2012 to provide Python bindings for the +[Chromium Embedded Framework](https://bitbucket.org/chromiumembedded/cef) (CEF). +The Chromium project focuses mainly on Google Chrome application +development while CEF focuses on facilitating embedded browser use cases in third-party applications. Lots of applications use CEF control, there are more than [100 million CEF instances](http://en.wikipedia.org/wiki/Chromium_Embedded_Framework#Applications_using_CEF) -installed around the world. [Examples of embedding](examples/README-examples.md) -Chrome browser are available for many popular GUI toolkits including: -wxPython, PyGTK, PyQt, PySide, Kivy, Panda3D and PyGame/PyOpenGL. +installed around the world. There are numerous use cases for CEF: -There are many use cases for CEF. You can embed a web browser control -based on Chromium with great HTML 5 support. You can use it to create -a HTML 5 based GUI in an application, this can act as a replacement for -standard GUI toolkits such as wxWidgets, Qt or GTK. In such case to -communicate between Python<>Javascript use [javascript bindings](docs/Tutorial.md#javascript-integration) -or embed an internal web server and talk using http requests. You -can render web content off-screen in applications that use custom -drawing frameworks. You can use it for automated testing of existing -applications. You can use it for web scraping or as a web crawler, -or other kind of internet bots. +1. Use it as a modern HTML5 based rendering engine that can act as + a replacement for classic desktop GUI frameworks. Think of it as Electron + for Python. +2. Embed a web browser widget in a classic Qt / GTK / wxPython desktop + application +3. Render web content off-screen in applications that use custom drawing + frameworks +4. Use it for automated testing of web applications with more advanced + capabilities than Selenium web browser automation due to CEF low level + programming APIs +5. Use it for web scraping, as a web crawler or other kind of internet bots - -## Major sponsors - - - - -
- - - - -
- - - - -

- -See the [Support development](#support-development) section for a list of -all the individuals and companies supporting CEF Python. - - -## Funding for v63.0 release - -For those interested in sponsoring a v63.0 release please see -[Issue #370](../../issues/370). +CEF Python also provides examples of embedding CEF for many Python GUI +frameworks such as PyQt, wxPython, PyGTK, PyGObject, Tkinter, Kivy, Panda3D, +PyGame, PyOpenGL, PyWin32, PySide and PySDL2. ## Install -You can install [pypi/cefpython3](https://pypi.python.org/pypi/cefpython3) -package using pip tool. On Linux pip 8.1+ is required. You can -also download packages for offline installation available on the -[GitHub Releases](../../releases) pages. Command to install with pip: +Command to install with pip: ``` -pip install cefpython3==57.0 +pip install cefpython3==66.1 ``` -If you get an error when importing the cefpython3 package on -Windows then see this section in the Knowledge Base document: -[ImportError: DLL load failed (Windows)](docs/Knowledge-Base.md#importerror-dll-load-failed-windows). +Hosted at [pypi/cefpython3](https://pypi.python.org/pypi/cefpython3). On Linux pip 8.1+ is required. -## Tutorial +You can also download packages for offline installation available on the [GitHub Releases](../../releases) pages. -See the [Tutorial.md](docs/Tutorial.md) file. +Below is a table with supported platforms, python versions and architectures. + +OS | Py2 | Py3 | 32bit | 64bit | Requirements +--- | --- | --- | --- | --- | --- +Windows | 2.7 | 3.4 / 3.5 / 3.6 / 3.7 / 3.8 / 3.9 | Yes | Yes | Windows 7+ (Note that Python 3.9 supports Windows 8.1+) +Linux | 2.7 | 3.4 / 3.5 / 3.6 / 3.7 | Yes | Yes | Debian 8+, Ubuntu 14.04+,
Fedora 24+, openSUSE 13.3+ +Mac | 2.7 | 3.4 / 3.5 / 3.6 / 3.7 | No | Yes | MacOS 10.9+ ## Examples -See the [README-examples.md](examples/README-examples.md) file. +- [Tutorial](docs/Tutorial.md) +- [All examples](examples/README-examples.md) +- [Snippets](examples/snippets/README-snippets.md) +- [PyInstaller packager](examples/pyinstaller/README-pyinstaller.md) ## Support -- Ask questions, report problems and issues on the [Forum](https://groups.google.com/group/cefpython) -- Supported examples are listed in the [README-examples.md](examples/README-examples.md) file +- Ask questions and report problems on the + [Forum](https://groups.google.com/group/cefpython) +- Supported examples are listed in the + [README-examples.md](examples/README-examples.md) file - Documentation is in the [docs/](docs) directory: - [Build instructions](docs/Build-instructions.md) - [Contributing code](docs/Contributing-code.md) @@ -104,112 +83,90 @@ See the [README-examples.md](examples/README-examples.md) file. - API reference is in the [api/](api) directory: - [API categories](api/API-categories.md#api-categories) - [API index](api/API-index.md#api-index) -- Additional documentation is available in [Issues labelled Knowledge Base](../../issues?q=is%3Aissue+is%3Aopen+label%3A%22Knowledge+Base%22) +- Additional documentation is available in + [Issues labelled Knowledge Base](../../issues?q=is%3Aissue+is%3Aopen+label%3A%22Knowledge+Base%22) - To search documentation use GitHub "This repository" search at the top. To narrow results to documentation only select - "Markdown" in the right pane. -- Wiki pages are deprecated and for v31 only - + "Markdown" in the side pane ## Support development -If you would like to support general CEF Python development efforts -by making a donation please click the Paypal Donate button: - - - -

- -If you would like to see some feature implemented you can make -a comment about that when making a donation. It will give it -a higher priority. - -If you are interested in sponsorship opportunities please contact Czarek -directly (linkedin profile or email). - -### Thanks - -* [2017] Many thanks to [ClearChat Inc.](https://clearchat.com/) for sponsoring - the v55/v56 releases for all platforms -* [2016-2017] Thanks to JetBrains for providing an Open Source license for - [PyCharm](https://www.jetbrains.com/pycharm/) -* [2012-2016] Thanks to those who have made a Paypal donation: - [Rentouch GmbH](http://www.rentouch.ch/), Walter Purvis, Rokas Stupuras, - Alex Rattray, Greg Kacy, Paul Korzhyk -* [2012-2016] Thanks to those who have donated their time through code contributions, - they are listed in the [Authors](Authors) file -* [2013-2015] Lots of thanks goes to [Cyan Inc.](http://www.blueplanet.com/) - for sponsoring this project for a long time, making CEF Python 3 mature -* [2014] Thanks to Adam Duston for donating a Macbook to aid the development - of Mac port -* [2013] Thanks to [Rentouch GmbH](http://www.rentouch.ch/) for sponsoring the - development of the off-screen rendering support -* [2013] Thanks to Thomas Wusatiuk for sponsoring the development of the web - response reading features - - -## Releases - -Information on planned new and current releases, supported platforms, -python versions, architectures and requirements. If you want to -support old operating systems then choose the v31 release. - -**Next release** - -- To see planned new features or bugs to be fixed in the - next release, see the - [next release](../../issues?q=is%3Aissue+is%3Aopen+label%3A%22next+release%22) - label in the tracker -- To see planned new features or bugs to be fixed in the - in one of next releases, see the - [next release 2](../../issues?q=is%3Aissue+is%3Aopen+label%3A%22next+release+2%22) - label in the tracker - -**Latest release** - -OS | Py2 | Py3 | 32bit | 64bit | Requirements ---- | --- | --- | --- | --- | --- -Windows | 2.7 | 3.4 / 3.5 / 3.6 | Yes | Yes | Windows 7+ -Linux | 2.7 | 3.4 / 3.5 / 3.6 | Yes | Yes | Debian 7+ / Ubuntu 12.04+ -Mac | 2.7 | 3.4 / 3.5 / 3.6 | No | Yes | MacOS 10.9+ - -These platforms are not supported yet: -- ARM - see [Issue #267](../../issues/267) -- Android - see [Issue #307](../../issues/307) - -**v31 release** - -OS | Py2 | Py3 | 32bit | 64bit | Requirements ---- | --- | --- | --- | --- | --- -Windows | 2.7 | No | Yes | Yes | Windows XP+ -Linux | 2.7 | No | Yes | Yes | Debian 7+ / Ubuntu 12.04+ -Mac | 2.7 | No | Yes | Yes | MacOS 10.7+ - -Additional information for v31.2 release: -- On Windows/Mac you can install with command: `pip install cefpython3==31.2` -- Downloads are available on [wiki pages](../../wiki#downloads) - and on GitHub Releases tagged [v31.2](../../releases/tag/v31.2). -- Documentation is on [wiki pages](../../wiki) -- API reference is available in revision [169a1b2](../../tree/169a1b20d3cd09879070d41aab28cfa195d2a7d5/docs/api) - - -## Other READMEs - -- [PyInstaller packager](examples/pyinstaller/README-pyinstaller.md) - - - -## Quick links - -### Docs - -- [Build instructions](docs/Build-instructions.md) -- [Knowledge Base](docs/Knowledge-Base.md) -- [Migration guide](docs/Migration-guide.md) -- [Tutorial](docs/Tutorial.md) - - -### API categories +To support general CEF Python development efforts you can make a donation using PayPal button below: + + + +
+ + +## Seeking sponsors + +CEF Python is seeking companies to sponsor development of this project. Most important +thing would be to have continuous monthly releases with updates to latest Chromium. There is +also lots of cool features and new settings that would be nice to implement. We have not yet +exposed all of upstream CEF APIs. If your company would like to sponsor CEF Python development efforts +then please contact [Czarek](https://www.linkedin.com/in/czarektomczak/). There are no active sponsors +at this moment. + + +### Previous sponsors + + + + + + + + + + + + +
+ + + + + +
+ + + + +
+ + +## API #### Modules @@ -246,6 +203,7 @@ Additional information for v31.2 release: #### Client handlers (interfaces) + * [AccessibilityHandler](api/AccessibilityHandler.md#accessibilityhandler-interface) * [DisplayHandler](api/DisplayHandler.md#displayhandler-interface) * [DownloadHandler](api/DownloadHandler.md#downloadhandler) * [FocusHandler](api/FocusHandler.md#focushandler-interface) @@ -268,6 +226,9 @@ Additional information for v31.2 release: ### API index +* [AccessibilityHandler (interface)](api/AccessibilityHandler.md#accessibilityhandler-interface) + * [_OnAccessibilityTreeChange](api/AccessibilityHandler.md#_onaccessibilitytreechange) + * [_OnAccessibilityLocationChange](api/AccessibilityHandler.md#_onaccessibilitylocationchange) * [Application settings](api/ApplicationSettings.md#application-settings) * [accept_language_list](api/ApplicationSettings.md#accept_language_list) * [app_user_model_id](api/ApplicationSettings.md#app_user_model_id) @@ -326,11 +287,13 @@ Additional information for v31.2 release: * [GetFrameCount](api/Browser.md#getframecount) * [GetFrameIdentifiers](api/Browser.md#getframeidentifiers) * [GetFrameNames](api/Browser.md#getframenames) + * [GetImage](api/Browser.md#getimage) * [GetJavascriptBindings](api/Browser.md#getjavascriptbindings) * [GetMainFrame](api/Browser.md#getmainframe) * [GetNSTextInputContext](api/Browser.md#getnstextinputcontext) * [GetOpenerWindowHandle](api/Browser.md#getopenerwindowhandle) * [GetOuterWindowHandle](api/Browser.md#getouterwindowhandle) + * [GetSetting](api/Browser.md#getsetting) * [GetUrl](api/Browser.md#geturl) * [GetUserData](api/Browser.md#getuserdata) * [GetWindowHandle](api/Browser.md#getwindowhandle) @@ -340,7 +303,9 @@ Additional information for v31.2 release: * [GoForward](api/Browser.md#goforward) * [HandleKeyEventAfterTextInputClient](api/Browser.md#handlekeyeventaftertextinputclient) * [HandleKeyEventBeforeTextInputClient](api/Browser.md#handlekeyeventbeforetextinputclient) + * [HasDevTools](api/Browser.md#hasdevtools) * [HasDocument](api/Browser.md#hasdocument) + * [Invalidate](api/Browser.md#invalidate) * [IsFullscreen](api/Browser.md#isfullscreen) * [IsLoading](api/Browser.md#isloading) * [IsMouseCursorChangeDisabled](api/Browser.md#ismousecursorchangedisabled) @@ -355,6 +320,7 @@ Additional information for v31.2 release: * [Reload](api/Browser.md#reload) * [ReloadIgnoreCache](api/Browser.md#reloadignorecache) * [ReplaceMisspelling](api/Browser.md#replacemisspelling) + * [SetAutoResizeEnabled](api/Browser.md#setautoresizeenabled) * [SetBounds](api/Browser.md#setbounds) * [SendKeyEvent](api/Browser.md#sendkeyevent) * [SendMouseClickEvent](api/Browser.md#sendmouseclickevent) @@ -362,6 +328,7 @@ Additional information for v31.2 release: * [SendMouseWheelEvent](api/Browser.md#sendmousewheelevent) * [SendFocusEvent](api/Browser.md#sendfocusevent) * [SendCaptureLostEvent](api/Browser.md#sendcapturelostevent) + * [SetAccessibilityState](api/Browser.md#setaccessibilitystate) * [SetClientCallback](api/Browser.md#setclientcallback) * [SetClientHandler](api/Browser.md#setclienthandler) * [SetFocus](api/Browser.md#setfocus) @@ -386,9 +353,9 @@ Additional information for v31.2 release: * [default_encoding](api/BrowserSettings.md#default_encoding) * [dom_paste_disabled](api/BrowserSettings.md#dom_paste_disabled) * [file_access_from_file_urls_allowed](api/BrowserSettings.md#file_access_from_file_urls_allowed) + * [inherit_client_handlers_for_popups](api/BrowserSettings.md#inherit_client_handlers_for_popups) * [image_load_disabled](api/BrowserSettings.md#image_load_disabled) * [javascript_disabled](api/BrowserSettings.md#javascript_disabled) - * [javascript_open_windows_disallowed](api/BrowserSettings.md#javascript_open_windows_disallowed) * [javascript_close_windows_disallowed](api/BrowserSettings.md#javascript_close_windows_disallowed) * [javascript_access_clipboard_disallowed](api/BrowserSettings.md#javascript_access_clipboard_disallowed) * [local_storage_disabled](api/BrowserSettings.md#local_storage_disabled) @@ -411,19 +378,23 @@ Additional information for v31.2 release: * [ExceptHook](api/cefpython.md#excepthook) * [GetAppSetting](api/cefpython.md#getappsetting) * [GetAppPath](api/cefpython.md#getapppath) + * [GetBrowserByIdentifier](api/cefpython.md#getbrowserbyidentifier) * [GetBrowserByWindowHandle](api/cefpython.md#getbrowserbywindowhandle) * [GetCommandLineSwitch](api/cefpython.md#getcommandlineswitch) + * [GetDataUrl](api/cefpython.md#getdataurl) * [GetGlobalClientCallback](api/cefpython.md#getglobalclientcallback) * [GetModuleDirectory](api/cefpython.md#getmoduledirectory) * [GetVersion](api/cefpython.md#getversion) * [Initialize](api/cefpython.md#initialize) * [IsThread](api/cefpython.md#isthread) + * [LoadCrlSetsFile](api/cefpython.md#loadcrlsetsfile) * [MessageLoop](api/cefpython.md#messageloop) * [MessageLoopWork](api/cefpython.md#messageloopwork) * [PostTask](api/cefpython.md#posttask) * [PostDelayedTask](api/cefpython.md#postdelayedtask) * [QuitMessageLoop](api/cefpython.md#quitmessageloop) * [SetGlobalClientCallback](api/cefpython.md#setglobalclientcallback) + * [SetGlobalClientHandler](api/cefpython.md#setglobalclienthandler) * [SetOsModalLoop](api/cefpython.md#setosmodalloop) * [Shutdown](api/cefpython.md#shutdown) * [Command line switches](api/CommandLineSwitches.md#command-line-switches) @@ -456,6 +427,7 @@ Additional information for v31.2 release: * [GetExpires](api/Cookie.md#getexpires) * [CookieManager (class)](api/CookieManager.md#cookiemanager-class) * [GetGlobalManager](api/CookieManager.md#getglobalmanager) + * [GetBlockingManager](api/CookieManager.md#getblockingmanager) * [CreateManager](api/CookieManager.md#createmanager) * [SetSupportedSchemes](api/CookieManager.md#setsupportedschemes) * [VisitAllCookies](api/CookieManager.md#visitallcookies) @@ -468,10 +440,12 @@ Additional information for v31.2 release: * [Visit](api/CookieVisitor.md#visit) * [DisplayHandler (interface)](api/DisplayHandler.md#displayhandler-interface) * [OnAddressChange](api/DisplayHandler.md#onaddresschange) + * [OnAutoResize](api/DisplayHandler.md#onautoresize) + * [OnConsoleMessage](api/DisplayHandler.md#onconsolemessage) + * [OnLoadingProgressChange](api/DisplayHandler.md#onloadingprogresschange) + * [OnStatusMessage](api/DisplayHandler.md#onstatusmessage) * [OnTitleChange](api/DisplayHandler.md#ontitlechange) * [OnTooltip](api/DisplayHandler.md#ontooltip) - * [OnStatusMessage](api/DisplayHandler.md#onstatusmessage) - * [OnConsoleMessage](api/DisplayHandler.md#onconsolemessage) * [DownloadHandler](api/DownloadHandler.md#downloadhandler) * [DpiAware (class)](api/DpiAware.md#dpiaware-class) * [CalculateWindowSize](api/DpiAware.md#calculatewindowsize) @@ -479,6 +453,7 @@ Additional information for v31.2 release: * [GetSystemDpi](api/DpiAware.md#getsystemdpi) * [IsProcessDpiAware](api/DpiAware.md#isprocessdpiaware) * [SetProcessDpiAware](api/DpiAware.md#setprocessdpiaware) + * [Scale](api/DpiAware.md#scale) * [DragData (object)](api/DragData.md#dragdata-object) * [IsLink](api/DragData.md#islink) * [IsFragment](api/DragData.md#isfragment) @@ -545,10 +520,10 @@ Additional information for v31.2 release: * [OnPreKeyEvent](api/KeyboardHandler.md#onprekeyevent) * [OnKeyEvent](api/KeyboardHandler.md#onkeyevent) * [LifespanHandler (interface)](api/LifespanHandler.md#lifespanhandler-interface) - * [OnBeforePopup](api/LifespanHandler.md#onbeforepopup) - * [_OnAfterCreated](api/LifespanHandler.md#_onaftercreated) * [DoClose](api/LifespanHandler.md#doclose) + * [_OnAfterCreated](api/LifespanHandler.md#_onaftercreated) * [OnBeforeClose](api/LifespanHandler.md#onbeforeclose) + * [OnBeforePopup](api/LifespanHandler.md#onbeforepopup) * [LoadHandler (interface)](api/LoadHandler.md#loadhandler-interface) * [OnLoadingStateChange](api/LoadHandler.md#onloadingstatechange) * [OnLoadStart](api/LoadHandler.md#onloadstart) @@ -607,7 +582,7 @@ Additional information for v31.2 release: * [ERR_UNSAFE_REDIRECT](api/NetworkError.md#err_unsafe_redirect) * [PaintBuffer (object)](api/PaintBuffer.md#paintbuffer-object) * [GetIntPointer](api/PaintBuffer.md#getintpointer) - * [GetString](api/PaintBuffer.md#getstring) + * [GetBytes](api/PaintBuffer.md#getbytes) * [RenderHandler (interface)](api/RenderHandler.md#renderhandler-interface) * [GetRootScreenRect](api/RenderHandler.md#getrootscreenrect) * [GetViewRect](api/RenderHandler.md#getviewrect) @@ -618,6 +593,7 @@ Additional information for v31.2 release: * [OnPaint](api/RenderHandler.md#onpaint) * [OnCursorChange](api/RenderHandler.md#oncursorchange) * [OnScrollOffsetChanged](api/RenderHandler.md#onscrolloffsetchanged) + * [OnTextSelectionChanged](api/RenderHandler.md#ontextselectionchanged) * [StartDragging](api/RenderHandler.md#startdragging) * [UpdateDragCursor](api/RenderHandler.md#updatedragcursor) * [Request (class)](api/Request.md#request-class) @@ -640,19 +616,21 @@ Additional information for v31.2 release: * [GetResourceType](api/Request.md#getresourcetype) * [GetTransitionType](api/Request.md#gettransitiontype) * [RequestHandler (interface)](api/RequestHandler.md#requesthandler-interface) + * [CanGetCookies](api/RequestHandler.md#cangetcookies) + * [CanSetCookie](api/RequestHandler.md#cansetcookie) + * [GetAuthCredentials](api/RequestHandler.md#getauthcredentials) + * [GetCookieManager](api/RequestHandler.md#getcookiemanager) + * [GetResourceHandler](api/RequestHandler.md#getresourcehandler) * [OnBeforeBrowse](api/RequestHandler.md#onbeforebrowse) + * [_OnBeforePluginLoad](api/RequestHandler.md#_onbeforepluginload) * [OnBeforeResourceLoad](api/RequestHandler.md#onbeforeresourceload) - * [GetResourceHandler](api/RequestHandler.md#getresourcehandler) + * [_OnCertificateError](api/RequestHandler.md#_oncertificateerror) + * [OnQuotaRequest](api/RequestHandler.md#onquotarequest) * [OnResourceRedirect](api/RequestHandler.md#onresourceredirect) * [OnResourceResponse](api/RequestHandler.md#onresourceresponse) - * [GetAuthCredentials](api/RequestHandler.md#getauthcredentials) - * [OnQuotaRequest](api/RequestHandler.md#onquotarequest) - * [GetCookieManager](api/RequestHandler.md#getcookiemanager) + * [OnPluginCrashed](api/RequestHandler.md#onplugincrashed) * [OnProtocolExecution](api/RequestHandler.md#onprotocolexecution) - * [_OnBeforePluginLoad](api/RequestHandler.md#_onbeforepluginload) - * [_OnCertificateError](api/RequestHandler.md#_oncertificateerror) * [OnRendererProcessTerminated](api/RequestHandler.md#onrendererprocessterminated) - * [OnPluginCrashed](api/RequestHandler.md#onplugincrashed) * [ResourceHandler (interface)](api/ResourceHandler.md#resourcehandler-interface) * [ProcessRequest](api/ResourceHandler.md#processrequest) * [GetResponseHeaders](api/ResourceHandler.md#getresponseheaders) @@ -700,7 +678,6 @@ Additional information for v31.2 release: * [SetAsChild](api/WindowInfo.md#setaschild) * [SetAsPopup](api/WindowInfo.md#setaspopup) * [SetAsOffscreen](api/WindowInfo.md#setasoffscreen) - * [SetTransparentPainting](api/WindowInfo.md#settransparentpainting) * [WindowUtils (class)](api/WindowUtils.md#windowutils-class) * [OnSetFocus ](api/WindowUtils.md#onsetfocus-win) * [OnSize ](api/WindowUtils.md#onsize-win) diff --git a/api/API-categories.md b/api/API-categories.md index 1f4fc9922..d1d7320e8 100644 --- a/api/API-categories.md +++ b/api/API-categories.md @@ -38,6 +38,7 @@ ### Client handlers (interfaces) + * [AccessibilityHandler](AccessibilityHandler.md#accessibilityhandler-interface) * [DisplayHandler](DisplayHandler.md#displayhandler-interface) * [DownloadHandler](DownloadHandler.md#downloadhandler) * [FocusHandler](FocusHandler.md#focushandler-interface) diff --git a/api/API-index.md b/api/API-index.md index 79fb25914..9535cb5b7 100644 --- a/api/API-index.md +++ b/api/API-index.md @@ -2,6 +2,9 @@ # API index +* [AccessibilityHandler (interface)](AccessibilityHandler.md#accessibilityhandler-interface) + * [_OnAccessibilityTreeChange](AccessibilityHandler.md#_onaccessibilitytreechange) + * [_OnAccessibilityLocationChange](AccessibilityHandler.md#_onaccessibilitylocationchange) * [Application settings](ApplicationSettings.md#application-settings) * [accept_language_list](ApplicationSettings.md#accept_language_list) * [app_user_model_id](ApplicationSettings.md#app_user_model_id) @@ -60,11 +63,13 @@ * [GetFrameCount](Browser.md#getframecount) * [GetFrameIdentifiers](Browser.md#getframeidentifiers) * [GetFrameNames](Browser.md#getframenames) + * [GetImage](Browser.md#getimage) * [GetJavascriptBindings](Browser.md#getjavascriptbindings) * [GetMainFrame](Browser.md#getmainframe) * [GetNSTextInputContext](Browser.md#getnstextinputcontext) * [GetOpenerWindowHandle](Browser.md#getopenerwindowhandle) * [GetOuterWindowHandle](Browser.md#getouterwindowhandle) + * [GetSetting](Browser.md#getsetting) * [GetUrl](Browser.md#geturl) * [GetUserData](Browser.md#getuserdata) * [GetWindowHandle](Browser.md#getwindowhandle) @@ -74,7 +79,9 @@ * [GoForward](Browser.md#goforward) * [HandleKeyEventAfterTextInputClient](Browser.md#handlekeyeventaftertextinputclient) * [HandleKeyEventBeforeTextInputClient](Browser.md#handlekeyeventbeforetextinputclient) + * [HasDevTools](Browser.md#hasdevtools) * [HasDocument](Browser.md#hasdocument) + * [Invalidate](Browser.md#invalidate) * [IsFullscreen](Browser.md#isfullscreen) * [IsLoading](Browser.md#isloading) * [IsMouseCursorChangeDisabled](Browser.md#ismousecursorchangedisabled) @@ -89,6 +96,7 @@ * [Reload](Browser.md#reload) * [ReloadIgnoreCache](Browser.md#reloadignorecache) * [ReplaceMisspelling](Browser.md#replacemisspelling) + * [SetAutoResizeEnabled](Browser.md#setautoresizeenabled) * [SetBounds](Browser.md#setbounds) * [SendKeyEvent](Browser.md#sendkeyevent) * [SendMouseClickEvent](Browser.md#sendmouseclickevent) @@ -96,6 +104,7 @@ * [SendMouseWheelEvent](Browser.md#sendmousewheelevent) * [SendFocusEvent](Browser.md#sendfocusevent) * [SendCaptureLostEvent](Browser.md#sendcapturelostevent) + * [SetAccessibilityState](Browser.md#setaccessibilitystate) * [SetClientCallback](Browser.md#setclientcallback) * [SetClientHandler](Browser.md#setclienthandler) * [SetFocus](Browser.md#setfocus) @@ -120,9 +129,9 @@ * [default_encoding](BrowserSettings.md#default_encoding) * [dom_paste_disabled](BrowserSettings.md#dom_paste_disabled) * [file_access_from_file_urls_allowed](BrowserSettings.md#file_access_from_file_urls_allowed) + * [inherit_client_handlers_for_popups](BrowserSettings.md#inherit_client_handlers_for_popups) * [image_load_disabled](BrowserSettings.md#image_load_disabled) * [javascript_disabled](BrowserSettings.md#javascript_disabled) - * [javascript_open_windows_disallowed](BrowserSettings.md#javascript_open_windows_disallowed) * [javascript_close_windows_disallowed](BrowserSettings.md#javascript_close_windows_disallowed) * [javascript_access_clipboard_disallowed](BrowserSettings.md#javascript_access_clipboard_disallowed) * [local_storage_disabled](BrowserSettings.md#local_storage_disabled) @@ -145,19 +154,23 @@ * [ExceptHook](cefpython.md#excepthook) * [GetAppSetting](cefpython.md#getappsetting) * [GetAppPath](cefpython.md#getapppath) + * [GetBrowserByIdentifier](cefpython.md#getbrowserbyidentifier) * [GetBrowserByWindowHandle](cefpython.md#getbrowserbywindowhandle) * [GetCommandLineSwitch](cefpython.md#getcommandlineswitch) + * [GetDataUrl](cefpython.md#getdataurl) * [GetGlobalClientCallback](cefpython.md#getglobalclientcallback) * [GetModuleDirectory](cefpython.md#getmoduledirectory) * [GetVersion](cefpython.md#getversion) * [Initialize](cefpython.md#initialize) * [IsThread](cefpython.md#isthread) + * [LoadCrlSetsFile](cefpython.md#loadcrlsetsfile) * [MessageLoop](cefpython.md#messageloop) * [MessageLoopWork](cefpython.md#messageloopwork) * [PostTask](cefpython.md#posttask) * [PostDelayedTask](cefpython.md#postdelayedtask) * [QuitMessageLoop](cefpython.md#quitmessageloop) * [SetGlobalClientCallback](cefpython.md#setglobalclientcallback) + * [SetGlobalClientHandler](cefpython.md#setglobalclienthandler) * [SetOsModalLoop](cefpython.md#setosmodalloop) * [Shutdown](cefpython.md#shutdown) * [Command line switches](CommandLineSwitches.md#command-line-switches) @@ -190,6 +203,7 @@ * [GetExpires](Cookie.md#getexpires) * [CookieManager (class)](CookieManager.md#cookiemanager-class) * [GetGlobalManager](CookieManager.md#getglobalmanager) + * [GetBlockingManager](CookieManager.md#getblockingmanager) * [CreateManager](CookieManager.md#createmanager) * [SetSupportedSchemes](CookieManager.md#setsupportedschemes) * [VisitAllCookies](CookieManager.md#visitallcookies) @@ -202,10 +216,12 @@ * [Visit](CookieVisitor.md#visit) * [DisplayHandler (interface)](DisplayHandler.md#displayhandler-interface) * [OnAddressChange](DisplayHandler.md#onaddresschange) + * [OnAutoResize](DisplayHandler.md#onautoresize) + * [OnConsoleMessage](DisplayHandler.md#onconsolemessage) + * [OnLoadingProgressChange](DisplayHandler.md#onloadingprogresschange) + * [OnStatusMessage](DisplayHandler.md#onstatusmessage) * [OnTitleChange](DisplayHandler.md#ontitlechange) * [OnTooltip](DisplayHandler.md#ontooltip) - * [OnStatusMessage](DisplayHandler.md#onstatusmessage) - * [OnConsoleMessage](DisplayHandler.md#onconsolemessage) * [DownloadHandler](DownloadHandler.md#downloadhandler) * [DpiAware (class)](DpiAware.md#dpiaware-class) * [CalculateWindowSize](DpiAware.md#calculatewindowsize) @@ -213,6 +229,7 @@ * [GetSystemDpi](DpiAware.md#getsystemdpi) * [IsProcessDpiAware](DpiAware.md#isprocessdpiaware) * [SetProcessDpiAware](DpiAware.md#setprocessdpiaware) + * [Scale](DpiAware.md#scale) * [DragData (object)](DragData.md#dragdata-object) * [IsLink](DragData.md#islink) * [IsFragment](DragData.md#isfragment) @@ -279,10 +296,10 @@ * [OnPreKeyEvent](KeyboardHandler.md#onprekeyevent) * [OnKeyEvent](KeyboardHandler.md#onkeyevent) * [LifespanHandler (interface)](LifespanHandler.md#lifespanhandler-interface) - * [OnBeforePopup](LifespanHandler.md#onbeforepopup) - * [_OnAfterCreated](LifespanHandler.md#_onaftercreated) * [DoClose](LifespanHandler.md#doclose) + * [_OnAfterCreated](LifespanHandler.md#_onaftercreated) * [OnBeforeClose](LifespanHandler.md#onbeforeclose) + * [OnBeforePopup](LifespanHandler.md#onbeforepopup) * [LoadHandler (interface)](LoadHandler.md#loadhandler-interface) * [OnLoadingStateChange](LoadHandler.md#onloadingstatechange) * [OnLoadStart](LoadHandler.md#onloadstart) @@ -341,7 +358,7 @@ * [ERR_UNSAFE_REDIRECT](NetworkError.md#err_unsafe_redirect) * [PaintBuffer (object)](PaintBuffer.md#paintbuffer-object) * [GetIntPointer](PaintBuffer.md#getintpointer) - * [GetString](PaintBuffer.md#getstring) + * [GetBytes](PaintBuffer.md#getbytes) * [RenderHandler (interface)](RenderHandler.md#renderhandler-interface) * [GetRootScreenRect](RenderHandler.md#getrootscreenrect) * [GetViewRect](RenderHandler.md#getviewrect) @@ -352,6 +369,7 @@ * [OnPaint](RenderHandler.md#onpaint) * [OnCursorChange](RenderHandler.md#oncursorchange) * [OnScrollOffsetChanged](RenderHandler.md#onscrolloffsetchanged) + * [OnTextSelectionChanged](RenderHandler.md#ontextselectionchanged) * [StartDragging](RenderHandler.md#startdragging) * [UpdateDragCursor](RenderHandler.md#updatedragcursor) * [Request (class)](Request.md#request-class) @@ -374,19 +392,21 @@ * [GetResourceType](Request.md#getresourcetype) * [GetTransitionType](Request.md#gettransitiontype) * [RequestHandler (interface)](RequestHandler.md#requesthandler-interface) + * [CanGetCookies](RequestHandler.md#cangetcookies) + * [CanSetCookie](RequestHandler.md#cansetcookie) + * [GetAuthCredentials](RequestHandler.md#getauthcredentials) + * [GetCookieManager](RequestHandler.md#getcookiemanager) + * [GetResourceHandler](RequestHandler.md#getresourcehandler) * [OnBeforeBrowse](RequestHandler.md#onbeforebrowse) + * [_OnBeforePluginLoad](RequestHandler.md#_onbeforepluginload) * [OnBeforeResourceLoad](RequestHandler.md#onbeforeresourceload) - * [GetResourceHandler](RequestHandler.md#getresourcehandler) + * [_OnCertificateError](RequestHandler.md#_oncertificateerror) + * [OnQuotaRequest](RequestHandler.md#onquotarequest) * [OnResourceRedirect](RequestHandler.md#onresourceredirect) * [OnResourceResponse](RequestHandler.md#onresourceresponse) - * [GetAuthCredentials](RequestHandler.md#getauthcredentials) - * [OnQuotaRequest](RequestHandler.md#onquotarequest) - * [GetCookieManager](RequestHandler.md#getcookiemanager) + * [OnPluginCrashed](RequestHandler.md#onplugincrashed) * [OnProtocolExecution](RequestHandler.md#onprotocolexecution) - * [_OnBeforePluginLoad](RequestHandler.md#_onbeforepluginload) - * [_OnCertificateError](RequestHandler.md#_oncertificateerror) * [OnRendererProcessTerminated](RequestHandler.md#onrendererprocessterminated) - * [OnPluginCrashed](RequestHandler.md#onplugincrashed) * [ResourceHandler (interface)](ResourceHandler.md#resourcehandler-interface) * [ProcessRequest](ResourceHandler.md#processrequest) * [GetResponseHeaders](ResourceHandler.md#getresponseheaders) @@ -434,7 +454,6 @@ * [SetAsChild](WindowInfo.md#setaschild) * [SetAsPopup](WindowInfo.md#setaspopup) * [SetAsOffscreen](WindowInfo.md#setasoffscreen) - * [SetTransparentPainting](WindowInfo.md#settransparentpainting) * [WindowUtils (class)](WindowUtils.md#windowutils-class) * [OnSetFocus ](WindowUtils.md#onsetfocus-win) * [OnSize ](WindowUtils.md#onsize-win) diff --git a/api/AccessibilityHandler.md b/api/AccessibilityHandler.md new file mode 100644 index 000000000..3433e0039 --- /dev/null +++ b/api/AccessibilityHandler.md @@ -0,0 +1,50 @@ +[API categories](API-categories.md) | [API index](API-index.md) + + +# AccessibilityHandler (interface) + +This handler is for use only with off-screen rendering enabled. +See [RenderHandler](RenderHandler.md) for details. + +Implement this interface to receive accessibility notification when +accessibility events have been registered. The methods of this class will +be called on the UI thread. + +Callbacks in this interface are not associated with any specific browser, +thus you must call +`cefpython`.[SetGlobalClientHandler](cefpython.md#setglobalclienthandler) +or [SetGlobalClientCallback](cefpython.md#setglobalclientcallback) +to use them. The callbacks names were prefixed +with "`_`" to distinguish this special behavior. + + +Table of contents: +* [Callbacks](#callbacks) + * [_OnAccessibilityTreeChange](#_onaccessibilitytreechange) + * [_OnAccessibilityLocationChange](#_onaccessibilitylocationchange) + + +## Callbacks + + +### _OnAccessibilityTreeChange + +| Parameter | Type | +| --- | --- | +| value | list | +| __Return__ | void | + +Called after renderer process sends accessibility tree changes to the +browser process. + + +### _OnAccessibilityLocationChange + +| Parameter | Type | +| --- | --- | +| value | list | +| __Return__ | void | + +Called after renderer process sends accessibility location changes to the +browser process. + diff --git a/api/ApplicationSettings.md b/api/ApplicationSettings.md index 209e6f791..a9ad20f1b 100644 --- a/api/ApplicationSettings.md +++ b/api/ApplicationSettings.md @@ -107,13 +107,18 @@ Example values that can be set in Win7 DPI settings (Control Panel Appearance an ### background_color (int) -Opaque background color used for accelerated content. By default the -background color will be white. Only the RGB compontents of the specified -value will be used. The alpha component must greater than 0 to enable use -of the background color but will be otherwise ignored. +Description from upstream CEF: +> Background color used for the browser before a document is loaded and when +> no document color is specified. The alpha component must be either fully +> opaque (0xFF) or fully transparent (0x00). If the alpha component is fully +> opaque then the RGB components will be used as the background color. If the +> alpha component is fully transparent for a windowed browser then the +> default value of opaque white be used. If the alpha component is fully +> transparent for a windowless (off-screen) browser then transparent painting +> will be enabled. 32-bit ARGB color value, not premultiplied. The color components are always -in a known order. Equivalent to the `SkColor` type. +in a known order. Equivalent to the `SkColor` type in Chromium. ### browser_subprocess_path @@ -180,17 +185,30 @@ Downloads are handled automatically. A default `SaveAs` file dialog provided by (bool) Default: False -EXPERIMENTAL: So far this was tested only on Linux and actually made app - significantly slower. Windows and Mac platforms were not - tested yet. Reported issue in upstream, see [Issue #246] - (https://github.com/cztomczak/cefpython/issues/246) for details. +This option is for use on Mac and Linux only. On Windows for best +performance you should use a multi-threaded message loop instead +of calling CefDoMessageLoopWork in a timer. + +EXPERIMENTAL (Linux): There are issues with this option on Linux. See + [Issue #246](https://github.com/cztomczak/cefpython/issues/246) + for details. It is recommended to use this option as a replacement for calls to cefpython.MessageLoopWork(). CEF Python will do these calls automatically using CEF's OnScheduleMessagePumpWork. This results in improved performance on Windows and Mac and resolves some bugs with missing keyboard events -on these platforms. See [Issue #246] -(https://github.com/cztomczak/cefpython/issues/246) for more details. +on these platforms. See [Issue #246](https://github.com/cztomczak/cefpython/issues/246) +for more details. + +IMPORTANT: Currently there are issues on Mac with both message loop work + and external message pump. In Qt apps calling message loop + work in a timer doesn't work anymore, you have to use external + message pump. In wxPython apps it is required to call a message + loop work in a timer and enable external message pump + both at the same time (an incorrect approach, but it works). + This is just a temporary solution and how this affects + performance was not tested. See [Issue #442](../../../issues/442) + for more details. Description from upstream CEF: > Set to true (1) to control browser process main (UI) thread message pump @@ -233,16 +251,18 @@ RequestHandler.[_OnCertificateError()](#_oncertificateerror) callback. Note that disk caching is enabled only when the "cache_path" option is set. -__NOTE ON CACHING__: the official CEF Python binary releases incorporate a patch -that changes the caching behavior on sites with SSL certificate errors -when used with this setting. Chromium by default disallows caching of -content when there is certificate error. CEF Python applies a patch to -Chromium sources to allow for caching even when there is certificate error, -but only when the "ignore_certificate_errors" option is set to True. +__NOTE ON CACHING__: Chromium by default disallows caching of +content when there is certificate error. There is a issue125.patch +in the patches/ directory that can be enabled when doing a custom +CEF build. This patch changes the caching behavior on sites with SSL +certificate errors when used with this setting. This patch can be +applied Chromium sources to allow for caching even when there is +certificate error, but only when the "ignore_certificate_errors" +option is set to True. When it's set to False then the Chromium's caching behavior does not change. Enabling caching with certificate errors is useful on local private networks that use self-signed SSL certificates. See the -referenced CEF topic in [Issue #125](../issues/125) for more details. +referenced CEF topic in [Issue #125](../../../issues/125) for more details. ### javascript_flags @@ -307,7 +327,6 @@ Accepted values - constants available in the cefpython module: * LOGSEVERITY_INFO * LOGSEVERITY_WARNING * LOGSEVERITY_ERROR (default) -* LOGSEVERITY_ERROR_REPORT * LOGSEVERITY_DISABLE @@ -319,6 +338,13 @@ thread. If false (0) than the [cefpython](cefpython.md).MessageLoopWork() function must be called from your application message loop. This option is only supported on Windows. +When this option is set to true, you don't call CEF message loop explicitilly +anymore. Also app's main thread is no more CEF's UI thread, thus many of API +calls will require using cef.[cefpython.md#posttask](PostTask) function to run +code on UI thread. You should also pay attention when reading API docs, as many +handlers/callbacks execute on specific threads, so when this option is On then +your app's code can start executing on different threads. + This option is not and cannot be supported on OS-X for architectural reasons. diff --git a/api/Browser.md b/api/Browser.md index 219e1bc1c..b34b90e2f 100644 --- a/api/Browser.md +++ b/api/Browser.md @@ -3,6 +3,9 @@ # Browser (object) +The methods of this object may be called on any thread unless otherwise +indicated in the comments. + Remember to free all browser references when closing app for the browser to shut down cleanly. Otherwise data such as cookies or other storage might not be flushed to disk @@ -39,11 +42,13 @@ Table of contents: * [GetFrameCount](#getframecount) * [GetFrameIdentifiers](#getframeidentifiers) * [GetFrameNames](#getframenames) + * [GetImage](#getimage) * [GetJavascriptBindings](#getjavascriptbindings) * [GetMainFrame](#getmainframe) * [GetNSTextInputContext](#getnstextinputcontext) * [GetOpenerWindowHandle](#getopenerwindowhandle) * [GetOuterWindowHandle](#getouterwindowhandle) + * [GetSetting](#getsetting) * [GetUrl](#geturl) * [GetUserData](#getuserdata) * [GetWindowHandle](#getwindowhandle) @@ -53,7 +58,9 @@ Table of contents: * [GoForward](#goforward) * [HandleKeyEventAfterTextInputClient](#handlekeyeventaftertextinputclient) * [HandleKeyEventBeforeTextInputClient](#handlekeyeventbeforetextinputclient) + * [HasDevTools](#hasdevtools) * [HasDocument](#hasdocument) + * [Invalidate](#invalidate) * [IsFullscreen](#isfullscreen) * [IsLoading](#isloading) * [IsMouseCursorChangeDisabled](#ismousecursorchangedisabled) @@ -68,6 +75,7 @@ Table of contents: * [Reload](#reload) * [ReloadIgnoreCache](#reloadignorecache) * [ReplaceMisspelling](#replacemisspelling) + * [SetAutoResizeEnabled](#setautoresizeenabled) * [SetBounds](#setbounds) * [SendKeyEvent](#sendkeyevent) * [SendMouseClickEvent](#sendmouseclickevent) @@ -75,6 +83,7 @@ Table of contents: * [SendMouseWheelEvent](#sendmousewheelevent) * [SendFocusEvent](#sendfocusevent) * [SendCaptureLostEvent](#sendcapturelostevent) + * [SetAccessibilityState](#setaccessibilitystate) * [SetClientCallback](#setclientcallback) * [SetClientHandler](#setclienthandler) * [SetFocus](#setfocus) @@ -302,7 +311,7 @@ Passing a python function here is not allowed, it is only possible through [Java | startLine=1 | int | | __Return__ | void | -Execute a string of JavaScript code in this frame. The `sciptURL` parameter is the URL where the script in question can be found, if any. The renderer may request this URL to show the developer the source of the error. The `startLine` parameter is the base line number to use for error reporting. +Execute a string of JavaScript code in this frame. The `scriptURL` parameter is the URL where the script in question can be found, if any. The renderer may request this URL to show the developer the source of the error. The `startLine` parameter is the base line number to use for error reporting. This function executes asynchronously so there is no way to get the returned value. @@ -313,15 +322,24 @@ Calling javascript from native code synchronously is not possible in CEF 3. It i | Parameter | Type | | --- | --- | -| searchID | int | +| searchId | int | | searchText | string | | forward | bool | | matchCase | bool | | findNext | bool | | __Return__ | void | -Search for |searchText|. |searchID| can be custom, it is so that you can have multiple searches running simultaneously. |forward| indicates whether to search forward or backward within the page. |matchCase| indicates whether the search should be case-sensitive. |findNext| indicates whether this is the first request or a follow-up. The CefFindHandler instance, if any, returned via CefClient::GetFindHandler will be called to report find results. +Description from upstream CEF: +> Search for |searchText|. |identifier| must be a unique ID and these IDs +> must strictly increase so that newer requests always have greater IDs than +> older requests. If |identifier| is zero or less than the previous ID value +> then it will be automatically assigned a new valid ID. |forward| indicates +> whether to search forward or backward within the page. |matchCase| +> indicates whether the search should be case-sensitive. |findNext| indicates +> whether this is the first request or a follow-up. The CefFindHandler +> instance, if any, returned via CefClient::GetFindHandler will be called to +> report find results. ### GetClientCallback @@ -358,7 +376,7 @@ Returns the focused [Frame](Frame.md) for the browser window. | name | string | | __Return__ | Frame | -Returns the [Frame](Frame.md) with the specified name, or NULL if not found. +Returns the [Frame](Frame.md) with the specified name, or NULL if not found. ### GetFrameByIdentifier @@ -411,6 +429,29 @@ Returns the identifiers of all existing frames. Returns the names of all existing frames. This list does not include the main frame. +### GetImage + +| | | +| --- | --- | +| __Return__ | tuple(bytes buffer, int width, int height) | + +Currently available only on Linux (Issue [#427](../../../issues/427)). + +Get browser contents as image. Only screen visible contents are returned. + +Returns an RGB buffer which can be converted to an image +using PIL library with such code: + +```py +from PIL import Image, ImageFile +buffer_len = (width * 3 + 3) & -4 +image = Image.frombytes("RGB", (width, height), data, + "raw", "RGB", buffer_len, 1) +ImageFile.MAXBLOCK = width * height +image.save("image.png", "PNG") +``` + + ### GetJavascriptBindings | | | @@ -459,6 +500,17 @@ Retrieve the CEF-internal (inner or outer) window handle of the browser that ope Get the most outer window handle. +### GetSetting + +| Parameter | Type | +| --- | --- | +| key | str | +| __Return__ | mixed | + +Get a browser setting. You can set browser settings by passing +`settings` parameter to `cef.CreateBrowserSync`. + + ### GetUrl | | | @@ -493,7 +545,8 @@ Returns an inner or outer window handle for the browser. If the browser was crea | --- | --- | | __Return__ | int | -Returns the globally unique identifier for this browser. +Returns the globally unique identifier for this browser. This value is also +used as the tabId for extension APIs. ### GetZoomLevel @@ -547,6 +600,17 @@ Handles a keyDown event prior to passing it through the NSTextInputClient machinery. +### HasDevTools + +| | | +| --- | --- | +| __Return__ | bool | + +Description from upstream CEF: +> Returns true if this browser currently has an associated DevTools browser. +> Must be called on the browser process UI thread. + + ### HasDocument | | | @@ -556,6 +620,23 @@ machinery. Returns true if a document has been loaded in the browser. +### Invalidate + +| | | +| --- | --- | +| element_type | PaintElementType | +| __Return__ | void | + +Description from upstream CEF: +> Invalidate the view. The browser will call CefRenderHandler::OnPaint +> asynchronously. This method is only used when window rendering is +> disabled. + +`PaintElementType` enum values defined in cefpython module: +* PET_VIEW +* PET_POPUP + + ### IsFullscreen | | | @@ -616,6 +697,13 @@ Returns true if window rendering is disabled. Load url in the main frame. +If the url is a local path it needs to start with the `file://` prefix. +If the url contains special characters it may need proper handling. +Starting with v66.1+ it is required for the app code to encode the url +properly. You can use the `pathlib.PurePath.as_uri` in Python 3 +or `urllib.pathname2url` in Python 2 (`urllib.request.pathname2url` +in Python 3) depending on your case. + ### Navigate @@ -701,6 +789,21 @@ If a misspelled word is currently selected in an editable node calling this method will replace it with the specified |word|. +### SetAutoResizeEnabled + +| Parameter | Type | +| --- | --- | +| enabled | bool | +| min_size | list[width, height] | +| max_size | list[width, heifght] | +| __Return__ | void | + +Description from upstream CEF: +> Enable notifications of auto resize via CefDisplayHandler::OnAutoResize. +> Notifications are disabled by default. |min_size| and |max_size| define the +> range of allowed sizes. + + ### SetBounds | Parameter | Type | @@ -810,6 +913,44 @@ Send a focus event to the browser. Send a capture lost event to the browser. +### SetAccessibilityState + +| | | +| --- | --- | +| state | cef_state_t | +| __Return__ | void | + +cef_state_t enum values defined in cefpython module: +- STATE_DEFAULT +- STATE_ENABLED +- STATE_DISABLED + +Description from upstream CEF: +> Set accessibility state for all frames. |accessibility_state| may be +> default, enabled or disabled. If |accessibility_state| is STATE_DEFAULT +> then accessibility will be disabled by default and the state may be further +> controlled with the "force-renderer-accessibility" and +> "disable-renderer-accessibility" command-line switches. If +> |accessibility_state| is STATE_ENABLED then accessibility will be enabled. +> If |accessibility_state| is STATE_DISABLED then accessibility will be +> completely disabled. +> +> For windowed browsers accessibility will be enabled in Complete mode (which +> corresponds to kAccessibilityModeComplete in Chromium). In this mode all +> platform accessibility objects will be created and managed by Chromium's +> internal implementation. The client needs only to detect the screen reader +> and call this method appropriately. For example, on macOS the client can +> handle the @"AXEnhancedUserInterface" accessibility attribute to detect +> VoiceOver state changes and on Windows the client can handle WM_GETOBJECT +> with OBJID_CLIENT to detect accessibility readers. +> +> For windowless browsers accessibility will be enabled in TreeOnly mode +> (which corresponds to kAccessibilityModeWebContentsOnly in Chromium). In +> this mode renderer accessibility is enabled, the full tree is computed, and +> events are passed to CefAccessibiltyHandler, but platform accessibility +> objects are not created. The client may implement platform accessibility +> objects using CefAccessibiltyHandler callbacks if desired. + ### SetClientCallback | Parameter | Type | diff --git a/api/BrowserSettings.md b/api/BrowserSettings.md index 0cc2816d6..ed2b2e50d 100644 --- a/api/BrowserSettings.md +++ b/api/BrowserSettings.md @@ -15,9 +15,9 @@ Table of contents: * [default_encoding](#default_encoding) * [dom_paste_disabled](#dom_paste_disabled) * [file_access_from_file_urls_allowed](#file_access_from_file_urls_allowed) + * [inherit_client_handlers_for_popups](#inherit_client_handlers_for_popups) * [image_load_disabled](#image_load_disabled) * [javascript_disabled](#javascript_disabled) - * [javascript_open_windows_disallowed](#javascript_open_windows_disallowed) * [javascript_close_windows_disallowed](#javascript_close_windows_disallowed) * [javascript_access_clipboard_disallowed](#javascript_access_clipboard_disallowed) * [local_storage_disabled](#local_storage_disabled) @@ -77,11 +77,18 @@ empty then "en-US,en" will be used. ### background_color (int) -Opaque background color used for the browser before a document is loaded -and when no document color is specified. By default the background color -will be the same as CefSettings.background_color. Only the RGB compontents -of the specified value will be used. The alpha component must greater than -0 to enable use of the background color but will be otherwise ignored. +Description from upstream CEF: +> Background color used for the browser before a document is loaded and when +> no document color is specified. The alpha component must be either fully +> opaque (0xFF) or fully transparent (0x00). If the alpha component is fully +> opaque then the RGB components will be used as the background color. If the +> alpha component is fully transparent for a windowed browser then the +> CefSettings.background_color value will be used. If the alpha component is +> fully transparent for a windowless (off-screen) browser then transparent +> painting will be enabled. + +32-bit ARGB color value, not premultiplied. The color components are always +in a known order. Equivalent to the `SkColor` type in Chromium. ### databases_disabled @@ -104,6 +111,21 @@ of the specified value will be used. The alpha component must greater than (bool) Controls whether file URLs will have access to other file URLs. Also configurable using the --allow-access-from-files switch. Other similar switches are: --allow-file-access and --allow-file-access-from-files. +### inherit_client_handlers_for_popups + + +(bool) Default: True. + +Whether to inherit client handlers and callbacks for popup windows +opened with "window.open". For example when you set a handler using +`browser.SetClientHandler` then this handler will also be resued +for popup windows that are created implicitilly via "window.open" +call in javascript or similar. If you implement +`LifespanHandler.OnBeforePopup` then you can control explicitilly +what handlers are set for the popup browser. To disable the default +behavior set this option to False. + + ### image_load_disabled (bool) Controls whether image URLs will be loaded from the network. A cached image will still be rendered if requested. Also configurable using the --disable-image-loading switch. @@ -114,11 +136,6 @@ of the specified value will be used. The alpha component must greater than (bool) Controls whether Javascript can be executed. Also configurable using the --disable-javascript switch. -### javascript_open_windows_disallowed - -(bool) Controls whether Javascript can be used for opening windows. Also configurable using the --disable-javascript-open-windows switch. - - ### javascript_close_windows_disallowed (bool) Controls whether JavaScript can be used to close windows that were not diff --git a/api/Cookie.md b/api/Cookie.md index 1271cf96b..0a46e99b0 100644 --- a/api/Cookie.md +++ b/api/Cookie.md @@ -3,7 +3,8 @@ # Cookie (class) -See also [CookieManager](CookieManager.md).SetCookie() and [CookieVisitor](CookieVisitor.md).Visit(). +See also [CookieManager](CookieManager.md).SetCookie(), [CookieVisitor](CookieVisitor.md).Visit() +and [ResourceHandler](ResourceHandler.md).CanGetCookie / CanSetCookie. Table of contents: diff --git a/api/CookieManager.md b/api/CookieManager.md index db53c9e06..b0d06a911 100644 --- a/api/CookieManager.md +++ b/api/CookieManager.md @@ -3,10 +3,11 @@ # CookieManager (class) -This class cannot be instantiated directly, use the CreateManager() -static method for this purpose. +Class used for managing cookies. The methods of this class may be called on +any thread unless otherwise indicated. -The cookie tests can be found in the wxpython.py script. +Use the `CookieManager.CreateManager` static method to instantiate +this class. TODO: in upstream CEF some methods here have a callback parameter that when non-NULL will execute asynchronously on the IO thread @@ -17,6 +18,7 @@ also have an OnComplete callback. Table of contents: * [Methods](#methods) * [GetGlobalManager](#getglobalmanager) + * [GetBlockingManager](#getblockingmanager) * [CreateManager](#createmanager) * [SetSupportedSchemes](#setsupportedschemes) * [VisitAllCookies](#visitallcookies) @@ -34,11 +36,33 @@ Table of contents: | | | | --- | --- | -| __Return__ | static [CookieManager](CookieManager.md) | +| __Return__ | [CookieManager](CookieManager.md) | Returns the global cookie manager. By default data will be stored at [ApplicationSettings](ApplicationSettings.md).cache_path if specified or in memory otherwise. +Description from upstream CEF: +> Returns the global cookie manager. By default data will be stored at +> CefSettings.cache_path if specified or in memory otherwise. If |callback| +> is non-NULL it will be executed asnychronously on the IO thread after the +> manager's storage has been initialized. Using this method is equivalent to +> calling CefRequestContext::GetGlobalContext()->GetDefaultCookieManager() + + +### GetBlockingManager + +| | | +| --- | --- | +| __Return__ | [CookieManager](CookieManager.md) | + +Description from upstream CEF: +> Returns a cookie manager that neither stores nor retrieves cookies. All +> usage of cookies will be blocked including cookies accessed via the network +> (request/response headers), via JavaScript (document.cookie), and via +> CefCookieManager methods. No cookies will be displayed in DevTools. If you +> wish to only block cookies sent via the network use the CefRequestHandler +> CanGetCookies and CanSetCookie methods instead. + ### CreateManager @@ -46,7 +70,7 @@ Returns the global cookie manager. By default data will be stored at | --- | --- | | path | string | | persistSessionCookies=False | bool | -| __Return__ | static [CookieManager](CookieManager.md) | +| __Return__ | [CookieManager](CookieManager.md) | Creates a new cookie manager. Otherwise, data will be stored at the specified |path|. To persist session cookies (cookies without an expiry @@ -174,11 +198,11 @@ browsers do not persist them. Returns false if cookies cannot be accessed. | Parameter | Type | | --- | --- | -| handler | CompletionHandler | +| callback | CompletionHandler (optional) | | __Return__ | bool | -Not yet implemented. - Flush the backing store (if any) to disk. If |callback| is non-NULL it will be executed asnychronously on the IO thread after the flush is complete. Returns false if cookies cannot be accessed. + +The callback arg is not implemented yet. diff --git a/api/DisplayHandler.md b/api/DisplayHandler.md index 11c860d3a..2c32ec1f4 100644 --- a/api/DisplayHandler.md +++ b/api/DisplayHandler.md @@ -3,18 +3,19 @@ # DisplayHandler (interface) -Implement this interface to handle events related to browser display state. The methods of this class will be called on the UI thread. - -For an example of how to implement handler see [cefpython](cefpython.md).CreateBrowser(). For a list of all handler interfaces see [API > Client handlers](API#Client_handlers). +Implement this interface to handle events related to browser display +state. The methods of this class will be called on the UI thread. Table of contents: * [Callbacks](#callbacks) * [OnAddressChange](#onaddresschange) + * [OnAutoResize](#onautoresize) + * [OnConsoleMessage](#onconsolemessage) + * [OnLoadingProgressChange](#onloadingprogresschange) + * [OnStatusMessage](#onstatusmessage) * [OnTitleChange](#ontitlechange) * [OnTooltip](#ontooltip) - * [OnStatusMessage](#onstatusmessage) - * [OnConsoleMessage](#onconsolemessage) ## Callbacks @@ -32,31 +33,50 @@ Table of contents: Called when a frame's address has changed. -### OnTitleChange + +### OnAutoResize | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | -| title | string | -| __Return__ | void | +| new_size | list[width, height] | +| __Return__ | bool | -Called when the page title changes. +Description from upstream CEF: +> Called when auto-resize is enabled via CefBrowserHost::SetAutoResizeEnabled +> and the contents have auto-resized. |new_size| will be the desired size in +> view coordinates. Return true if the resize was handled or false for +> default handling. -### OnTooltip +### OnConsoleMessage | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | -| text_out | list | +| level | int | +| message | string | +| source | string | +| line | int | | __Return__ | bool | -Called when the browser is about to display a tooltip. `text_out[0]` contains the -text that will be displayed in the tooltip. To handle the display of the -tooltip yourself return true. Otherwise, you can optionally modify `text_out[0]` -and then return false to allow the browser to display the tooltip. -When window rendering is disabled the application is responsible for -drawing tooltips and the return value is ignored. +Called to display a console message. Return true to stop the message from +being output to the console. + +|level| can be one of the same values as in ApplicationSettings.[log_severity](ApplicationSettings.md#log_severity). + + +### OnLoadingProgressChange + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| progress | double | +| __Return__ | void | + +Description from upstream CEF: +> Called when the overall page loading progress has changed. |progress| +> ranges from 0.0 to 1.0. ### OnStatusMessage @@ -70,15 +90,28 @@ drawing tooltips and the return value is ignored. Called when the browser receives a status message. -### OnConsoleMessage +### OnTitleChange | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | -| message | string | -| source | string | -| line | int | +| title | string | +| __Return__ | void | + +Called when the page title changes. + + +### OnTooltip + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| text_out | list | | __Return__ | bool | -Called to display a console message. Return true to stop the message from -being output to the console. +Called when the browser is about to display a tooltip. `text_out[0]` contains the +text that will be displayed in the tooltip. To handle the display of the +tooltip yourself return true. Otherwise, you can optionally modify `text_out[0]` +and then return false to allow the browser to display the tooltip. +When window rendering is disabled the application is responsible for +drawing tooltips and the return value is ignored. diff --git a/api/DpiAware.md b/api/DpiAware.md index a86d85d37..5a335b216 100644 --- a/api/DpiAware.md +++ b/api/DpiAware.md @@ -16,6 +16,7 @@ Table of contents: * [GetSystemDpi](#getsystemdpi) * [IsProcessDpiAware](#isprocessdpiaware) * [SetProcessDpiAware](#setprocessdpiaware) + * [Scale](#scale) @@ -37,13 +38,13 @@ Enabling High DPI support in app can be done by embedding a DPI awareness xml ma | height | int | | __Return__ | tuple | +Deprecated. Use `Scale()` method instead which can handle +non standard DPI settings such as '132%' on Windows 10. + This utility function will adjust width/height using OS DPI settings. For 800/600 with Win7 DPI settings being set to "Larger 150%" will return 1200/900. -Calculation for DPI < 96 is not yet supported. Use -the `GetSystemDpi` method for that. - ### EnableHighDpiSupport @@ -68,20 +69,29 @@ Description from upstream CEF: Returns tuple(int dpix, int dpiy). +Returns Windows DPI settings ("Custom scaling" on Win10). + Win7 DPI (Control Panel > Appearance and Personalization > Display): * text size Larger 150% => dpix/dpiy 144 * text size Medium 125% => dpix/dpiy 120 * text size Smaller 100% => dpix/dpiy 96 -Example zoom levels based on DPI. For use with the ApplicationSettings.`auto_zooming` option. +Example zoom levels based on DPI. For use with the +ApplicationSettings.`auto_zooming` option. * dpix=96 zoomlevel=0.0 * dpix=120 zoomlevel=1.0 * dpix=144 zoomlevel=2.0 * dpix=72 zoomlevel=-1.0 -If DPI awareness wasn't yet enabled, then `GetSystemDpi` will always return a default 96 DPI. +If DPI awareness wasn't yet enabled, then `GetSystemDpi` will always +return a default 96 DPI. + +DPI settings should not be cached. When `SetProcessDpiAware` +is not yet called, then OS returns 96 DPI, even though it +is set to 144 DPI. After DPI Awareness is enabled for the +running process it will return the correct 144 DPI. ### IsProcessDpiAware @@ -106,3 +116,13 @@ See [Issue #358](../../../issues/358) for how the behavior changed in latest CEF. This method now internally calls `EnableHighDpiSupport()`. Enables DPI awareness for the running process. Embedding a DPI manifest in .exe is the prefered way, as it gives more reliable results, otherwise some display bugs may appear (discussed in the "Introduction" section on this page). + + +### Scale + +| Parameter | Type | +| --- | --- | +| size | int/tuple/list | +| __Return__ | tuple | + +Scale units for high DPI devices. diff --git a/api/DragData.md b/api/DragData.md index cc7dee861..70901a248 100644 --- a/api/DragData.md +++ b/api/DragData.md @@ -81,10 +81,12 @@ Return the text/html fragment that is being dragged. | --- | --- | | __Return__ | [Image](Image.md) | -Linux-only currently (#251). +Description from upstream CEF: +> Get the image representation of drag data. May return NULL if no image +> representation is available. -Get image representation of drag data. Check with HasImage() first, -otherwise if there is no image an exception is thrown. +Check with HasImage() first, otherwise if there is no image an exception +is thrown. ### GetImageHotspot @@ -93,9 +95,7 @@ otherwise if there is no image an exception is thrown. | --- | --- | | __Return__ | [Image](Image.md) | -Linux-only currently (#251). - -Get image hotspot (drag start location relative to image dimensions). +Get the image hotspot (drag start location relative to image dimensions). ### HasImage @@ -104,7 +104,5 @@ Get image hotspot (drag start location relative to image dimensions). | --- | --- | | __Return__ | bool | -Linux-only currently (#251). - -Whether image representation of drag data is available. +Returns true if an image representation of drag data is available. diff --git a/api/Frame.md b/api/Frame.md index 87dbc89cd..057129122 100644 --- a/api/Frame.md +++ b/api/Frame.md @@ -228,9 +228,16 @@ Take also a look at a [custom resource handler](ResourceHandler.md). Load the contents of |value| with the specified dummy |url|. |url| should have a standard scheme (for example, http scheme) or behaviors like -link clicks and web security restrictions may not behave as expected. +link clicks and web security restrictions may not behave as expected. LoadString() can be called only after the Renderer process has been created. +If the url is a local path it needs to start with the `file://` prefix. +If the url contains special characters it may need proper handling. +Starting with v66.1+ it is required for the app code to encode the url +properly. You can use the `pathlib.PurePath.as_uri` in Python 3 +or `urllib.pathname2url` in Python 2 (`urllib.request.pathname2url` +in Python 3) depending on your case. + ### LoadUrl diff --git a/api/KeyboardHandler.md b/api/KeyboardHandler.md index f80828054..4735a88a7 100644 --- a/api/KeyboardHandler.md +++ b/api/KeyboardHandler.md @@ -38,7 +38,7 @@ KeyEvent is a dictionary with the following keys: | type | KeyEventType | The type of keyboard event | | modifiers | KeyEventFlags | Bit flags describing any pressed modifier keys | | windows_key_code | int | The Windows key code for the key event. This value is used by the DOM specification. Sometimes it comes directly from the event (i.e. on Windows) and sometimes it's determined using a mapping function. See "chromium/KeyboardCodes.h" for a list of values. | -| native_key_code | int | The actual key code genenerated by the platform | +| native_key_code | int | The actual key code generated by the platform | | is_system_key | bool | Indicates whether the event is considered a "system key" event. For Windows see [WM_SYSKEYDOWN](http://msdn.microsoft.com/en-us/library/ms646286.aspx). This value will always be false on non-Windows platforms. | | character | wchar_t or unsigned short | The character generated by the keystroke | | unmodified_character | wchar_t or unsigned short | Same as 'character' but unmodified by any concurrently-held modifiers (except shift). This is useful for working out shortcut keys. | diff --git a/api/LifespanHandler.md b/api/LifespanHandler.md index e4bac696a..1794d62d7 100644 --- a/api/LifespanHandler.md +++ b/api/LifespanHandler.md @@ -3,73 +3,42 @@ # LifespanHandler (interface) -Implement this interface to handle events related to browser life span. The methods of this class will be called on the UI thread. +Implement this interface to handle events related to browser life span. +The methods of this class will be called on the UI thread. -For an example of how to implement a handler see [cefpython](cefpython.md).CreateBrowser(). For a list of all handler interfaces see [API > Client handlers](API#Client_handlers). +Related code snippets: +- [onbeforeclose.py](../examples/snippets/onbeforeclose.py) Table of contents: * [Callbacks](#callbacks) - * [OnBeforePopup](#onbeforepopup) - * [_OnAfterCreated](#_onaftercreated) * [DoClose](#doclose) + * [_OnAfterCreated](#_onaftercreated) * [OnBeforeClose](#onbeforeclose) + * [OnBeforePopup](#onbeforepopup) ## Callbacks -### OnBeforePopup +### DoClose | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | -| frame | [Frame](Frame.md) | -| target_url | string | -| target_frame_name | string | -| target_disposition | WindowOpenDisposition | -| user_gesture | bool | -| popup_features | None | -| window_info_out | list[[WindowInfo](WindowInfo.md)] | -| client | None | -| browser_settings_out | list[[BrowserSettings](BrowserSettings.md)] | -| no_javascript_access_out | list[bool] | | __Return__ | bool | -Called on the IO thread before a new popup browser is created. The -|browser| and |frame| values represent the source of the popup request. The -|target_url| and |target_frame_name| values indicate where the popup -browser should navigate and may be empty if not specified with the request. -The |target_disposition| value indicates where the user intended to open -the popup (e.g. current tab, new tab, etc). The |user_gesture| value will -be true if the popup was opened via explicit user gesture (e.g. clicking a -link) or false if the popup opened automatically (e.g. via the -DomContentLoaded event). The |popup_features| structure contains additional -information about the requested popup window. To allow creation of the -popup browser optionally modify |windowInfo|, |client|, |browserSettings| and -|no_javascript_access| and return false. To cancel creation of the popup -browser return true. The |client| and |settings| values will default to the -source browser's values. If the |no_javascript_access| value is set to -false the new browser will not be scriptable and may not be hosted in the -same renderer process as the source browser. Any modifications to -|window_info| will be ignored if the parent browser is wrapped in a -CefBrowserView. - -Note that if you return True and create the popup window yourself, then -the popup window and parent window will not be able to script each other. -There will be no "window.opener" property available in the popup window. +Called when a browser has recieved a request to close. This may result +directly from a call to [Browser](Browser.md).`CloseBrowser` or indirectly +if the +browser is a top-level OS window created by CEF and the user attempts to +close the window. This method will be called after the Javascript +'onunload' event has been fired. It will not be called for browsers after +the associated OS window has been destroyed (for those browsers it is no +longer possible to cancel the close). -`WindowOpenDisposition` constants in the cefpython module: -* WOD_UNKNOWN, -* WOD_CURRENT_TAB, -* WOD_SINGLETON_TAB, -* WOD_NEW_FOREGROUND_TAB, -* WOD_NEW_BACKGROUND_TAB, -* WOD_NEW_POPUP, -* WOD_NEW_WINDOW, -* WOD_SAVE_TO_DISK, -* WOD_OFF_THE_RECORD, -* WOD_IGNORE_ACTION +See complete description of this callback in [cef_life_span_handler.h] +(..|src|include|cef_life_span_handler.h). ### _OnAfterCreated @@ -85,26 +54,6 @@ notification that references |browser|. This callback will be executed during browser creation, thus you must call [cefpython](cefpython.md).SetGlobalClientCallback() to use it. The callback name was prefixed with "`_`" to distinguish this special behavior. -### DoClose - -| Parameter | Type | -| --- | --- | -| browser | [Browser](Browser.md) | -| __Return__ | bool | - -Called when a browser has recieved a request to close. This may result -directly from a call to [Browser](Browser.md).`CloseBrowser` or indirectly -if the -browser is a top-level OS window created by CEF and the user attempts to -close the window. This method will be called after the Javascript -'onunload' event has been fired. It will not be called for browsers after -the associated OS window has been destroyed (for those browsers it is no -longer possible to cancel the close). - -See complete description of this callback in [cef_life_span_handler.h] -(..|src|include|cef_life_span_handler.h). - - ### OnBeforeClose | Parameter | Type | @@ -117,3 +66,63 @@ browser object and do not attempt to execute any methods on the browser object after this callback returns. This callback will be the last notification that references |browser|. See DoClose() documentation for additional usage information. + + +### OnBeforePopup + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| frame | [Frame](Frame.md) | +| target_url | string | +| target_frame_name | string | +| target_disposition | WindowOpenDisposition | +| user_gesture | bool | +| popup_features | None | +| window_info_out | list[[WindowInfo](WindowInfo.md)] | +| client | None | +| browser_settings_out | list[[BrowserSettings](BrowserSettings.md)] | +| no_javascript_access_out | list[bool] | +| __Return__ | bool | + +Description from upstream CEF: +> Called on the UI thread before a new popup browser is created. The +> |browser| and |frame| values represent the source of the popup request. The +> |target_url| and |target_frame_name| values indicate where the popup +> browser should navigate and may be empty if not specified with the request. +> The |target_disposition| value indicates where the user intended to open +> the popup (e.g. current tab, new tab, etc). The |user_gesture| value will +> be true if the popup was opened via explicit user gesture (e.g. clicking a +> link) or false if the popup opened automatically (e.g. via the +> DomContentLoaded event). The |popup_features| structure contains additional +> information about the requested popup window. To allow creation of the +> popup browser optionally modify |windowInfo|, |client|, |browserSettings| and +> |no_javascript_access| and return false. To cancel creation of the popup +> browser return true. The |client| and |settings| values will default to the +> source browser's values. If the |no_javascript_access| value is set to +> false the new browser will not be scriptable and may not be hosted in the +> same renderer process as the source browser. Any modifications to +> |window_info| will be ignored if the parent browser is wrapped in a +> CefBrowserView. Popup browser creation will be canceled if the parent +> browser is destroyed before the popup browser creation completes (indicated +> by a call to OnAfterCreated for the popup browser). + +`WindowOpenDisposition` constants in the cefpython module: +* WOD_UNKNOWN, +* WOD_CURRENT_TAB, +* WOD_SINGLETON_TAB, +* WOD_NEW_FOREGROUND_TAB, +* WOD_NEW_BACKGROUND_TAB, +* WOD_NEW_POPUP, +* WOD_NEW_WINDOW, +* WOD_SAVE_TO_DISK, +* WOD_OFF_THE_RECORD, +* WOD_IGNORE_ACTION + +Note that if you return True and create the popup window yourself, then +the popup window and parent window will not be able to script each other. +There will be no "window.opener" property available in the popup window. +To avoid this issue create a hidden window when your application starts. +Parent the new popup browser to the hidden window in OnBeforePopup. After +the browser exists (OnAfterCreated) create the desired target window +and re-parent the browser to that target window. diff --git a/api/PaintBuffer.md b/api/PaintBuffer.md index edd9376d3..c6509db21 100644 --- a/api/PaintBuffer.md +++ b/api/PaintBuffer.md @@ -9,7 +9,7 @@ This object used in: [RenderHandler](RenderHandler.md).OnPaint(). Table of contents: * [Methods](#methods) * [GetIntPointer](#getintpointer) - * [GetString](#getstring) + * [GetBytes](#getbytes) ## Methods @@ -28,7 +28,7 @@ Description from upstream CEF: > image with an upper-left origin. -### GetString +### GetBytes | Parameter | Type | | --- | --- | diff --git a/api/RenderHandler.md b/api/RenderHandler.md index bb25ac01d..a33a2154f 100644 --- a/api/RenderHandler.md +++ b/api/RenderHandler.md @@ -22,6 +22,7 @@ Table of contents: * [OnPaint](#onpaint) * [OnCursorChange](#oncursorchange) * [OnScrollOffsetChanged](#onscrolloffsetchanged) + * [OnTextSelectionChanged](#ontextselectionchanged) * [StartDragging](#startdragging) * [UpdateDragCursor](#updatedragcursor) @@ -177,6 +178,25 @@ Called when the browser's cursor has changed. If |type| is CT_CUSTOM then Called when the scroll offset has changed. +### OnTextSelectionChanged + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| selected_text | str | +| selected_range | list[x, y] | +| __Return__ | void | + +Description from upstream CEF: +> Called when text selection has changed for the specified |browser|. +> |selected_text| is the currently selected text and |selected_range| is +> the character range. + +NOTE: this callback seems to be called only when selecting text +with a mouse. When selecting text programmatically using javascript +code it doesn't get called. + + ### StartDragging | Parameter | Type | diff --git a/api/Request.md b/api/Request.md index 47e8b462c..d9d0ece38 100644 --- a/api/Request.md +++ b/api/Request.md @@ -95,9 +95,10 @@ Set the request method type. | --- | --- | | __Return__ | list/dict | -Get the post data. If the form content type is "multipart/form-data" -then the post data will be returned as a list. If the form content -type is "application/x-www-form-urlencoded" then the post data will +Get the post data. All strings are byte strings. If the form content +type is "multipart/form-data" then the post data will be returned +as a list. If the form content type is +"application/x-www-form-urlencoded" then the post data will be returned as a dict. @@ -108,8 +109,8 @@ be returned as a dict. | postData | list/dict | | __Return__ | void | -Set the post data. See GetPostData() for an explanation of the -postData type. +Set the post data. All strings are expected to be byte strings. +See GetPostData() for an explanation of the postData type. ### GetHeaderMap @@ -166,15 +167,20 @@ be removed and ignored. Get the flags used in combination with WebRequest. -Available flags (access via `cefpython.Request.Flags["xxx"]`): +Available flags below. Can be accessed via `cefpython.Request.Flags["xxx"]`. +These flags are also defined as constants starting with "UR_FLAG_" +in the cefpython module.requ * **None** - Default behavior. -* **SkipCache** - If set the cache will be skipped when handling the request. -* **AllowCachedCredentials** - If set user name, password, and cookies may be - sent with the request, and cookies may be saved from the response. +* **SkipCache** - If set the cache will be skipped when handling the request. Setting this value is equivalent to specifying the "Cache-Control: no-cache" request header. Setting this value in combination with UR_FLAG_ONLY_FROM_CACHE will cause the request to fail. +* **OnlyFromCache** - If set the request will fail if it cannot be served from the cache (or some equivalent local store). Setting this value is equivalent to specifying the "Cache-Control: only-if-cached" request header. Setting this value in combination with UR_FLAG_SKIP_CACHE will cause the request to fail. +* **AllowStoredCredentials** - If set user name, password, and cookies may be sent with the request, and cookies may be saved from the response. * **ReportUploadProgress** - If set upload progress events will be generated when a request has a body. * **NoDownloadData** - If set the [WebRequestClient](WebRequestClient.md)::`OnDownloadData` method will not be called. * **NoRetryOn5xx** - If set 5xx redirect errors will be propagated to the observer instead of automatically re-tried. This currently only applies for requests originated in the browser process. +* **StopOnRedirect** - If set 3XX responses will cause the fetch to halt immediately rather than continue through the redirect. + + ### SetFlags @@ -185,6 +191,7 @@ Available flags (access via `cefpython.Request.Flags["xxx"]`): | __Return__ | void | Set the flags used in combination with [WebRequest](WebRequest.md). +See GetFlags() for possible values. ### GetFirstPartyForCookies diff --git a/api/RequestHandler.md b/api/RequestHandler.md index 01b2ea99b..f1ef8bf72 100644 --- a/api/RequestHandler.md +++ b/api/RequestHandler.md @@ -4,131 +4,69 @@ # RequestHandler (interface) Implement this interface to handle events related to browser requests. +The methods of this class will be called on the thread indicated. -For an example of how to implement handler see -[cefpython](cefpython.md).CreateBrowserSync(). For a list of all handler -interfaces see [API > Client handlers](API#Client_handlers). - -The `RequestHandler` tests can be found in the old wxpython.py script (v31). - -Not yet exposed in CEF Python: -* OnOpenURLFromTab -* OnSelectClientCertificate +Related code snippets: +- [network_cookies.py](../examples/snippets/network_cookies.py) +Available in upstream CEF, but not yet exposed to CEF Python: +- OnOpenURLFromTab +- OnSelectClientCertificate Table of contents: * [Callbacks](#callbacks) + * [CanGetCookies](#cangetcookies) + * [CanSetCookie](#cansetcookie) + * [GetAuthCredentials](#getauthcredentials) + * [GetCookieManager](#getcookiemanager) + * [GetResourceHandler](#getresourcehandler) * [OnBeforeBrowse](#onbeforebrowse) + * [_OnBeforePluginLoad](#_onbeforepluginload) * [OnBeforeResourceLoad](#onbeforeresourceload) - * [GetResourceHandler](#getresourcehandler) + * [_OnCertificateError](#_oncertificateerror) + * [OnQuotaRequest](#onquotarequest) * [OnResourceRedirect](#onresourceredirect) * [OnResourceResponse](#onresourceresponse) - * [GetAuthCredentials](#getauthcredentials) - * [OnQuotaRequest](#onquotarequest) - * [GetCookieManager](#getcookiemanager) + * [OnPluginCrashed](#onplugincrashed) * [OnProtocolExecution](#onprotocolexecution) - * [_OnBeforePluginLoad](#_onbeforepluginload) - * [_OnCertificateError](#_oncertificateerror) * [OnRendererProcessTerminated](#onrendererprocessterminated) - * [OnPluginCrashed](#onplugincrashed) ## Callbacks -### OnBeforeBrowse +### CanGetCookies | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | | frame | [Frame](Frame.md) | | request | [Request](Request.md) | -| is_redirect | bool | | __Return__ | bool | -Called on the UI thread before browser navigation. Return true to cancel -the navigation or false to allow the navigation to proceed. The |request| -object cannot be modified in this callback. -[DisplayHandler](DisplayHandler.md).`OnLoadingStateChange` will be -called twice in all cases. -If the navigation is allowed [LoadHandler](LoadHandler.md).`OnLoadStart` and -`OnLoadEnd` will be called. If the navigation is canceled -[LoadHandler](LoadHandler.md).`OnLoadError` will be called with -an |error_code| value of ERR_ABORTED. +Description from upstream CEF: +> Called on the IO thread before sending a network request with a "Cookie" +> request header. Return true to allow cookies to be included in the network +> request or false to block cookies. The |request| object should not be +> modified in this callback. -### OnBeforeResourceLoad +### CanSetCookie | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | | frame | [Frame](Frame.md) | | request | [Request](Request.md) | +| cookie | [Cookie](Cookie.md) | | __Return__ | bool | -Called on the IO thread before a resource request is loaded. The |request| -object may be modified. To cancel the request return true otherwise return -false. - - -### GetResourceHandler - -| Parameter | Type | -| --- | --- | -| browser | [Browser](Browser.md) | -| frame | [Frame](Frame.md) | -| request | [Request](Request.md) | -| __Return__ | [ResourceHandler](ResourceHandler.md) | - -Called on the IO thread before a resource is loaded. To allow the resource -to load normally return None. To specify a handler for the resource return -a [ResourceHandler](ResourceHandler.md) object. The |request| object should -not be modified in this callback. - -The [ResourceHandler](ResourceHandler.md) object is a python class that -implements the `ResourceHandler` callbacks. Remember to keep a strong -reference to this object while resource is being loaded. - -The `GetResourceHandler` example can be found in the old v31 -"wxpython-response.py" script on Linux. - - -### OnResourceRedirect - -| Parameter | Type | -| --- | --- | -| browser | [Browser](Browser.md) | -| frame | [Frame](Frame.md) | -| old_url | string | -| new_url_out | list[string] | -| request | [Request](Request.md) | -| response | [Response](Response.md) | -| __Return__ | void | - Description from upstream CEF: -> Called on the IO thread when a resource load is redirected. The |request| -> parameter will contain the old URL and other request-related information. -> The |response| parameter will contain the response that resulted in the -> redirect. The |new_url| parameter will contain the new URL and can be -> changed if desired. The |request| object cannot be modified in this -> callback. - - -### OnResourceResponse - -| | | -| --- | --- | -| __Return__ | void | - -Available in upstream CEF, but not yet exposed to CEF Python. -See Issue #229. - -You can implement this functionality by using -[ResourceHandler](ResourceHandler.md) and [WebRequest](WebRequest.md) -/ [WebRequestClient](WebRequestClient.md). For an example see the -_OnResourceResponse() method in the old v31 [wxpython-response.py] -example. +> Called on the IO thread when receiving a network request with a +> "Set-Cookie" response header value represented by |cookie|. Return true to +> allow the cookie to be stored or false to block the cookie. The |request| +> object should not be modified in this callback. ### GetAuthCredentials @@ -168,28 +106,6 @@ Example implementations: [[3]](https://github.com/cztomczak/cefpython/blob/cefpython31/cefpython/http_authentication_win.pyx). -### OnQuotaRequest - -| Parameter | Type | -| --- | --- | -| browser | [Browser](Browser.md) | -| origin_url | string | -| new_size | long | -| callback | RequestCallback | -| __Return__ | bool | - -Called on the IO thread when javascript requests a specific storage quota -size via the `webkitStorageInfo.requestQuota` function. |origin_url| is the -origin of the page making the request. |new_size| is the requested quota -size in bytes. Return true to continue the request and call -CefRequestCallback::Continue() either in this method or at a later time to -grant or deny the request. Return false to cancel the request immediately. - -The `RequestCallback` object methods: -* void Continue(bool allow) -* void Cancel() - - ### GetCookieManager | Parameter | Type | @@ -203,12 +119,21 @@ 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 None. +**IMPORTANT**: In some cases this callback is not called due to a +race condition. See Issue [#429](../../../issues/429) for details. + To successfully implement separate cookie manager per browser session, you have to set ApplicationSettings.`unique_request_context_per_browser` to True. Otherwise the browser param passed to this callback will always be the same first browser that was created using [cefpython](cefpython.md).`CreateBrowserSync`. +**NOTE**: If implementing custom cookie managers you will encounter +problems similar to [Issue #365](../../../issues/365) ("Cookies not +flushed to disk when closing app immediately"). To resolve +it you have to call CookieManager.[FlushStore](CookieManager.md#flushstore) +method when closing associated browser. + Popup browsers created javascript's window.open share the same renderer process and request context. If you want to have separate cookie managers for popups created using window.open then you have @@ -218,31 +143,51 @@ the window on your own and embed browser in it. The `CreateAnotherBrowser` function from the old v31 wxpython example does that. -IMPORTANT: in an exceptional case the `browser` parameter could be -None, so you should handle such case. During testing this issue did -not occur, but it may happen in some yet unknown scenarios. - -### OnProtocolExecution +### GetResourceHandler | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | -| url | string | -| allow_execution_out | list[bool] | -| __Return__ | void | +| frame | [Frame](Frame.md) | +| request | [Request](Request.md) | +| __Return__ | [ResourceHandler](ResourceHandler.md) | -Called on the UI thread to handle requests for URLs with an unknown -protocol component. Set |allow_execution_out[0]| to True to attempt -execution via the registered OS protocol handler, if any. +Called on the IO thread before a resource is loaded. To allow the resource +to load normally return None. To specify a handler for the resource return +a [ResourceHandler](ResourceHandler.md) object. The |request| object should +not be modified in this callback. -__SECURITY NOTE__: You should use this callback to enforce restrictions -based on scheme, host or other url analysis before allowing OS execution. +The [ResourceHandler](ResourceHandler.md) object is a python class that +implements the `ResourceHandler` callbacks. Remember to keep a strong +reference to this object while resource is being loaded. -There's no default implementation for OnProtocolExecution on Linux, -you have to make OS system call on your own. You probably also need -to use [LoadHandler](LoadHandler.md)::OnLoadError() when implementing -this on Linux. +The `GetResourceHandler` example can be found in the old v31 +"wxpython-response.py" script on Linux. + + +### OnBeforeBrowse + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| frame | [Frame](Frame.md) | +| request | [Request](Request.md) | +| user_gesture | bool | +| is_redirect | bool | +| __Return__ | bool | + +Description from upstream CEF: +> Called on the UI thread before browser navigation. Return true to cancel +> the navigation or false to allow the navigation to proceed. The |request| +> object cannot be modified in this callback. +> CefLoadHandler::OnLoadingStateChange will be called twice in all cases. +> If the navigation is allowed CefLoadHandler::OnLoadStart and +> CefLoadHandler::OnLoadEnd will be called. If the navigation is canceled +> CefLoadHandler::OnLoadError will be called with an |errorCode| value of +> ERR_ABORTED. The |user_gesture| value will be true if the browser +> navigated via explicit user gesture (e.g. clicking a link) or false if it +> navigated automatically (e.g. via the DomContentLoaded event). ### _OnBeforePluginLoad @@ -275,7 +220,6 @@ Description from upstream CEF: > purge the plugin list cache and potentially trigger new calls to this > method call CefRequestContext::PurgePluginListCache. - Return True to block loading of the plugin. This callback will be executed during browser creation, thus you must @@ -288,6 +232,20 @@ This callback is called every time the page tries to load a plugin (perhaps even multiple times per plugin). +### OnBeforeResourceLoad + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| frame | [Frame](Frame.md) | +| request | [Request](Request.md) | +| __Return__ | bool | + +Called on the IO thread before a resource request is loaded. The |request| +object may be modified. To cancel the request return true otherwise return +false. + + ### _OnCertificateError | Parameter | Type | @@ -314,21 +272,63 @@ The `RequestCallback` object methods: * void Cancel() -### OnRendererProcessTerminated +### OnQuotaRequest | Parameter | Type | | --- | --- | | browser | [Browser](Browser.md) | -| status | TerminationStatus | +| origin_url | string | +| new_size | long | +| callback | RequestCallback | +| __Return__ | bool | + +Called on the IO thread when javascript requests a specific storage quota +size via the `webkitStorageInfo.requestQuota` function. |origin_url| is the +origin of the page making the request. |new_size| is the requested quota +size in bytes. Return true to continue the request and call +CefRequestCallback::Continue() either in this method or at a later time to +grant or deny the request. Return false to cancel the request immediately. + +The `RequestCallback` object methods: +* void Continue(bool allow) +* void Cancel() + + +### OnResourceRedirect + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| frame | [Frame](Frame.md) | +| old_url | string | +| new_url_out | list[string] | +| request | [Request](Request.md) | +| response | [Response](Response.md) | | __Return__ | void | -Called when the render process terminates unexpectedly. |status| indicates -how the process terminated. +Description from upstream CEF: +> Called on the IO thread when a resource load is redirected. The |request| +> parameter will contain the old URL and other request-related information. +> The |response| parameter will contain the response that resulted in the +> redirect. The |new_url| parameter will contain the new URL and can be +> changed if desired. The |request| object cannot be modified in this +> callback. -`TerminationStatus` constants in the cefpython module: - * TS_ABNORMAL_TERMINATION - Non-zero exit status. - * TS_PROCESS_WAS_KILLED - SIGKILL or task manager kill. - * TS_PROCESS_CRASHED - Segmentation fault. + +### OnResourceResponse + +| | | +| --- | --- | +| __Return__ | void | + +Available in upstream CEF, but not yet exposed to CEF Python. +See Issue #229. + +You can implement this functionality by using +[ResourceHandler](ResourceHandler.md) and [WebRequest](WebRequest.md) +/ [WebRequestClient](WebRequestClient.md). For an example see the +_OnResourceResponse() method in the old v31 [wxpython-response.py] +example. ### OnPluginCrashed @@ -341,3 +341,42 @@ how the process terminated. Called when a plugin has crashed. |plugin_path| is the path of the plugin that crashed. + + +### OnProtocolExecution + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| url | string | +| allow_execution_out | list[bool] | +| __Return__ | void | + +Called on the UI thread to handle requests for URLs with an unknown +protocol component. Set |allow_execution_out[0]| to True to attempt +execution via the registered OS protocol handler, if any. + +__SECURITY NOTE__: You should use this callback to enforce restrictions +based on scheme, host or other url analysis before allowing OS execution. + +There's no default implementation for OnProtocolExecution on Linux, +you have to make OS system call on your own. You probably also need +to use [LoadHandler](LoadHandler.md)::OnLoadError() when implementing +this on Linux. + + +### OnRendererProcessTerminated + +| Parameter | Type | +| --- | --- | +| browser | [Browser](Browser.md) | +| status | TerminationStatus | +| __Return__ | void | + +Called when the render process terminates unexpectedly. |status| indicates +how the process terminated. + +`TerminationStatus` constants in the cefpython module: + * TS_ABNORMAL_TERMINATION - Non-zero exit status. + * TS_PROCESS_WAS_KILLED - SIGKILL or task manager kill. + * TS_PROCESS_CRASHED - Segmentation fault. diff --git a/api/V8ContextHandler.md b/api/V8ContextHandler.md index 9c6f6fbc3..b88a86418 100644 --- a/api/V8ContextHandler.md +++ b/api/V8ContextHandler.md @@ -3,7 +3,9 @@ # V8ContextHandler (interface) -Implement this interface to handle javascript exceptions globally. +Implement this interface to handle render process callbacks. +Through inter-process messaging you are notified about these events +in the browser process. Table of contents: diff --git a/api/WebRequestClient.md b/api/WebRequestClient.md index d8431cecc..0c75a668d 100644 --- a/api/WebRequestClient.md +++ b/api/WebRequestClient.md @@ -65,7 +65,7 @@ response (or -1 if not determined). | Parameter | Type | | --- | --- | | web_request | [WebRequest](WebRequest.md) | -| data | string | +| data | bytes | | __Return__ | void | Called when some part of the response is read. |data| contains the current diff --git a/api/WindowInfo.md b/api/WindowInfo.md index 319e0d6fc..957b87570 100644 --- a/api/WindowInfo.md +++ b/api/WindowInfo.md @@ -15,7 +15,6 @@ Table of contents: * [SetAsChild](#setaschild) * [SetAsPopup](#setaspopup) * [SetAsOffscreen](#setasoffscreen) - * [SetTransparentPainting](#settransparentpainting) ## Methods @@ -51,20 +50,21 @@ Available only on Windows. | parentWindowHandle | int | | __Return__ | void | -Upstream CEF description: +Description from upstream CEF: > Create the browser using windowless (off-screen) rendering. No window will be created for the browser and all rendering will occur via the CefRenderHandler interface. The |parent| value will be used to identify monitor info and to act as the parent window for dialogs, context menus, etc. If |parent| is not provided then the main screen monitor will be used and some functionality that requires a parent window may not function -correctly. If |transparent| is true a transparent background color will be -used (RGBA=0x00000000). If |transparent| is false the background will be -white and opaque. In order to create windowless browsers the +correctly. In order to create windowless browsers the CefSettings.windowless_rendering_enabled value must be set to true. +Transparent painting is enabled by default but can be disabled by setting +CefBrowserSettings.background_color to an opaque value. Call this method to disable windowed rendering and to use -[RenderHandler](RenderHandler.md). See the Panda3D and Kivy examples. +[RenderHandler](RenderHandler.md). See the pysdl2, screenshot, panda3d +and kivy examples. In order to create windowless browsers the ApplicationSettings.[windowless_rendering_enabled](ApplicationSettings.md#windowless_rendering_enabled) @@ -73,12 +73,3 @@ value must be set to true. You can pass 0 as `parentWindowHandle`, but then some things like context menus and plugins may not display correctly. - -### SetTransparentPainting - -| Parameter | Type | -| --- | --- | -| transparentPainting | bool | -| __Return__ | void | - -This method is intended for use with off-screen rendering only. diff --git a/api/cefpython.md b/api/cefpython.md index ea7c54cda..ae7d255c3 100644 --- a/api/cefpython.md +++ b/api/cefpython.md @@ -13,19 +13,23 @@ Table of contents: * [ExceptHook](#excepthook) * [GetAppSetting](#getappsetting) * [GetAppPath](#getapppath) + * [GetBrowserByIdentifier](#getbrowserbyidentifier) * [GetBrowserByWindowHandle](#getbrowserbywindowhandle) * [GetCommandLineSwitch](#getcommandlineswitch) + * [GetDataUrl](#getdataurl) * [GetGlobalClientCallback](#getglobalclientcallback) * [GetModuleDirectory](#getmoduledirectory) * [GetVersion](#getversion) * [Initialize](#initialize) * [IsThread](#isthread) + * [LoadCrlSetsFile](#loadcrlsetsfile) * [MessageLoop](#messageloop) * [MessageLoopWork](#messageloopwork) * [PostTask](#posttask) * [PostDelayedTask](#postdelayedtask) * [QuitMessageLoop](#quitmessageloop) * [SetGlobalClientCallback](#setglobalclientcallback) + * [SetGlobalClientHandler](#setglobalclienthandler) * [SetOsModalLoop](#setosmodalloop) * [Shutdown](#shutdown) @@ -55,6 +59,13 @@ All parameters are optional. This function can only be called on the UI thread. +If the url is a local path it needs to start with the `file://` prefix. +If the url contains special characters it may need proper handling. +Starting with v66.1+ it is required for the app code to encode the url +properly. You can use the `pathlib.PurePath.as_uri` in Python 3 +or `urllib.pathname2url` in Python 2 (`urllib.request.pathname2url` +in Python 3) depending on your case. + The "window_title" parameter will be used only when parent window provided in window_info was set to 0. This is for use with hello_world.py and tutorial.py examples which don't use @@ -62,7 +73,8 @@ any third party GUI framework for creation of top-level window. After the call to CreateBrowserSync() the page is not yet loaded, if you want your next lines of code to do some stuff on the -webpage you will have to implement LoadHandler.[OnLoadingStateChange]((LoadHandler.md#onloadingstatechange)) +webpage you will have to implement +LoadHandler.[OnLoadingStateChange](LoadHandler.md#onloadingstatechange) callback. @@ -106,6 +118,17 @@ to Initialize(). Returns None if key is not found. Get path to where application resides. +### GetBrowserByIdentifier + +| Parameter | Type | +| --- | --- | +| identifier | int | +| __Return__ | void | + +Get browser by identifier. Browser identifier can be obtained by +calling `Browser.GetIdentifier`. + + ### GetBrowserByWindowHandle | Parameter | Type | @@ -126,6 +149,20 @@ Get browser by outer or inner window handle. An outer window handle is the one t Returns the [CommandLineSwitches](CommandLineSwitches.md) switch that was passed to Initialize(). Returns None if key is not found. +### GetDataUrl + +| Parameter | Type | +| --- | --- | +| data | string | +| mediatype="html" (optional) | string | +| __Return__ | object | + +Convert data to a Data URL. Only "html" media type is currently supported. + +See: +https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs + + ### GetGlobalClientCallback | Parameter | Type | @@ -133,7 +170,8 @@ Returns the [CommandLineSwitches](CommandLineSwitches.md) switch that was passed | name | string | | __Return__ | object | -Returns a global client callback that was set using SetGlobalClientCallback(). Returns None if callback was not set. +Returns a global client callback that was set using SetGlobalClientCallback() +or SetGlobalClientHandler. Returns None if callback was not set. ### GetModuleDirectory @@ -186,6 +224,22 @@ CEF maintains multiple internal threads that are used for handling different typ See PostTask() for a list of threads. +### LoadCrlSetsFile + +| Parameter | Type | +| --- | --- | +| path | bytes | +| __Return__ | bool | + +Description from upstream CEF: +> Loads the existing "Certificate Revocation Lists" file that is managed by +> Google Chrome. This file can generally be found in Chrome's User Data +> directory (e.g. "C:\Users\[User]\AppData\Local\Google\Chrome\User Data\" on +> Windows) and is updated periodically by Chrome's component updater service. +> Must be called in the browser process after the context has been initialized. +> See https://dev.chromium.org/Home/chromium-security/crlsets for background. + + ### MessageLoop | | | @@ -193,7 +247,7 @@ See PostTask() for a list of threads. | __Return__ | void | Run the CEF message loop. Use this function instead of an application- -provided message loop to get the best balance between performance and +provided message loop to get the best balance between performance and CPU usage. This function should only be called on the main application thread (UI thread) and only if cefpython.Initialize() is called with a [ApplicationSettings](ApplicationSettings.md).multi_threaded_message_loop @@ -237,19 +291,18 @@ Description from upstream CEF: Post a task for execution on the thread associated with this task runner. Execution will occur asynchronously. Only Browser process threads are allowed. -An example usage is in the wxpython.py example on Windows, in implementation of LifespanHandler.OnBeforePopup(). - List of threads in the Browser process: -* cef.TID_UI: The main thread in the browser. This will be the same as the main application thread if cefpython.Initialize() is called with a ApplicationSettings.multi_threaded_message_loop value of false. -* cef.TID_DB: Used to interact with the database. -* cef.TID_FILE: Used to interact with the file system. -* cef.TID_FILE_USER_BLOCKING: Used for file system operations that block user interactions. Responsiveness of this thread affects users. -* cef.TID_PROCESS_LAUNCHER: Used to launch and terminate browser processes. -* cef.TID_CACHE: Used to handle slow HTTP cache operations. -* cef.TID_IO: Used to process IPC and network messages. +* cef.TID_UI: The main thread in the browser. This will be the same as the main application thread if cefpython.Initialize() is called with a ApplicationSettings.multi_threaded_message_loop value of false. Do not perform blocking tasks on this thread. All tasks posted after CefBrowserProcessHandler::OnContextInitialized() and before CefShutdown() are guaranteed to run. This thread will outlive all other CEF threads. +* cef.TID_FILE (alias cef.TID_FILE_BACKGROUND): Used for blocking tasks (e.g. file system access) where the user won't notice if the task takes an arbitrarily long time to complete. All tasks posted after CefBrowserProcessHandler::OnContextInitialized() and before CefShutdown() are guaranteed to run. +* cef.TID_FILE_USER_VISIBLE: Used for blocking tasks (e.g. file system access) that affect UI or responsiveness of future user interactions. Do not use if an immediate response to a user interaction is expected. All tasks posted after CefBrowserProcessHandler::OnContextInitialized() and before CefShutdown() are guaranteed to run. Examples: + - Updating the UI to reflect progress on a long task. + - Loading data that might be shown in the UI after a future user + interaction. +* cef.TID_FILE_USER_BLOCKING: Used for blocking tasks (e.g. file system access) that affect UI immediately after a user interaction. All tasks posted after CefBrowserProcessHandler::OnContextInitialized() and before CefShutdown() are guaranteed to run. Example: Generating data shown in the UI immediately after a click. +* cef.TID_IO: Used to process IPC and network messages. Do not perform blocking tasks on this thread. All tasks posted after CefBrowserProcessHandler::OnContextInitialized() and before CefShutdown() are guaranteed to run. List of threads in the Renderer process: -* cef.TID_RENDERER: The main thread in the renderer. Used for all webkit and V8 interaction. +* cef.TID_RENDERER: Tasks may be posted to this thread after CefRenderProcessHandler::OnRenderThreadCreated but are not guaranteed to run before sub-process termination (sub-processes may be killed at any time without warning). ### PostDelayedTask @@ -291,6 +344,23 @@ Some client callbacks are not associated with any browser. In such case use this Example of using SetGlobalClientCallback() is provided in the wxpython.py example. +### SetGlobalClientHandler + +| Parameter | Type | +| --- | --- | +| handler | object | +| __Return__ | void | + +Set client handler object (class instance). Its members will be inspected. +Private methods that are not meant to be callbacks should have their names +prepended with two underscores. Methods with single underscore or no +underscore are treated the same as client callbacks. + +You can call this method multiple times to set many handlers. For +example you can create in your code several objects named AccessibilityHandler, +RequestHandler etc. + + ### SetOsModalLoop | Parameter | Type | diff --git a/docs/Build-instructions.md b/docs/Build-instructions.md index fc5436a34..9ca4d6e99 100644 --- a/docs/Build-instructions.md +++ b/docs/Build-instructions.md @@ -12,6 +12,7 @@ Table of contents: * [Build using prebuilt CEF binaries and libraries](#build-using-prebuilt-cef-binaries-and-libraries) * [Build using CEF binaries from Spotify Automated Builds](#build-using-cef-binaries-from-spotify-automated-builds) * [Build upstream CEF from sources](#build-upstream-cef-from-sources) + * [Building old unsupported version of Chromium](#building-old-unsupported-version-of-chromium) * [Possible errors](#possible-errors) * [Build CEF manually](#build-cef-manually) * [CEF Automated Builds (Spotify and Adobe)](#cef-automated-builds-spotify-and-adobe) @@ -65,8 +66,9 @@ are named "cefpythonXX" where XX is Chromium version number. from [here](https://www.microsoft.com/en-us/download/details.aspx?id=44266) 5) For Python 2.7 and when using using "Visual C++ compiler for Python 2.7" - you have to install "Visual C++ 2008 Redistributable Package (x64)" - from [here](https://www.microsoft.com/en-us/download/details.aspx?id=15336) + you have to install "Visual C++ 2008 Redistributable Package" + from [here](https://www.microsoft.com/en-us/download/details.aspx?id=29) + and [here](https://www.microsoft.com/en-us/download/details.aspx?id=15336) 6) Clone cefpython, checkout for example "cefpython57" branch that includes Chromium v57, then create a build/ directory and enter it: @@ -163,7 +165,8 @@ requirements common for all platforms. * For Python 2.7 install "Microsoft Visual C++ Compiler for Python 2.7" from [here](https://www.microsoft.com/en-us/download/details.aspx?id=44266) * When using "Visual C++ compiler for Python 2.7" you have to install - "Microsoft Visual C++ 2008 Redistributable Package (x64)" from + "Microsoft Visual C++ 2008 Redistributable Package" from + [here](https://www.microsoft.com/en-us/download/details.aspx?id=29) and [here](https://www.microsoft.com/en-us/download/details.aspx?id=15336) * For Python 2.7 copy "cefpython/src/windows/py27/stdint.h" to "%LocalAppData%\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\include\" @@ -192,16 +195,18 @@ requirements common for all platforms. * Install packages: `sudo apt-get install cmake g++ libgtk2.0-dev libgtkglext1-dev` * If building CEF from sources: - * Official binaries are built on Ubuntu 14.04 (cmake 2.8.12, g++ 4.8.4) - * Download [ninja](http://martine.github.io/ninja/) 1.7.1 or later + * Official binaries are built on Ubuntu 14.04 (cmake 2.8.12, g++ 4.8.4) and these instructions apply to that OS + * For Fedora build dependencies see [Issue #466](https://github.com/cztomczak/cefpython/issues/466#issuecomment-419794341) + * Download [ninja](https://github.com/ninja-build/ninja/releases) 1.7.1 or later and copy it to /usr/bin and chmod 755. - * Install/upgrade required packages using one of the three methods below + * Install/upgrade required packages using one of the four methods below (these packages should be upgraded each time you update to newer CEF): - 1. Type command: `sudo apt-get install bison build-essential cdbs curl devscripts dpkg-dev elfutils fakeroot flex g++ git-core git-svn gperf libapache2-mod-php5 libasound2-dev libav-tools libbrlapi-dev libbz2-dev libcairo2-dev libcap-dev libcups2-dev libcurl4-gnutls-dev libdrm-dev libelf-dev libexif-dev libffi-dev libgconf2-dev libgl1-mesa-dev libglib2.0-dev libglu1-mesa-dev libgnome-keyring-dev libgtk2.0-dev libkrb5-dev libnspr4-dev libnss3-dev libpam0g-dev libpci-dev libpulse-dev libsctp-dev libspeechd-dev libsqlite3-dev libssl-dev libudev-dev libwww-perl libxslt1-dev libxss-dev libxt-dev libxtst-dev mesa-common-dev openbox patch perl php5-cgi pkg-config python python-cherrypy3 python-crypto python-dev python-psutil python-numpy python-opencv python-openssl python-yaml rpm ruby subversion ttf-dejavu-core ttf-indic-fonts ttf-kochi-gothic ttf-kochi-mincho fonts-thai-tlwg wdiff wget zip` - 2. See the list of packages on the + 1. For 64-bit build, type this command: `sudo apt-get install bison build-essential cdbs curl devscripts dpkg-dev elfutils fakeroot flex g++ git-core git-svn gperf libapache2-mod-php5 libasound2-dev libav-tools libbrlapi-dev libbz2-dev libcairo2-dev libcap-dev libcups2-dev libcurl4-gnutls-dev libdrm-dev libelf-dev libexif-dev libffi-dev libgconf2-dev libgconf-2-4 libgl1-mesa-dev libglib2.0-dev libglu1-mesa-dev libgnome-keyring-dev libgtk2.0-dev libkrb5-dev libnspr4-dev libnss3-dev libpam0g-dev libpci-dev libpulse-dev libsctp-dev libspeechd-dev libsqlite3-dev libssl-dev libudev-dev libwww-perl libxslt1-dev libxss-dev libxt-dev libxtst-dev mesa-common-dev openbox patch perl php5-cgi pkg-config python python-cherrypy3 python-crypto python-dev python-psutil python-numpy python-opencv python-openssl python-yaml rpm ruby subversion ttf-dejavu-core ttf-indic-fonts ttf-kochi-gothic ttf-kochi-mincho fonts-thai-tlwg wdiff wget zip` + 2. For 32-bit build, type this command: `bison build-essential cdbs curl devscripts dpkg-dev elfutils fakeroot flex g++ git-core git-svn gperf libapache2-mod-php5 libasound2-dev libav-tools libbrlapi-dev libbz2-dev libcairo2-dev libcap-dev libcups2-dev libcurl4-gnutls-dev libdrm-dev libelf-dev libexif-dev libffi-dev libgconf2-dev libgl1-mesa-dev libglib2.0-dev libglu1-mesa-dev libgnome-keyring-dev libgtk2.0-dev libkrb5-dev libnspr4-dev libnss3-dev libpam0g-dev libpci-dev libpulse-dev libsctp-dev libspeechd-dev libsqlite3-dev libssl-dev libudev-dev libwww-perl libxslt1-dev libxss-dev libxt-dev libxtst-dev mesa-common-dev openbox patch perl php5-cgi pkg-config python python-cherrypy3 python-crypto python-dev python-psutil python-numpy python-opencv python-openssl python-yaml rpm ruby subversion ttf-dejavu-core ttf-indic-fonts ttf-kochi-gothic ttf-kochi-mincho fonts-thai-tlwg wdiff wget zip lib32gcc1 lib32stdc++6 libc6-i386 linux-libc-dev:i386 libasound2:i386 libcap2:i386 libelf-dev:i386 libfontconfig1:i386 libgconf-2-4:i386 libglib2.0-0:i386 libgpm2:i386 libgtk2.0-0:i386 libgtk-3-0:i386 libncurses5:i386 libnss3:i386 libpango1.0-0:i386 libssl1.0.0:i386 libtinfo-dev:i386 libxcomposite1:i386 libxcursor1:i386 libxdamage1:i386 libxi6:i386 libxrandr2:i386 libxss1:i386 libxtst6:i386` + 3. See the list of packages on the [cef/AutomatedBuildSetup.md](https://bitbucket.org/chromiumembedded/cef/wiki/AutomatedBuildSetup.md#markdown-header-linux-configuration) wiki page. - 2. Run the install-build-deps.sh script - + 4. Run the install-build-deps.sh script - instructions provided further down on this page. * To build on Debian 7 see [cef/BuildingOnDebian7.md](https://bitbucket.org/chromiumembedded/cef/wiki/BuildingOnDebian7.md) and @@ -222,7 +227,6 @@ requirements common for all platforms. * Download [cmake](https://cmake.org/download/) and add it to PATH. - ### All platforms * Install/update dependencies for the tools by executing: @@ -300,6 +304,7 @@ python ../tools/build.py xx.x ## Build upstream CEF from sources + Building CEF from sources is a very long process that can take several hours depending on your CPU speed and the platform you're building on. To speed up the process you can pass the --fast-build flag, however @@ -351,6 +356,26 @@ module, make installer package, install the package and run unit tests and examples. See the notes for commands for creating package installer and/or wheel package for distribution. +### Building old unsupported version of Chromium + +When building an old version of Chromium you may get into issues. +For example as of this writing the latest CEF Python version is +v57, but current support Chromium version is v64. Now when building +v57 you may encounter issues since Chromium build tools had +many updates since v57. You have to checkout depot_tools from the +revision when Chromium v57 was released. When running automate.py +tool the depot_tools repository resides in `build_dir/depot_tools/` +directory. If you didn't run automate.py then you can find repository +url in automate-git.py script. For example for v57 release to checkout +an old revision of depot_tools you can use this command: + +``` +git checkout master@{2017-04-20} +``` + +After that set `DEPOT_TOOLS_UPDATE=0` environment variable and then +run automate.py tool. + ### Possible errors __Debug_GN_arm/ configuration error (Linux)__: Even though building diff --git a/docs/Contributing-code.md b/docs/Contributing-code.md index bbcefc260..fb56e115f 100644 --- a/docs/Contributing-code.md +++ b/docs/Contributing-code.md @@ -12,6 +12,7 @@ Table of contents: * [API docs](#api-docs) * [Unit tests](#unit-tests) * [Platforms](#platforms) +* [GIL](#gil) * [Authors](#authors) * [Updating CEF version](#updating-cef-version) @@ -123,6 +124,24 @@ In most cases new code should run fine on all platforms, but in some cases it might be required to test on all platforms before PR is merged. +## GIL + +In the pxd file, functions should be defined as "nogil" to avoid +deadlocks when calling CEF functions. In the pyx file the call must +use the "with nogil" statement. + +From [Cython's documentation](http://docs.cython.org/src/userguide/external_C_code.html#acquiring-and-releasing-the-gil): + +> Note that acquiring the GIL is a blocking thread-synchronising operation, +> and therefore potentially costly. It might not be worth releasing the GIL +> for minor calculations. Usually, I/O operations and substantial computations +> in parallel code will benefit from it. + +Revision [ec1ce78](https://github.com/cztomczak/cefpython/commit/ec1ce788373bb9e0fd2cedd71e900c3877e9185a) removes the GIL lock from the +following calls: Initialize(), Shutdown(), CreateBrowserSync(), +SetOsModalLoop(), QuitMessageLoop(), CefExecuteProcess(). There still +might be some more functions from which the GIL lock should be removed. + ## Authors In your pull request modify also the [Authors](../Authors) file diff --git a/docs/Knowledge-Base.md b/docs/Knowledge-Base.md index 648523e6e..c68f4cc06 100644 --- a/docs/Knowledge-Base.md +++ b/docs/Knowledge-Base.md @@ -1,10 +1,12 @@ # Knowledge Base Table of contents: -* [ImportError: DLL load failed (Windows)](#importerror-dll-load-failed-windows) * [Notifications about new releases / commits](#notifications-about-new-releases--commits) * [Changes in API after CEF updates](#changes-in-api-after-cef-updates) * [Differences between Python 2 and Python 3](#differences-between-python-2-and-python-3) +* [How to enable debug information in examples?](#how-to-enable-debug-information-in-examples) +* [Remote debugging with Google Chrome instance](#remote-debugging-with-google-chrome-instance) +* [Debugging using various chrome:// protocol uris](#debugging-using-various-chrome-protocol-uris) * [A blank window on Mac/Linux](#a-blank-window-on-maclinux) * [Location of CEF framework in Mac apps](#location-of-cef-framework-in-mac-apps) * [Flash support](#flash-support) @@ -12,47 +14,12 @@ Table of contents: * [How to capture Audio and Video in HTML5?](#how-to-capture-audio-and-video-in-html5) * [Touch and multi-touch support](#touch-and-multi-touch-support) * [Black or white browser screen](#black-or-white-browser-screen) -* [How to enable debug information in examples?](#how-to-enable-debug-information-in-examples) * [Python crashes with "Segmentation fault" - how to debug?](#python-crashes-with-segmentation-fault---how-to-debug) * [Windows XP support](#windows-xp-support) * [Mac 32-bit support](#mac-32-bit-support) * [Security](#security) -## ImportError: DLL load failed (Windows) - -If you get such an error on Windows: -```Text -import cefpython3 -Traceback (most recent call last): - File "", line 1, in - File "C:\Python3\lib\site-packages\cefpython3\__init__.py", line 59, in - from . import cefpython_py36 as cefpython -ImportError: DLL load failed: The specified module could not be found. -``` - -Then most probably this is caused, because you are missing -"msvcp140.dll" dependency (for Python 3.5/3.6 for example). This -is a dependency for Python C++ extensions (eg. cefpython_py36.pyd -depends on it). For Python 3.5/3.6 to fix this download -[Visual C++ Redistributable for VS2015](https://www.microsoft.com/en-us/download/details.aspx?id=52685) -(13 MB) - this is just a VC++ redistributable, not a Visual Studio -package. For 32-bit download "vc_redist.x86.exe" file and for -64-bit download "vc_redist.x64.exe" file. - -Explanation: msvcp140.dll is the DLL for the C++ runtime library. -This dependency is added by Cython when building CEF Python -module. It seems that Python 3.6 only ships "vcruntime140.dll" -which is the DLL for the C runtime library. - -On a side note, when using pyinstaller/py2exe tools for -freezing application into exe then these tools should -automatically detect the msvcp140.dll dependency and ship it -with your application. - -Created [Issue #359](../../../issues/359) to track this problem. - - ## Notifications about new releases / commits To be notified of new releases subscribe to this [RSS/Atom feed](../../../releases.atom). @@ -67,19 +34,15 @@ To be notified on new commits subscribe to this [RSS/Atom feed](../../../commits ## Changes in API after CEF updates CEF Python depends on CEF and API breaks are inevitable when updating -to latest CEF. The [Migration Guide](Migration-guide.md) document which -is still under works, will list most notable breaking changes since -v31 release. Until it's done go to go to the [GitHub Releases](../../../releases) -page and check release notes for all the releases -that appeared between your old version and the new version. Look for -lists named "Changes in API that break backward compatibility" or -similar. - -Due to unavoidable changes in API it is recommended for your setup -scripts that use for example PIP to install the cefpython3 package, +to latest CEF. The [Migration Guide](Migration-guide.md) document +lists most notable breaking changes for each release. Full chanelogs +can be found on [GitHub Releases](../../../releases) pages. + +Due to unavoidable changes in upstream API it is recommended for your setup +scripts, that for example use PIP to install the cefpython3 package, to hardcode the cefpython version string. If for example using PIP's -requirements.txt file then list the cefpython3 package in the -following format: `cefpython3 == 31.2`. +`requirements.txt` file then include the cefpython3 package in the +following format if using e.g. cefpython v57.0: `cefpython3 == 57.0`. ## Differences between Python 2 and Python 3 @@ -89,6 +52,101 @@ they are all unicode strings. Be aware of this when porting cefpython based apps to Python 3, as it may cause issues. +## How to enable debug information in examples? + +You can pass "--debug" command line flag to any of CEF Python +examples and unit tests. It will also work with your app, as +this feature is enabled in CEF Python's core. When this flag is +passed the following settings will be set: +```python +settings = { + "debug": True, + "log_severity": cef.LOGSEVERITY_INFO, + "log_file": "debug.log", +} +cef.Initialize(settings=settings) +``` + +Now you should see debug information displayed in console like this: +``` +[CEF Python] Initialize() called +[CEF Python] CefExecuteProcess(): exitCode = -1 +[CEF Python] CefInitialize() +[CEF Python] App_OnBeforeCommandLineProcessing_BrowserProcess() +[CEF Python] Command line string for the browser process: ... +``` + + +## Remote debugging with Google Chrome instance + +Remote debugging is enabled by default and is configurable using +the ApplicationSettings.[remote_debugging_port](../api/ApplicationSettings.md#remote_debugging_port) option. +When launching app you can see in console log the random port that +was generated: + +``` +DevTools listening on ws://127.0.0.1:63967/devtools/browser/c52ad9ad-bf40-47d1-b2d1-be392d536a2b +``` + +You can debug remotely in two ways: + +1. Debug with CEF devtools. Open the `http://127.0.0.1:port` url + (replace port with e.g. 63967 in our case) in a Google Chrome + browser. You will see a list of CEF browser instances running + which you can debug with DevTools. + This way of debugging has the same sets of features as opening DevTools + popup via `Browser.ShowDevTools` method or using the "Show DevTools" + option from mouse context menu in a CEF app. CEF DevTools has some + limits, not all features of Google Chrome DevTools do work. There + is another way to remotely debug that can workaround these limits, + see the point 2 below. + +2. If some features don't work when debugging with CEF devtools you can + use dedicated DevTools for Node in Google Chrome browser. For example + as of CEF v70 the devtools feature "Save as HAR file" doesn't work, + however it works with dedicated DevTools for Node. Follow these steps + to use dedicated DevTools for Node with CEF: + + 1. In Google Chrome browser open `chrome://inspect` url and click + "Open dedicated DevTools for Node" + 2. Add `localhost:1234` connection and close the popup window + 3. Set `ApplicationSettings.remote_debugging_port` to `1234` and + run your app + 4. Refresh the `chrome://inspect` page in Google Chrome browser + 5. You should see a new target on the Remote Target list. Click + "inspect" link for this target. + + +## Debugging using various chrome:// protocol uris + +The `chrome://` protocol uris give you access to various debugging +tools. For example if you encounter GPU issues then after the issue +occured load the `chrome://gpu` to see a list of errors. + +Here is a list of supported `chrome://` protocol uris as of v55.2: +- chrome://accessibility +- chrome://appcache-internals +- chrome://blob-internals +- chrome://credits +- chrome://gpu +- chrome://histograms +- chrome://indexeddb-internals +- chrome://license +- chrome://media-internals +- chrome://net-export +- chrome://net-internals +- chrome://network-error +- chrome://network-errors +- chrome://resources +- chrome://serviceworker-internals +- chrome://system +- chrome://tracing +- chrome://version +- chrome://view-http-cache +- chrome://webrtc-internals +- chrome://webui-hosts + + ## A blank window on Mac/Linux A blank window might appear when your Python does not support @@ -214,31 +272,6 @@ appear even after disabling GPU hardware acceleration. This is normal because GPU was disabled so WebGL cannot work. -## How to enable debug information in examples? - -You can pass "--debug" command line flag to any of CEF Python -examples and unit tests. It will also work with your app, as -this feature is enabled in CEF Python's core. When this flag is -passed the following settings will be set: -```python -settings = { - "debug": True, - "log_severity": cef.LOGSEVERITY_INFO, - "log_file": "debug.log", -} -cef.Initialize(settings=settings) -``` - -Now you should see debug information displayed in console like this: -``` -[CEF Python] Initialize() called -[CEF Python] CefExecuteProcess(): exitCode = -1 -[CEF Python] CefInitialize() -[CEF Python] App_OnBeforeCommandLineProcessing_BrowserProcess() -[CEF Python] Command line string for the browser process: ... -``` - - ## Python crashes with "Segmentation fault" - how to debug? Install gdb: diff --git a/docs/Migration-guide.md b/docs/Migration-guide.md index ae06f835d..5ad3d4384 100644 --- a/docs/Migration-guide.md +++ b/docs/Migration-guide.md @@ -15,31 +15,46 @@ in your application. Table of contents: -* [v50+ Distribution packages](#v50-distribution-packages) +* [v49+ Distribution packages](#v49-distribution-packages) +* [v49+ cefbuilds.com is deprected, use Spotify Automated CEF Builds](#v49-cefbuildscom-is-deprected-use-spotify-automated-cef-builds) +* [v49+ Build instructions and build tools](#v49-build-instructions-and-build-tools) +* [v49: GPU acceleration should be disabled on Windows XP](#v49-gpu-acceleration-should-be-disabled-on-windows-xp) +* [v49 (Win) Handlers' callbacks and other interfaces](#v49-win-handlers-callbacks-and-other-interfaces) +* [v49+ High DPI support on Windows](#v49-high-dpi-support-on-windows) +* [v49 (Win) Do not call the 'WindowUtils.OnSize' function](#v49-win-do-not-call-the-windowutilsonsize-function) +* [v49+ Notify CEF on move or resize events](#v49-notify-cef-on-move-or-resize-events) +* [v49+ Flash support](#v49-flash-support) +* [v49+ Off-screen-rendering: new option "windowless_rendering_enabled"](#v49-off-screen-rendering-new-option-windowless_rendering_enabled) +* [v49+ BrowserSettings options removed](#v49-browsersettings-options-removed) +* [v49+ cef.Request.Flags changed](#v49-cefrequestflags-changed) +* [v49+ Request.GetHeaderMap and SetHeaderMap change](#v49-requestgetheadermap-and-setheadermap-change) +* [v49+ (Win) HTTPS cache problems on pages with certificate errors](#v49-win-https-cache-problems-on-pages-with-certificate-errors) * [v50+ Importing the cefpython3 package on Linux](#v50-importing-the-cefpython3-package-on-linux) * [v50+ Install X11 error handlers on Linux](#v50-install-x11-error-handlers-on-linux) * [v50+ Set window bounds on Linux](#v50-set-window-bounds-on-linux) -* [v50+ Notify CEF on move or resize events](#v50-notify-cef-on-move-or-resize-events) * [v50+ Keyboard focus issues on Linux](#v50-keyboard-focus-issues-on-linux) * [v50+ Windows XP and Vista are no more supported](#v50-windows-xp-and-vista-are-no-more-supported) * [v50+ Mac 32-bit is no more supported](#v50-mac-32-bit-is-no-more-supported) -* [v50+ cefbuilds.com is deprected, use Spotify Automated CEF Builds](#v50-cefbuildscom-is-deprected-use-spotify-automated-cef-builds) -* [v50+ Build instructions and build tools](#v50-build-instructions-and-build-tools) -* [v51+ Off-screen-rendering: new option "windowless_rendering_enabled"](#v51-off-screen-rendering-new-option-windowless_rendering_enabled) * [v51+ Remove LifespanHandler.RunModal](#v51-remove-lifespanhandlerrunmodal) -* [v51+ BrowserSettings options removed](#v51-browsersettings-options-removed) -* [v51+ cef.Request.Flags changed](#v51-cefrequestflags-changed) -* [v51+ Request.GetHeaderMap and SetHeaderMap change](#v51-requestgetheadermap-and-setheadermap-change) -* [v54+ GTK 3 example doesn't work anymore on Linux](#v54-gtk-3-example-doesnt-work-anymore-on-linux) * [v54+ libcef.so library is stripped from symbols on Linux](#v54-libcefso-library-is-stripped-from-symbols-on-linux) -* [v55+ HTTPS cache problems on pages with certificate errors](#v55-https-cache-problems-on-pages-with-certificate-errors) * [v55.3+ Handlers' callbacks and other interfaces](#v553-handlers-callbacks-and-other-interfaces) * [v56+ MacOS 10.9+ required to run](#v56-macos-109-required-to-run) * [v57.1+ High DPI support on Windows](#v571-high-dpi-support-on-windows) - - - -## v50+ Distribution packages +* [v66+ Linux patch that fixed HTTPS cache problems on pages with certificate errors was disabled](#v66-linux-patch-that-fixed-https-cache-problems-on-pages-with-certificate-errors-was-disabled) +* [v66+ DisplayHandler.OnConsoleMessage has a new param 'level'](#v66-displayhandleronconsolemessage-has-a-new-param-level) +* [v66+ LifespanHandler.OnBeforePopup is now called on UI thread](#v66-lifespanhandleronbeforepopup-is-now-called-on-ui-thread) +* [v66+ RequestHandler.OnBeforeBrowse has a new param 'user_gesture'](#v66-requesthandleronbeforebrowse-has-a-new-param-user_gesture) +* [v66+ Window transparency changes](#v66-window-transparency-changes) +* [v66+ BrowserSettings.javascript_open_windows_disallowed option was removed](#v66-browsersettingsjavascript_open_windows_disallowed-option-was-removed) +* [v66+ Threads removed: TID_DB, TID_PROCESS_LAUNCHER, TID_CACHE](#v66-threads-removed-tid_db-tid_process_launcher-tid_cache) +* [v66+ cef.Request.Flags changed](#v66-cefrequestflags-changed) +* [v66+ RequestHandler.GetCookieManager not getting called in some cases](#v66-requesthandlergetcookiemanager-not-getting-called-in-some-cases) +* [v66+ Changes to Mac apps that integrate into existing message loop (Qt, wxPython)](#v66-changes-to-mac-apps-that-integrate-into-existing-message-loop-qt-wxpython) +* [v66.1+ Navigation urls passed to CreateBrowserSync or LoadUrl methods need to be encoded by app code](#v661-navigation-urls-passed-to-createbrowsersync-or-loadurl-methods-need-to-be-encoded-by-app-code) +* [v67+ Do not call the 'WindowUtils.OnSize' function](#v67-do-not-call-the-windowutilsonsize-function) + + +## v49+ Distribution packages In latest CEF Python there is only one distribution package available: a wheel package. Wheel packages are distributed on @@ -67,120 +82,135 @@ in an automated manner, it might be reconsidered in the future to provide debian packages again. -## v50+ Importing the cefpython3 package on Linux +## v49+ cefbuilds.com is deprected, use Spotify Automated CEF Builds -In the past on Linux it was required for the cefpython3 package -to be imported before any other packages due to tcmalloc global -hook being loaded. This is not required anymore, tcmalloc is -disabled by default. +The cefbuilds.com site with CEF prebuilt binaries is now deprecated. +From now on download prebuilt CEF binaries from the Spotify Automated +CEF Builds: +http://opensource.spotify.com/cefbuilds/index.html -## v50+ Install X11 error handlers on Linux -It is required to install X11 error handlers on Linux, otherwise -you will see 'BadWindow' errors happening - sometimes randomly - -which will cause application to terminate. Since v56+ x11 error -handlers are installed automatically by default during the call -to cef.Initialize(). However sometimes that is not enough like -for example in the wxpython.py example which requires the x11 -error handlers to be installed manually after wx was initialized, -and that is because wx initialization had reset x11 error handlers -that were installed earlier during cef initialization (Issue [#334](../../../issues/334)). +## v49+ Build instructions and build tools -You can install X11 error handlers by calling: -``` -WindowUtils = cef.WindowUtils() -WindowUtils.InstallX11ErrorHandlers() -``` +There were many changes in regards to building CEF and CEF Python. +There are now new tools in the tools/ root directory that fully +automate building CEF and CEF Python. CEF Python now provides +upstream CEF prebuilt binaries and libraries on GitHub Releases +tagged eg. "v49-upstream". With these binaries you can build +CEF Python from sources in less than 10 minutes. See the new +[Build instructions](Build-instructions.md) document. -API ref: WindowUtils.[InstallX11ErrorHandlers()](../api/WindowUtils.md#installx11errorhandlers-linux) +## v49: GPU acceleration should be disabled on Windows XP -## v50+ Set window bounds on Linux +On XP you should disable GPU acceleration by setting the `--disable-gpu` +and `--disable-gpu-compositing` switches. These switches can +be passed programmatically to `cef.Initialize`, see +[api/Command Line Switches](../api/CommandLineSwitches.md). -It is now required to set window bounds during window "resize", -"move" and "configure" events on Linux. You can do so by calling: -``` -browser.SetBounds(x, y, width, height) -``` +## v49 (Win) Handlers' callbacks and other interfaces -API ref: Browser.[SetBounds()](../api/Browser.md#setbounds) +In v49.0 release for Windows all handlers' +callbacks and other interfaces such as +CookieVisitor, StringVisitor and WebRequestClient, are now called +using keyword arguments (Issue [#291](../../../issues/291)). +This will cause many of existing code to break. This is how you +should declare callbacks using the new style: +``` +def OnLoadStart(self, browser, **_): + pass -## v50+ Notify CEF on move or resize events +def OnLoadStart(self, **kwargs): + browser = kwargs["browser"] +``` -It is required to notify the browser on move or resize events -so that popup widgets (e.g. \) are displayed in the correct -location and dismissed when the window moves. Also so that -drag & drop areas are updated accordingly. +In the first declaration you see that only one argument is +declared, the browser, the others unused will be in the "_" +variable (the name of the variable is so that PyCharm doesn't +warn about unused variable). + +Even if you specify and use all arguments, always add the +unused kwargs (`**_`) at the end: ``` -browser.NotifyMoveOrResizeStarted() +def OnLoadStart(self, browser, frame, **_): + pass ``` -API ref: Browser.[NotifyMoveOrResizeStarted()](../api/Browser.md#notifymoveorresizestarted) - +This will be handy in the future, in a case when upstream CEF +adds a new argument to the API, your code won't break. When +an argument is removed in upstream CEF API, if it's possible +CEF Python will try to keep backward compatibility by +emulating behavior of the old argument. -## v50+ Keyboard focus issues on Linux +In case of OnLoadStart, when you've used "browser" and "frame" +names for the arguments, your code won't break. However in +many other callbacks, where you've used argument names that +differed from how they were named in API docs, your code will +break. Also argument names were changed from camelCase +to underscores. For example the OnLoadEnd callback has renamed +the `httpStatusCode` argument to `http_code`. So in this case +your code will definitely break, unless you've also used +"http_code" for argument name. -There several keyboard focus issues on Linux since CEF library -replaced GTK library with X11 library. Most of these issues are -fixed in examples by calling SetFocus in LoadHandler.OnLoadStart -during initial app loading and/or by calling SetFocus in -FocusHandler.OnGotFocus. This keyboard focus issues need to be -fixed in usptream CEF. For more details see Issue [#284](../../../issues/284). +## v49+ High DPI support on Windows -## v50+ Windows XP and Vista are no more supported +It is recommended to embed a DPI awareness manifest in both the main +process and the subprocesses (the subprocess.exe executable) instead +of calling `DpiAware`.[SetProcessDpiAware](../api/DpiAware.md#setprocessdpiaware) +which sets DPI awareness only for the main process. -CEF Python v31.2 was the last version to support Windows XP. -This is due to Chromium/CEF dropping XP support, last version -that supported XP was CEF v49. +The `ApplicationSettings`.[auto_zooming](../api/ApplicationSettings.md#auto_zooming) +option has a default value of an empty string now. Previously the +default was "system_dpi". When enabling High DPI support you should +set it to "system_dpi" explicitilly. +Note that `DpiAware`.[CalculateWindowSize](../api/DpiAware.md#calculatewindowsize) +does not handle all DPI settings (e.g. 132% on Windows 10). +In newer CEF Python there is available `DpiAware`[Scale](../api/DpiAware.md#scale) +which is more reliable and can handle all DPI resolutions. You can copy see +its implementation in `src/dpi_aware_win.pyx`. -## v50+ Mac 32-bit is no more supported -CEF Python v31.2 was the last version to support Mac 32-bit. -This is due to CEF/Chromium dropping 32-bit support, last version -that supported 32-bit was CEF v38. +## v49 (Win) Do not call the 'WindowUtils.OnSize' function +This function can sometimes cause app hanging during window resize. +Call instead the new `WindowUtils`.[UpdateBrowserSize](../api/WindowUtils.md#updatebrowsersize) +function. Except when you use the `pywin32.py` example, in such case +`WindowUtils.OnSize` must be called. +See [Issue #464](../../../issues/464) for more details. -## v50+ cefbuilds.com is deprected, use Spotify Automated CEF Builds -The cefbuilds.com site with CEF prebuilt binaries is now deprecated. -From now on download prebuilt CEF binaries from the Spotify Automated -CEF Builds: +## v49+ Notify CEF on move or resize events -http://opensource.spotify.com/cefbuilds/index.html +It is required to notify the browser on move or resize events +so that popup widgets (e.g. \) are displayed in the correct +location and dismissed when the window moves. Also so that +drag & drop areas are updated accordingly. Call +Browser.[NotifyMoveOrResizeStarted()](../api/Browser.md#notifymoveorresizestarted) +during a move or resize event in your app window. -## v50+ Build instructions and build tools +## v49+ Flash support -There were many changes in regards to building CEF and CEF Python. -There are now new tools in the tools/ root directory that fully -automate building CEF and CEF Python. CEF Python now provides -upstream CEF prebuilt binaries and libraries on GitHub Releases -tagged eg. "v56-upstream". With these binaries you can build -CEF Python from sources in less than 10 minutes. See the new -[Build instructions](Build-instructions.md) document. +See [Issue #235](../../../issues/235) ("Flash support in CEF v49+") +for instructions on how to enable Flash. -## v51+ Off-screen-rendering: new option "windowless_rendering_enabled" +## v49+ Off-screen-rendering: new option "windowless_rendering_enabled" When using off-screen-rendering you must set the ApplicationSettings "windowless_rendering_enabled" option to True. This applies to -examples such as: Kivy, Panda3D and screenshot example. +examples such as: Kivy, Panda3D, PySDL2 and screenshot example. API ref: ApplicationSettings.[windowless_rendering_enabled](../api/ApplicationSettings.md#windowless_rendering_enabled) -## v51+ Remove LifespanHandler.RunModal - -LifespanHandler.RunModal callback is no more available. - - -## v51+ BrowserSettings options removed +## v49+ BrowserSettings options removed The following options were removed from BrowserSettings: - user_style_sheet_location @@ -189,7 +219,7 @@ The following options were removed from BrowserSettings: - author_and_user_styles_disabled -## v51+ cef.Request.Flags changed +## v49+ cef.Request.Flags changed The following flags were removed from cef.Request.Flags: - AllowCookies @@ -199,7 +229,7 @@ The following flags were removed from cef.Request.Flags: API ref: Request.[GetFlags](../api/Request.md#getflags) -## v51+ Request.GetHeaderMap and SetHeaderMap change +## v49+ Request.GetHeaderMap and SetHeaderMap change GetHeaderMap() will not include the Referer value if any and SetHeaderMap() will ignore the Referer value. @@ -207,30 +237,90 @@ and SetHeaderMap() will ignore the Referer value. API ref: Request.[GetHeaderMap](../api/Request.md#getheadermap) -## v54+ GTK 3 example doesn't work anymore on Linux +## v49+ (Win) HTTPS cache problems on pages with certificate errors -Currently GTK 3 example is broken on Linux. You can either -downgrade to an old cefpython v53 (available on GitHub release -page) or use GTK 2 example. For more details on the problem see -Issue [#261](../../../issues/261). +The fix for HTTPS cache problems on pages with certificate errors +(and that includes self-signed certificates) is no more applied +on Windows. +See Issue [#125](../../../issues/125) for more details. -## v54+ libcef.so library is stripped from symbols on Linux -Symbols useful for debugging are no more available in libcef.so -shipped with distribution packages on Linux. This is explained -in details in Issue [#262](../../../issues/262). +## v50+ Importing the cefpython3 package on Linux +In the past on Linux it was required for the cefpython3 package +to be imported before any other packages due to tcmalloc global +hook being loaded. This is not required anymore, tcmalloc is +disabled by default. -## v55+ HTTPS cache problems on pages with certificate errors -The fix for HTTPS cache problems on pages with certificate errors -is no more applied on Windows. +## v50+ Install X11 error handlers on Linux -Soon this will fix also won't be applied on Linux anymore when -cefpython starts using CEF prebuilt binaries from Spotify. +It is required to install X11 error handlers on Linux, otherwise +you will see 'BadWindow' errors happening - sometimes randomly - +which will cause application to terminate. Since v56+ x11 error +handlers are installed automatically by default during the call +to cef.Initialize(). However sometimes that is not enough like +for example in the wxpython.py example which requires the x11 +error handlers to be installed manually after wx was initialized, +and that is because wx initialization had reset x11 error handlers +that were installed earlier during cef initialization (Issue [#334](../../../issues/334)). + +You can install X11 error handlers by calling: +``` +WindowUtils = cef.WindowUtils() +WindowUtils.InstallX11ErrorHandlers() +``` + +API ref: WindowUtils.[InstallX11ErrorHandlers()](../api/WindowUtils.md#installx11errorhandlers-linux) + + +## v50+ Set window bounds on Linux + +It is now required to set window bounds during window "resize", +"move" and "configure" events on Linux. You can do so by calling: + +``` +browser.SetBounds(x, y, width, height) +``` + +API ref: Browser.[SetBounds()](../api/Browser.md#setbounds) -See Issue [#125](../../../issues/125) for more details. + +## v50+ Keyboard focus issues on Linux + +There several keyboard focus issues on Linux since CEF library +replaced GTK library with X11 library. Most of these issues are +fixed in examples by calling SetFocus in LoadHandler.OnLoadStart +during initial app loading and/or by calling SetFocus in +FocusHandler.OnGotFocus. This keyboard focus issues need to be +fixed in usptream CEF. For more details see Issue [#284](../../../issues/284). + + +## v50+ Windows XP and Vista are no more supported + +CEF Python v49.0 was the last version to support Windows XP. +This is due to Chromium/CEF dropping XP support, last version +that supported XP was CEF v49. + + +## v50+ Mac 32-bit is no more supported + +CEF Python v31.2 was the last version to support Mac 32-bit. +This is due to CEF/Chromium dropping 32-bit support, last version +that supported 32-bit was CEF v38. + + +## v51+ Remove LifespanHandler.RunModal + +LifespanHandler.RunModal callback is no more available. + + +## v54+ libcef.so library is stripped from symbols on Linux + +Symbols useful for debugging are no more available in libcef.so +shipped with distribution packages on Linux. This is explained +in details in Issue [#262](../../../issues/262). ## v55.3+ Handlers' callbacks and other interfaces @@ -295,3 +385,124 @@ option should have its value set to an empty string (a default now) for High DPI support. In previous versions the default value was "system_dpi" and if you have set it explicitilly in your application, then you should change it to an empty string now. + + +## v66+ Linux patch that fixed HTTPS cache problems on pages with certificate errors was disabled + +That patch allowed for HTTPS caching to work when using self-signed +certificates (or any invalid certificate). This doesn't work anymore. +If you need this feature then you can build from sources and apply +the patch yourself. See Issue [#125](../../../issues/125) for more details. + + +## v66+ DisplayHandler.OnConsoleMessage has a new param 'level' + +The DisplayHandler.[OnConsoleMessage](../api/DisplayHandler.md#onconsolemessage) +callback has a new param `level`. + + +## v66+ LifespanHandler.OnBeforePopup is now called on UI thread + +The LifespanHandler.[OnBeforePopup](../api/LifespanHandler.md#onbeforepopup) +callback is now called on UI thread. Previously it was called on +IO thread. + + +## v66+ RequestHandler.OnBeforeBrowse has a new param 'user_gesture' + +The RequestHandler.[OnBeforeBrowse](../api/RequestHandler.md#onbeforebrowse) +callback has a new param `user_gesture`. + + +## v66+ Window transparency changes + +1. OSR windows (off-screen rendering, also known as windowless) are now +transparent by default. You can control its transperency with +ApplicationSettings.[background_color](../api/ApplicationSettings.md#background_color) and BrowserSettings.[background_color](../api/BrowserSettings.md#background_color) options. +The WindowInfo.`SetTransparentPainting` method is now deprecated. Calling +it with True will do nothing, and calling it with False **will result +in exception**. + +2. It is now possible to have +transparent windows also in **windowed mode**. This seems to be working +only on Linux (got it working on Fedora with just a change in window setting). + + +## v66+ BrowserSettings.javascript_open_windows_disallowed option was removed + +The BrowserSettings.`javascript_open_windows_disallowed` option was removed +(setting it will do nothing). + + +## v66+ Threads removed: TID_DB, TID_PROCESS_LAUNCHER, TID_CACHE + +These threads and their corresponding constants in the cefpython module +were removed: TID_DB, TID_PROCESS_LAUNCHER, TID_CACHE. + +New threads were added, see cefpython.[PostTask](../api/cefpython.md#posttask) +description for a complete list of threads. + + +## v66+ cef.Request.Flags changed + +Flags removed: +- AllowCachedCredentials + +Flags added: +- OnlyFromCache +- AllowStoredCredentials +- StopOnRedirect + +See a complete list of flags in the description of +cef.Request.[GetFlags](../api/Request.md#getflags) method. + + +## v66+ RequestHandler.GetCookieManager not getting called in some cases + +In some cases the RequestHandler.[GetCookieManager](../api/RequestHandler.md#getcookiemanager) +callback is not getting called due to a race condition. +This bug is to be fixed in Issue [#429](../../../issues/429). + + +## v66+ Changes to Mac apps that integrate into existing message loop (Qt, wxPython) + +These changes are required only on Mac platform. + +In Qt apps calling message loop work in a timer doesn't work anymore. +You have to enable external message pump by setting +ApplicationSettings.[external_message_pump](../api/ApplicationSettings.md#external_message_pump) +to `True`. The `qt.py` example was updated to disable calling +message loop work in a timer. External message pump +is a recommended way over calling message loop work in a timer on Mac, +so this should make Qt apps work smoothly. + +In wxPython apps you have to implement both approaches for +integrating with existing message loop at the same time: +1. Call `cef.MessageLoopWork` in a 10ms timer +2. Set `ApplicationSettings.external_message_pump` to True + +This is not a correct approach and is only a temporary fix for wxPython +apps. More testing is required to check if that resolves all the issues +with message loop freezing. Only basic testing was performed. It was not +tested of how this change affects performance. + +See Issue [#442](../../../issues/442) for more details on the issues. + +## v66.1+ Navigation urls passed to CreateBrowserSync or LoadUrl methods need to be encoded by app code + +[Issue #384](../../../issues/384) fixes problems with browser failing to load +urls containing certain characters by not encoding the url anymore. From now +on it is required for the app code to encode the url properly. You can use +the `pathlib.PurePath.as_uri` in Python 3 or `urllib.pathname2url` in +Python 2 (`urllib.request.pathname2url` in Python 3) depending on your case. + +The `cef.GetNavigateUrl` function was removed from the cefpython3 module. + + +## v67+ Do not call the 'WindowUtils.OnSize' function + +This function can sometimes cause app hanging during window resize. +Call instead the new `WindowUtils`.[UpdateBrowserSize](../api/WindowUtils.md#updatebrowsersize) +function. Except when you use the `pywin32.py` example, in such case +`WindowUtils.OnSize` must be called. +See [Issue #464](../../../issues/464) for more details. \ No newline at end of file diff --git a/docs/Tutorial.md b/docs/Tutorial.md index 40a1da385..11cf5db71 100644 --- a/docs/Tutorial.md +++ b/docs/Tutorial.md @@ -9,7 +9,8 @@ basics. This tutorial will discuss the three featured examples: [hello_world.py](../examples/hello_world.py), [tutorial.py](../examples/tutorial.py) and [screenshot.py](../examples/screenshot.py). There are many -more examples that you can find in the [README-examples.md](../examples/README-examples.md) +more examples that you can find in the +[README-examples.md](../examples/README-examples.md) file, but these examples are out of scope for this tutorial. @@ -39,7 +40,7 @@ Run the commands below to install the cefpython3 package, clone the repository and run the Hello World example: ```commandline -pip install cefpython3==57.0 +pip install cefpython3==66.0 git clone https://github.com/cztomczak/cefpython.git cd cefpython/examples/ python hello_world.py @@ -68,10 +69,10 @@ Google website. Let's analyze the code from that example: 1. `from cefpython3 import cefpython as cef` - Import the cefpython module and make a short "cef" alias 2. `sys.excepthook = cef.ExceptHook` - Overwrite Python's default - exception handler so that all CEF sub-processes are terminated - when Python exception occurs. To understand this better read the - "Architecture" and "Handling Python exceptions" sections - further down in this Tutorial. + exception handler so that all CEF sub-processes are reliably + terminated when Python exception occurs. To understand this + better read the "Architecture" and "Handling Python exceptions" + sections further down in this Tutorial. 3. `cef.Initialize()` - Initialize CEF. This function must be called somewhere in the beginning of your code. It must be called before any application window is created. It must be called only once @@ -139,9 +140,9 @@ special handling. When Python exception occurs then main process is terminated. For CEF this means that the Browser process is terminated, however there may still be running CEF sub-processes like Renderer process, GPU process, etc. To terminate these -sub-processes cef.[Shutdown](../api/cefpython.md#shutdown) +sub-processes cleanly cef.[Shutdown](../api/cefpython.md#shutdown) must be called and if running CEF message loop then it must be -stopped first. In all CEF Python examples you can find such +stopped first. In most of CEF Python examples you can find such a line that overwrites the default exception handler in Python: ```python @@ -159,7 +160,8 @@ The cef.ExceptHook helper function does the following: which exits the process with status 1, without calling cleanup handlers, flushing stdio buffers, etc. -See CEF Python's ExceptHook source code in src/[helpers.pyx](../src/helpers.pyx). +If you would like to modify `ExceptHook` behavior, see its source code +in src/[helpers.pyx](../src/helpers.pyx) file. ## Settings @@ -260,7 +262,7 @@ MyProduct/10.00 Safari/537.36 ``` To change the whole user agent string use the "user_agent" -option. For example set it to "MyApp/40.00 MyProduct/10.00" +option. For example set it to "MyAgent/20.00 MyProduct/10.00" and both User-Agent HTTP header and js navigator.userAgent will be: ```text @@ -409,7 +411,8 @@ html_to_data_uri("test", js_callback_1); Python and Javascript can also communicate using http requests by running an internal web-server. See for example [SimpleHTTPServer](https://docs.python.org/2/library/simplehttpserver.html) -in Python docs. +in Python docs. In upstream CEF there is available a fast built-in +web server and [Issue #445](../../../issues/445) is to expose its API. With http requests it is possible for synchronous communication from Javascript to Python by performing @@ -431,18 +434,15 @@ however these APIs were not yet exposed to CEF Python. ## Javascript exceptions and Python exceptions -There are cases when executing Javascript code may end up with -Python exception being thrown: +When a Python function is invoked from Javascript and it fails, +a Python exception will be thrown. When Python executes a Javascript +callback and it fails, a Javascript exception will be thrown. -1. When a Python function is invoked from Javascript and it fails, - a Python exception will be thrown -2. When Python executes a Javascript callback and it fails, - a Python exception will be thrown - -In other cases to see Javascript exceptions open Developer Tools +To see Javascript exceptions open Developer Tools window using mouse context menu and switch to Console tab. -There are multiple ways to catch/intercept javascript exceptions: +There are multiple ways to intercept javascript exceptions programmaticaly +in CEF: 1. In Javascript you can register "window.onerror" event to catch all Javascript exceptions @@ -683,6 +683,7 @@ official examples are provided for these. See the following issues in the tracker for all available packagers: * cx_Freeze - see [Issue #338](../../../issues/338) +* Cython - see [Issue #407](../../../issues/407) * py2exe - see [Issue #35](../../../issues/35) * py2app - see [Issue #337](../../../issues/337) * Nuitka - see [Issue #396](../../../issues/396) diff --git a/examples/README-examples.md b/examples/README-examples.md index 8b50f1f8d..ec2f9bcd3 100644 --- a/examples/README-examples.md +++ b/examples/README-examples.md @@ -3,7 +3,13 @@ Table of contents: * [Hello World!](#hello-world) * [Supported examples](#supported-examples) -* [More examples](#more-examples) + * [Featured](#featured) + * [Snippets](#snippets) + * [GUI frameworks](#gui-frameworks) + * [Build executable with PyInstaller](#build-executable-with-pyinstaller) + * [Unit tests](#unit-tests) +* [Other examples](#other-examples) +* [More examples to come](#more-examples-to-come) ## Hello World! @@ -11,7 +17,7 @@ Instructions to install the cefpython3 package, clone the repository and run the hello_world.py example: ``` -pip install cefpython3==57.0 +pip install cefpython3==66.0 git clone https://github.com/cztomczak/cefpython.git cd cefpython/examples/ python hello_world.py @@ -26,7 +32,7 @@ in sources to see whether this is a known issue with available workarounds. -**Featured** +### Featured - [hello_world.py](hello_world.py) - Basic example, doesn't require any third party GUI framework to run @@ -37,43 +43,57 @@ workarounds. section. -**Embedding using various GUI frameworks** +### Snippets + +For small code snippets that show various CEF features and are easy to +understand see the [README-snippets.md](snippets/README-snippets.md) +document. + + +### GUI frameworks + +Examples of embedding CEF browser using various GUI frameworks: - [gtk2.py](gtk2.py): example for [PyGTK](http://www.pygtk.org/) library (GTK 2) - [gtk3.py](gtk3.py): example for [PyGObject / PyGI](https://wiki.gnome.org/Projects/PyGObject) library (GTK 3). Currently broken on Mac ([#310](../../../issues/310)). - [pysdl2.py](pysdl2.py): off-screen rendering example for - [PySDL2](https://github.com/marcusva/py-sdl2) library. Currently tested - only on Linux. + [PySDL2](https://github.com/marcusva/py-sdl2) library. Example has some + issues that are reported in Issue [#324](../../../issues/324). - [pywin32.py](pywin32.py): example for [pywin32](https://github.com/mhammond/pywin32) library - [qt.py](qt.py): example for [PyQt4](https://wiki.python.org/moin/PyQt4), [PyQt5](https://pypi.python.org/pypi/PyQt5) - and [PySide](https://wiki.qt.io/PySide) libraries + and [PySide](https://wiki.qt.io/PySide) libraries. + PyQt4 and PySide examples are currently broken on Linux, see + [Issue #452](../../../issues/452). - [tkinter_.py](tkinter_.py): example for [Tkinter](https://wiki.python.org/moin/TkInter). Currently broken on Mac ([#309](../../../issues/309)). - [wxpython.py](wxpython.py): example for [wxPython](https://wxpython.org/) - toolkit + toolkit. This example implements High DPI support on Windows. -**Build executable using Python packagers** +### Build executable with PyInstaller - [PyInstaller example](pyinstaller/README-pyinstaller.md): example of packaging app using [PyInstaller](http://www.pyinstaller.org/) - packager + packager. Currently this example supports only Windows platform. -**Unit tests** +### Unit tests There are also available unit tests and its usage of the API can -be of some use. See [main_test.py](../unittests/main_test.py). +be of some use. See: +- [main_test.py](../unittests/main_test.py) - windowed rendering general tests +- [osr_test.py](../unittests/osr_test.py) - off-screen rendering tests -## More examples +## Other examples -There are even more examples available, some of them are externally -maintained. +There are even more examples available, they do not reside in the examples/ +directory. Some of them were created for old verions of CEF and were not +yet ported to latest CEF. Some of them are externally maintained. - Kivy framework: see [Kivy](https://github.com/cztomczak/cefpython/wiki/Kivy) wiki page. @@ -87,7 +107,39 @@ maintained. for reading/modifying web requests: see the [wxpython-response.py](https://github.com/cztomczak/cefpython/blob/cefpython31/cefpython/cef3/linux/binaries_64bit/wxpython-response.py) example in the cefpython31 branch. - Example of using Python network library (urllib3/openssl) instead of Chromium's - network library - see [gist by Massimiliano Dal Cero](https://gist.github.com/yattamax/0252a3c5dc54a2f81650d5c0eafabf99) - -There are ongoing efforts to add these examples to the official examples/ -directory, see issues in the tracker. + network library - see [gist by Massimiliano Dal Cero](https://gist.github.com/cztomczak/83b77cbdda03ccef81e22e8bd36a51f6) +- Example of passing exceptions from Python to Javascript and using await syntax to receive values from python return values - see [Managed python calls example by Elliot Woods](https://github.com/elliotwoods/cefpython-tests/tree/0180b22eac10a1bde08820ca192fdc30eb93f00d/6.%20Managed%20python%20calls) + +## More examples to come + +Here is a list of issues in the tracker to create or upgrade examples: + +- [Issue #323](../../../issues/323) - "Create cocos2d example" +- [Issue #322](../../../issues/322) - "Create pyglet example" +- [Issue #312](../../../issues/312) - "Easy to use CefBrowser widgets + for many popular GUI toolkits" +- [Issue #301](../../../issues/301) - "Fix cefpython3.wx package to work + with latest v55+" +- [Issue #289](../../../issues/289) - "Pygame / PyOpenGL example" +- [Issue #288](../../../issues/288) - "Create panda3d_.py example" +- [Issue #285](../../../issues/285) - "[kivy_.py] Refactor example, make + it work cross-platform and move it + to examples/" +- [Issue #252](../../../issues/252) - "Use CEF views in Hello World, Tutorial + and Offscreen examples, and in Unit + tests" +- [Issue #224](../../../issues/224) - "Port CEF 1 examples to CEF 3" +- [Issue #109](../../../issues/109) - "The ResourceHandler example" + +Packaging examples: + +- [Issue #407](../../../issues/407) - "Example of packaging app using + Cython compiler" +- [Issue #396](../../../issues/396) - "Example of packaging app using + Nuitka compiler" +- [Issue #338](../../../issues/338) - "Example of packaging app using + cx_Freeze" +- [Issue #337](../../../issues/337) - "Example of packaging app using + py2app" +- [Issue #135](../../../issues/135) - "Example of packaging app using + pyinstaller" diff --git a/examples/hello_world.py b/examples/hello_world.py index 0157267f5..789f4666e 100644 --- a/examples/hello_world.py +++ b/examples/hello_world.py @@ -1,5 +1,12 @@ # Hello world example. Doesn't depend on any third party GUI framework. -# Tested with CEF Python v55.3+. +# Tested with CEF Python v57.0+. +# +# ==== High DPI support on Windows ==== +# To enable DPI awareness on Windows you have to either embed DPI aware manifest +# in your executable created with pyinstaller or change python.exe properties manually: +# Compatibility > High DPI scaling override > Application. +# Setting DPI awareness programmatically via a call to cef.DpiAware.EnableHighDpiSupport +# is problematic in Python, may not work and can cause display glitches. from cefpython3 import cefpython as cef import platform @@ -17,10 +24,14 @@ def main(): def check_versions(): - print("[hello_world.py] CEF Python {ver}".format(ver=cef.__version__)) + ver = cef.GetVersion() + print("[hello_world.py] CEF Python {ver}".format(ver=ver["version"])) + print("[hello_world.py] Chromium {ver}".format(ver=ver["chrome_version"])) + print("[hello_world.py] CEF {ver}".format(ver=ver["cef_version"])) print("[hello_world.py] Python {ver} {arch}".format( - ver=platform.python_version(), arch=platform.architecture()[0])) - assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this" + ver=platform.python_version(), + arch=platform.architecture()[0])) + assert cef.__version__ >= "57.0", "CEF Python v57.0+ required to run this" if __name__ == '__main__': diff --git a/examples/pyinstaller/README-pyinstaller.md b/examples/pyinstaller/README-pyinstaller.md index caf3ff81e..f148bbceb 100644 --- a/examples/pyinstaller/README-pyinstaller.md +++ b/examples/pyinstaller/README-pyinstaller.md @@ -12,10 +12,8 @@ Table of contents: This is an example of using [PyInstaller](http://www.pyinstaller.org/) packager to build executable from one of CEF Python's examples -(wxpython.py). Although this pyinstaller example supports only packaging -on Windows, CEF can be packaged on all platforms without problems, but -this specific packaging example just wasn't tested on other platforms. -Pull requests are welcome. +(wxpython.py). This pyinstaller example supports packaging +on Windows, Linux and Darwin but was mainly tested on Windows platform. To install required packages type: ``` diff --git a/examples/pyinstaller/hook-cefpython3.py b/examples/pyinstaller/hook-cefpython3.py index e36c8ed30..9160f67f9 100644 --- a/examples/pyinstaller/hook-cefpython3.py +++ b/examples/pyinstaller/hook-cefpython3.py @@ -1,6 +1,6 @@ """ This is PyInstaller hook file for CEF Python. This file -helps pyinstaller find CEF Python dependencies that are +helps PyInstaller find CEF Python dependencies that are required to run final executable. See PyInstaller docs for hooks: @@ -13,8 +13,14 @@ import re import sys import PyInstaller -from PyInstaller.utils.hooks import is_module_satisfies +from PyInstaller.utils.hooks import is_module_satisfies, get_package_paths +from PyInstaller.compat import is_win, is_darwin, is_linux from PyInstaller import log as logging +try: + # PyInstaller >= 4.0 doesn't support Python 2.7 + from PyInstaller.compat import is_py2 +except ImportError: + is_py2 = None # Constants CEFPYTHON_MIN_VERSION = "57.0" @@ -24,14 +30,10 @@ # TODO: use this code to work cross-platform: # > from PyInstaller.utils.hooks import get_package_paths # > get_package_paths("cefpython3") -CEFPYTHON3_DIR = os.path.join( - os.path.dirname(sys.executable), - 'Lib', 'site-packages', 'cefpython3') -if platform.system() == "Windows": - CYTHON_MODULE_EXT = ".pyd" -else: - CYTHON_MODULE_EXT = ".so" +CEFPYTHON3_DIR = get_package_paths("cefpython3")[1] + +CYTHON_MODULE_EXT = ".pyd" if is_win else ".so" # Globals logger = logging.getLogger(__name__) @@ -39,9 +41,9 @@ # Functions def check_platforms(): - if platform.system() != "Windows": - raise SystemExit("Error: Currently only Windows platform is " - " supported, see Issue #135.") + if not is_win and not is_darwin and not is_linux: + raise SystemExit("Error: Currently only Windows, Linux and Darwin " + "platforms are supported, see Issue #135.") def check_pyinstaller_version(): @@ -51,7 +53,7 @@ def check_pyinstaller_version(): # Example version string for dev version of pyinstaller: # > 3.3.dev0+g5dc9557c version = PyInstaller.__version__ - match = re.search(r"^\d+\.\d+", version) + match = re.search(r"^\d+\.\d+(\.\d+)?", version) if not (match.group(0) >= PYINSTALLER_MIN_VERSION): raise SystemExit("Error: pyinstaller %s or higher is required" % PYINSTALLER_MIN_VERSION) @@ -97,8 +99,8 @@ def get_excluded_cefpython_modules(): def get_cefpython3_datas(): - """Returning all cefpython binaries as DATAS, because - pyinstaller does strange things and fails if these are + """Returning almost all of cefpython binaries as DATAS (see exception + below), because pyinstaller does strange things and fails if these are returned as BINARIES. It first updates manifest in .dll files: >> Updating manifest in chrome_elf.dll @@ -114,32 +116,70 @@ def get_cefpython3_datas(): as pyinstaller would fail to find binary depdendencies on these files. + One exception is subprocess (subprocess.exe on Windows) executable + file, which is passed to pyinstaller as BINARIES in order to collect + its dependecies. + DATAS are in format: tuple(full_path, dest_subdir). """ ret = list() + if is_win: + cefdatadir = "." + elif is_darwin or is_linux: + cefdatadir = "." + else: + assert False, "Unsupported system {}".format(platform.system()) + # Binaries, licenses and readmes in the cefpython3/ directory for filename in os.listdir(CEFPYTHON3_DIR): # Ignore Cython modules which are already handled by # pyinstaller automatically. - if filename[:-4] in get_cefpython_modules(): + if filename[:-len(CYTHON_MODULE_EXT)] in get_cefpython_modules(): continue + # CEF binaries and datas - if filename[-4:] in [".exe", ".dll", ".so", ".pak", ".dat", ".bin", - ".txt"]\ - or filename in ["License", "subprocess"]: - logger.info("Include cefpython3 data: %s" % filename) - ret.append((os.path.join(CEFPYTHON3_DIR, filename), - "")) - - # The .pak files in cefpython3/locales/ directory - locales_dir = os.path.join(CEFPYTHON3_DIR, "locales") - assert os.path.exists(locales_dir), "locales/ dir not found in cefpython3" - for filename in os.listdir(locales_dir): - logger.info("Include cefpython3 data: %s/%s" % ( - os.path.basename(locales_dir), filename)) - ret.append((os.path.join(locales_dir, filename), - "locales")) + extension = os.path.splitext(filename)[1] + if extension in \ + [".exe", ".dll", ".pak", ".dat", ".bin", ".txt", ".so", ".plist"] \ + or filename.lower().startswith("license"): + logger.info("Include cefpython3 data: {}".format(filename)) + ret.append((os.path.join(CEFPYTHON3_DIR, filename), cefdatadir)) + + if is_darwin: + # "Chromium Embedded Framework.framework/Resources" with subdirectories + # is required. Contain .pak files and locales (each locale in separate + # subdirectory). + resources_subdir = \ + os.path.join("Chromium Embedded Framework.framework", "Resources") + base_path = os.path.join(CEFPYTHON3_DIR, resources_subdir) + assert os.path.exists(base_path), \ + "{} dir not found in cefpython3".format(resources_subdir) + for path, dirs, files in os.walk(base_path): + for file in files: + absolute_file_path = os.path.join(path, file) + dest_path = os.path.relpath(path, CEFPYTHON3_DIR) + ret.append((absolute_file_path, dest_path)) + logger.info("Include cefpython3 data: {}".format(dest_path)) + elif is_win or is_linux: + # The .pak files in cefpython3/locales/ directory + locales_dir = os.path.join(CEFPYTHON3_DIR, "locales") + assert os.path.exists(locales_dir), \ + "locales/ dir not found in cefpython3" + for filename in os.listdir(locales_dir): + logger.info("Include cefpython3 data: {}/{}".format( + os.path.basename(locales_dir), filename)) + ret.append((os.path.join(locales_dir, filename), + os.path.join(cefdatadir, "locales"))) + + # Optional .so/.dll files in cefpython3/swiftshader/ directory + swiftshader_dir = os.path.join(CEFPYTHON3_DIR, "swiftshader") + if os.path.isdir(swiftshader_dir): + for filename in os.listdir(swiftshader_dir): + logger.info("Include cefpython3 data: {}/{}".format( + os.path.basename(swiftshader_dir), filename)) + ret.append((os.path.join(swiftshader_dir, filename), + os.path.join(cefdatadir, "swiftshader"))) return ret @@ -178,7 +218,7 @@ def get_cefpython3_datas(): "urllib", "weakref", ] -if sys.version_info.major == 2: +if is_py2: hiddenimports += [ "urlparse", ] @@ -186,8 +226,13 @@ def get_cefpython3_datas(): # Excluded modules excludedimports = get_excluded_cefpython_modules() -# Include binaries -binaries = [] +# Include binaries requiring to collect its dependencies +if is_darwin or is_linux: + binaries = [(os.path.join(CEFPYTHON3_DIR, "subprocess"), ".")] +elif is_win: + binaries = [(os.path.join(CEFPYTHON3_DIR, "subprocess.exe"), ".")] +else: + binaries = [] # Include datas datas = get_cefpython3_datas() diff --git a/examples/pyinstaller/pyinstaller.py b/examples/pyinstaller/pyinstaller.py index aedc3669e..67bb8934a 100644 --- a/examples/pyinstaller/pyinstaller.py +++ b/examples/pyinstaller/pyinstaller.py @@ -25,13 +25,15 @@ EXE_EXT = ".exe" elif platform.system() == "Darwin": EXE_EXT = ".app" +elif platform.system() == "Linux": + EXE_EXT = "" def main(): # Platforms supported - if platform.system() != "Windows": - raise SystemExit("Error: Only Windows platform is currently " - "supported. See Issue #135 for details.") + if platform.system() not in ["Windows", "Darwin", "Linux"]: + raise SystemExit("Error: Only Windows, Linux and Darwin platforms are " + "currently supported. See Issue #135 for details.") # Make sure nothing is cached from previous build. # Delete the build/ and dist/ directories. diff --git a/examples/pysdl2.py b/examples/pysdl2.py index 2b7aa8cb5..97f9293dc 100644 --- a/examples/pysdl2.py +++ b/examples/pysdl2.py @@ -1,26 +1,44 @@ """ Example of embedding CEF browser using PySDL2 library. -This example is incomplete, see "Missing functionality" section -further down. Pull requests for the missing functionality are welcome. +Requires PySDL2 and SDL2 libraries, see install instructions further +down. + +This example is incomplete and has some issues, see the "Known issues" +section further down. Pull requests with fixes are welcome. + +Usage: + + python pysdl2.py [-v] [-h] [-r {software|hardware}] + + -v turn on debug messages + -r specify hardware (default) or software rendering + -h display help info -Requires PySDL2 and SDL2 libraries. - Tested configurations: -- Fedora 25: SDL2 2.0.5 with PySDL2 0.9.3 +- Windows 7: SDL 2.0.7 and PySDL2 0.9.6 +- Mac 10.9: SDL 2.0.7 and PySDL2 0.9.6 +- Fedora 26: SDL2 2.0.7 with PySDL2 0.9.6 - Ubuntu 14.04: SDL2 with PySDL2 0.9.6 Install instructions: 1. Install SDL libraries for your OS, e.g: + - Windows: Download SDL2.dll from http://www.libsdl.org/download-2.0.php + and put SDL2.dll in C:\Python27\ (where you've installed Python) + - Mac: Install Homebrew from https://brew.sh/ + and then type "brew install sdl2" - Fedora: sudo dnf install SDL2 SDL2_ttf SDL2_image SDL2_gfx SDL2_mixer - Ubuntu: sudo apt-get install libsdl2-dev 2. Install PySDL2 using pip package manager: pip install PySDL2 - -Missing functionality: + +Known issues (pull requests are welcome): +- There are issues when running on slow machine - key events are being + lost (noticed on Mac only), see Issue #324 for more details +- Performance is still not perfect, see Issue #324 for further details - Keyboard modifiers that are not yet handled in this example: ctrl, marking text inputs with the shift key. -- Mouse dragging +- Dragging with mouse not implemented - Window size is fixed, cannot be resized GUI controls: @@ -32,33 +50,97 @@ https://github.com/neilmunday/pes/blob/master/lib/pes/ui.py """ +import argparse +import logging import sys + + +def die(msg): + """ + Helper function to exit application on failed imports etc. + """ + sys.stderr.write("%s\n" % msg) + sys.exit(1) + + try: # noinspection PyUnresolvedReferences from cefpython3 import cefpython as cef except ImportError: - print("ERROR: cefpython3 package not found") - print("To install type: `pip install cefpython3`") - sys.exit(1) + die("ERROR: cefpython3 package not found\n" + " To install type: pip install cefpython3") + try: # noinspection PyUnresolvedReferences import sdl2 # noinspection PyUnresolvedReferences import sdl2.ext -except ImportError: - print("ERROR: SDL2 package not found") - print("To install type: `pip install PySDL2`") - sys.exit(1) +except ImportError as exc: + excstr = repr(exc) + if "No module named sdl2" in excstr: + die("ERROR: PySDL2 package not found\n" + " To install type: pip install PySDL2") + elif ("could not find any library for SDL2" + " (PYSDL2_DLL_PATH: unset)" in excstr): + die("ERROR: SDL2 package not found.\n" + " See install instructions in top comment in sources.") + else: + die(excstr) + try: # noinspection PyUnresolvedReferences from PIL import Image except ImportError: - print("ERROR: PIL package not found") - print("To install type: pip install Pillow") - sys.exit(1) + die("ERROR: PIL package not found\n" + " To install type: pip install Pillow") + + +if sys.platform == 'darwin': + try: + import AppKit + except ImportError: + die("ERROR: pyobjc package not found\n" + " To install type: pip install pyobjc") def main(): + """ + Parses input, initializes everything and then runs the main loop of the + program, which handles input and draws the scene. + """ + parser = argparse.ArgumentParser( + description='PySDL2 / cefpython example', + add_help=True + ) + parser.add_argument( + '-v', + '--verbose', + help='Turn on debug info', + dest='verbose', + action='store_true' + ) + parser.add_argument( + '-r', + '--renderer', + help='Specify hardware or software rendering', + default='hardware', + dest='renderer', + choices=['software', 'hardware'] + ) + args = parser.parse_args() + logLevel = logging.INFO + if args.verbose: + logLevel = logging.DEBUG + logging.basicConfig( + format='[%(filename)s %(levelname)s]: %(message)s', + level=logLevel + ) + logging.info("Using PySDL2 %s" % sdl2.__version__) + version = sdl2.SDL_version() + sdl2.SDL_GetVersion(version) + logging.info( + "Using SDL2 %s.%s.%s" % (version.major, version.minor, version.patch) + ) # The following variables control the dimensions of the window # and browser display area width = 800 @@ -69,19 +151,44 @@ def main(): browserHeight = height - headerHeight browserWidth = width # Mouse wheel fudge to enhance scrolling - scrollEnhance = 20 + scrollEnhance = 40 + # desired frame rate + frameRate = 100 # Initialise CEF for offscreen rendering sys.excepthook = cef.ExceptHook - cef.Initialize(settings={"windowless_rendering_enabled": True}) + switches = { + # Tweaking OSR performance by setting the same Chromium flags + # as in upstream cefclient (Issue #240). + "disable-surfaces": "", + "disable-gpu": "", + "disable-gpu-compositing": "", + "enable-begin-frame-scheduling": "", + } + browser_settings = { + # Tweaking OSR performance (Issue #240) + "windowless_frame_rate": frameRate + } + cef.Initialize(settings={"windowless_rendering_enabled": True}, + switches=switches) + + if sys.platform == 'darwin': + # On MacOS, the NSApplication created in the cefpython initialization + # will be hidden if windowless is specified. In order for SDL to receive + # propper input events and for the application to show up in the + # command-tab list, the application must be made "regular". + AppKit.NSApplication.sharedApplication().setActivationPolicy_( + AppKit.NSApplicationActivationPolicyRegular) + logging.debug("cef initialised") window_info = cef.WindowInfo() window_info.SetAsOffscreen(0) # Initialise SDL2 for video (add other init constants if you # require other SDL2 functionality e.g. mixer, # TTF, joystick etc. sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) + logging.debug("SDL2 initialised") # Create the window window = sdl2.video.SDL_CreateWindow( - 'cefpython3 SDL2 Demo', + b'cefpython3 SDL2 Demo', sdl2.video.SDL_WINDOWPOS_UNDEFINED, sdl2.video.SDL_WINDOWPOS_UNDEFINED, width, @@ -90,22 +197,49 @@ def main(): ) # Define default background colour (black in this case) backgroundColour = sdl2.SDL_Color(0, 0, 0) - # Create the renderer using hardware acceleration - renderer = sdl2.SDL_CreateRenderer(window, -1, - sdl2.render.SDL_RENDERER_ACCELERATED) + renderer = None + if args.renderer == 'hardware': + # Create the renderer using hardware acceleration + logging.info("Using hardware rendering") + renderer = sdl2.SDL_CreateRenderer( + window, + -1, + sdl2.render.SDL_RENDERER_ACCELERATED + ) + else: + # Create the renderer using software acceleration + logging.info("Using software rendering") + renderer = sdl2.SDL_CreateRenderer( + window, + -1, + sdl2.render.SDL_RENDERER_SOFTWARE + ) # Set-up the RenderHandler, passing in the SDL2 renderer renderHandler = RenderHandler(renderer, width, height - headerHeight) # Create the browser instance - browser = cef.CreateBrowserSync(window_info, url="https://www.google.com/") + browser = cef.CreateBrowserSync(window_info, + url="https://www.google.com/", + settings=browser_settings) browser.SetClientHandler(LoadHandler()) browser.SetClientHandler(renderHandler) # Must call WasResized at least once to let know CEF that # viewport size is available and that OnPaint may be called. browser.SendFocusEvent(True) browser.WasResized() + # Begin the main rendering loop running = True + # FPS debug variables + frames = 0 + logging.debug("beginning rendering loop") + resetFpsTime = True + fpsTime = 0 while running: + # record when we started drawing this frame + startTime = sdl2.timer.SDL_GetTicks() + if resetFpsTime: + fpsTime = sdl2.timer.SDL_GetTicks() + resetFpsTime = False # Convert SDL2 events into CEF events (where appropriate) events = sdl2.ext.get_events() for event in events: @@ -113,10 +247,14 @@ def main(): or (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE)): running = False + logging.debug("SDL2 QUIT event") break if event.type == sdl2.SDL_MOUSEBUTTONDOWN: if event.button.button == sdl2.SDL_BUTTON_LEFT: if event.button.y > headerHeight: + logging.debug( + "SDL2 MOUSEBUTTONDOWN event (left button)" + ) # Mouse click triggered in browser region browser.SendMouseClickEvent( event.button.x, @@ -128,6 +266,7 @@ def main(): elif event.type == sdl2.SDL_MOUSEBUTTONUP: if event.button.button == sdl2.SDL_BUTTON_LEFT: if event.button.y > headerHeight: + logging.debug("SDL2 MOUSEBUTTONUP event (left button)") # Mouse click triggered in browser region browser.SendMouseClickEvent( event.button.x, @@ -143,6 +282,7 @@ def main(): event.motion.y - headerHeight, False) elif event.type == sdl2.SDL_MOUSEWHEEL: + logging.debug("SDL2 MOUSEWHEEL event") # Mouse wheel event x = event.wheel.x if x < 0: @@ -158,6 +298,7 @@ def main(): elif event.type == sdl2.SDL_TEXTINPUT: # Handle text events to get actual characters typed rather # than the key pressed. + logging.debug("SDL2 TEXTINPUT event: %s" % event.text.text) keycode = ord(event.text.text) key_event = { "type": cef.KEYEVENT_CHAR, @@ -177,6 +318,7 @@ def main(): browser.SendKeyEvent(key_event) elif event.type == sdl2.SDL_KEYDOWN: # Handle key down events for non-text keys + logging.debug("SDL2 KEYDOWN event") if event.key.keysym.sym == sdl2.SDLK_RETURN: keycode = event.key.keysym.sym key_event = { @@ -202,13 +344,17 @@ def main(): key_event = { "type": cef.KEYEVENT_RAWKEYDOWN, "windows_key_code": keycode, - "character": keycode, - "unmodified_character": keycode, + "native_key_code": get_native_key(keycode), + # For raw key events, the character and unmodified + # character codes should be 0. + "character": 0, + "unmodified_character": 0, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) elif event.type == sdl2.SDL_KEYUP: # Handle key up events for non-text keys + logging.debug("SDL2 KEYUP event") if event.key.keysym.sym in [ sdl2.SDLK_RETURN, sdl2.SDLK_BACKSPACE, @@ -225,6 +371,11 @@ def main(): key_event = { "type": cef.KEYEVENT_KEYUP, "windows_key_code": keycode, + "native_key_code": get_native_key(keycode), + # On raw key up events, the character and unmodified + # character need to be defined, otherwise pressing + # one of the above-listed keys will eat the next + # normal keypress. "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE @@ -250,6 +401,17 @@ def main(): sdl2.SDL_Rect(0, headerHeight, browserWidth, browserHeight) ) sdl2.SDL_RenderPresent(renderer) + # FPS debug code + frames += 1 + if sdl2.timer.SDL_GetTicks() - fpsTime > 1000: + logging.debug("FPS: %d" % frames) + frames = 0 + resetFpsTime = True + # regulate frame rate + if sdl2.timer.SDL_GetTicks() - startTime < 1000.0 / frameRate: + sdl2.timer.SDL_Delay( + (1000 // frameRate) - (sdl2.timer.SDL_GetTicks() - startTime) + ) # User exited exit_app() @@ -270,31 +432,61 @@ def get_key_code(key): if key in key_map: return key_map[key] # Key not mapped, raise exception - print("[pysdl2.py] Keyboard mapping incomplete:" - " unsupported SDL key %d." - " See https://wiki.libsdl.org/SDLKeycodeLookup for mapping." - % key) + logging.error( + """ + Keyboard mapping incomplete: unsupported SDL key %d. + See https://wiki.libsdl.org/SDLKeycodeLookup for mapping. + """ % key + ) return None +# The key events on MacOS have different native keycode than on other operating +# systems. This table is a translation from Windows-keycodes to MacOS ones. +MACOS_TRANSLATION_TABLE = { + # Backspace + 0x08: 0x33, + + # Left arrow + 0x25: 0x7B, + # Up arrow + 0x26: 0x7E, + # Right arrow + 0x27: 0x7C, + # Down arrow + 0x28: 0x7D, +} + + +def get_native_key(key): + """ + Helper function for returning the correct native key map for the operating + system. + """ + if sys.platform == 'darwin': + return MACOS_TRANSLATION_TABLE.get(key, key) + + return key + + class LoadHandler(object): """Simple handler for loading URLs.""" - + def OnLoadingStateChange(self, is_loading, **_): if not is_loading: - print("[pysdl2.py] Page loading complete") - + logging.info("Page loading complete") + def OnLoadError(self, frame, failed_url, **_): if not frame.IsMain(): return - print("[pysdl2.py] Failed to load %s" % failed_url) + logging.error("Failed to load %s" % failed_url) class RenderHandler(object): """ Handler for rendering web pages to the screen via SDL2. - + The object's texture property is exposed to allow the main rendering loop to access the SDL2 texture. @@ -305,11 +497,11 @@ def __init__(self, renderer, width, height): self.__height = height self.__renderer = renderer self.texture = None - + def GetViewRect(self, rect_out, **_): rect_out.extend([0, 0, self.__width, self.__height]) return True - + def OnPaint(self, element_type, paint_buffer, **_): """ Using the pixel data from CEF's offscreen rendering @@ -359,9 +551,9 @@ def OnPaint(self, element_type, paint_buffer, **_): depth = 32 pitch = self.__width * 4 else: - print("[pysdl2.py] ERROR: Unsupported mode: %s" % mode) + logging.error("ERROR: Unsupported mode: %s" % mode) exit_app() - + pxbuf = image.tobytes() # Create surface surface = sdl2.SDL_CreateRGBSurfaceFrom( @@ -384,14 +576,14 @@ def OnPaint(self, element_type, paint_buffer, **_): # Free the surface sdl2.SDL_FreeSurface(surface) else: - print("[pysdl2.py] WARNING: Unsupport element_type in OnPaint") + logging.warning("Unsupport element_type in OnPaint") def exit_app(): """Tidy up SDL2 and CEF before exiting.""" sdl2.SDL_Quit() cef.Shutdown() - print("[pysdl2.py] Exited gracefully") + logging.info("Exited gracefully") if __name__ == "__main__": diff --git a/examples/pywin32.py b/examples/pywin32.py index d18aa54ed..bf8d2b9be 100644 --- a/examples/pywin32.py +++ b/examples/pywin32.py @@ -108,7 +108,7 @@ def check_versions(): pywin32_version = fp.read().strip() print("[pywin32.py] pywin32 {ver}".format(ver=pywin32_version)) - assert cef.__version__ >= "57.0", "CEF Python v57.0 required to run this" + assert cef.__version__ >= "57.0", "CEF Python v57.0+ required to run this" def create_browser(window_info, settings, url): diff --git a/examples/qt.py b/examples/qt.py index 6993e1da1..efb1b381f 100644 --- a/examples/qt.py +++ b/examples/qt.py @@ -3,15 +3,15 @@ # bar and a browser. # # Tested configurations: -# - PyQt 5.8.2 on Windows/Linux/Mac -# - PyQt 4.11 (qt 4.8) on Windows/Linux -# - PySide 1.2 (qt 4.8) on Windows/Linux/Mac +# - PyQt 5.8.2 (qt 5.8.0) on Windows/Linux/Mac +# - PyQt 4.10.4 / 4.11.4 (qt 4.8.6 / 4.8.7) on Windows/Linux +# - PySide 1.2.1 (qt 4.8.6) on Windows/Linux/Mac +# - PySide2 5.6.0, 5.11.2 (qt 5.6.2, 5.11.2) on Windows/Linux/Mac # - CEF Python v55.4+ # # Issues with PySide 1.2: # - Mac: Keyboard focus issues when switching between controls (Issue #284) # - Mac: Mouse cursor never changes when hovering over links (Issue #311) -# - Windows/Mac: Sometimes process hangs when quitting app (Issue #360) from cefpython3 import cefpython as cef import ctypes @@ -23,6 +23,7 @@ PYQT4 = False PYQT5 = False PYSIDE = False +PYSIDE2 = False if "pyqt4" in sys.argv: PYQT4 = True @@ -48,11 +49,24 @@ from PySide.QtGui import * # noinspection PyUnresolvedReferences from PySide.QtCore import * +elif "pyside2" in sys.argv: + PYSIDE2 = True + # noinspection PyUnresolvedReferences + import PySide2 + # noinspection PyUnresolvedReferences + from PySide2 import QtCore + # noinspection PyUnresolvedReferences + from PySide2.QtGui import * + # noinspection PyUnresolvedReferences + from PySide2.QtCore import * + # noinspection PyUnresolvedReferences + from PySide2.QtWidgets import * else: print("USAGE:") print(" qt.py pyqt4") print(" qt.py pyqt5") print(" qt.py pyside") + print(" qt.py pyside2") sys.exit(1) # Fix for PyCharm hints warnings when using static methods @@ -77,14 +91,22 @@ def main(): check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error - cef.Initialize() + settings = {} + if MAC: + # Issue #442 requires enabling message pump on Mac + # in Qt example. Calling cef.DoMessageLoopWork in a timer + # doesn't work anymore. + settings["external_message_pump"] = True + + cef.Initialize(settings) app = CefApplication(sys.argv) main_window = MainWindow() main_window.show() main_window.activateWindow() main_window.raise_() app.exec_() - app.stopTimer() + if not cef.GetAppSetting("external_message_pump"): + app.stopTimer() del main_window # Just to be safe, similarly to "del app" del app # Must destroy app object before calling Shutdown cef.Shutdown() @@ -100,6 +122,9 @@ def check_versions(): elif PYSIDE: print("[qt.py] PySide {v1} (qt {v2})".format( v1=PySide.__version__, v2=QtCore.__version__)) + elif PYSIDE2: + print("[qt.py] PySide2 {v1} (qt {v2})".format( + v1=PySide2.__version__, v2=QtCore.__version__)) # CEF Python version requirement assert cef.__version__ >= "55.4", "CEF Python v55.4+ required to run this" @@ -108,6 +133,9 @@ class MainWindow(QMainWindow): def __init__(self): # noinspection PyArgumentList super(MainWindow, self).__init__(None) + # Avoids crash when shutting down CEF (issue #360) + if PYSIDE: + self.setAttribute(Qt.WA_DeleteOnClose, True) self.cef_widget = None self.navigation_bar = None if PYQT4: @@ -116,6 +144,8 @@ def __init__(self): self.setWindowTitle("PyQt5 example") elif PYSIDE: self.setWindowTitle("PySide example") + elif PYSIDE2: + self.setWindowTitle("PySide2 example") self.setFocusPolicy(Qt.StrongFocus) self.setupLayout() @@ -137,7 +167,7 @@ def setupLayout(self): frame.setLayout(layout) self.setCentralWidget(frame) - if PYQT5 and WINDOWS: + if (PYSIDE2 or PYQT5) and WINDOWS: # On Windows with PyQt5 main window must be shown first # before CEF browser is embedded, otherwise window is # not resized and application hangs during resize. @@ -146,7 +176,7 @@ def setupLayout(self): # Browser can be embedded only after layout was set up self.cef_widget.embedBrowser() - if PYQT5 and LINUX: + if (PYSIDE2 or PYQT5) and LINUX: # On Linux with PyQt5 the QX11EmbedContainer widget is # no more available. An equivalent in Qt5 is to create # a hidden window, embed CEF browser in it and then @@ -182,6 +212,8 @@ def __init__(self, parent=None): def focusInEvent(self, event): # This event seems to never get called on Linux, as CEF is # stealing all focus due to Issue #284. + if cef.GetAppSetting("debug"): + print("[qt.py] CefWidget.focusInEvent") if self.browser: if WINDOWS: WindowUtils.OnSetFocus(self.getHandle(), 0, 0, 0) @@ -190,11 +222,13 @@ def focusInEvent(self, event): def focusOutEvent(self, event): # This event seems to never get called on Linux, as CEF is # stealing all focus due to Issue #284. + if cef.GetAppSetting("debug"): + print("[qt.py] CefWidget.focusOutEvent") if self.browser: self.browser.SetFocus(False) def embedBrowser(self): - if PYQT5 and LINUX: + if (PYSIDE2 or PYQT5) and LINUX: # noinspection PyUnresolvedReferences self.hidden_window = QWindow() window_info = cef.WindowInfo() @@ -257,7 +291,8 @@ def resizeEvent(self, event): class CefApplication(QApplication): def __init__(self, args): super(CefApplication, self).__init__(args) - self.timer = self.createTimer() + if not cef.GetAppSetting("external_message_pump"): + self.timer = self.createTimer() self.setupIcon() def createTimer(self): @@ -305,14 +340,20 @@ class FocusHandler(object): def __init__(self, cef_widget): self.cef_widget = cef_widget + def OnTakeFocus(self, **_): + if cef.GetAppSetting("debug"): + print("[qt.py] FocusHandler.OnTakeFocus") + def OnSetFocus(self, **_): - pass + if cef.GetAppSetting("debug"): + print("[qt.py] FocusHandler.OnSetFocus") def OnGotFocus(self, browser, **_): + if cef.GetAppSetting("debug"): + print("[qt.py] FocusHandler.OnGotFocus") + self.cef_widget.setFocus() # Temporary fix no. 1 for focus issues on Linux (Issue #284) if LINUX: - print("[qt.py] FocusHandler.OnGotFocus:" - " keyboard focus fix no. 1 (Issue #284)") browser.SetFocus(True) diff --git a/examples/screenshot.py b/examples/screenshot.py index 0f23b627b..5ca8d4913 100644 --- a/examples/screenshot.py +++ b/examples/screenshot.py @@ -24,6 +24,15 @@ Tested configurations: - CEF Python v57.0+ - Pillow 2.3.0 / 4.1.0 + +NOTE: There are limits in Chromium on viewport size. For some + websites with huge viewport size it won't work. In such + case it is required to reduce viewport size to an usual + size of a window and perform scrolling programmatically + using javascript while making a screenshot for each of + the scrolled region. Then at the end combine all the + screenshots into one. To force a paint event in OSR + mode call cef.Invalidate(). """ from cefpython3 import cefpython as cef @@ -33,8 +42,8 @@ import sys try: - from PIL import Image, PILLOW_VERSION -except: + from PIL import Image, __version__ as PILLOW_VERSION +except ImportError: print("[screenshot.py] Error: PIL module not available. To install" " type: pip install Pillow") sys.exit(1) @@ -55,9 +64,26 @@ def main(): os.remove(SCREENSHOT_PATH) command_line_arguments() # Off-screen-rendering requires setting "windowless_rendering_enabled" - # option, so that RenderHandler callbacks are called. - cef.Initialize(settings={"windowless_rendering_enabled": True}) - create_browser() + # option. + settings = { + "windowless_rendering_enabled": True, + } + switches = { + # GPU acceleration is not supported in OSR mode, so must disable + # it using these Chromium switches (Issue #240 and #463) + "disable-gpu": "", + "disable-gpu-compositing": "", + # Tweaking OSR performance by setting the same Chromium flags + # as in upstream cefclient (Issue #240). + "enable-begin-frame-scheduling": "", + "disable-surfaces": "", # This is required for PDF ext to work + } + browser_settings = { + # Tweaking OSR performance (Issue #240) + "windowless_frame_rate": 30, # Default frame rate in CEF is 30 + } + cef.Initialize(settings=settings, switches=switches) + create_browser(browser_settings) cef.MessageLoop() cef.Shutdown() print("[screenshot.py] Opening screenshot with default application") @@ -65,9 +91,13 @@ def main(): def check_versions(): - print("[screenshot.py] CEF Python {ver}".format(ver=cef.__version__)) + ver = cef.GetVersion() + print("[screenshot.py] CEF Python {ver}".format(ver=ver["version"])) + print("[screenshot.py] Chromium {ver}".format(ver=ver["chrome_version"])) + print("[screenshot.py] CEF {ver}".format(ver=ver["cef_version"])) print("[screenshot.py] Python {ver} {arch}".format( - ver=platform.python_version(), arch=platform.architecture()[0])) + ver=platform.python_version(), + arch=platform.architecture()[0])) print("[screenshot.py] Pillow {ver}".format(ver=PILLOW_VERSION)) assert cef.__version__ >= "57.0", "CEF Python v57.0+ required to run this" @@ -95,7 +125,7 @@ def command_line_arguments(): sys.exit(1) -def create_browser(): +def create_browser(settings): # Create browser in off-screen-rendering mode (windowless mode) # by calling SetAsOffscreen method. In such mode parent window # handle can be NULL (0). @@ -107,6 +137,7 @@ def create_browser(): print("[screenshot.py] Loading url: {url}" .format(url=URL)) browser = cef.CreateBrowserSync(window_info=window_info, + settings=settings, url=URL) browser.SetClientHandler(LoadHandler()) browser.SetClientHandler(RenderHandler()) @@ -127,6 +158,8 @@ def save_screenshot(browser): "raw", "RGBA", 0, 1) image.save(SCREENSHOT_PATH, "PNG") print("[screenshot.py] Saved image: {path}".format(path=SCREENSHOT_PATH)) + # See comments in exit_app() why PostTask must be used + cef.PostTask(cef.TID_UI, exit_app, browser) def open_with_default_application(path): @@ -157,9 +190,10 @@ def OnLoadingStateChange(self, browser, is_loading, **_): # Loading is complete sys.stdout.write(os.linesep) print("[screenshot.py] Web page loading is complete") - save_screenshot(browser) - # See comments in exit_app() why PostTask must be used - cef.PostTask(cef.TID_UI, exit_app, browser) + print("[screenshot.py] Will save screenshot in 2 seconds") + # Give up to 2 seconds for the OnPaint call. Most of the time + # it is already called, but sometimes it may be called later. + cef.PostDelayedTask(cef.TID_UI, 2000, save_screenshot, browser) def OnLoadError(self, browser, frame, error_code, failed_url, **_): """Called when the resource load for a navigation fails @@ -201,8 +235,8 @@ def OnPaint(self, browser, element_type, paint_buffer, **_): # reasons it would be better not to copy this string. # I think that Python makes a copy of that string when # passing it to SetUserData. - buffer_string = paint_buffer.GetString(mode="rgba", - origin="top-left") + buffer_string = paint_buffer.GetBytes(mode="rgba", + origin="top-left") # Browser object provides GetUserData/SetUserData methods # for storing custom data associated with browser. browser.SetUserData("OnPaint.buffer_string", buffer_string) diff --git a/examples/snippets/README-snippets.md b/examples/snippets/README-snippets.md new file mode 100644 index 000000000..0f41e4f3f --- /dev/null +++ b/examples/snippets/README-snippets.md @@ -0,0 +1,48 @@ +# Snippets README + +Table of contents: +* [Hello World!](#hello-world) +* [Snippets](#snippets) + + +## Hello World! + +Instructions to install the cefpython3 package, clone +the repository and run the `javascript_bindings.py` snippet: + +``` +pip install cefpython3==66.0 +git clone https://github.com/cztomczak/cefpython.git +cd cefpython/examples/snippets/ +python javascript_bindings.py +``` + + +## Snippets + +Below are small code snippets that show various CEF features and +are easy to understand. These are available in the [examples/snippets/](./) +directory. If looking for non-trivial examples then see the +[README-examples.md](../README-examples.md) document. + + +- [cookies.py](cookies.py) - Shows how to fetch all cookies, + all cookies for a given url and how to delete a specific cookie. +- [javascript_bindings.py](javascript_bindings.py) - Communicate + between Python and Javascript asynchronously using + inter-process messaging with the use of Javascript Bindings. +- [javascript_errors.py](javascript_errors.py) - Two ways for + intercepting Javascript errors. +- [mouse_clicks.py](mouse_clicks.py) - Perform mouse clicks + and mouse movements programmatically. +- [network_cookies.py](network_cookies.py) - Implement + interfaces to block or allow cookies over network requests. +- [onbeforeclose.py](onbeforeclose.py) - Implement interface + to execute custom code before browser window closes. +- [ondomready.py](ondomready.py) - Execute custom Python code + on a web page as soon as DOM is ready. +- [onpagecomplete.py](onpagecomplete.py) - Execute custom + Python code on a web page when page loading is complete. +- [setcookie.py](setcookie.py) - Shows how to set a cookie +- [window_size.py](window_size.py) - Set initial window size + without use of any third party GUI framework. diff --git a/examples/snippets/cookies.py b/examples/snippets/cookies.py new file mode 100644 index 000000000..bd732a78a --- /dev/null +++ b/examples/snippets/cookies.py @@ -0,0 +1,62 @@ +"""Shows how to fetch all cookies, all cookies for +a given url and how to delete a specific cookie. For +an example on how to set a cookie see the 'setcookie.py' +snippet.""" + +from cefpython3 import cefpython as cef + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync( + url="http://www.html-kit.com/tools/cookietester/", + window_title="Cookies") + browser.SetClientHandler(LoadHandler()) + cef.MessageLoop() + del browser + cef.Shutdown() + + +class LoadHandler(object): + def OnLoadingStateChange(self, browser, is_loading, **_): + if is_loading: + print("Page loading complete - start visiting cookies") + manager = cef.CookieManager.GetGlobalManager() + # Must keep a strong reference to the CookieVisitor object + # while cookies are being visited. + self.cookie_visitor = CookieVisitor() + # Visit all cookies + result = manager.VisitAllCookies(self.cookie_visitor) + if not result: + print("Error: could not access cookies") + # To visit cookies only for a given url uncomment the + # code below. + """ + url = "http://www.html-kit.com/tools/cookietester/" + http_only_cookies = False + result = manager.VisitUrlCookies(url, http_only_cookies, + self.cookie_visitor) + if not result: + print("Error: could not access cookies") + """ + + +class CookieVisitor(object): + def Visit(self, cookie, count, total, delete_cookie_out): + """This callback is called on the IO thread.""" + print("Cookie {count}/{total}: '{name}', '{value}'" + .format(count=count+1, total=total, name=cookie.GetName(), + value=cookie.GetValue())) + # Set a cookie named "delete_me" and it will be deleted. + # You have to refresh page to see whether it succeeded. + if cookie.GetName() == "delete_me": + # 'delete_cookie_out' arg is a list passed by reference. + # Set its '0' index to True to delete the cookie. + delete_cookie_out[0] = True + print("Deleted cookie: {name}".format(name=cookie.GetName())) + # Return True to continue visiting more cookies + return True + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/javascript_bindings.py b/examples/snippets/javascript_bindings.py new file mode 100644 index 000000000..41ca1d762 --- /dev/null +++ b/examples/snippets/javascript_bindings.py @@ -0,0 +1,69 @@ +""" +Communicate between Python and Javascript asynchronously using +inter-process messaging with the use of Javascript Bindings. +""" + +from cefpython3 import cefpython as cef + +g_htmlcode = """ + + + + + + + +

Javascript Bindings

+
+ + +""" + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode), + window_title="Javascript Bindings") + browser.SetClientHandler(LoadHandler()) + bindings = cef.JavascriptBindings() + bindings.SetFunction("py_function", py_function) + bindings.SetFunction("py_callback", py_callback) + browser.SetJavascriptBindings(bindings) + cef.MessageLoop() + del browser + cef.Shutdown() + + +def py_function(value, js_callback): + print("Value sent from Javascript: "+value) + js_callback.Call("I am a Python string #2", py_callback) + + +def py_callback(value): + print("Value sent from Javascript: "+value) + + +class LoadHandler(object): + def OnLoadEnd(self, browser, **_): + browser.ExecuteFunction("js_function", "I am a Python string #1") + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/javascript_errors.py b/examples/snippets/javascript_errors.py new file mode 100644 index 000000000..c33ef8d73 --- /dev/null +++ b/examples/snippets/javascript_errors.py @@ -0,0 +1,61 @@ +""" +Two ways for intercepting Javascript errors: +1. window.onerror event in Javascript +2. DisplayHandler.OnConsoleMessage in Python +""" + +from cefpython3 import cefpython as cef + +g_htmlcode = """ + + + + + + + +

Javascript Errors

+
+ + +""" + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode), + window_title="Javascript Errors") + browser.SetClientHandler(DisplayHandler()) + cef.MessageLoop() + cef.Shutdown() + + +class DisplayHandler(object): + def OnConsoleMessage(self, browser, message, line, **_): + if "error" in message.lower() or "uncaught" in message.lower(): + logmsg = "[Py:OnConsoleMessage] {message} (line {line})" \ + .format(message=message, line=line) + print(logmsg) + browser.ExecuteFunction("print", logmsg) + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/keyboard_handler.py b/examples/snippets/keyboard_handler.py new file mode 100644 index 000000000..9b8e40c8a --- /dev/null +++ b/examples/snippets/keyboard_handler.py @@ -0,0 +1,19 @@ +from cefpython3 import cefpython as cef + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync(url="https://www.google.com/", + window_title="Keyboard Handler") + browser.SetClientHandler(KeyboardHandler()) + cef.MessageLoop() + del browser + cef.Shutdown() + + +class KeyboardHandler(object): + def OnKeyEvent(self, browser, event, event_handle, **_): + print("OnKeyEvent: "+str(event)) + +if __name__ == '__main__': + main() diff --git a/examples/snippets/mouse_clicks.py b/examples/snippets/mouse_clicks.py new file mode 100644 index 000000000..e8ace36a4 --- /dev/null +++ b/examples/snippets/mouse_clicks.py @@ -0,0 +1,51 @@ +# Perform mouse clicks and mouse movements programmatically. + +from cefpython3 import cefpython as cef + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync( + url="data:text/html,

Mouse clicks snippet

" + "This text will be selected after one second.
" + "This text will be selected after two seconds.", + window_title="Mouse clicks") + browser.SetClientHandler(LifespanHandler()) + cef.MessageLoop() + del browser + cef.Shutdown() + + +def click_after_1_second(browser): + print("Click after 1 second") + # Mouse move to the top-left corner of the text + browser.SendMouseMoveEvent(0, 70, False, 0) + # Left mouse button click in the top-left corner of the text + browser.SendMouseClickEvent(0, 70, cef.MOUSEBUTTON_LEFT, False, 1) + # Mouse move to the bottom-right corner of the text, + # while holding left mouse button. + browser.SendMouseMoveEvent(400, 80, False, cef.EVENTFLAG_LEFT_MOUSE_BUTTON) + # Release left mouse button + browser.SendMouseClickEvent(400, 80, cef.MOUSEBUTTON_LEFT, True, 1) + cef.PostDelayedTask(cef.TID_UI, 1000, click_after_2_seconds, browser) + + +def click_after_2_seconds(browser): + print("Click after 2 seconds") + browser.SendMouseMoveEvent(0, 90, False, 0) + browser.SendMouseClickEvent(0, 90, cef.MOUSEBUTTON_LEFT, False, 1) + browser.SendMouseMoveEvent(400, 99, False, cef.EVENTFLAG_LEFT_MOUSE_BUTTON) + browser.SendMouseClickEvent(400, 99, cef.MOUSEBUTTON_LEFT, True, 1) + cef.PostDelayedTask(cef.TID_UI, 1000, click_after_1_second, browser) + + +class LifespanHandler(object): + def OnLoadEnd(self, browser, **_): + # Execute function with a delay of 1 second after page + # has completed loading. + print("Page loading is complete") + cef.PostDelayedTask(cef.TID_UI, 1000, click_after_1_second, browser) + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/network_cookies.py b/examples/snippets/network_cookies.py new file mode 100644 index 000000000..c3631cff5 --- /dev/null +++ b/examples/snippets/network_cookies.py @@ -0,0 +1,51 @@ +""" +Implement RequestHandler.CanGetCookies and CanSetCookie +to block or allow cookies over network requests. +""" + +from cefpython3 import cefpython as cef + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync( + url="http://www.html-kit.com/tools/cookietester/", + window_title="Network cookies") + browser.SetClientHandler(RequestHandler()) + cef.MessageLoop() + del browser + cef.Shutdown() + + +class RequestHandler(object): + def __init__(self): + self.getcount = 0 + self.setcount = 0 + + def CanGetCookies(self, frame, request, **_): + # There are multiple iframes on that website, let's log + # cookies only for the main frame. + if frame.IsMain(): + self.getcount += 1 + print("-- CanGetCookies #"+str(self.getcount)) + print("url="+request.GetUrl()[0:80]) + print("") + # Return True to allow reading cookies or False to block + return True + + def CanSetCookie(self, frame, request, cookie, **_): + # There are multiple iframes on that website, let's log + # cookies only for the main frame. + if frame.IsMain(): + self.setcount += 1 + print("-- CanSetCookie @"+str(self.setcount)) + print("url="+request.GetUrl()[0:80]) + print("Name="+cookie.GetName()) + print("Value="+cookie.GetValue()) + print("") + # Return True to allow setting cookie or False to block + return True + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/onbeforeclose.py b/examples/snippets/onbeforeclose.py new file mode 100644 index 000000000..9b072e964 --- /dev/null +++ b/examples/snippets/onbeforeclose.py @@ -0,0 +1,26 @@ +""" +Implement LifespanHandler.OnBeforeClose to execute custom +code before browser window closes. +""" + +from cefpython3 import cefpython as cef + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync(url="https://www.google.com/", + window_title="OnBeforeClose") + browser.SetClientHandler(LifespanHandler()) + cef.MessageLoop() + del browser + cef.Shutdown() + + +class LifespanHandler(object): + def OnBeforeClose(self, browser): + print("Browser ID: {}".format(browser.GetIdentifier())) + print("Browser will close and app will exit") + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/ondomready.py b/examples/snippets/ondomready.py new file mode 100644 index 000000000..8775129c7 --- /dev/null +++ b/examples/snippets/ondomready.py @@ -0,0 +1,50 @@ +""" +Execute custom Python code on a web page as soon as DOM is ready. +Implements a custom "_OnDomReady" event in the LoadHandler object. +""" + +from cefpython3 import cefpython as cef + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync(url="https://www.google.com/", + window_title="_OnDomReady event") + load_handler = LoadHandler(browser) + browser.SetClientHandler(load_handler) + bindings = cef.JavascriptBindings() + bindings.SetFunction("LoadHandler_OnDomReady", + load_handler["_OnDomReady"]) + browser.SetJavascriptBindings(bindings) + cef.MessageLoop() + del load_handler + del browser + cef.Shutdown() + + +class LoadHandler(object): + def __init__(self, browser): + self.browser = browser + + def __getitem__(self, key): + return getattr(self, key) + + def OnLoadStart(self, browser, **_): + browser.ExecuteJavascript(""" + if (document.readyState === "complete") { + LoadHandler_OnDomReady(); + } else { + document.addEventListener("DOMContentLoaded", function() { + LoadHandler_OnDomReady(); + }); + } + """) + + def _OnDomReady(self): + print("DOM is ready!") + self.browser.ExecuteFunction("alert", + "Message from Python: DOM is ready!") + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/onpagecomplete.py b/examples/snippets/onpagecomplete.py new file mode 100644 index 000000000..e118e8e7c --- /dev/null +++ b/examples/snippets/onpagecomplete.py @@ -0,0 +1,35 @@ +""" +Execute custom Python code on a web page when page loading is complete. +Implements a custom "_OnPageComplete" event in the LoadHandler object. +""" + +from cefpython3 import cefpython as cef + + +def main(): + cef.Initialize() + browser = cef.CreateBrowserSync(url="https://www.google.com/", + window_title="_OnPageComplete event") + browser.SetClientHandler(LoadHandler()) + cef.MessageLoop() + del browser + cef.Shutdown() + + +class LoadHandler(object): + def OnLoadingStateChange(self, browser, is_loading, **_): + """For detecting if page loading has ended it is recommended + to use OnLoadingStateChange which is most reliable. The OnLoadEnd + callback also available in LoadHandler can sometimes fail in + some cases e.g. when image loading hangs.""" + if not is_loading: + self._OnPageComplete(browser) + + def _OnPageComplete(self, browser): + print("Page loading is complete!") + browser.ExecuteFunction("alert", "Message from Python: Page loading" + " is complete!") + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/setcookie.py b/examples/snippets/setcookie.py new file mode 100644 index 000000000..04a99508e --- /dev/null +++ b/examples/snippets/setcookie.py @@ -0,0 +1,36 @@ +""" +Shows how to set a cookie. +""" + +from cefpython3 import cefpython as cef +import datetime + + +def main(): + cef.Initialize() + cef.CreateBrowserSync( + url="http://www.html-kit.com/tools/cookietester/", + window_title="Set a cookie") + manager = cef.CookieManager.GetGlobalManager() + cookie = cef.Cookie() + cookie.Set({ + "name": "my_cookie", + "value": "my_value", + # Make sure domain is a valid value otherwise it crashes + # app (Issue #459) + "domain": "www.html-kit.com", + "path": "/", + "secure": False, + "httpOnly": False, + "creation": datetime.datetime(2018, 8, 22), + "lastAccess": datetime.datetime(2018, 8, 22), + "hasExpires": True, + "expires": datetime.datetime(2028, 12, 31, 23, 59, 59), + }) + manager.SetCookie("http://www.html-kit.com/", cookie) + cef.MessageLoop() + cef.Shutdown() + + +if __name__ == '__main__': + main() diff --git a/examples/snippets/window_size.py b/examples/snippets/window_size.py new file mode 100644 index 000000000..5a7b04d0f --- /dev/null +++ b/examples/snippets/window_size.py @@ -0,0 +1,38 @@ +""" +Set initial window size to 900/640px without use of +any third party GUI framework. On Linux/Mac you can set +window size by calling WindowInfo.SetAsChild. On Windows +you can accomplish this by calling Windows native functions +using the ctypes module. +""" + +from cefpython3 import cefpython as cef +import ctypes +import platform + + +def main(): + cef.Initialize() + window_info = cef.WindowInfo() + parent_handle = 0 + # This call has effect only on Mac and Linux. + # All rect coordinates are applied including X and Y parameters. + window_info.SetAsChild(parent_handle, [0, 0, 900, 640]) + browser = cef.CreateBrowserSync(url="https://www.google.com/", + window_info=window_info, + window_title="Window size") + if platform.system() == "Windows": + window_handle = browser.GetOuterWindowHandle() + insert_after_handle = 0 + # X and Y parameters are ignored by setting the SWP_NOMOVE flag + SWP_NOMOVE = 0x0002 + # noinspection PyUnresolvedReferences + ctypes.windll.user32.SetWindowPos(window_handle, insert_after_handle, + 0, 0, 900, 640, SWP_NOMOVE) + cef.MessageLoop() + del browser + cef.Shutdown() + + +if __name__ == '__main__': + main() diff --git a/examples/tkinter_.py b/examples/tkinter_.py index 024e0feb2..327f171fb 100644 --- a/examples/tkinter_.py +++ b/examples/tkinter_.py @@ -13,8 +13,11 @@ # Known issue on Linux: When typing url, mouse must be over url # entry widget otherwise keyboard focus is lost (Issue #255 # and Issue #284). +# Other focus issues discussed in Issue #535. + from cefpython3 import cefpython as cef +import ctypes try: import tkinter as tk except ImportError: @@ -41,7 +44,7 @@ def main(): - logger.setLevel(_logging.INFO) + logger.setLevel(_logging.DEBUG) stream_handler = _logging.StreamHandler() formatter = _logging.Formatter("[%(filename)s] %(message)s") stream_handler.setFormatter(formatter) @@ -52,22 +55,26 @@ def main(): logger.info("Tk {ver}".format(ver=tk.Tcl().eval('info patchlevel'))) assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this" sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error + # Tk must be initialized before CEF otherwise fatal error (Issue #306) root = tk.Tk() app = MainFrame(root) - # Tk must be initialized before CEF otherwise fatal error (Issue #306) - cef.Initialize() + settings = {} + if MAC: + settings["external_message_pump"] = True + cef.Initialize(settings=settings) app.mainloop() + logger.debug("Main loop exited") cef.Shutdown() - class MainFrame(tk.Frame): def __init__(self, root): self.browser_frame = None self.navigation_bar = None + self.root = root # Root - root.geometry("800x600") + root.geometry("900x640") tk.Grid.rowconfigure(root, 0, weight=1) tk.Grid.columnconfigure(root, 0, weight=1) @@ -121,7 +128,9 @@ def on_focus_out(self, _): def on_close(self): if self.browser_frame: self.browser_frame.on_root_close() - self.master.destroy() + self.browser_frame = None + else: + self.master.destroy() def get_browser(self): if self.browser_frame: @@ -144,14 +153,16 @@ def setup_icon(self): class BrowserFrame(tk.Frame): - def __init__(self, master, navigation_bar=None): + def __init__(self, mainframe, navigation_bar=None): self.navigation_bar = navigation_bar self.closing = False self.browser = None - tk.Frame.__init__(self, master) + tk.Frame.__init__(self, mainframe) + self.mainframe = mainframe self.bind("", self.on_focus_in) self.bind("", self.on_focus_out) self.bind("", self.on_configure) + """For focus problems see Issue #255 and Issue #535. """ self.focus_set() def embed_browser(self): @@ -161,27 +172,42 @@ def embed_browser(self): self.browser = cef.CreateBrowserSync(window_info, url="https://www.google.com/") assert self.browser + self.browser.SetClientHandler(LifespanHandler(self)) self.browser.SetClientHandler(LoadHandler(self)) self.browser.SetClientHandler(FocusHandler(self)) self.message_loop_work() def get_window_handle(self): - if self.winfo_id() > 0: - return self.winfo_id() - elif MAC: - # On Mac window id is an invalid negative value (Issue #308). - # This is kind of a dirty hack to get window handle using - # PyObjC package. If you change structure of windows then you + if MAC: + # Do not use self.winfo_id() on Mac, because of these issues: + # 1. Window id sometimes has an invalid negative value (Issue #308). + # 2. Even with valid window id it crashes during the call to NSView.setAutoresizingMask: + # https://github.com/cztomczak/cefpython/issues/309#issuecomment-661094466 + # + # To fix it using PyObjC package to obtain window handle. If you change structure of windows then you # need to do modifications here as well. + # + # There is still one issue with this solution. Sometimes there is more than one window, for example when application + # didn't close cleanly last time Python displays an NSAlert window asking whether to Reopen that window. In such + # case app will crash and you will see in console: + # > Fatal Python error: PyEval_RestoreThread: NULL tstate + # > zsh: abort python tkinter_.py + # Error messages related to this: https://github.com/cztomczak/cefpython/issues/441 + # + # There is yet another issue that might be related as well: + # https://github.com/cztomczak/cefpython/issues/583 + # noinspection PyUnresolvedReferences from AppKit import NSApp # noinspection PyUnresolvedReferences import objc - # Sometimes there is more than one window, when application - # didn't close cleanly last time Python displays an NSAlert - # window asking whether to Reopen that window. + logger.info("winfo_id={}".format(self.winfo_id())) # noinspection PyUnresolvedReferences - return objc.pyobjc_id(NSApp.windows()[-1].contentView()) + content_view = objc.pyobjc_id(NSApp.windows()[-1].contentView()) + logger.info("content_view={}".format(content_view)) + return content_view + elif self.winfo_id() > 0: + return self.winfo_id() else: raise Exception("Couldn't obtain window handle") @@ -201,7 +227,9 @@ def on_root_configure(self): def on_mainframe_configure(self, width, height): if self.browser: if WINDOWS: - WindowUtils.OnSize(self.get_window_handle(), 0, 0, 0) + ctypes.windll.user32.SetWindowPos( + self.browser.GetWindowHandle(), 0, + 0, 0, width, height, 0x0002) elif LINUX: self.browser.SetBounds(0, 0, width, height) self.browser.NotifyMoveOrResizeStarted() @@ -213,14 +241,20 @@ def on_focus_in(self, _): def on_focus_out(self, _): logger.debug("BrowserFrame.on_focus_out") - if self.browser: + """For focus problems see Issue #255 and Issue #535. """ + if LINUX and self.browser: self.browser.SetFocus(False) def on_root_close(self): + logger.info("BrowserFrame.on_root_close") if self.browser: + logger.debug("CloseBrowser") self.browser.CloseBrowser(True) self.clear_browser_references() - self.destroy() + else: + logger.debug("tk.Frame.destroy") + self.destroy() + def clear_browser_references(self): # Clear browser references that you keep anywhere in your @@ -228,6 +262,16 @@ def clear_browser_references(self): self.browser = None +class LifespanHandler(object): + + def __init__(self, tkFrame): + self.tkFrame = tkFrame + + def OnBeforeClose(self, browser, **_): + logger.debug("LifespanHandler.OnBeforeClose") + self.tkFrame.quit() + + class LoadHandler(object): def __init__(self, browser_frame): @@ -239,6 +283,7 @@ def OnLoadStart(self, browser, **_): class FocusHandler(object): + """For focus problems see Issue #255 and Issue #535. """ def __init__(self, browser_frame): self.browser_frame = browser_frame @@ -250,13 +295,15 @@ def OnTakeFocus(self, next_component, **_): def OnSetFocus(self, source, **_): logger.debug("FocusHandler.OnSetFocus, source={source}" .format(source=source)) - return False + if LINUX: + return False + else: + return True def OnGotFocus(self, **_): - """Fix CEF focus issues (#255). Call browser frame's focus_set - to get rid of type cursor in url entry widget.""" logger.debug("FocusHandler.OnGotFocus") - self.browser_frame.focus_set() + if LINUX: + self.browser_frame.focus_set() class NavigationBar(tk.Frame): @@ -337,7 +384,7 @@ def on_load_url(self, _): self.master.get_browser().LoadUrl(self.url_entry.get()) def on_button1(self, _): - """Fix CEF focus issues (#255). See also FocusHandler.OnGotFocus.""" + """For focus problems see Issue #255 and Issue #535. """ logger.debug("NavigationBar.on_button1") self.master.master.focus_force() diff --git a/examples/tutorial.py b/examples/tutorial.py index a4dbf49e8..860bbe12c 100644 --- a/examples/tutorial.py +++ b/examples/tutorial.py @@ -1,5 +1,5 @@ # Tutorial example. Doesn't depend on any third party GUI framework. -# Tested with CEF Python v56.2+ +# Tested with CEF Python v57.0+ from cefpython3 import cefpython as cef import base64 @@ -78,10 +78,14 @@ def main(): def check_versions(): - print("[tutorial.py] CEF Python {ver}".format(ver=cef.__version__)) + ver = cef.GetVersion() + print("[tutorial.py] CEF Python {ver}".format(ver=ver["version"])) + print("[tutorial.py] Chromium {ver}".format(ver=ver["chrome_version"])) + print("[tutorial.py] CEF {ver}".format(ver=ver["cef_version"])) print("[tutorial.py] Python {ver} {arch}".format( - ver=platform.python_version(), arch=platform.architecture()[0])) - assert cef.__version__ >= "56.2", "CEF Python v56.2+ required to run this" + ver=platform.python_version(), + arch=platform.architecture()[0])) + assert cef.__version__ >= "57.0", "CEF Python v57.0+ required to run this" def html_to_data_uri(html, js_callback=None): diff --git a/examples/wxpython.py b/examples/wxpython.py index 6adfa9c4f..92dd7d834 100644 --- a/examples/wxpython.py +++ b/examples/wxpython.py @@ -5,7 +5,7 @@ # - wxPython 4.0 on Windows/Mac/Linux # - wxPython 3.0 on Windows/Mac # - wxPython 2.8 on Linux -# - CEF Python v55.4+ +# - CEF Python v66.0+ import wx from cefpython3 import cefpython as cef @@ -13,17 +13,25 @@ import sys import os -# Fix for PyCharm hints warnings when using static methods -WindowUtils = cef.WindowUtils() - # Platforms WINDOWS = (platform.system() == "Windows") LINUX = (platform.system() == "Linux") MAC = (platform.system() == "Darwin") +if MAC: + try: + # noinspection PyUnresolvedReferences + from AppKit import NSApp + except ImportError: + print("[wxpython.py] Error: PyObjC package is missing, " + "cannot fix Issue #371") + print("[wxpython.py] To install PyObjC type: " + "pip install -U pyobjc") + sys.exit(1) + # Configuration -WIDTH = 800 -HEIGHT = 600 +WIDTH = 900 +HEIGHT = 640 # Globals g_count_windows = 0 @@ -33,6 +41,12 @@ def main(): check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error settings = {} + if MAC: + # Issue #442 requires enabling message pump on Mac + # and calling message loop work in a timer both at + # the same time. This is an incorrect approach + # and only a temporary fix. + settings["external_message_pump"] = True if WINDOWS: # noinspection PyUnresolvedReferences, PyArgumentList cef.DpiAware.EnableHighDpiSupport() @@ -51,25 +65,59 @@ def check_versions(): ver=platform.python_version(), arch=platform.architecture()[0])) print("[wxpython.py] wxPython {ver}".format(ver=wx.version())) # CEF Python version requirement - assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this" + assert cef.__version__ >= "66.0", "CEF Python v66.0+ required to run this" + + +def scale_window_size_for_high_dpi(width, height): + """Scale window size for high DPI devices. This func can be + called on all operating systems, but scales only for Windows. + If scaled value is bigger than the work area on the display + then it will be reduced.""" + if not WINDOWS: + return width, height + (_, _, max_width, max_height) = wx.GetClientDisplayRect().Get() + # noinspection PyUnresolvedReferences + (width, height) = cef.DpiAware.Scale((width, height)) + if width > max_width: + width = max_width + if height > max_height: + height = max_height + return width, height class MainFrame(wx.Frame): def __init__(self): - wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, - title='wxPython example', size=(WIDTH, HEIGHT)) self.browser = None # Must ignore X11 errors like 'BadWindow' and others by # installing X11 error handlers. This must be done after # wx was intialized. if LINUX: - WindowUtils.InstallX11ErrorHandlers() + cef.WindowUtils.InstallX11ErrorHandlers() global g_count_windows g_count_windows += 1 + if WINDOWS: + # noinspection PyUnresolvedReferences, PyArgumentList + print("[wxpython.py] System DPI settings: %s" + % str(cef.DpiAware.GetSystemDpi())) + if hasattr(wx, "GetDisplayPPI"): + print("[wxpython.py] wx.GetDisplayPPI = %s" % wx.GetDisplayPPI()) + print("[wxpython.py] wx.GetDisplaySize = %s" % wx.GetDisplaySize()) + + print("[wxpython.py] MainFrame declared size: %s" + % str((WIDTH, HEIGHT))) + size = scale_window_size_for_high_dpi(WIDTH, HEIGHT) + print("[wxpython.py] MainFrame DPI scaled size: %s" % str(size)) + + wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, + title='wxPython example', size=size) + # wxPython will set a smaller size when it is bigger + # than desktop size. + print("[wxpython.py] MainFrame actual size: %s" % self.GetSize()) + self.setup_icon() self.create_menu() self.Bind(wx.EVT_CLOSE, self.OnClose) @@ -81,20 +129,12 @@ def __init__(self): self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize) if MAC: - try: - # noinspection PyUnresolvedReferences - from AppKit import NSApp - # Make the content view for the window have a layer. - # This will make all sub-views have layers. This is - # necessary to ensure correct layer ordering of all - # child views and their layers. This fixes Window - # glitchiness during initial loading on Mac (Issue #371). - NSApp.windows()[0].contentView().setWantsLayer_(True) - except ImportError: - print("[wxpython.py] Warning: PyObjC package is missing, " - "cannot fix Issue #371") - print("[wxpython.py] To install PyObjC type: " - "pip install -U pyobjc") + # Make the content view for the window have a layer. + # This will make all sub-views have layers. This is + # necessary to ensure correct layer ordering of all + # child views and their layers. This fixes Window + # glitchiness during initial loading on Mac (Issue #371). + NSApp.windows()[0].contentView().setWantsLayer_(True) if LINUX: # On Linux must show before embedding browser, so that handle @@ -131,7 +171,7 @@ def create_menu(self): def embed_browser(self): window_info = cef.WindowInfo() (width, height) = self.browser_panel.GetClientSize().Get() - assert self.browser_panel.GetHandle(), "Window handle not available yet" + assert self.browser_panel.GetHandle(), "Window handle not available" window_info.SetAsChild(self.browser_panel.GetHandle(), [0, 0, width, height]) self.browser = cef.CreateBrowserSync(window_info, @@ -142,16 +182,16 @@ def OnSetFocus(self, _): if not self.browser: return if WINDOWS: - WindowUtils.OnSetFocus(self.browser_panel.GetHandle(), - 0, 0, 0) + cef.WindowUtils.OnSetFocus(self.browser_panel.GetHandle(), + 0, 0, 0) self.browser.SetFocus(True) def OnSize(self, _): if not self.browser: return if WINDOWS: - WindowUtils.OnSize(self.browser_panel.GetHandle(), - 0, 0, 0) + cef.WindowUtils.OnSize(self.browser_panel.GetHandle(), + 0, 0, 0) elif LINUX: (x, y) = (0, 0) (width, height) = self.browser_panel.GetSize().Get() diff --git a/patches/issue231.patch b/patches/issue231.patch index 6e62498ed..8bcb91fb0 100644 --- a/patches/issue231.patch +++ b/patches/issue231.patch @@ -115,7 +115,7 @@ index 15026ab5..a3d21052 100644 --- libcef_dll/wrapper/libcef_dll_wrapper.cc +++ libcef_dll/wrapper/libcef_dll_wrapper.cc @@ -880,6 +880,23 @@ CEF_GLOBAL bool CefGetPath(PathKey key, CefString& path) { - return _retval?true:false; + return _retval ? true : false; } +CEF_GLOBAL bool CefOverridePath(PathKey key, const CefString& path) { diff --git a/patches/issue251.patch b/patches/issue251.patch deleted file mode 100644 index dabe34743..000000000 --- a/patches/issue251.patch +++ /dev/null @@ -1,366 +0,0 @@ -diff --git include/capi/cef_drag_data_capi.h include/capi/cef_drag_data_capi.h -index e1fcfd8c..084fea20 100644 ---- include/capi/cef_drag_data_capi.h -+++ include/capi/cef_drag_data_capi.h -@@ -39,6 +39,7 @@ - #pragma once - - #include "include/capi/cef_base_capi.h" -+#include "include/capi/cef_image_capi.h" - #include "include/capi/cef_stream_capi.h" - - #ifdef __cplusplus -@@ -195,6 +196,21 @@ typedef struct _cef_drag_data_t { - /// - void (CEF_CALLBACK *add_file)(struct _cef_drag_data_t* self, - const cef_string_t* path, const cef_string_t* display_name); -+ -+ /// -+ // Get image representation of drag data (may be NULL). -+ /// -+ struct _cef_image_t* (CEF_CALLBACK *get_image)(struct _cef_drag_data_t* self); -+ -+ /// -+ // Get image hotspot (drag start location relative to image dimensions). -+ /// -+ cef_point_t (CEF_CALLBACK *get_image_hotspot)(struct _cef_drag_data_t* self); -+ -+ /// -+ // Whether image representation of drag data is available. -+ /// -+ int (CEF_CALLBACK *has_image)(struct _cef_drag_data_t* self); - } cef_drag_data_t; - - -diff --git include/cef_drag_data.h include/cef_drag_data.h -index 29b85e84..de37ecc4 100644 ---- include/cef_drag_data.h -+++ include/cef_drag_data.h -@@ -39,6 +39,7 @@ - #pragma once - - #include "include/cef_base.h" -+#include "include/cef_image.h" - #include "include/cef_stream.h" - #include - -@@ -193,6 +194,24 @@ class CefDragData : public virtual CefBaseRefCounted { - /// - /*--cef(optional_param=display_name)--*/ - virtual void AddFile(const CefString& path, const CefString& display_name) =0; -+ -+ /// -+ // Get image representation of drag data (may be NULL). -+ /// -+ /*--cef()--*/ -+ virtual CefRefPtr GetImage() =0; -+ -+ /// -+ // Get image hotspot (drag start location relative to image dimensions). -+ /// -+ /*--cef()--*/ -+ virtual CefPoint GetImageHotspot() =0; -+ -+ /// -+ // Whether image representation of drag data is available. -+ /// -+ /*--cef()--*/ -+ virtual bool HasImage() =0; - }; - - #endif // CEF_INCLUDE_CEF_DRAG_DATA_H_ -diff --git libcef/browser/osr/browser_platform_delegate_osr.cc libcef/browser/osr/browser_platform_delegate_osr.cc -index 148ef49c..bfec55b7 100644 ---- libcef/browser/osr/browser_platform_delegate_osr.cc -+++ libcef/browser/osr/browser_platform_delegate_osr.cc -@@ -7,6 +7,7 @@ - #include - - #include "libcef/browser/browser_host_impl.h" -+#include "libcef/browser/image_impl.h" - #include "libcef/browser/osr/render_widget_host_view_osr.h" - #include "libcef/browser/osr/web_contents_view_osr.h" - #include "libcef/common/drag_data_impl.h" -@@ -432,7 +433,11 @@ void CefBrowserPlatformDelegateOsr::StartDragging( - CefRefPtr handler = - browser_->GetClient()->GetRenderHandler(); - if (handler.get()) { -- CefRefPtr drag_data(new CefDragDataImpl(drop_data)); -+ CefRefPtr cef_image(new CefImageImpl(image)); -+ CefPoint cef_image_pos(CefPoint(image_offset.x(), image_offset.y())); -+ CefRefPtr drag_data(new CefDragDataImpl(drop_data, -+ cef_image, -+ cef_image_pos)); - drag_data->SetReadOnly(true); - base::MessageLoop::ScopedNestableTaskAllower allow( - base::MessageLoop::current()); -diff --git libcef/common/drag_data_impl.cc libcef/common/drag_data_impl.cc -index a8e2c8e1..6db3da39 100644 ---- libcef/common/drag_data_impl.cc -+++ libcef/common/drag_data_impl.cc -@@ -19,6 +19,15 @@ CefDragDataImpl::CefDragDataImpl(const content::DropData& data) - read_only_(false) { - } - -+CefDragDataImpl::CefDragDataImpl(const content::DropData& data, -+ CefRefPtr image, -+ const CefPoint& image_hotspot) -+ : data_(data), -+ image_(image), -+ image_hotspot_(image_hotspot), -+ read_only_(false) { -+} -+ - CefDragDataImpl::CefDragDataImpl() - : read_only_(false) { - } -@@ -31,7 +40,7 @@ CefRefPtr CefDragDataImpl::Clone() { - CefDragDataImpl* drag_data = NULL; - { - base::AutoLock lock_scope(lock_); -- drag_data = new CefDragDataImpl(data_); -+ drag_data = new CefDragDataImpl(data_, image_, image_hotspot_); - } - return drag_data; - } -@@ -187,3 +196,18 @@ void CefDragDataImpl::SetReadOnly(bool read_only) { - - read_only_ = read_only; - } -+ -+CefRefPtr CefDragDataImpl::GetImage() { -+ base::AutoLock lock_scope(lock_); -+ return image_; -+} -+ -+CefPoint CefDragDataImpl::GetImageHotspot() { -+ base::AutoLock lock_scope(lock_); -+ return image_hotspot_; -+} -+ -+bool CefDragDataImpl::HasImage() { -+ base::AutoLock lock_scope(lock_); -+ return image_ ? true : false; -+} -diff --git libcef/common/drag_data_impl.h libcef/common/drag_data_impl.h -index 64f29ed3..37c398d2 100644 ---- libcef/common/drag_data_impl.h -+++ libcef/common/drag_data_impl.h -@@ -7,6 +7,7 @@ - #pragma once - - #include "include/cef_drag_data.h" -+#include "include/cef_image.h" - - #include - -@@ -18,6 +19,9 @@ class CefDragDataImpl : public CefDragData { - public: - CefDragDataImpl(); - explicit CefDragDataImpl(const content::DropData& data); -+ CefDragDataImpl(const content::DropData& data, -+ CefRefPtr image, -+ const CefPoint& image_hotspot); - - CefRefPtr Clone() override; - bool IsReadOnly() override; -@@ -41,6 +45,9 @@ class CefDragDataImpl : public CefDragData { - void SetFragmentBaseURL(const CefString& fragment) override; - void ResetFileContents() override; - void AddFile(const CefString& path, const CefString& display_name) override; -+ CefRefPtr GetImage() override; -+ CefPoint GetImageHotspot() override; -+ bool HasImage() override; - - // This method is not safe. Use Lock/Unlock to get mutually exclusive access. - content::DropData* drop_data() { -@@ -53,6 +60,8 @@ class CefDragDataImpl : public CefDragData { - - private: - content::DropData data_; -+ CefRefPtr image_; -+ CefPoint image_hotspot_; - - // True if this object is read-only. - bool read_only_; -diff --git libcef_dll/cpptoc/drag_data_cpptoc.cc libcef_dll/cpptoc/drag_data_cpptoc.cc -index 381b88b9..01a39793 100644 ---- libcef_dll/cpptoc/drag_data_cpptoc.cc -+++ libcef_dll/cpptoc/drag_data_cpptoc.cc -@@ -11,6 +11,7 @@ - // - - #include "libcef_dll/cpptoc/drag_data_cpptoc.h" -+#include "libcef_dll/cpptoc/image_cpptoc.h" - #include "libcef_dll/cpptoc/stream_writer_cpptoc.h" - #include "libcef_dll/transfer_util.h" - -@@ -367,6 +368,50 @@ void CEF_CALLBACK drag_data_add_file(struct _cef_drag_data_t* self, - CefString(display_name)); - } - -+struct _cef_image_t* CEF_CALLBACK drag_data_get_image( -+ struct _cef_drag_data_t* self) { -+ // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING -+ -+ DCHECK(self); -+ if (!self) -+ return NULL; -+ -+ // Execute -+ CefRefPtr _retval = CefDragDataCppToC::Get(self)->GetImage(); -+ -+ // Return type: refptr_same -+ return CefImageCppToC::Wrap(_retval); -+} -+ -+cef_point_t CEF_CALLBACK drag_data_get_image_hotspot( -+ struct _cef_drag_data_t* self) { -+ // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING -+ -+ DCHECK(self); -+ if (!self) -+ return CefPoint(); -+ -+ // Execute -+ cef_point_t _retval = CefDragDataCppToC::Get(self)->GetImageHotspot(); -+ -+ // Return type: simple -+ return _retval; -+} -+ -+int CEF_CALLBACK drag_data_has_image(struct _cef_drag_data_t* self) { -+ // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING -+ -+ DCHECK(self); -+ if (!self) -+ return 0; -+ -+ // Execute -+ bool _retval = CefDragDataCppToC::Get(self)->HasImage(); -+ -+ // Return type: bool -+ return _retval; -+} -+ - } // namespace - - -@@ -395,6 +440,9 @@ CefDragDataCppToC::CefDragDataCppToC() { - GetStruct()->set_fragment_base_url = drag_data_set_fragment_base_url; - GetStruct()->reset_file_contents = drag_data_reset_file_contents; - GetStruct()->add_file = drag_data_add_file; -+ GetStruct()->get_image = drag_data_get_image; -+ GetStruct()->get_image_hotspot = drag_data_get_image_hotspot; -+ GetStruct()->has_image = drag_data_has_image; - } - - template<> CefRefPtr CefCppToCRefCounted CefDragDataCToCpp::GetImage() { -+ cef_drag_data_t* _struct = GetStruct(); -+ if (CEF_MEMBER_MISSING(_struct, get_image)) -+ return NULL; -+ -+ // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING -+ -+ // Execute -+ cef_image_t* _retval = _struct->get_image(_struct); -+ -+ // Return type: refptr_same -+ return CefImageCToCpp::Wrap(_retval); -+} -+ -+CefPoint CefDragDataCToCpp::GetImageHotspot() { -+ cef_drag_data_t* _struct = GetStruct(); -+ if (CEF_MEMBER_MISSING(_struct, get_image_hotspot)) -+ return CefPoint(); -+ -+ // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING -+ -+ // Execute -+ cef_point_t _retval = _struct->get_image_hotspot(_struct); -+ -+ // Return type: simple -+ return _retval; -+} -+ -+bool CefDragDataCToCpp::HasImage() { -+ cef_drag_data_t* _struct = GetStruct(); -+ if (CEF_MEMBER_MISSING(_struct, has_image)) -+ return false; -+ -+ // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING -+ -+ // Execute -+ int _retval = _struct->has_image(_struct); -+ -+ // Return type: bool -+ return _retval?true:false; -+} -+ - - // CONSTRUCTOR - Do not edit by hand. - -diff --git libcef_dll/ctocpp/drag_data_ctocpp.h libcef_dll/ctocpp/drag_data_ctocpp.h -index 5b202710..20262388 100644 ---- libcef_dll/ctocpp/drag_data_ctocpp.h -+++ libcef_dll/ctocpp/drag_data_ctocpp.h -@@ -54,6 +54,9 @@ class CefDragDataCToCpp - void SetFragmentBaseURL(const CefString& base_url) OVERRIDE; - void ResetFileContents() OVERRIDE; - void AddFile(const CefString& path, const CefString& display_name) OVERRIDE; -+ CefRefPtr GetImage() OVERRIDE; -+ CefPoint GetImageHotspot() OVERRIDE; -+ bool HasImage() OVERRIDE; - }; - - #endif // CEF_LIBCEF_DLL_CTOCPP_DRAG_DATA_CTOCPP_H_ -diff --git tests/ceftests/os_rendering_unittest.cc tests/ceftests/os_rendering_unittest.cc -index 8fa110fa..c8f49d9c 100644 ---- tests/ceftests/os_rendering_unittest.cc -+++ tests/ceftests/os_rendering_unittest.cc -@@ -1007,6 +1007,28 @@ class OSRTestHandler : public RoutingTestHandler, - CefRenderHandler::DragOperationsMask allowed_ops, - int x, int y) override { - if (test_type_ == OSR_TEST_DRAG_DROP_START_DRAGGING && started()) { -+ // Drag image representation -+ EXPECT_TRUE(drag_data->HasImage()); -+ CefRefPtr image = drag_data->GetImage(); -+ EXPECT_TRUE(image.get() != NULL); -+ if (image.get()) { -+ // Drag image height seem to be always + 1px greater than -+ // the drag rect on Linux. But whether this is true on all -+ // platforms not sure, so to be safe lets allow it to be -+ // +/- 1px. -+ EXPECT_GE(image->GetWidth(), GetScaledInt(kDragDivRect.width)); -+ EXPECT_LE(image->GetWidth(), GetScaledInt(kDragDivRect.width) + 1); -+ EXPECT_GE(image->GetHeight(), GetScaledInt(kDragDivRect.height)); -+ EXPECT_LE(image->GetHeight(), GetScaledInt(kDragDivRect.height) + 1); -+ } -+ // During testing hotspot was (15, 23) and with scale_factor 2x -+ // it was (15, 18). I don't know how the algorithm works, so -+ // testing only rect boundaries. -+ CefPoint hotspot = drag_data->GetImageHotspot(); -+ EXPECT_GT(hotspot.x, 0); -+ EXPECT_LT(hotspot.x, GetScaledInt(kDragDivRect.width)); -+ EXPECT_GT(hotspot.y, 0); -+ EXPECT_LT(hotspot.y, GetScaledInt(kDragDivRect.height)); - DestroySucceededTestSoon(); - return false; - } else if ((test_type_ == OSR_TEST_DRAG_DROP_UPDATE_CURSOR || diff --git a/patches/patch.py b/patches/patch.py index 80a33921e..b6358b4dc 100644 --- a/patches/patch.py +++ b/patches/patch.py @@ -1,6 +1,6 @@ # CEF Python patches to Chromium and CEF. # See upstream cef/patch/patch.cfg for how patching works in CEF. -# Current working directory is cef_build_dir/chromium/cef/ . +# Current working directory is cef_build_dir/chromium/src/ . # See also docs/Build-instructions.md and tools/automate.py . import platform @@ -12,11 +12,11 @@ # ALL PLATFORMS # noinspection PyUnresolvedReferences patches.extend([ - { - # Fixes HTTPS cache problems with private certificates - 'name': 'issue125', - 'path': '../net/http/' - }, + #{ + # # (Disabled) Fixes HTTPS cache problems with private certificates + # 'name': 'issue125', + # 'path': 'net/http/' + #}, ]) # LINUX @@ -26,11 +26,6 @@ { # Discovery of the "icudtl.dat" file fails on Linux. 'name': 'issue231', - 'path': './' - }, - { - # Adds drag-image representation during drag & drop in OSR mode. - 'name': 'issue251', - 'path': './' + 'path': 'cef/' }, ]) diff --git a/src/browser.pyx b/src/browser.pyx index 406a01c90..c8cba03ad 100644 --- a/src/browser.pyx +++ b/src/browser.pyx @@ -5,6 +5,7 @@ include "cefpython.pyx" cimport cef_types +from cef_types cimport cef_state_t IF UNAME_SYSNAME == "Linux": cimport x11 @@ -18,6 +19,8 @@ MOUSEBUTTON_RIGHT = cef_types.MBT_RIGHT cdef dict g_pyBrowsers = {} +# See also g_browser_settings defined in cefpython.pyx + # Unreferenced browsers are added to this list in OnBeforeClose(). # Must keep a list of unreferenced browsers so that a new reference # is not created in GetPyBrowser() when browser was closed. @@ -33,6 +36,20 @@ cdef PyBrowser GetPyBrowserById(int browserId): return g_pyBrowsers[browserId] return None +cdef py_bool IsBrowserClosed(CefRefPtr[CefBrowser] cefBrowser): + """Possibly fix Issue #455 by using this helper function to detect + if browser is closing/closed.""" + # CefBrowser may sometimes be NULL e.g. Issue #429, Issue #454. + if not cefBrowser.get(): + return True + if not cefBrowser.get().GetHost().get(): + return True + cdef int browserId = cefBrowser.get().GetIdentifier() + if browserId in g_unreferenced_browsers \ + or browserId in g_closed_browsers: + return True + return False + cdef PyBrowser GetPyBrowser(CefRefPtr[CefBrowser] cefBrowser, callerIdStr="GetPyBrowser"): """The second argument 'callerIdStr' is so that a debug @@ -74,7 +91,8 @@ cdef PyBrowser GetPyBrowser(CefRefPtr[CefBrowser] cefBrowser, cdef JavascriptBindings javascriptBindings cdef PyBrowser tempPyBrowser - if browserId in g_unreferenced_browsers: + if browserId in g_unreferenced_browsers \ + or browserId in g_closed_browsers: # This browser was already unreferenced due to OnBeforeClose # was already called. An incomplete new instance of Browser # object is created. This instance doesn't have the client @@ -106,9 +124,15 @@ cdef PyBrowser GetPyBrowser(CefRefPtr[CefBrowser] cefBrowser, openerHandle = pyBrowser.GetOpenerWindowHandle() for identifier, tempPyBrowser in g_pyBrowsers.items(): if tempPyBrowser.GetWindowHandle() == openerHandle: - clientCallbacks = tempPyBrowser.GetClientCallbacksDict() - if clientCallbacks: - pyBrowser.SetClientCallbacksDict(clientCallbacks) + # tempPyBrowser is a parent browser + if tempPyBrowser.GetSetting("inherit_client_handlers_for_popups"): + if pyBrowser.GetIdentifier() not in g_browser_settings: + g_browser_settings[pyBrowser.GetIdentifier()] = {} + g_browser_settings[pyBrowser.GetIdentifier()]["inherit_client_handlers_for_popups"] =\ + tempPyBrowser.GetSetting("inherit_client_handlers_for_popups") + clientCallbacks = tempPyBrowser.GetClientCallbacksDict() + if clientCallbacks: + pyBrowser.SetClientCallbacksDict(clientCallbacks) javascriptBindings = tempPyBrowser.GetJavascriptBindings() if javascriptBindings: if javascriptBindings.GetBindToPopups(): @@ -119,9 +143,13 @@ cdef PyBrowser GetPyBrowser(CefRefPtr[CefBrowser] cefBrowser, cdef void RemovePyBrowser(int browserId) except *: # Called from LifespanHandler_OnBeforeClose(). global g_pyBrowsers, g_unreferenced_browsers + cdef PyBrowser pyBrowser if browserId in g_pyBrowsers: # noinspection PyUnresolvedReferences Debug("del g_pyBrowsers[%s]" % browserId) + pyBrowser = g_pyBrowsers[browserId] + pyBrowser.cefBrowser.Assign(NULL) + del pyBrowser del g_pyBrowsers[browserId] g_unreferenced_browsers.append(browserId) else: @@ -138,6 +166,15 @@ cpdef PyBrowser GetBrowserByWindowHandle(WindowHandle windowHandle): return pyBrowser return None + +cpdef PyBrowser GetBrowserByIdentifier(int identifier): + cdef PyBrowser pyBrowser + for browserId in g_pyBrowsers: + pyBrowser = g_pyBrowsers[browserId] + if pyBrowser.GetIdentifier() == identifier: + return pyBrowser + return None + cdef public void PyBrowser_ShowDevTools(CefRefPtr[CefBrowser] cefBrowser ) except * with gil: # Called from ClientHandler::OnContextMenuCommand @@ -198,7 +235,8 @@ cdef class PyBrowser: # DisplayHandler self.allowedClientCallbacks += [ "OnAddressChange", "OnTitleChange", "OnTooltip", - "OnStatusMessage", "OnConsoleMessage"] + "OnStatusMessage", "OnConsoleMessage", "OnAutoResize", + "OnLoadingProgressChange"] # KeyboardHandler self.allowedClientCallbacks += ["OnPreKeyEvent", "OnKeyEvent"] # RequestHandler @@ -210,7 +248,7 @@ cdef class PyBrowser: "OnQuotaRequest", "OnProtocolExecution", "GetResourceHandler", "OnBeforeBrowse", "OnRendererProcessTerminated", - "OnPluginCrashed"] + "OnPluginCrashed", "CanGetCookies", "CanSetCookie"] # RequestContextHandler self.allowedClientCallbacks += ["GetCookieManager"] # LoadHandler @@ -227,7 +265,11 @@ cdef class PyBrowser: "GetScreenRect", "OnPopupShow", "OnPopupSize", "OnPaint", "OnCursorChange", "OnScrollOffsetChanged", - "StartDragging", "UpdateDragCursor"] + "StartDragging", "UpdateDragCursor", + "OnTextSelectionChanged"] + # V8ContextHandler + self.allowedClientCallbacks += ["OnContextCreated", + "OnContextReleased"] # JavascriptDialogHandler self.allowedClientCallbacks += ["OnJavascriptDialog", "OnBeforeUnloadJavascriptDialog", @@ -274,6 +316,42 @@ cdef class PyBrowser: cpdef JavascriptBindings GetJavascriptBindings(self): return self.javascriptBindings + cdef bytes b(self, int x): + return struct.pack(b'> 8 + red = (pixel & 16711680) >> 16 + offset = (x + width * y) * 3 + pixels[offset:offset+3] = self.b(red), self.b(green),\ + self.b(blue) + XDestroyImage(image) + return b''.join(pixels), width, height + ELSE: + NonCriticalError("GetImage not implemented on this platform") + return None + + cpdef object GetSetting(self, py_string key): + cdef int browser_id = self.GetIdentifier() + if browser_id in g_browser_settings: + if key in g_browser_settings[browser_id]: + return g_browser_settings[browser_id][key] + return None + # -------------- # CEF API. # -------------- @@ -294,7 +372,32 @@ cdef class PyBrowser: pass cpdef py_void CloseBrowser(self, py_bool forceClose=False): + # Browser can be closed in two ways. Either by calling + # CloseBrowser explicitilly or by destroying window + # object and in such case lifespanHandler.OnBeforeClose + # will be called. Debug("CefBrowser::CloseBrowser(%s)" % forceClose) + + # Fix Issue #454 "Crash on exit when closing browser + # immediately during initial loading". + if not self.cefBrowser.get(): + Debug("cefBrowser.get() failed in CloseBrowser") + return + # From testing it seems that only cefBrowser.get() can fail, + # however let's check the host as well just to be safe. + if not self.cefBrowser.get().GetHost().get(): + Debug("cefBrowser.get().GetHost() failed in CloseBrowser") + return + + # Flush cookies to disk. Temporary solution for Issue #365. + # A similar call is made in LifespanHandler_OnBeforeClose. + # If using GetCookieManager to implement custom cookie managers + # then flushing of cookies would need to be handled manually. + self.GetCefBrowserHost().get().GetRequestContext().get() \ + .GetDefaultCookieManager( + NULL) \ + .get().FlushStore(NULL) + cdef int browserId = self.GetCefBrowser().get().GetIdentifier() self.GetCefBrowserHost().get().CloseBrowser(bool(forceClose)) global g_closed_browsers @@ -399,9 +502,16 @@ cdef class PyBrowser: cpdef py_void GoForward(self): self.GetCefBrowser().get().GoForward() + cpdef py_bool HasDevTools(self): + return self.GetCefBrowserHost().get().HasDevTools() + cpdef py_bool HasDocument(self): return self.GetCefBrowser().get().HasDocument() + cpdef py_void Invalidate(self, + cef_types.cef_paint_element_type_t element_type): + return self.GetCefBrowserHost().get().Invalidate(element_type) + cpdef py_bool IsFullscreen(self): return bool(self.isFullscreen) @@ -434,12 +544,26 @@ cdef class PyBrowser: PyToCefString(word, cef_word) self.GetCefBrowserHost().get().ReplaceMisspelling(cef_word) + cpdef py_void SetAutoResizeEnabled(self, + py_bool enabled, + list min_size, + list max_size): + self.GetCefBrowserHost().get().SetAutoResizeEnabled( + bool(enabled), + CefSize(min_size[0], min_size[1]), + CefSize(max_size[0], max_size[1]) + ) + + cpdef py_void SetBounds(self, int x, int y, int width, int height): IF UNAME_SYSNAME == "Linux": x11.SetX11WindowBounds(self.GetCefBrowser(), x, y, width, height) ELSE: NonCriticalError("SetBounds() not implemented on this platform") + cpdef py_void SetAccessibilityState(self, cef_state_t state): + self.GetCefBrowserHost().get().SetAccessibilityState(state) + cpdef py_void SetFocus(self, enable): self.GetCefBrowserHost().get().SetFocus(bool(enable)) @@ -452,11 +576,8 @@ cdef class PyBrowser: cpdef py_void ShowDevTools(self): cdef CefWindowInfo window_info IF UNAME_SYSNAME == "Windows": - # On Windows with empty window_info structure the devtools - # window doesn't appear. - window_info.SetAsPopup( - self.GetOpenerWindowHandle(), - PyToCefStringValue("DevTools")) + window_info.SetAsPopup(self.GetWindowHandle(), + PyToCefStringValue("DevTools")) cdef CefBrowserSettings settings cdef CefPoint inspect_element_at self.GetCefBrowserHost().get().ShowDevTools( diff --git a/src/cef_types.pyx b/src/cef_types.pyx new file mode 100644 index 000000000..6d9ad5fe5 --- /dev/null +++ b/src/cef_types.pyx @@ -0,0 +1,9 @@ +# Copyright (c) 2014 CEF Python, see the Authors file. +# All rights reserved. Licensed under BSD 3-clause license. +# Project website: https://github.com/cztomczak/cefpython + +cimport cef_types + +STATE_DEFAULT = cef_types.STATE_DEFAULT +STATE_ENABLED = cef_types.STATE_ENABLED +STATE_DISABLED = cef_types.STATE_DISABLED diff --git a/src/cef_v32..v51_changes.txt b/src/cef_v32..v51_changes.txt new file mode 100644 index 000000000..d14c1f125 --- /dev/null +++ b/src/cef_v32..v51_changes.txt @@ -0,0 +1,139 @@ +Changes in v31..v51. +Not all changes are listed here. + +CefEnableHighDPISupport() + +CefRequestContext + NEW BROWSER SETTINGS that can be get/set using request context: + * GetAllPreferences - all preferences for browser's request context + * SetPreference + * many more methods has/get/canset... + _cef_request_context_settings_t: + cache_path + persist_session_cookies + persist_user_preferences + ignore_certificate_errors + PurgePluginListCache + GetDefaultCookieManager + GetCachePath + IsSharingWith - possible to create new context that shares + storage with another context + more methods... + +CefRequestContextHandler + OnBeforePluginLoad + +CefBrowserSettings + windowless_frame_rate - **OSR** + +CefBrowserHost + GetNavigationEntries + PrintToPDF + ParentWindowWillClose() - REMOVED, update .py examples + SetWindowVisibility() + ShowDevTools(WindowInfo, CefClient, BrowserSettings, inspect_element_at) + CloseDevTools [DONE] + ReplaceMisspelling + AddWordToDictionary + Invalidate + NotifyMoveOrResizeStarted() - call in WM_MOVE, WM_MOVING, WM_SIZING on Win + GetWindowlessFrameRate - **OSR** + SetWindowlessFrameRate - **OSR** + DragTargetDragEnter + DragTargetDragOver + DragTargetDragLeave + DragTargetDrop + DragSourceEndedAt + DragSourceSystemDragEnded + HasDevTools + DownloadImage + HasView + +CefRequestHandler + OnOpenURLFromTab + OnBeforeResourceLoad - new arg CefRequestCallback + OnResourceResponse + GetResourceResponseFilter - easy way to alter response, no need for the + complicated wxpython-response.py example (Issue #229) + OnResourceLoadComplete + OnCertificateError - new args: browser and ssl_info. + No more need to set it using + cefpython.SetGlobalClientCallback() + OnRenderViewReady + +Support for handling onbeforeunload in LifespanHandler::DoClose with +the use of Browser.TryCloseBrowser() or Browser.CloseBrowser. + +CefRequest + SetReferrer + GetReferrerURL + GetReferrerPolicy + GetIdentifier + +CefResponse + GetError + SetError + +CEF exposes Views/Aura framework as an alternative API +for client applications. This can be a replacement for +WinAPI/GTK/X11/Cocoa UI frameworks. See for more info: +https://bitbucket.org/chromiumembedded/cef/issues/1749 + +CefPrintHandler - Linux only +CefPrintSettings + +CefDisplayHandler + OnFaviconURLChange + OnFullscreenModeChange + +CefRenderHandler + OnCursorChange - new args: type and custom_cursor_info + StartDragging + UpdateDragCursor + OnScrollOffsetChanged - new args: x,y + + +In upstream cefclient: +1. g_signal_connect(G_OBJECT(window_), "configure-event", + G_CALLBACK(&RootWindowGtk::WindowConfigure), this); + browser->GetHost()->NotifyMoveOrResizeStarted(); +2. g_signal_connect(G_OBJECT(window_), "focus-in-event", + G_CALLBACK(&RootWindowGtk::WindowFocusIn), this); + self->browser_window_->SetFocus(true); + +When window is minimized set browser size to 0x0 to reduce resource usage. +See cefclient: +- on Windows see https://github.com/cztomczak/phpdesktop/issues/179 +- on Linux see root_window_gtk.cc > WindowState + +CefContextMenuHandler + RunContextMenu +CefContextMenuParams + GetMisspelledWord + GetDictionarySuggestions + IsSpellCheckEnabled + IsCustomMenu + IsPepperMenu + +CefCompletionCallback - added to many cookie functions to run asynchronously + on the IO thread + +include/cef_parser.h - url/css/json/etc parsers + +CefResourceBundle +CefResponseFilter + +CefValue + +cef_get_current_platform_thread_id() +cef_get_current_platform_thread_handle() + +cef_get_xdisplay(); + +include/cef_ssl_info.h +include/wrapper/cef_helpers.h - CefDeleteOnThread() free object on + the specified thread +include/wrapper/cef_resource_manager.h + +CefPostData + HasExcludedElements diff --git a/src/cef_v59..v66_changes.txt b/src/cef_v59..v66_changes.txt new file mode 100644 index 000000000..fab7e5e75 --- /dev/null +++ b/src/cef_v59..v66_changes.txt @@ -0,0 +1,171 @@ +Changes in v59..v66 + +BREAKAGE (needs updating Migration Guide doc) +-------- + ++ cef_display_handler.h +- + OnConsoleMessage: new param 'level' +- + update migration guide + ++ cef_life_span_handler.h +- + OnBeforePopup: created on UI thread instead of IO thread + - + update checks for thread + - + update migration guide + ++ cef_print_handler.h +- + Modify subprocess/print_handler_gtk.h and .cpp files + (copy from upstream cefclient) +- + OnPrintSettings new param +- + OnPrintDialog new param +- + OnPrintJob new param +- + OnPrintReset new param + ++ cef_render_process_handler.h +- + Remove OnBeforeNavigation in subprocess/cefpython_app.h and .cpp files + ++ cef_request_handler.h +- + OnBeforeBrowse: new param 'user_gesture' +- + update Migration Guide + ++ internal/cef_linux.h ++ internal/cef_types_linux.h ++ internal/cef_mac.h ++ internal/cef_types_mac.h ++ internal/cef_win.h ++ internal/cef_types_win.h +- + OSR windows are transparent by default. To change it set + CefBrowserSettings.background_color . +- + CefWindowInfo (cef_window_info_t): transparent_painting_enabled option removed +- + CefWindowInfo.SetAsWindowless: 'transparent' param removed +- + Deprecate WindowInfo.SetTransparentPainting method. When set + to True do nothing. If set to False then raise Exception + and provide info on CefBrowserSettings.background_color. + - + Update Migration Guide doc + +internal/cef_types.h +- + cef_settings_t: + - + javascript_open_windows option removed (keep a dummy for BC) + - + update Migration Guide +- + cef_thread_id_t: + - + TID_DB removed (update Migration Guide) + - + TID_PROCESS_LAUNCHER removed (update Migration Guide) + - + TID_CACHE removed (update Migration Guide) + - + Added threads: TID_FILE_BACKGROUND, TID_FILE_USER_VISIBLE + + ++ cef_urlrequest.h +- + cef_urlrequest_flags_t: + - + Add: UR_FLAG_ONLY_FROM_CACHE, UR_FLAG_ALLOW_STORED_CREDENTIALS, + UR_FLAG_STOP_ON_REDIRECT + - + Remove: UR_FLAG_ALLOW_CACHED_CREDENTIALS + + +MISC +---- ++ Compare src/client_handler/dialog_handler_gtk.cpp (and .h) with upstream + cefclient files ++ In subprocess/print_handler_gtk.cpp use GetWindow implementation + from x11.cpp + +NEW FEATURES +------------ + ++ unittests/osr_test.py - new test for off-screen rendering mode ++ cefpython.SetGlobalClientHandler ++ Browser.Invalidate ++ CookieManager.FlushStore ++ BrowserSettings.inherit_client_handlers_for_popups ++ Browser.GetSetting ++ cefpython.GetBrowserByIdentifier ++ Browser.HasDevTools ++ examples/snippets/ + + onbeforeclose.py + + network_cookies.py + + mouse_clicks.py + + javascript_bindings.py + + javascript_errors.py + + ondomready.py + + onpagecomplete ++ cef.GetDataUrl + +internal/cef_types.h ++ cef_log_severity_t: new key LOGSEVERITY_DEBUG (no need to expose, + same as LOGSEVERITY_VERBOSE, see code comments in setting.pyx ++ cef_settings_t: + + background_color: OSR windows can set an ARGB background color ++ cef_path_key_t (informational only): + + PK_DIR_RESOURCES new key ++ cef_popup_features_t: some keys removed (not exposed, informational only) ++ cef_referrer_policy_t changes (not exposed, info only) + +cef_accessibility_handler.h ++ CefAccessibilityHandler ++ CefRenderHandler::GetAccessibilityHandler + +cef_render_handler.h ++ OnTextSelectionChanged + +cef_browser.h ++ SetAccessibilityState ++ SetAutoResizeEnabled +- GetExtension +- IsBackgroundHost + +cef_cookie.h ++ GetBlockingManager + +cef_display_handler.h ++ OnAutoResize ++ OnLoadingProgressChange + +cef_drag_data.h ++ GetImage (cross-platform) ++ GetImageHotspot (cross-platform) ++ HasImage (cross-platform) + +cef_extension.h +- CefExtension +- Will require exposing CefRequestContext object and its methods + LoadExtension, DidLoadExtension, etc. + +cef_request_context.h +- LoadExtension +- DidLoadExtension +- HasExtension +- GetExtensions +- GetExtension + +cef_request_context_handler.h +- OnRequestContextInitialized + +cef_extension_handler.h +- CefGetExtensionResourceCallback +- CefExtensionHandler + +cef_file_util.h ++ CefLoadCRLSetsFile + +cef_request_handler.h ++ CanGetCookies ++ CanSetCookie + +cef_response.h +- GetURL +- SetURL + +cef_server.h +- You can easily start a web server in Python, so exposing this API + doesn't seem to be of great value? +- CefServer: a web server that supports HTTP and WebSocket requests +- CefServerHandler + +cef_v8.h +- CefV8ArrayBufferReleaseCallback +- CefV8Value new methods: + - CreateArrayBuffer (does not own the buffer) + - IsArrayBuffer + - GetArrayBufferReleaseCallback + - NeuterArrayBuffer + +cef_urlrequest.h +- ResponseWasCached \ No newline at end of file diff --git a/src/cefpython.pyx b/src/cefpython.pyx index b83af6198..c3b1e1a13 100644 --- a/src/cefpython.pyx +++ b/src/cefpython.pyx @@ -2,152 +2,6 @@ # All rights reserved. Licensed under BSD 3-clause license. # Project website: https://github.com/cztomczak/cefpython -""" -CHANGES in CEF since v31..v51. -Below are listed new or modified functions/classes, but not all of them. -------------------------------------------------------------------------------- - -CefEnableHighDPISupport() - -CefRequestContext - NEW BROWSER SETTINGS that can be get/set using request context: - * GetAllPreferences - all preferences for browser's request context - * SetPreference - * many more methods has/get/canset... - _cef_request_context_settings_t: - cache_path - persist_session_cookies - persist_user_preferences - ignore_certificate_errors - PurgePluginListCache - GetDefaultCookieManager - GetCachePath - IsSharingWith - possible to create new context that shares - storage with another context - more methods... - -CefRequestContextHandler - OnBeforePluginLoad - -CefBrowserSettings - windowless_frame_rate - **OSR** - -CefBrowserHost - GetNavigationEntries - PrintToPDF - ParentWindowWillClose() - REMOVED, update .py examples - SetWindowVisibility() - ShowDevTools(WindowInfo, CefClient, BrowserSettings, inspect_element_at) - CloseDevTools [DONE] - ReplaceMisspelling - AddWordToDictionary - Invalidate - NotifyMoveOrResizeStarted() - call in WM_MOVE, WM_MOVING, WM_SIZING on Win - GetWindowlessFrameRate - **OSR** - SetWindowlessFrameRate - **OSR** - DragTargetDragEnter - DragTargetDragOver - DragTargetDragLeave - DragTargetDrop - DragSourceEndedAt - DragSourceSystemDragEnded - HasDevTools - DownloadImage - HasView - -CefRequestHandler - OnOpenURLFromTab - OnBeforeResourceLoad - new arg CefRequestCallback - OnResourceResponse - GetResourceResponseFilter - easy way to alter response, no need for the - complicated wxpython-response.py example (Issue #229) - OnResourceLoadComplete - OnCertificateError - new args: browser and ssl_info. - No more need to set it using - cefpython.SetGlobalClientCallback() - OnRenderViewReady - -Support for handling onbeforeunload in LifespanHandler::DoClose with -the use of Browser.TryCloseBrowser() or Browser.CloseBrowser. - -CefRequest - SetReferrer - GetReferrerURL - GetReferrerPolicy - GetIdentifier - -CefResponse - GetError - SetError - -CEF exposes Views/Aura framework as an alternative API -for client applications. This can be a replacement for -WinAPI/GTK/X11/Cocoa UI frameworks. See for more info: -https://bitbucket.org/chromiumembedded/cef/issues/1749 - -CefPrintHandler - Linux only -CefPrintSettings - -CefDisplayHandler - OnFaviconURLChange - OnFullscreenModeChange - -CefRenderHandler - OnCursorChange - new args: type and custom_cursor_info - StartDragging - UpdateDragCursor - OnScrollOffsetChanged - new args: x,y - - -In upstream cefclient: -1. g_signal_connect(G_OBJECT(window_), "configure-event", - G_CALLBACK(&RootWindowGtk::WindowConfigure), this); - browser->GetHost()->NotifyMoveOrResizeStarted(); -2. g_signal_connect(G_OBJECT(window_), "focus-in-event", - G_CALLBACK(&RootWindowGtk::WindowFocusIn), this); - self->browser_window_->SetFocus(true); - -When window is minimized set browser size to 0x0 to reduce resource usage. -See cefclient: -- on Windows see https://github.com/cztomczak/phpdesktop/issues/179 -- on Linux see root_window_gtk.cc > WindowState - -CefContextMenuHandler - RunContextMenu -CefContextMenuParams - GetMisspelledWord - GetDictionarySuggestions - IsSpellCheckEnabled - IsCustomMenu - IsPepperMenu - -CefCompletionCallback - added to many cookie functions to run asynchronously - on the IO thread - -include/cef_parser.h - url/css/json/etc parsers - -CefResourceBundle -CefResponseFilter - -CefValue - -cef_get_current_platform_thread_id() -cef_get_current_platform_thread_handle() - -cef_get_xdisplay(); - -include/cef_ssl_info.h -include/wrapper/cef_helpers.h - CefDeleteOnThread() free object on - the specified thread -include/wrapper/cef_resource_manager.h - -CefPostData - HasExcludedElements - -------------------------------------------------------------------------------- -END OF: CHANGES in CEF since v31..v47. -""" - # IMPORTANT notes: # # - cdef/cpdef functions returning something other than a Python object @@ -278,20 +132,26 @@ import json import datetime # noinspection PyUnresolvedReferences import random +# noinspection PyUnresolvedReferences +import struct +# noinspection PyUnresolvedReferences +import base64 -if sys.version_info.major == 2: +# Must use compile-time condition instead of checking sys.version_info.major +# otherwise results in "ImportError: cannot import name urlencode" strange +# error in Python 3.6. +IF PY_MAJOR_VERSION == 2: # noinspection PyUnresolvedReferences import urlparse -else: # noinspection PyUnresolvedReferences - from urllib import parse as urlparse - -if sys.version_info.major == 2: + from urllib import urlencode as urllib_urlencode + from urllib import quote as urlparse_quote +ELSE: # noinspection PyUnresolvedReferences - from urllib import pathname2url as urllib_pathname2url -else: + from urllib import parse as urlparse + from urllib.parse import quote as urlparse_quote # noinspection PyUnresolvedReferences - from urllib.request import pathname2url as urllib_pathname2url + from urllib.parse import urlencode as urllib_urlencode # noinspection PyUnresolvedReferences from cpython.version cimport PY_MAJOR_VERSION @@ -391,6 +251,7 @@ from cef_types cimport ( CefKeyEvent, CefMouseEvent, CefScreenInfo, PathKey, PK_DIR_EXE, PK_DIR_MODULE, int32, uint32, int64, uint64, + cef_log_severity_t, ) # noinspection PyUnresolvedReferences @@ -439,6 +300,7 @@ from main_message_loop cimport * # noinspection PyUnresolvedReferences from cef_views cimport * from cef_log cimport * +from cef_file_util cimport * # ----------------------------------------------------------------------------- # GLOBAL VARIABLES @@ -451,6 +313,7 @@ g_debug = False # The string_encoding key must be set early here and also in Initialize. g_applicationSettings = {"string_encoding": "utf-8"} g_commandLineSwitches = {} +g_browser_settings = {} # If ApplicationSettings.unique_request_context_per_browser is False # then a shared request context is used for all browsers. Otherwise @@ -468,6 +331,7 @@ cdef dict g_globalClientCallbacks = {} # ----------------------------------------------------------------------------- +include "cef_types.pyx" include "utils.pyx" include "string_utils.pyx" IF UNAME_SYSNAME == "Windows": @@ -507,13 +371,10 @@ include "command_line.pyx" include "app.pyx" include "drag_data.pyx" include "helpers.pyx" - -# Currently used only on Linux via DragData. Do not include on other -# platforms otherwise warning about unused function appears. -IF UNAME_SYSNAME == "Linux": - include "image.pyx" +include "image.pyx" # Handlers +include "handlers/accessibility_handler.pyx" include "handlers/browser_process_handler.pyx" include "handlers/display_handler.pyx" include "handlers/focus_handler.pyx" @@ -642,9 +503,7 @@ def Initialize(applicationSettings=None, commandLineSwitches=None, **kwargs): Debug("Initialize() called") - # Mac initialization. Need to call NSApplication.sharedApplication() - # and do NSApplication methods swizzling to implement - # CrAppControlProtocol. See Issue 156. + # Additional initialization on Mac, see util_mac.mm. IF UNAME_SYSNAME == "Darwin": MacInitialize() @@ -726,6 +585,15 @@ def Initialize(applicationSettings=None, commandLineSwitches=None, **kwargs): application_settings["single_process"] = False # ------------------------------------------------------------------------ + # ------------------------------------------------------------------------ + # Fix GPUCache/ folder creation when using in-memory cache (Issue #419) + # ------------------------------------------------------------------------ + if not "cache_path" in application_settings: + application_settings["cache_path"] = "" + if not application_settings["cache_path"]: + g_commandLineSwitches["disable-gpu-shader-disk-cache"] = "" + + cdef CefRefPtr[CefApp] cefApp = new CefPythonApp() IF UNAME_SYSNAME == "Windows": @@ -756,8 +624,11 @@ def Initialize(applicationSettings=None, commandLineSwitches=None, **kwargs): # External message pump if GetAppSetting("external_message_pump")\ and not g_external_message_pump.get(): - g_external_message_pump.reset( - MainMessageLoopExternalPump.Create().get()) + Debug("Create external message pump") + # Using .reset() here to assign new instance was causing + # MainMessageLoopExternalPump destructor to be called. Strange. + g_external_message_pump.Assign( + MainMessageLoopExternalPump.Create()) Debug("CefInitialize()") cdef cpp_bool ret @@ -852,17 +723,18 @@ def CreateBrowserSync(windowInfo=None, if window_title and windowInfo.parentWindowHandle == 0: windowInfo.windowName = window_title + # Browser settings if not browserSettings: browserSettings = {} - + # CEF Python only settings + if "inherit_client_handlers_for_popups" not in browserSettings: + browserSettings["inherit_client_handlers_for_popups"] = True cdef CefBrowserSettings cefBrowserSettings SetBrowserSettings(browserSettings, &cefBrowserSettings) cdef CefWindowInfo cefWindowInfo SetCefWindowInfo(cefWindowInfo, windowInfo) - navigateUrl = GetNavigateUrl(navigateUrl) - Debug("navigateUrl: %s" % navigateUrl) cdef CefString cefNavigateUrl PyToCefString(navigateUrl, cefNavigateUrl) @@ -905,6 +777,15 @@ def CreateBrowserSync(windowInfo=None, Debug("CefBrowser window handle = " +str(cefBrowser.get().GetHost().get().GetWindowHandle())) + # Make a copy as browserSettings is a reference only that might + # get destroyed later. + global g_browser_settings + cdef int browser_id = cefBrowser.get().GetIdentifier() + g_browser_settings[browser_id] = {} + for key in browserSettings: + g_browser_settings[browser_id][key] =\ + copy.deepcopy(browserSettings[key]) + # Request context - part 2/2. if g_applicationSettings["unique_request_context_per_browser"]: requestContextHandler.get().SetBrowser(cefBrowser) @@ -977,11 +858,6 @@ def QuitMessageLoop(): def Shutdown(): Debug("Shutdown()") - # Release shared request context. This is sometimes causing - # segmentation fault, so disabling it for now. See Issue #333: - # https://github.com/cztomczak/cefpython/issues/333 - # OFF: g_shared_request_context.Assign(NULL) - # Run some message loop work, force closing browsers and then run # some message loop work again for the browsers to close cleanly. # @@ -1063,15 +939,26 @@ def Shutdown(): NonCriticalError("Shutdown called, but there are still browser" " references alive") - Debug("CefShutdown()") - with nogil: - CefShutdown() + # Release shared request context. In the past this was sometimes + # causing segmentation fault. See Issue #333: + # https://github.com/cztomczak/cefpython/issues/333 + # Debug("Free g_shared_request_context") + # g_shared_request_context.Assign(NULL) - # Release external message pump, as in cefclient after Shutdown + # Release external message pump before CefShutdown, so that + # message pump timer is killed. if g_external_message_pump.get(): + Debug("Reset external message pump") # Reset will set it to NULL g_external_message_pump.reset() + Debug("CefShutdown()") + with nogil: + CefShutdown() + + # Additional cleanup on Mac, see util_mac.mm. + IF UNAME_SYSNAME == "Darwin": + MacShutdown() def SetOsModalLoop(py_bool modalLoop): cdef cpp_bool cefModalLoop = bool(modalLoop) @@ -1080,12 +967,32 @@ def SetOsModalLoop(py_bool modalLoop): cpdef py_void SetGlobalClientCallback(py_string name, object callback): global g_globalClientCallbacks - if name in ["OnCertificateError", "OnBeforePluginLoad", "OnAfterCreated"]: + # Global callbacks are prefixed with "_" in documentation. + # Accept both with and without a prefix. + if name.startswith("_"): + name = name[1:] + if name in ["OnCertificateError", "OnBeforePluginLoad", "OnAfterCreated", + "OnAccessibilityTreeChange", "OnAccessibilityLocationChange"]: g_globalClientCallbacks[name] = callback else: raise Exception("SetGlobalClientCallback() failed: "\ "invalid callback name = %s" % name) +cpdef py_void SetGlobalClientHandler(object clientHandler): + if not hasattr(clientHandler, "__class__"): + raise Exception("SetGlobalClientHandler() failed: __class__ " + "attribute missing") + cdef dict methods = {} + cdef py_string key + cdef object method + cdef tuple value + for value in inspect.getmembers(clientHandler, + predicate=inspect.ismethod): + key = value[0] + method = value[1] + if key and key[0:2] != '__': + SetGlobalClientCallback(key, method) + cpdef object GetGlobalClientCallback(py_string name): global g_globalClientCallbacks if name in g_globalClientCallbacks: @@ -1111,3 +1018,13 @@ cpdef dict GetVersion(): cef_commit_hash=__cef_commit_hash__, cef_commit_number=__cef_commit_number__, ) + +cpdef LoadCrlSetsFile(py_string path): + CefLoadCRLSetsFile(PyToCefStringValue(path)) + +cpdef GetDataUrl(data, mediatype="html"): + if PY_MAJOR_VERSION >= 3: + data = data.encode("utf-8", "replace") + b64 = base64.b64encode(data).decode("utf-8", "replace") + ret = "data:text/html;base64,{data}".format(data=b64) + return ret diff --git a/src/client_handler/Makefile b/src/client_handler/Makefile index bdb2ee728..25e645ff7 100644 --- a/src/client_handler/Makefile +++ b/src/client_handler/Makefile @@ -23,7 +23,7 @@ SRC = client_handler.cpp cookie_visitor.cpp resource_handler.cpp \ download_handler.cpp focus_handler.cpp js_dialog_handler.cpp \ keyboard_handler.cpp lifespan_handler.cpp load_handler.cpp \ render_handler.cpp request_handler.cpp dialog_handler.cpp \ - cef_log.cpp \ + cef_log.cpp accessibility_handler.cpp \ $(SRC_MORE) OBJ = $(filter %.o, $(SRC:.cpp=.o) $(SRC:.mm=.o)) @@ -37,6 +37,7 @@ INC = -I./../ -I./../common/ -I$(PYTHON_INCLUDE) \ -I/usr/include/glib-2.0 \ -I/usr/include/cairo \ -I/usr/include/pango-1.0 \ + -I/usr/include/harfbuzz \ -I/usr/include/gdk-pixbuf-2.0 \ -I/usr/include/atk-1.0 \ -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include \ diff --git a/src/client_handler/accessibility_handler.cpp b/src/client_handler/accessibility_handler.cpp new file mode 100644 index 000000000..a75ab2f69 --- /dev/null +++ b/src/client_handler/accessibility_handler.cpp @@ -0,0 +1,19 @@ +// Copyright (c) 2018 CEF Python, see the Authors file. +// All rights reserved. Licensed under BSD 3-clause license. +// Project website: https://github.com/cztomczak/cefpython + +#include "accessibility_handler.h" +#include "common/cefpython_public_api.h" + + +void AccessibilityHandler::OnAccessibilityTreeChange( + CefRefPtr value) { + REQUIRE_UI_THREAD(); + AccessibilityHandler_OnAccessibilityTreeChange(value); +} + +void AccessibilityHandler::OnAccessibilityLocationChange( + CefRefPtr value) { + REQUIRE_UI_THREAD(); + AccessibilityHandler_OnAccessibilityLocationChange(value); +} diff --git a/src/client_handler/accessibility_handler.h b/src/client_handler/accessibility_handler.h new file mode 100644 index 000000000..ba18171c5 --- /dev/null +++ b/src/client_handler/accessibility_handler.h @@ -0,0 +1,20 @@ +// Copyright (c) 2018 CEF Python, see the Authors file. +// All rights reserved. Licensed under BSD 3-clause license. +// Project website: https://github.com/cztomczak/cefpython + +#include "common/cefpython_public_api.h" +#include "include/cef_accessibility_handler.h" + + +class AccessibilityHandler : public CefAccessibilityHandler +{ +public: + AccessibilityHandler(){} + virtual ~AccessibilityHandler(){} + + virtual void OnAccessibilityTreeChange(CefRefPtr value) override; + virtual void OnAccessibilityLocationChange(CefRefPtr value) override; + +private: + IMPLEMENT_REFCOUNTING(AccessibilityHandler); +}; diff --git a/src/client_handler/client_handler.cpp b/src/client_handler/client_handler.cpp index f55da8123..daf9a4e59 100644 --- a/src/client_handler/client_handler.cpp +++ b/src/client_handler/client_handler.cpp @@ -30,6 +30,7 @@ bool ClientHandler::OnProcessMessageReceived( CefProcessId source_process, CefRefPtr message) { + // Return true if message was handled. if (source_process != PID_RENDERER) { return false; } @@ -42,6 +43,12 @@ bool ClientHandler::OnProcessMessageReceived( if (arguments->GetSize() == 1 && arguments->GetType(0) == VTYPE_INT) { int64 frameId = arguments->GetInt(0); CefRefPtr frame = browser->GetFrame(frameId); + if (!frame.get()) { + // Frame was already destroyed while IPC messaging was + // executing. Issue #431. User callback will not be + // executed in such case. + return true; + } V8ContextHandler_OnContextCreated(browser, frame); return true; } else { @@ -56,6 +63,11 @@ bool ClientHandler::OnProcessMessageReceived( && arguments->GetType(1) == VTYPE_INT) { int browserId = arguments->GetInt(0); int64 frameId = arguments->GetInt(1); + // Even if frame was alrady destroyed (Issue #431) you still + // want to call V8ContextHandler_OnContextReleased as it releases + // some resources. Thus passing IDs instead of actual + // objects. Cython code in V8ContextHandler_OnContextReleased + // will handle a case when frame is already destroyed. V8ContextHandler_OnContextReleased(browserId, frameId); return true; } else { @@ -75,8 +87,13 @@ bool ClientHandler::OnProcessMessageReceived( int64 frameId = arguments->GetInt(0); CefString functionName = arguments->GetString(1); CefRefPtr functionArguments = arguments->GetList(2); - CefRefPtr frame = browser->GetFrame(frameId); - V8FunctionHandler_Execute(browser, frame, functionName, + // Even if frame was already destroyed (Issue #431) you still + // want to call V8FunctionHandler_Execute, as it can run + // Python code without issues and doesn't require an actual + // frame. Thus passing IDs instead of actual objects. Cython + // code in V8FunctionHandler_Execute will handle a case when + // frame is already destroyed. + V8FunctionHandler_Execute(browser, frameId, functionName, functionArguments); return true; } else { @@ -100,18 +117,6 @@ bool ClientHandler::OnProcessMessageReceived( " messageName=ExecutePythonCallback"; return false; } - } else if (messageName == "RemovePythonCallbacksForFrame") { - CefRefPtr arguments = message->GetArgumentList(); - if (arguments->GetSize() == 1 && arguments->GetType(0) == VTYPE_INT) { - int frameId = arguments->GetInt(0); - RemovePythonCallbacksForFrame(frameId); - return true; - } else { - LOG(ERROR) << "[Browser process] OnProcessMessageReceived():" - " invalid arguments," - " messageName=ExecutePythonCallback"; - return false; - } } return false; } diff --git a/src/client_handler/dialog_handler_gtk.cpp b/src/client_handler/dialog_handler_gtk.cpp index 3d53e78a6..ce5a4d4e0 100644 --- a/src/client_handler/dialog_handler_gtk.cpp +++ b/src/client_handler/dialog_handler_gtk.cpp @@ -1,8 +1,5 @@ -// Default dialog handler implementation on Linux. -// Copied from upstream cefclient with changes: -// - Rewrote GetWindow() func -// - Removed "client" namespace -// - Changed titles of JS alerts, removed URL and "Javascript" word +// COPIED from upstream "cef/tests/cefclient/browser/" directory +// with minor modifications. See the .patch file in current directory. // Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that @@ -10,16 +7,12 @@ #include #include -#include -#include -#include #include "include/cef_browser.h" #include "include/cef_parser.h" #include "include/wrapper/cef_helpers.h" #include "include/base/cef_logging.h" - #include "dialog_handler_gtk.h" #include "x11.h" @@ -43,10 +36,10 @@ std::string GetDescriptionFromMimeType(const std::string& mime_type) { const char* mime_type; const char* label; } kWildCardMimeTypes[] = { - { "audio", "Audio Files" }, - { "image", "Image Files" }, - { "text", "Text Files" }, - { "video", "Video Files" }, + {"audio", "Audio Files"}, + {"image", "Image Files"}, + {"text", "Text Files"}, + {"video", "Video Files"}, }; for (size_t i = 0; @@ -138,52 +131,9 @@ void AddFilters(GtkFileChooser* chooser, } } -GtkWindow* GetWindow(CefRefPtr browser) { - // -- REWRITTEN FOR CEF PYTHON USE CASE -- - // X11 window handle - ::Window xwindow = browser->GetHost()->GetWindowHandle(); - // X11 display - ::Display* xdisplay = cef_get_xdisplay(); - // GDK display - GdkDisplay* gdk_display = NULL; - if (xdisplay) { - // See if we can find GDK display using X11 display - gdk_display = gdk_x11_lookup_xdisplay(xdisplay); - } - if (!gdk_display) { - // If not then get the default display - gdk_display = gdk_display_get_default(); - } - if (!gdk_display) { - // The tkinter_.py and hello_world.py examples do not use GTK - // internally, so GTK wasn't yet initialized and must do it - // now, so that display is available. Also must install X11 - // error handlers to avoid 'BadWindow' errors. - LOG(INFO) << "[Browser process] Initialize GTK"; - gtk_init(0, NULL); - InstallX11ErrorHandlers(); - // Now the display is available - gdk_display = gdk_display_get_default(); - } - // In kivy_.py example getting error message: - // > Can't create GtkPlug as child of non-GtkSocket - // However dialog handler works just fine. - GtkWidget* widget = gtk_plug_new_for_display(gdk_display, xwindow); - // Getting top level widget doesn't seem to be required. - // OFF: GtkWidget* toplevel = gtk_widget_get_toplevel(widget); - GtkWindow* window = GTK_WINDOW(widget); - if (!window) { - LOG(ERROR) << "No GtkWindow for browser"; - } - return window; -} - } // namespace - -ClientDialogHandlerGtk::ClientDialogHandlerGtk() - : gtk_dialog_(NULL) { -} +ClientDialogHandlerGtk::ClientDialogHandlerGtk() : gtk_dialog_(NULL) {} bool ClientDialogHandlerGtk::OnFileDialog( CefRefPtr browser, @@ -200,7 +150,7 @@ bool ClientDialogHandlerGtk::OnFileDialog( // Remove any modifier flags. FileDialogMode mode_type = - static_cast(mode & FILE_DIALOG_TYPE_MASK); + static_cast(mode & FILE_DIALOG_TYPE_MASK); if (mode_type == FILE_DIALOG_OPEN || mode_type == FILE_DIALOG_OPEN_MULTIPLE) { action = GTK_FILE_CHOOSER_ACTION_OPEN; @@ -238,25 +188,20 @@ bool ClientDialogHandlerGtk::OnFileDialog( } } - GtkWindow* window = GetWindow(browser); + GtkWindow* window = CefBrowser_GetGtkWindow(browser); if (!window) return false; GtkWidget* dialog = gtk_file_chooser_dialog_new( - title_str.c_str(), - GTK_WINDOW(window), - action, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - accept_button, GTK_RESPONSE_ACCEPT, - NULL); + title_str.c_str(), GTK_WINDOW(window), action, GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL, accept_button, GTK_RESPONSE_ACCEPT, NULL); if (mode_type == FILE_DIALOG_OPEN_MULTIPLE) gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), TRUE); if (mode_type == FILE_DIALOG_SAVE) { gtk_file_chooser_set_do_overwrite_confirmation( - GTK_FILE_CHOOSER(dialog), - !!(mode & FILE_DIALOG_OVERWRITEPROMPT_FLAG)); + GTK_FILE_CHOOSER(dialog), !!(mode & FILE_DIALOG_OVERWRITEPROMPT_FLAG)); } gtk_file_chooser_set_show_hidden(GTK_FILE_CHOOSER(dialog), @@ -269,8 +214,7 @@ bool ClientDialogHandlerGtk::OnFileDialog( struct stat sb; if (stat(file_path.c_str(), &sb) == 0 && S_ISREG(sb.st_mode)) { // Use the directory and name of the existing file. - gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), - file_path.data()); + gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), file_path.data()); exists = true; } @@ -337,14 +281,13 @@ bool ClientDialogHandlerGtk::OnFileDialog( return true; } -bool ClientDialogHandlerGtk::OnJSDialog( - CefRefPtr browser, - const CefString& origin_url, - JSDialogType dialog_type, - const CefString& message_text, - const CefString& default_prompt_text, - CefRefPtr callback, - bool& suppress_message) { +bool ClientDialogHandlerGtk::OnJSDialog(CefRefPtr browser, + const CefString& origin_url, + JSDialogType dialog_type, + const CefString& message_text, + const CefString& default_prompt_text, + CefRefPtr callback, + bool& suppress_message) { CEF_REQUIRE_UI_THREAD(); GtkButtonsType buttons = GTK_BUTTONS_NONE; @@ -378,26 +321,20 @@ bool ClientDialogHandlerGtk::OnJSDialog( // title += CefFormatUrlForSecurityDisplay(origin_url).ToString(); } - GtkWindow* window = GetWindow(browser); + GtkWindow* window = CefBrowser_GetGtkWindow(browser); if (!window) return false; - gtk_dialog_ = gtk_message_dialog_new(GTK_WINDOW(window), - GTK_DIALOG_MODAL, - gtk_message_type, - buttons, - "%s", + gtk_dialog_ = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_MODAL, + gtk_message_type, buttons, "%s", message_text.ToString().c_str()); - g_signal_connect(gtk_dialog_, - "delete-event", - G_CALLBACK(gtk_widget_hide_on_delete), - NULL); + g_signal_connect(gtk_dialog_, "delete-event", + G_CALLBACK(gtk_widget_hide_on_delete), NULL); gtk_window_set_title(GTK_WINDOW(gtk_dialog_), title.c_str()); GtkWidget* ok_button = gtk_dialog_add_button(GTK_DIALOG(gtk_dialog_), - GTK_STOCK_OK, - GTK_RESPONSE_OK); + GTK_STOCK_OK, GTK_RESPONSE_OK); if (dialog_type != JSDIALOGTYPE_PROMPT) gtk_widget_grab_focus(ok_button); diff --git a/src/client_handler/dialog_handler_gtk.h b/src/client_handler/dialog_handler_gtk.h index aba4857ae..59f65eda1 100644 --- a/src/client_handler/dialog_handler_gtk.h +++ b/src/client_handler/dialog_handler_gtk.h @@ -1,6 +1,5 @@ -// Default dialog handler implementation on Linux. -// Copied from upstream cefclient with changes: -// - Removed "client" namespace +// COPIED from upstream "cef/tests/cefclient/browser/" directory +// with minor modifications. See the .patch file in current directory. // Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that @@ -37,15 +36,14 @@ class ClientDialogHandlerGtk : public CefDialogHandler, const CefString& default_prompt_text, CefRefPtr callback, bool& suppress_message) OVERRIDE; - bool OnBeforeUnloadDialog( - CefRefPtr browser, - const CefString& message_text, - bool is_reload, - CefRefPtr callback) OVERRIDE; + bool OnBeforeUnloadDialog(CefRefPtr browser, + const CefString& message_text, + bool is_reload, + CefRefPtr callback) OVERRIDE; void OnResetDialogState(CefRefPtr browser) OVERRIDE; private: - static void OnDialogResponse(GtkDialog *dialog, + static void OnDialogResponse(GtkDialog* dialog, gint response_id, ClientDialogHandlerGtk* handler); diff --git a/src/client_handler/dialog_handler_gtk.patch b/src/client_handler/dialog_handler_gtk.patch new file mode 100644 index 000000000..784929217 --- /dev/null +++ b/src/client_handler/dialog_handler_gtk.patch @@ -0,0 +1,127 @@ +diff --git dialog_handler_gtk.cc dialog_handler_gtk.cc +index 042be2ca..ce5a4d4e 100644 +--- dialog_handler_gtk.cc ++++ dialog_handler_gtk.cc +@@ -1,18 +1,20 @@ ++// COPIED from upstream "cef/tests/cefclient/browser/" directory ++// with minor modifications. See the .patch file in current directory. ++ + // Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights + // reserved. Use of this source code is governed by a BSD-style license that + // can be found in the LICENSE file. + +-#include "tests/cefclient/browser/dialog_handler_gtk.h" +- + #include + #include + + #include "include/cef_browser.h" + #include "include/cef_parser.h" + #include "include/wrapper/cef_helpers.h" +-#include "tests/cefclient/browser/root_window.h" + +-namespace client { ++#include "include/base/cef_logging.h" ++#include "dialog_handler_gtk.h" ++#include "x11.h" + + namespace { + +@@ -129,18 +131,6 @@ void AddFilters(GtkFileChooser* chooser, + } + } + +-GtkWindow* GetWindow(CefRefPtr browser) { +- scoped_refptr root_window = +- RootWindow::GetForBrowser(browser->GetIdentifier()); +- if (root_window) { +- GtkWindow* window = GTK_WINDOW(root_window->GetWindowHandle()); +- if (!window) +- LOG(ERROR) << "No GtkWindow for browser"; +- return window; +- } +- return NULL; +-} +- + } // namespace + + ClientDialogHandlerGtk::ClientDialogHandlerGtk() : gtk_dialog_(NULL) {} +@@ -198,7 +188,7 @@ bool ClientDialogHandlerGtk::OnFileDialog( + } + } + +- GtkWindow* window = GetWindow(browser); ++ GtkWindow* window = CefBrowser_GetGtkWindow(browser); + if (!window) + return false; + +@@ -308,30 +298,30 @@ bool ClientDialogHandlerGtk::OnJSDialog(CefRefPtr browser, + case JSDIALOGTYPE_ALERT: + buttons = GTK_BUTTONS_NONE; + gtk_message_type = GTK_MESSAGE_WARNING; +- title = "JavaScript Alert"; ++ title = "Alert"; + break; + + case JSDIALOGTYPE_CONFIRM: + buttons = GTK_BUTTONS_CANCEL; + gtk_message_type = GTK_MESSAGE_QUESTION; +- title = "JavaScript Confirm"; ++ title = "Confirm"; + break; + + case JSDIALOGTYPE_PROMPT: + buttons = GTK_BUTTONS_CANCEL; + gtk_message_type = GTK_MESSAGE_QUESTION; +- title = "JavaScript Prompt"; ++ title = "Prompt"; + break; + } + + js_dialog_callback_ = callback; + + if (!origin_url.empty()) { +- title += " - "; +- title += CefFormatUrlForSecurityDisplay(origin_url).ToString(); ++ // title += " - "; ++ // title += CefFormatUrlForSecurityDisplay(origin_url).ToString(); + } + +- GtkWindow* window = GetWindow(browser); ++ GtkWindow* window = CefBrowser_GetGtkWindow(browser); + if (!window) + return false; + +@@ -413,5 +403,3 @@ void ClientDialogHandlerGtk::OnDialogResponse(GtkDialog* dialog, + + handler->OnResetDialogState(NULL); + } +- +-} // namespace client +diff --git dialog_handler_gtk.h dialog_handler_gtk.h +index 163d0a35..59f65eda 100644 +--- dialog_handler_gtk.h ++++ dialog_handler_gtk.h +@@ -1,3 +1,6 @@ ++// COPIED from upstream "cef/tests/cefclient/browser/" directory ++// with minor modifications. See the .patch file in current directory. ++ + // Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights + // reserved. Use of this source code is governed by a BSD-style license that + // can be found in the LICENSE file. +@@ -11,8 +14,6 @@ + #include "include/cef_dialog_handler.h" + #include "include/cef_jsdialog_handler.h" + +-namespace client { +- + class ClientDialogHandlerGtk : public CefDialogHandler, + public CefJSDialogHandler { + public: +@@ -53,6 +54,4 @@ class ClientDialogHandlerGtk : public CefDialogHandler, + DISALLOW_COPY_AND_ASSIGN(ClientDialogHandlerGtk); + }; + +-} // namespace client +- + #endif // CEF_TESTS_CEFCLIENT_BROWSER_DIALOG_HANDLER_GTK_H_ diff --git a/src/client_handler/display_handler.cpp b/src/client_handler/display_handler.cpp index a30109d06..b00bf6a51 100644 --- a/src/client_handler/display_handler.cpp +++ b/src/client_handler/display_handler.cpp @@ -39,10 +39,24 @@ void DisplayHandler::OnStatusMessage(CefRefPtr browser, bool DisplayHandler::OnConsoleMessage(CefRefPtr browser, - const CefString& message, - const CefString& source, - int line) + cef_log_severity_t level, + const CefString& message, + const CefString& source, + int line) { REQUIRE_UI_THREAD(); - return DisplayHandler_OnConsoleMessage(browser, message, source, line); + return DisplayHandler_OnConsoleMessage(browser, level, message, source, + line); } + +bool DisplayHandler::OnAutoResize(CefRefPtr browser, + const CefSize& new_size) { + REQUIRE_UI_THREAD(); + return DisplayHandler_OnAutoResize(browser, new_size); +} + +void DisplayHandler::OnLoadingProgressChange(CefRefPtr browser, + double progress) { + REQUIRE_UI_THREAD(); + return DisplayHandler_OnLoadingProgressChange(browser, progress); +} \ No newline at end of file diff --git a/src/client_handler/display_handler.h b/src/client_handler/display_handler.h index 6b6810cac..a281713d9 100644 --- a/src/client_handler/display_handler.h +++ b/src/client_handler/display_handler.h @@ -28,10 +28,17 @@ class DisplayHandler : public CefDisplayHandler const CefString& value) override; bool OnConsoleMessage(CefRefPtr browser, + cef_log_severity_t level, const CefString& message, const CefString& source, int line) override; + bool OnAutoResize(CefRefPtr browser, + const CefSize& new_size) override; + + void OnLoadingProgressChange(CefRefPtr browser, + double progress) override; + private: IMPLEMENT_REFCOUNTING(DisplayHandler); }; diff --git a/src/client_handler/lifespan_handler.cpp b/src/client_handler/lifespan_handler.cpp index d54f5f0a5..b4d7d52f6 100644 --- a/src/client_handler/lifespan_handler.cpp +++ b/src/client_handler/lifespan_handler.cpp @@ -21,7 +21,7 @@ bool LifespanHandler::OnBeforePopup(CefRefPtr browser, CefBrowserSettings& settings, bool* no_javascript_access) { - REQUIRE_IO_THREAD(); + REQUIRE_UI_THREAD(); // Note: passing popupFeatures is not yet supported. const int popupFeaturesNotImpl = 0; return LifespanHandler_OnBeforePopup(browser, frame, target_url, diff --git a/src/client_handler/render_handler.cpp b/src/client_handler/render_handler.cpp index f6b4d5bec..cf45d15ee 100644 --- a/src/client_handler/render_handler.cpp +++ b/src/client_handler/render_handler.cpp @@ -106,3 +106,11 @@ void RenderHandler::UpdateDragCursor(CefRefPtr browser, REQUIRE_UI_THREAD(); RenderHandler_UpdateDragCursor(browser, operation); } + +void RenderHandler::OnTextSelectionChanged(CefRefPtr browser, + const CefString& selected_text, + const CefRange& selected_range) { + REQUIRE_UI_THREAD(); + RenderHandler_OnTextSelectionChanged(browser, selected_text, + selected_range); +} diff --git a/src/client_handler/render_handler.h b/src/client_handler/render_handler.h index 5baae3202..75eee86c5 100644 --- a/src/client_handler/render_handler.h +++ b/src/client_handler/render_handler.h @@ -4,14 +4,21 @@ #include "common/cefpython_public_api.h" #include "include/cef_render_handler.h" +#include "accessibility_handler.h" -class RenderHandler : public CefRenderHandler +class RenderHandler : public CefRenderHandler, + public AccessibilityHandler { public: RenderHandler(){} virtual ~RenderHandler(){} + CefRefPtr GetAccessibilityHandler() + override { + return this; + } + bool GetRootScreenRect(CefRefPtr browser, CefRect& rect) override; @@ -57,6 +64,10 @@ class RenderHandler : public CefRenderHandler void UpdateDragCursor(CefRefPtr browser, cef_drag_operations_mask_t operation) override; + void OnTextSelectionChanged(CefRefPtr browser, + const CefString& selected_text, + const CefRange& selected_range) override; + private: IMPLEMENT_REFCOUNTING(RenderHandler); }; diff --git a/src/client_handler/request_handler.cpp b/src/client_handler/request_handler.cpp index c06e098d3..5227b8921 100644 --- a/src/client_handler/request_handler.cpp +++ b/src/client_handler/request_handler.cpp @@ -9,10 +9,12 @@ bool RequestHandler::OnBeforeBrowse(CefRefPtr browser, CefRefPtr frame, CefRefPtr request, + bool user_gesture, bool is_redirect) { REQUIRE_UI_THREAD(); - return RequestHandler_OnBeforeBrowse(browser, frame, request, is_redirect); + return RequestHandler_OnBeforeBrowse(browser, frame, request, + user_gesture, is_redirect); } @@ -115,3 +117,18 @@ void RequestHandler::OnPluginCrashed(CefRefPtr browser, REQUIRE_UI_THREAD(); RequestHandler_OnPluginCrashed(browser, plugin_path); } + +bool RequestHandler::CanGetCookies(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) { + REQUIRE_IO_THREAD(); + return RequestHandler_CanGetCookies(browser, frame, request); +} + +bool RequestHandler::CanSetCookie(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + const CefCookie& cookie) { + REQUIRE_IO_THREAD(); + return RequestHandler_CanSetCookie(browser, frame, request, cookie); +} diff --git a/src/client_handler/request_handler.h b/src/client_handler/request_handler.h index afaf3f832..7e5e0e6c3 100644 --- a/src/client_handler/request_handler.h +++ b/src/client_handler/request_handler.h @@ -17,6 +17,7 @@ class RequestHandler : public CefRequestHandler bool OnBeforeBrowse(CefRefPtr browser, CefRefPtr frame, CefRefPtr request, + bool user_gesture, bool is_redirect) override; ReturnValue OnBeforeResourceLoad(CefRefPtr browser, @@ -66,6 +67,15 @@ class RequestHandler : public CefRequestHandler void OnPluginCrashed(CefRefPtr browser, const CefString& plugin_path) override; + bool CanGetCookies(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override; + + bool CanSetCookie(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + const CefCookie& cookie) override; + private: IMPLEMENT_REFCOUNTING(RequestHandler); }; diff --git a/src/client_handler/util_mac.h b/src/client_handler/util_mac.h index 37ec7266b..63ee1dff7 100644 --- a/src/client_handler/util_mac.h +++ b/src/client_handler/util_mac.h @@ -11,6 +11,7 @@ #include "include/cef_browser.h" void MacInitialize(); +void MacShutdown(); void MacSetWindowTitle(CefRefPtr browser, char* title); #endif // CEFPYTHON_UTIL_MAC_H_ diff --git a/src/client_handler/util_mac.mm b/src/client_handler/util_mac.mm index f2e14cd1b..4916b253a 100644 --- a/src/client_handler/util_mac.mm +++ b/src/client_handler/util_mac.mm @@ -2,6 +2,16 @@ // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. +// Copyright (c) 2015 CEF Python, see the Authors file. +// All rights reserved. Licensed under BSD 3-clause license. +// Project website: https://github.com/cztomczak/cefpython + +// Some code was copied from here: +// java-cef: src/master/native/util_mac.mm +// upstream cef: src/tests/ceftests/run_all_unittests_mac.mm +// upstream cef: src/tests/cefclient/cefclient_mac.mm +// upstream cef: src/tests/cefsimple/cefsimple_mac.mm + #import "util_mac.h" #import #include @@ -11,13 +21,14 @@ namespace { +// static NSAutoreleasePool* g_autopool = nil; BOOL g_handling_send_event = false; } // namespace -// Add the necessary CrAppControlProtocol -// functionality to NSApplication using categories and swizzling. -@interface NSApplication (CEFPythonApplication) +// Add the necessary CefAppProtocol functionality to NSApplication +// using categories and swizzling (Issue #442, Issue #156). +@interface NSApplication (CEFPythonApplication) - (BOOL)isHandlingSendEvent; - (void)setHandlingSendEvent:(BOOL)handlingSendEvent; @@ -63,9 +74,16 @@ - (void)_swizzled_terminate:(id)sender { @end void MacInitialize() { + // OFF: it's causing a crash during shutdown release + // g_autopool = [[NSAutoreleasePool alloc] init]; [NSApplication sharedApplication]; } +void MacShutdown() { + // OFF: it's causing a crash during shutdown release + // [g_autopool release]; +} + void MacSetWindowTitle(CefRefPtr browser, char* title) { NSView* view = browser->GetHost()->GetWindowHandle(); NSString* nstitle = [NSString stringWithFormat:@"%s" , title]; diff --git a/src/client_handler/x11.cpp b/src/client_handler/x11.cpp index 18f7ce030..2e97a6e91 100644 --- a/src/client_handler/x11.cpp +++ b/src/client_handler/x11.cpp @@ -2,6 +2,9 @@ // All rights reserved. Licensed under BSD 3-clause license. // Project website: https://github.com/cztomczak/cefpython +// NOTE: This file is also used by "subprocess" and "libcefpythonapp" +// targets during build. + #include "x11.h" #include "include/base/cef_logging.h" @@ -24,6 +27,7 @@ void InstallX11ErrorHandlers() { // Copied from upstream cefclient. // Install xlib error handlers so that the application won't be terminated // on non-fatal errors. Must be done after initializing GTK. + LOG(INFO) << "[Browser process] Install X11 error handlers"; XSetErrorHandler(XErrorHandlerImpl); XSetIOErrorHandler(XIOErrorHandlerImpl); } @@ -46,3 +50,70 @@ void SetX11WindowTitle(CefRefPtr browser, char* title) { ::Display* xdisplay = cef_get_xdisplay(); XStoreName(xdisplay, xwindow, title); } + +GtkWindow* CefBrowser_GetGtkWindow(CefRefPtr browser) { + // TODO: Should return NULL when using the Views framework + // -- REWRITTEN FOR CEF PYTHON USE CASE -- + // X11 window handle + ::Window xwindow = browser->GetHost()->GetWindowHandle(); + // X11 display + ::Display* xdisplay = cef_get_xdisplay(); + // GDK display + GdkDisplay* gdk_display = NULL; + if (xdisplay) { + // See if we can find GDK display using X11 display + gdk_display = gdk_x11_lookup_xdisplay(xdisplay); + } + if (!gdk_display) { + // If not then get the default display + gdk_display = gdk_display_get_default(); + } + if (!gdk_display) { + // The tkinter_.py and hello_world.py examples do not use GTK + // internally, so GTK wasn't yet initialized and must do it + // now, so that display is available. Also must install X11 + // error handlers to avoid 'BadWindow' errors. + // -- + // A similar code is in cefpython_app.cpp and it might already + // been executed. If making changes here, make changes there + // as well. + LOG(INFO) << "[Browser process] Initialize GTK"; + gtk_init(0, NULL); + InstallX11ErrorHandlers(); + // Now the display is available + gdk_display = gdk_display_get_default(); + } + // In kivy_.py example getting error message: + // > Can't create GtkPlug as child of non-GtkSocket + // However dialog handler works just fine. + GtkWidget* widget = gtk_plug_new_for_display(gdk_display, xwindow); + // Getting top level widget doesn't seem to be required. + // OFF: GtkWidget* toplevel = gtk_widget_get_toplevel(widget); + GtkWindow* window = GTK_WINDOW(widget); + if (!window) { + LOG(ERROR) << "No GtkWindow for browser"; + } + return window; +} + +XImage* CefBrowser_GetImage(CefRefPtr browser) { + ::Display* display = cef_get_xdisplay(); + if (!display) { + LOG(ERROR) << "XOpenDisplay failed in CefBrowser_GetImage"; + return NULL; + } + ::Window browser_window = browser->GetHost()->GetWindowHandle(); + XWindowAttributes attrs; + if (!XGetWindowAttributes(display, browser_window, &attrs)) { + LOG(ERROR) << "XGetWindowAttributes failed in CefBrowser_GetImage"; + return NULL; + } + XImage* image = XGetImage(display, browser_window, + 0, 0, attrs.width, attrs.height, + AllPlanes, ZPixmap); + if (!image) { + LOG(ERROR) << "XGetImage failed in CefBrowser_GetImage"; + return NULL; + } + return image; +} diff --git a/src/client_handler/x11.h b/src/client_handler/x11.h index cd5931875..d92ee41ed 100644 --- a/src/client_handler/x11.h +++ b/src/client_handler/x11.h @@ -5,9 +5,15 @@ #pragma once #include +#include +#include + #include "include/cef_browser.h" void InstallX11ErrorHandlers(); void SetX11WindowBounds(CefRefPtr browser, int x, int y, int width, int height); void SetX11WindowTitle(CefRefPtr browser, char* title); + +GtkWindow* CefBrowser_GetGtkWindow(CefRefPtr browser); +XImage* CefBrowser_GetImage(CefRefPtr browser); diff --git a/src/common/cefpython_public_api.h b/src/common/cefpython_public_api.h index 0fbd60a56..c796388e6 100644 --- a/src/common/cefpython_public_api.h +++ b/src/common/cefpython_public_api.h @@ -44,6 +44,12 @@ #include "../../build/build_cefpython/cefpython_py35_fixed.h" #elif PY_MINOR_VERSION == 6 #include "../../build/build_cefpython/cefpython_py36_fixed.h" +#elif PY_MINOR_VERSION == 7 +#include "../../build/build_cefpython/cefpython_py37_fixed.h" +#elif PY_MINOR_VERSION == 8 +#include "../../build/build_cefpython/cefpython_py38_fixed.h" +#elif PY_MINOR_VERSION == 9 +#include "../../build/build_cefpython/cefpython_py39_fixed.h" #endif // PY_MINOR_VERSION #endif // PY_MAJOR_VERSION diff --git a/src/compile_time_constants.pxi b/src/compile_time_constants.pxi index 632aab59c..bf130d6ed 100644 --- a/src/compile_time_constants.pxi +++ b/src/compile_time_constants.pxi @@ -1,3 +1,10 @@ # This file was generated by setup.py + +# Type this command to ignore changes to this file: +# git update-index --assume-unchanged src/compile_time_constants.pxi + DEF UNAME_SYSNAME = "Windows" DEF PY_MAJOR_VERSION = 3 +cdef extern from "limits.h": + cdef int INT_MIN + cdef int INT_MAX diff --git a/src/cookie.pyx b/src/cookie.pyx index 45b692ccb..6d90144b0 100644 --- a/src/cookie.pyx +++ b/src/cookie.pyx @@ -119,6 +119,19 @@ cdef class Cookie: return CefToPyString(cefString) cpdef py_void SetDomain(self, py_string domain): + pattern = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-_]{0,61}[a-z0-9])?\.)" + r"+[a-z0-9][a-z0-9-_]{0,61}[a-z]$") + if PY_MAJOR_VERSION == 2: + assert isinstance(domain, bytes), "domain type is not bytes" + domain = domain.decode(g_applicationSettings["string_encoding"], + errors=BYTES_DECODE_ERRORS) + try: + if not pattern.match(domain.encode("idna").decode("ascii")): + raise Exception("Cookie.SetDomain() failed, invalid domain: {0}" + .format(domain)) + except UnicodeError: + raise Exception("Cookie.SetDomain() failed, invalid domain: {0}" + .format(domain)) cdef CefString cefString cefString.Attach(&self.cefCookie.domain, False) PyToCefString(domain, cefString) @@ -181,9 +194,12 @@ cdef class Cookie: # CookieManager # ------------------------------------------------------------------------------ -class CookieManager: - @staticmethod - def GetGlobalManager(): +class CookieManager(object): + """Class used for managing cookies. To instantiate this class + call CreateManager() static method.""" + + @classmethod + def GetGlobalManager(cls): global g_globalCookieManager cdef CefRefPtr[CefCookieManager] cefCookieManager if not g_globalCookieManager: @@ -192,11 +208,28 @@ class CookieManager: g_globalCookieManager = CreatePyCookieManager(cefCookieManager) return g_globalCookieManager - @staticmethod - def CreateManager(py_string path, py_bool persistSessionCookies=False): + @classmethod + def GetBlockingManager(cls): + return CreatePyCookieManager(CefCookieManager_GetBlockingManager()) + + @classmethod + def CreateManager(cls, py_string path, + py_bool persist_session_cookies=False): + """ + Create a new cookie manager. + :param path: + :type path: str + :param persist_session_cookies: + :type path: bool + :return: CookieManager object + :rtype: CookieManager + """ + # When PyCharm generates a stub for the cefpython module + # it doesn't use the above docstring for code inspections. + # No idea why. cdef CefRefPtr[CefCookieManager] cefCookieManager cefCookieManager = CefCookieManager_CreateManager( - PyToCefStringValue(path), bool(persistSessionCookies), + PyToCefStringValue(path), bool(persist_session_cookies), NULL) if cefCookieManager != NULL and cefCookieManager.get(): return CreatePyCookieManager(cefCookieManager) @@ -268,6 +301,11 @@ cdef class PyCookieManager: PyToCefStringValue(path), bool(persistSessionCookies), NULL) + cpdef py_bool FlushStore(self, callback=None): + return self.cefCookieManager.get().FlushStore( + NULL) + + # ------------------------------------------------------------------------------ # PyCookieVisitor # ------------------------------------------------------------------------------ diff --git a/src/cpp_utils/Makefile b/src/cpp_utils/Makefile index 338fd960b..e6a6a2fe5 100644 --- a/src/cpp_utils/Makefile +++ b/src/cpp_utils/Makefile @@ -7,7 +7,7 @@ OUT = libcpp_utils.a INC = -I./../ -I/usr/include/gtk-2.0 \ -I/usr/include/glib-2.0 -I/usr/lib/i386-linux-gnu/gtk-2.0/include \ -I/usr/lib/i386-linux-gnu/glib-2.0/include -I/usr/include/cairo \ - -I/usr/include/pango-1.0 -I/usr/include/gdk-pixbuf-2.0 \ + -I/usr/include/pango-1.0 -I/usr/include/harfbuzz -I/usr/include/gdk-pixbuf-2.0 \ -I/usr/include/atk-1.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include \ -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include \ -I/usr/lib64/glib-2.0/include -I/usr/lib64/gtk-2.0/include \ diff --git a/src/dpi_aware_win.pyx b/src/dpi_aware_win.pyx index 4a02184c7..a7fc345fa 100644 --- a/src/dpi_aware_win.pyx +++ b/src/dpi_aware_win.pyx @@ -6,42 +6,65 @@ include "cefpython.pyx" class DpiAware: - @staticmethod - def GetSystemDpi(): - # Win7 DPI (Control Panel > Appearance and Personalization > Display): - # text size Larger 150% => dpix/dpiy 144 - # text size Medium 125% => dpix/dpiy 120 - # text size Smaller 100% => dpix/dpiy 96 - # - # dpix=96 zoomlevel=0.0 - # dpix=120 zoomlevel=1.0 - # dpix=144 zoomlevel=2.0 - # dpix=72 zoomlevel=-1.0 - # - # If DPI awareness wasn't yet enabled, then GetSystemDpi - # will always return a default 96 DPI. + @classmethod + def GetSystemDpi(cls): + """Returns Windows DPI settings ("Custom scaling" on Win10). + + Win7 DPI (Control Panel > Appearance and Personalization > Display): + text size Larger 150% => dpix/dpiy 144 + text size Medium 125% => dpix/dpiy 120 + text size Smaller 100% => dpix/dpiy 96 + + DPI settings should not be cached. When SetProcessDpiAware + is not yet called, then OS returns 96 DPI, even though it + is set to 144 DPI. After DPI Awareness is enabled for the + running process it will return the correct 144 DPI. + """ cdef int dpix = 0 cdef int dpiy = 0 GetSystemDpi(&dpix, &dpiy) - return tuple(dpix, dpiy) + return dpix, dpiy - @staticmethod - def CalculateWindowSize(int width, int height): + @classmethod + def CalculateWindowSize(cls, int width, int height): + """@DEPRECATED. Use Scale() method instead.""" # Calculation for DPI < 96 is not yet supported. GetDpiAwareWindowSize(&width, &height) - return tuple(width, height) + return width, height + + @classmethod + def Scale(cls, arg): + """Scale units for high DPI devices. Argument can be an int, + tuple or list.""" + (dpix, dpiy) = DpiAware.GetSystemDpi() + # - Using only "dpix" value to calculate zoom level since all + # modern displays have equal horizontal and vertical resolution. + default_dpix = 96 + scale = MulDiv(dpix, 100, default_dpix) + if isinstance(arg, (int, long)): + v = arg + new_value = MulDiv(v, scale, 100) + return new_value + ret_tuple = isinstance(arg, tuple) + ret = list() + for i,v in enumerate(arg): + v = int(v) + ret.append(MulDiv(v, scale, 100)) + if ret_tuple: + return tuple(ret) + return ret - @staticmethod - def IsProcessDpiAware(): + @classmethod + def IsProcessDpiAware(cls): return IsProcessDpiAware() - @staticmethod - def SetProcessDpiAware(): + @classmethod + def SetProcessDpiAware(cls): """Deprecated.""" DpiAware.EnableHighDpiSupport() - @staticmethod - def EnableHighDpiSupport(): + @classmethod + def EnableHighDpiSupport(cls): # This CEF function sets process to be DPI aware. This # CEF func is also called in subprocesses. CefEnableHighDPISupport() diff --git a/src/drag_data.pyx b/src/drag_data.pyx index ddb7d9f98..5da99a6f2 100644 --- a/src/drag_data.pyx +++ b/src/drag_data.pyx @@ -36,20 +36,16 @@ cdef class DragData: cpdef py_string GetFragmentHtml(self): return CefToPyString(self.cef_drag_data.get().GetFragmentHtml()) - IF UNAME_SYSNAME == "Linux": - - cpdef PyImage GetImage(self): - cdef CefRefPtr[CefImage] cef_image =\ - self.cef_drag_data.get().GetImage() - if not cef_image.get(): - raise Exception("Image is not available") - return PyImage_Init(cef_image) - - cpdef tuple GetImageHotspot(self): - cdef CefPoint point = self.cef_drag_data.get().GetImageHotspot() - return (point.x, point.y) - - cpdef py_bool HasImage(self): - return self.cef_drag_data.get().HasImage() - - # END IF UNAME_SYSNAME == "Linux": + cpdef PyImage GetImage(self): + cdef CefRefPtr[CefImage] cef_image =\ + self.cef_drag_data.get().GetImage() + if not cef_image.get(): + raise Exception("Image is not available") + return PyImage_Init(cef_image) + + cpdef tuple GetImageHotspot(self): + cdef CefPoint point = self.cef_drag_data.get().GetImageHotspot() + return point.x, point.y + + cpdef py_bool HasImage(self): + return self.cef_drag_data.get().HasImage() diff --git a/src/extern/cef/cef_browser.pxd b/src/extern/cef/cef_browser.pxd index 50a70393a..da209d5c3 100644 --- a/src/extern/cef/cef_browser.pxd +++ b/src/extern/cef/cef_browser.pxd @@ -11,10 +11,11 @@ from libcpp cimport bool as cpp_bool from libcpp.vector cimport vector as cpp_vector from cef_frame cimport CefFrame cimport cef_types -from cef_types cimport int64 +from cef_types cimport int64, cef_state_t, CefSize from cef_types cimport CefBrowserSettings, CefPoint from cef_drag_data cimport CefDragData from cef_types cimport CefMouseEvent +from cef_request_context cimport CefRequestContext from cef_process_message cimport CefProcessMessage, CefProcessId @@ -61,6 +62,9 @@ cdef extern from "include/cef_browser.h": const CefBrowserSettings& settings, const CefPoint& inspect_element_at) void CloseDevTools() + cpp_bool HasDevTools() + + CefRefPtr[CefRequestContext] GetRequestContext() void Find(int identifier, const CefString& searchText, cpp_bool forward, cpp_bool matchCase, cpp_bool findNext) @@ -83,6 +87,12 @@ cdef extern from "include/cef_browser.h": void ReplaceMisspelling(const CefString& word) void AddWordToDictionary(const CefString& word) + void SetAccessibilityState(cef_state_t accessibility_state) + void Invalidate(cef_types.cef_paint_element_type_t element_type) + void SetAutoResizeEnabled(cpp_bool enabled, + const CefSize& min_size, + const CefSize& max_size) + cdef cppclass CefBrowser: diff --git a/src/extern/cef/cef_cookie.pxd b/src/extern/cef/cef_cookie.pxd index 94263a6b4..c113aea9a 100644 --- a/src/extern/cef/cef_cookie.pxd +++ b/src/extern/cef/cef_cookie.pxd @@ -27,11 +27,17 @@ cdef extern from "include/cef_cookie.h": cdef CefRefPtr[CefCookieManager] CefCookieManager_GetGlobalManager \ "CefCookieManager::GetGlobalManager"( CefRefPtr[CefCompletionCallback] callback) + + cdef CefRefPtr[CefCookieManager] CefCookieManager_GetBlockingManager \ + "CefCookieManager::GetBlockingManager"() + + cdef CefRefPtr[CefCookieManager] CefCookieManager_CreateManager \ "CefCookieManager::CreateManager"( const CefString& path, cpp_bool persist_session_cookies, CefRefPtr[CefCompletionCallback] callback) + cdef cppclass CefCookieManager: void SetSupportedSchemes(const cpp_vector[CefString]& schemes, CefRefPtr[CefCompletionCallback] callback) @@ -47,7 +53,7 @@ cdef extern from "include/cef_cookie.h": cpp_bool SetStoragePath(const CefString& path, cpp_bool persist_session_cookies, CefRefPtr[CefCompletionCallback] callback) - # cpp_bool FlushStore(CefRefPtr[CefCompletionCallback] handler) + cpp_bool FlushStore(CefRefPtr[CefCompletionCallback] callback) cdef cppclass CefCookieVisitor: pass diff --git a/src/extern/cef/cef_cookie_manager_namespace.pxd b/src/extern/cef/cef_cookie_manager_namespace.pxd index bcc8a1b33..daf1a0f38 100644 --- a/src/extern/cef/cef_cookie_manager_namespace.pxd +++ b/src/extern/cef/cef_cookie_manager_namespace.pxd @@ -10,6 +10,8 @@ from cef_cookie cimport CefCookie # noinspection PyUnresolvedReferences from cef_cookie cimport CefSetCookieCallback, CefDeleteCookiesCallback from cef_ptr cimport CefRefPtr +# noinspection PyUnresolvedReferences +from cef_callback cimport CefCompletionCallback # We need to pass C++ class methods by reference to a function, # it is not possible with such syntax: @@ -28,3 +30,5 @@ cdef extern from "include/cef_cookie.h" namespace "CefCookieManager": cpp_bool DeleteCookies(const CefString& url, const CefString& cookie_name, CefRefPtr[CefDeleteCookiesCallback] callback) + + cpp_bool FlushStore(CefRefPtr[CefCompletionCallback] callback) diff --git a/src/extern/cef/cef_file_util.pxd b/src/extern/cef/cef_file_util.pxd new file mode 100644 index 000000000..52e62580d --- /dev/null +++ b/src/extern/cef/cef_file_util.pxd @@ -0,0 +1,8 @@ +# Copyright (c) 2018 CEF Python, see the Authors file. +# All rights reserved. Licensed under BSD 3-clause license. +# Project website: https://github.com/cztomczak/cefpython + +from cef_string cimport CefString + +cdef extern from "include/cef_file_util.h": + void CefLoadCRLSetsFile(const CefString& path) diff --git a/src/extern/cef/cef_linux.pxd b/src/extern/cef/cef_linux.pxd index e42b9dd5d..4ae54bf94 100644 --- a/src/extern/cef/cef_linux.pxd +++ b/src/extern/cef/cef_linux.pxd @@ -15,8 +15,7 @@ cdef extern from "include/internal/cef_linux.h": cdef cppclass CefWindowInfo: void SetAsChild(CefWindowHandle parent, const CefRect& windowRect) - void SetAsWindowless(CefWindowHandle parent, - cpp_bool transparent) + void SetAsWindowless(CefWindowHandle parent) cdef cppclass CefMainArgs: CefMainArgs() diff --git a/src/extern/cef/cef_mac.pxd b/src/extern/cef/cef_mac.pxd index ec6a0898c..5bc92f49f 100644 --- a/src/extern/cef/cef_mac.pxd +++ b/src/extern/cef/cef_mac.pxd @@ -14,8 +14,7 @@ cdef extern from "include/internal/cef_mac.h": cdef cppclass CefWindowInfo: void SetAsChild(CefWindowHandle parent, int x, int y, int width, int height) - void SetAsWindowless(CefWindowHandle parent, - cpp_bool transparent) + void SetAsWindowless(CefWindowHandle parent) cdef cppclass CefMainArgs: CefMainArgs() diff --git a/src/extern/cef/cef_request_context.pxd b/src/extern/cef/cef_request_context.pxd index 811cf72f5..116741749 100644 --- a/src/extern/cef/cef_request_context.pxd +++ b/src/extern/cef/cef_request_context.pxd @@ -5,6 +5,8 @@ from cef_ptr cimport CefRefPtr # noinspection PyUnresolvedReferences from cef_request_context_handler cimport CefRequestContextHandler +from cef_callback cimport CefCompletionCallback +from cef_cookie cimport CefCookieManager cdef extern from "include/cef_request_context.h": cdef cppclass CefRequestContext: @@ -14,3 +16,5 @@ cdef extern from "include/cef_request_context.h": CefRefPtr[CefRequestContext] CreateContext( CefRefPtr[CefRequestContext] other, CefRefPtr[CefRequestContextHandler] handler) + CefRefPtr[CefCookieManager] GetDefaultCookieManager( + CefRefPtr[CefCompletionCallback] callback) diff --git a/src/extern/cef/cef_scoped_ptr.pxd b/src/extern/cef/cef_scoped_ptr.pxd index 4498360cd..2e770a5b9 100644 --- a/src/extern/cef/cef_scoped_ptr.pxd +++ b/src/extern/cef/cef_scoped_ptr.pxd @@ -13,3 +13,5 @@ cdef extern from "include/base/cef_scoped_ptr.h": void reset(T* p) # noinspection PyUnresolvedReferences T* get() + # noinspection PyUnresolvedReferences + scoped_ptr[T]& Assign "operator="(scoped_ptr[T] p) diff --git a/src/extern/cef/cef_string.pxd b/src/extern/cef/cef_string.pxd index 74f2e342b..0986d7a6c 100644 --- a/src/extern/cef/cef_string.pxd +++ b/src/extern/cef/cef_string.pxd @@ -21,5 +21,5 @@ cdef extern from "include/internal/cef_string.h": cpp_bool FromString(cpp_string& str) cpp_string ToString() cpp_wstring ToWString() - char* c_str() + const char* c_str() size_t length() diff --git a/src/extern/cef/cef_task.pxd b/src/extern/cef/cef_task.pxd index 806cbe897..fbc0181e0 100644 --- a/src/extern/cef/cef_task.pxd +++ b/src/extern/cef/cef_task.pxd @@ -9,7 +9,6 @@ from cef_types cimport int64 from cef_ptr cimport CefRefPtr cdef extern from "include/cef_task.h": - ctypedef int CefThreadId ctypedef cef_types.cef_thread_id_t CefThreadId cdef cpp_bool CefCurrentlyOn(CefThreadId) diff --git a/src/extern/cef/cef_types.pxd b/src/extern/cef/cef_types.pxd index 435726298..6bd21ba46 100644 --- a/src/extern/cef/cef_types.pxd +++ b/src/extern/cef/cef_types.pxd @@ -78,7 +78,6 @@ cdef extern from "include/internal/cef_types.h": cef_string_t default_encoding cef_state_t remote_fonts cef_state_t javascript - cef_state_t javascript_open_windows cef_state_t javascript_close_windows cef_state_t javascript_access_clipboard cef_state_t javascript_dom_paste @@ -116,6 +115,7 @@ cdef extern from "include/internal/cef_types.h": ctypedef enum cef_log_severity_t: LOGSEVERITY_DEFAULT, LOGSEVERITY_VERBOSE, + LOGSEVERITY_DEBUG = LOGSEVERITY_VERBOSE, LOGSEVERITY_INFO, LOGSEVERITY_WARNING, LOGSEVERITY_ERROR, @@ -123,11 +123,10 @@ cdef extern from "include/internal/cef_types.h": ctypedef enum cef_thread_id_t: TID_UI, - TID_DB, + TID_FILE_BACKGROUND TID_FILE, + TID_FILE_USER_VISIBLE, TID_FILE_USER_BLOCKING, - TID_PROCESS_LAUNCHER, - TID_CACHE, TID_IO, TID_RENDERER @@ -162,12 +161,14 @@ cdef extern from "include/internal/cef_types.h": # WebRequest ctypedef enum cef_urlrequest_flags_t: - UR_FLAG_NONE = 0, - UR_FLAG_SKIP_CACHE = 1 << 0, - UR_FLAG_ALLOW_CACHED_CREDENTIALS = 1 << 1, - UR_FLAG_REPORT_UPLOAD_PROGRESS = 1 << 3, - UR_FLAG_NO_DOWNLOAD_DATA = 1 << 6, - UR_FLAG_NO_RETRY_ON_5XX = 1 << 7, + UR_FLAG_NONE = 0, + UR_FLAG_SKIP_CACHE = 1 << 0, + UR_FLAG_ONLY_FROM_CACHE = 1 << 1, + UR_FLAG_ALLOW_STORED_CREDENTIALS = 1 << 2, + UR_FLAG_REPORT_UPLOAD_PROGRESS = 1 << 3, + UR_FLAG_NO_DOWNLOAD_DATA = 1 << 4, + UR_FLAG_NO_RETRY_ON_5XX = 1 << 5, + UR_FLAG_STOP_ON_REDIRECT = 1 << 6, # CefListValue, CefDictionaryValue - types. ctypedef enum cef_value_type_t: @@ -343,6 +344,7 @@ cdef extern from "include/internal/cef_types.h": PK_FILE_MODULE, PK_LOCAL_APP_DATA, PK_USER_DATA, + PK_DIR_RESOURCES, ctypedef cef_path_key_t PathKey ctypedef enum cef_plugin_policy_t: @@ -375,3 +377,7 @@ cdef extern from "include/internal/cef_types.h": ctypedef enum cef_focus_source_t: FOCUS_SOURCE_NAVIGATION, FOCUS_SOURCE_SYSTEM, + + cdef cppclass CefRange: + int from_val "from" + int to_val "to" diff --git a/src/extern/cef/cef_values.pxd b/src/extern/cef/cef_values.pxd index 201bb82be..3210432b4 100644 --- a/src/extern/cef/cef_values.pxd +++ b/src/extern/cef/cef_values.pxd @@ -12,6 +12,19 @@ cdef extern from "include/cef_values.h": cdef CefRefPtr[CefBinaryValue] CefBinaryValue_Create \ "CefBinaryValue::Create"(const void* data, size_t data_size) + cdef cppclass CefValue: + cpp_bool IsValid() + cpp_bool IsOwned() + cpp_bool IsReadOnly() + cef_value_type_t GetType() + cpp_bool GetBool() + int GetInt() + double GetDouble() + CefString GetString() + CefRefPtr[CefBinaryValue] GetBinary() + CefRefPtr[CefDictionaryValue] GetDictionary() + CefRefPtr[CefListValue] GetList() + cdef cppclass CefBinaryValue: cpp_bool IsValid() cpp_bool IsOwned() @@ -59,20 +72,20 @@ cdef extern from "include/cef_values.h": cpp_bool SetSize(size_t size) size_t GetSize() cpp_bool Clear() - cpp_bool Remove(int index) - cef_value_type_t GetType(int index) - cpp_bool GetBool(int index) - int GetInt(int index) - double GetDouble(int index) - CefString GetString(int index) - CefRefPtr[CefBinaryValue] GetBinary(int index) - CefRefPtr[CefDictionaryValue] GetDictionary(int index) - CefRefPtr[CefListValue] GetList(int index) - cpp_bool SetNull(int index) - cpp_bool SetBool(int index, cpp_bool value) - cpp_bool SetInt(int index, int value) - cpp_bool SetDouble(int index, double value) - cpp_bool SetString(int index, const CefString& value) - cpp_bool SetBinary(int index, CefRefPtr[CefBinaryValue] value) - cpp_bool SetDictionary(int index, CefRefPtr[CefDictionaryValue] value) - cpp_bool SetList(int index, CefRefPtr[CefListValue] value) + cpp_bool Remove(size_t index) + cef_value_type_t GetType(size_t index) + cpp_bool GetBool(size_t index) + int GetInt(size_t index) + double GetDouble(size_t index) + CefString GetString(size_t index) + CefRefPtr[CefBinaryValue] GetBinary(size_t index) + CefRefPtr[CefDictionaryValue] GetDictionary(size_t index) + CefRefPtr[CefListValue] GetList(size_t index) + cpp_bool SetNull(size_t index) + cpp_bool SetBool(size_t index, cpp_bool value) + cpp_bool SetInt(size_t index, int value) + cpp_bool SetDouble(size_t index, double value) + cpp_bool SetString(size_t index, const CefString& value) + cpp_bool SetBinary(size_t index, CefRefPtr[CefBinaryValue] value) + cpp_bool SetDictionary(size_t index, CefRefPtr[CefDictionaryValue] value) + cpp_bool SetList(size_t index, CefRefPtr[CefListValue] value) diff --git a/src/extern/cef/cef_win.pxd b/src/extern/cef/cef_win.pxd index ce742d79a..5e341b75b 100644 --- a/src/extern/cef/cef_win.pxd +++ b/src/extern/cef/cef_win.pxd @@ -21,8 +21,7 @@ cdef extern from "include/internal/cef_win.h": RECT windowRect) void SetAsPopup(CefWindowHandle parent, const CefString& windowName) - void SetAsWindowless(CefWindowHandle parent, - cpp_bool transparent) + void SetAsWindowless(CefWindowHandle parent) cdef cppclass CefMainArgs: CefMainArgs() diff --git a/src/extern/dpi_aware_win.pxd b/src/extern/dpi_aware_win.pxd index 3842062a2..fd9a3cbe1 100644 --- a/src/extern/dpi_aware_win.pxd +++ b/src/extern/dpi_aware_win.pxd @@ -9,4 +9,3 @@ cdef extern from "client_handler/dpi_aware.h": cdef void GetDpiAwareWindowSize(int* width, int* height) cdef void SetProcessDpiAware() cdef cpp_bool IsProcessDpiAware() - diff --git a/src/extern/linux.pxd b/src/extern/linux.pxd index fb565243b..b2da7068d 100644 --- a/src/extern/linux.pxd +++ b/src/extern/linux.pxd @@ -7,3 +7,26 @@ cdef extern from "gtk/gtk.h" nogil: ctypedef void* GtkWidget cdef GtkWidget* gtk_plug_new(GdkNativeWindow socket_id) cdef void gtk_widget_show(GtkWidget* widget) + + ctypedef char* XPointer + ctypedef struct XImage: + int width + int height + int xoffset # number of pixels offset in X direction + int format # XYBitmap, XYPixmap, ZPixmap + char *data # pointer to image data + int byte_order # data byte order, LSBFirst, MSBFirst + int bitmap_unit # quant. of scanline 8, 16, 32 + int bitmap_bit_order # LSBFirst, MSBFirst + int bitmap_pad # 8, 16, 32 either XY or ZPixmap + int depth # depth of image + int bytes_per_line # accelerator to next scanline + int bits_per_pixel # bits per pixel (ZPixmap) + unsigned long red_mask # bits in z arrangement + unsigned long green_mask + unsigned long blue_mask + XPointer *obdata + void *funcs + void XDestroyImage(XImage *ximage) + unsigned long XGetPixel(XImage* image, int x, int y) + diff --git a/src/extern/mac.pxd b/src/extern/mac.pxd index cca038b98..e23b4b980 100644 --- a/src/extern/mac.pxd +++ b/src/extern/mac.pxd @@ -7,4 +7,5 @@ from cef_browser cimport CefBrowser cdef extern from "client_handler/util_mac.h": void MacInitialize() + void MacShutdown() void MacSetWindowTitle(CefRefPtr[CefBrowser] browser, char* title) diff --git a/src/extern/windows.pxd b/src/extern/windows.pxd index 82355a60e..5e329b2a3 100644 --- a/src/extern/windows.pxd +++ b/src/extern/windows.pxd @@ -23,6 +23,8 @@ cdef extern from "Windows.h" nogil: ctypedef HICON HCURSOR ctypedef unsigned int UINT + ctypedef unsigned int UINT_PTR + # noinspection PyUnresolvedReferences ctypedef wchar_t* LPCTSTR # noinspection PyUnresolvedReferences @@ -49,7 +51,11 @@ cdef extern from "Windows.h" nogil: cdef size_t mbstowcs(wchar_t *wcstr, const_char *mbstr, size_t count) ctypedef void* HDWP + cdef int SWP_NOZORDER + cdef int SWP_NOACTIVATE + cdef int SWP_FRAMECHANGED + cdef HDWP BeginDeferWindowPos(int nNumWindows) cdef HDWP DeferWindowPos( HDWP hWinPosInfo, HWND hWnd, HWND hWndInsertAfter, @@ -64,8 +70,6 @@ cdef extern from "Windows.h" nogil: cdef BOOL PostMessage( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) - ctypedef unsigned int UINT_PTR - ctypedef unsigned int UINT ctypedef struct TIMERPROC: pass cdef UINT_PTR SetTimer( @@ -108,9 +112,6 @@ cdef extern from "Windows.h" nogil: cdef BOOL SetWindowPos( HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, int cy, UINT uFlags) - cdef int SWP_NOZORDER - cdef int SWP_NOACTIVATE - cdef int SWP_FRAMECHANGED cdef DWORD GetLastError() cdef BOOL IsWindow(HWND hWnd) @@ -127,3 +128,5 @@ cdef extern from "Windows.h" nogil: cdef int ICON_SMALL cdef HWND GetParent(HWND hwnd) + cdef int MulDiv(int number, int numerator, int denominator) + diff --git a/src/extern/x11.pxd b/src/extern/x11.pxd index 4e481f246..e60b31a08 100644 --- a/src/extern/x11.pxd +++ b/src/extern/x11.pxd @@ -5,9 +5,11 @@ from cef_ptr cimport CefRefPtr # noinspection PyUnresolvedReferences from cef_browser cimport CefBrowser +from linux cimport XImage cdef extern from "client_handler/x11.h" nogil: void InstallX11ErrorHandlers() void SetX11WindowBounds(CefRefPtr[CefBrowser] browser, int x, int y, int width, int height) void SetX11WindowTitle(CefRefPtr[CefBrowser] browser, char* title) + XImage* CefBrowser_GetImage(CefRefPtr[CefBrowser] browser) diff --git a/src/frame.pyx b/src/frame.pyx index 6535791dc..812e4b3c9 100644 --- a/src/frame.pyx +++ b/src/frame.pyx @@ -7,6 +7,10 @@ include "browser.pyx" cdef dict g_pyFrames = {} +# If a frame was unreferenced (browser closed or OnContextReleased) +# it shouldn't be kept global anymore. +cdef list g_unreferenced_frames = [] # [str unique identifier, ..] + cdef object GetUniqueFrameId(int browserId, object frameId): return str(browserId) +"#"+ str(frameId) @@ -28,8 +32,17 @@ cdef PyFrame GetPyFrame(CefRefPtr[CefFrame] cefFrame): assert (frameId and browserId), "frameId or browserId empty" cdef object uniqueFrameId = GetUniqueFrameId(browserId, frameId) - if uniqueFrameId in g_pyFrames: - return g_pyFrames[uniqueFrameId] + if frameId < 0: + # Underlying frame does not yet exist. In such case PyFrame + # is not stored in g_pyFrames since frameId is invalid. + # However even though frame is not supposed to exist, you + # can still call CefFrame.ExecuteFunction and it works fine + # in tutorial.py example. + Debug("GetPyFrame(): underlying frame does not yet exist:" + " browserId = {0}, frameId = {1}".format(browserId, frameId)) + else: + if uniqueFrameId in g_pyFrames: + return g_pyFrames[uniqueFrameId] # This code probably ain't needed. # ---- @@ -46,9 +59,13 @@ cdef PyFrame GetPyFrame(CefRefPtr[CefFrame] cefFrame): pyFrame = PyFrame(browserId, frameId) pyFrame.cefFrame = cefFrame - if browserId in g_unreferenced_browsers: + if uniqueFrameId in g_unreferenced_frames \ + or frameId < 0 \ + or browserId in g_unreferenced_browsers \ + or browserId in g_closed_browsers: # Browser was already globally unreferenced in OnBeforeClose, - # thus all frames are globally unreferenced too. Create a new + # thus all frames are globally unreferenced too, or frame + # was unreferenced in OnContextReleased. Create a new # incomplete instance of PyFrame object. Read comments in # browser.pyx > GetPyBrowser and in Browser.md for what # "incomplete" means. @@ -60,17 +77,23 @@ cdef PyFrame GetPyFrame(CefRefPtr[CefFrame] cefFrame): # SIDE EFFECT: two calls to GetPyFrame for the same frame object # may return two different PyFrame objects. Compare # frame objects always using GetIdentifier(). - # Debug("GetPyFrame(): create new PyFrame, frameId=%s" % frameId) + Debug("GetPyFrame(): create new PyFrame, frameId=%s" % frameId) g_pyFrames[uniqueFrameId] = pyFrame return pyFrame cdef void RemovePyFrame(int browserId, object frameId) except *: # Called from V8ContextHandler_OnContextReleased(). global g_pyFrames + cdef PyFrame pyFrame cdef object uniqueFrameId = GetUniqueFrameId(browserId, frameId) if uniqueFrameId in g_pyFrames: Debug("del g_pyFrames[%s]" % uniqueFrameId) + pyFrame = g_pyFrames[uniqueFrameId] + pyFrame.cefFrame.Assign(NULL) + del pyFrame del g_pyFrames[uniqueFrameId] + g_unreferenced_frames.append(uniqueFrameId) + RemovePythonCallbacksForFrame(frameId) else: Debug("RemovePyFrame() FAILED: uniqueFrameId = %s" % uniqueFrameId) @@ -85,7 +108,13 @@ cdef void RemovePyFramesForBrowser(int browserId) except *: toRemove.append(uniqueFrameId) for uniqueFrameId in toRemove: Debug("del g_pyFrames[%s]" % uniqueFrameId) + pyFrame = g_pyFrames[uniqueFrameId] + pyFrame.cefFrame.Assign(NULL) + del pyFrame del g_pyFrames[uniqueFrameId] + g_unreferenced_frames.append(uniqueFrameId) + # RemovePythonCallbacksForBrowser already called + # in LifespanHandler_OnBeforeClose. cdef class PyFrame: cdef CefRefPtr[CefFrame] cefFrame @@ -182,7 +211,6 @@ cdef class PyFrame: self.GetCefFrame().get().LoadString(cefValue, cefUrl) cpdef py_void LoadUrl(self, py_string url): - url = GetNavigateUrl(url) cdef CefString cefUrl PyToCefString(url, cefUrl) self.GetCefFrame().get().LoadURL(cefUrl) diff --git a/src/handlers/accessibility_handler.pyx b/src/handlers/accessibility_handler.pyx new file mode 100644 index 000000000..055fb61cf --- /dev/null +++ b/src/handlers/accessibility_handler.pyx @@ -0,0 +1,34 @@ +# Copyright (c) 2018 CEF Python, see the Authors file. +# All rights reserved. Licensed under BSD 3-clause license. +# Project website: https://github.com/cztomczak/cefpython + +include "../cefpython.pyx" +include "../browser.pyx" +include "../frame.pyx" +include "../process_message_utils.pyx" + +cdef public void AccessibilityHandler_OnAccessibilityTreeChange( + CefRefPtr[CefValue] cefValue + ) except * with gil: + cdef object value = CefValueToPyValue(cefValue) + cdef object callback + try: + callback = GetGlobalClientCallback("OnAccessibilityTreeChange") + if callback: + callback(value=value) + except: + (exc_type, exc_value, exc_trace) = sys.exc_info() + sys.excepthook(exc_type, exc_value, exc_trace) + +cdef public void AccessibilityHandler_OnAccessibilityLocationChange( + CefRefPtr[CefValue] cefValue + ) except * with gil: + cdef object value = CefValueToPyValue(cefValue) + cdef object callback + try: + callback = GetGlobalClientCallback("OnAccessibilityLocationChange") + if callback: + callback(value=value) + except: + (exc_type, exc_value, exc_trace) = sys.exc_info() + sys.excepthook(exc_type, exc_value, exc_trace) diff --git a/src/handlers/display_handler.pyx b/src/handlers/display_handler.pyx index d67cb4d17..7d66d00f7 100644 --- a/src/handlers/display_handler.pyx +++ b/src/handlers/display_handler.pyx @@ -25,6 +25,25 @@ cdef public void DisplayHandler_OnAddressChange( (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) + +cdef public cpp_bool DisplayHandler_OnAutoResize( + CefRefPtr[CefBrowser] cef_browser, + const CefSize& new_size + ) except * with gil: + cdef PyBrowser browser + cdef object callback + try: + browser = GetPyBrowser(cef_browser, "OnAutoResize") + callback = browser.GetClientCallback("OnAutoResize") + if callback: + return bool(callback(browser=browser, new_size=[new_size.width, + new_size.height])) + return False + except: + (exc_type, exc_value, exc_trace) = sys.exc_info() + sys.excepthook(exc_type, exc_value, exc_trace) + + cdef public void DisplayHandler_OnTitleChange( CefRefPtr[CefBrowser] cefBrowser, const CefString& cefTitle @@ -85,6 +104,7 @@ cdef public void DisplayHandler_OnStatusMessage( cdef public cpp_bool DisplayHandler_OnConsoleMessage( CefRefPtr[CefBrowser] cefBrowser, + cef_log_severity_t level, const CefString& cefMessage, const CefString& cefSource, int line @@ -100,10 +120,26 @@ cdef public cpp_bool DisplayHandler_OnConsoleMessage( pySource = CefToPyString(cefSource) callback = pyBrowser.GetClientCallback("OnConsoleMessage") if callback: - returnValue = callback(browser=pyBrowser, message=pyMessage, - source=pySource, line=line) + returnValue = callback(browser=pyBrowser, level=level, + message=pyMessage, source=pySource, + line=line) return bool(returnValue) return False except: (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) + +cdef public void DisplayHandler_OnLoadingProgressChange( + CefRefPtr[CefBrowser] cefBrowser, + double progress + ) except * with gil: + cdef PyBrowser pyBrowser + cdef object callback + try: + pyBrowser = GetPyBrowser(cefBrowser, "OnLoadingProgressChange") + callback = pyBrowser.GetClientCallback("OnLoadingProgressChange") + if callback: + callback(browser=pyBrowser, progress=progress) + except: + (exc_type, exc_value, exc_trace) = sys.exc_info() + sys.excepthook(exc_type, exc_value, exc_trace) diff --git a/src/handlers/keyboard_handler.pyx b/src/handlers/keyboard_handler.pyx index c895b9b5e..30c04e2f5 100644 --- a/src/handlers/keyboard_handler.pyx +++ b/src/handlers/keyboard_handler.pyx @@ -3,6 +3,7 @@ # Project website: https://github.com/cztomczak/cefpython include "../cefpython.pyx" +include "../browser.pyx" # noinspection PyUnresolvedReferences cimport cef_types @@ -72,39 +73,67 @@ cdef public cpp_bool KeyboardHandler_OnPreKeyEvent( (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) + +cdef py_bool HandleKeyboardShortcuts(PyBrowser browser, dict event): + """Default implementation for keyboard shortcuts on Mac (Issue #161).""" + if platform.system() == "Darwin": + if event["modifiers"] == 128 \ + and event["type"] != KEYEVENT_RAWKEYDOWN: + # Copy and paste was handled in RAWKEYDOWN, return True + if event["native_key_code"] in [8, 9]: + return True + if event["modifiers"] == 128 \ + and event["type"] == KEYEVENT_RAWKEYDOWN: + # Select all: command + a + if event["native_key_code"] == 0: + browser.GetMainFrame().SelectAll() + return True + # Copy: command + c + elif event["native_key_code"] == 8: + browser.GetMainFrame().Copy() + return True + # Paste: command + v + elif event["native_key_code"] == 9: + browser.GetMainFrame().Paste() + return True + # Cut: command + x + elif event["native_key_code"] == 7: + browser.GetMainFrame().Cut() + return True + # Undo: command + z + elif event["native_key_code"] == 6: + browser.GetMainFrame().Undo() + return True + elif event["modifiers"] == 130 \ + and event["type"] == KEYEVENT_RAWKEYDOWN: + # Redo: command + shift + z + if event["native_key_code"] == 6: + browser.GetMainFrame().Redo() + return True + return False + cdef public cpp_bool KeyboardHandler_OnKeyEvent( CefRefPtr[CefBrowser] cefBrowser, const cef_types.CefKeyEvent& cefEvent, cef_types.CefEventHandle cefEventHandle ) except * with gil: - cdef PyBrowser pyBrowser - cdef dict pyEvent + cdef PyBrowser browser + cdef dict event cdef py_bool returnValue cdef object callback try: - pyBrowser = GetPyBrowser(cefBrowser, "OnKeyEvent") - pyEvent = CefToPyKeyEvent(cefEvent) - callback = pyBrowser.GetClientCallback("OnKeyEvent") + browser = GetPyBrowser(cefBrowser, "OnKeyEvent") + event = CefToPyKeyEvent(cefEvent) + callback = browser.GetClientCallback("OnKeyEvent") if callback: returnValue = callback( - browser=pyBrowser, - event=pyEvent, + browser=browser, + event=event, event_handle=PyLong_FromVoidPtr(cefEventHandle)) # If returnValue is False then handle copy/paste on Mac if returnValue: return bool(returnValue) - if platform.system() == "Darwin": - # Handle copy: command + c - if pyEvent["modifiers"] == 128 \ - and pyEvent["native_key_code"] == 8: - pyBrowser.GetFocusedFrame().Copy() - return True - # Handle paste: command + v - elif pyEvent["modifiers"] == 128 \ - and pyEvent["native_key_code"] == 9: - pyBrowser.GetFocusedFrame().Paste() - return True - return False + return bool(HandleKeyboardShortcuts(browser, event)) except: (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) diff --git a/src/handlers/lifespan_handler.pyx b/src/handlers/lifespan_handler.pyx index 32a3f0c46..bfe22bd11 100644 --- a/src/handlers/lifespan_handler.pyx +++ b/src/handlers/lifespan_handler.pyx @@ -110,6 +110,7 @@ cdef public void LifespanHandler_OnBeforeClose( CefRefPtr[CefBrowser] cefBrowser ) except * with gil: cdef PyBrowser pyBrowser + cdef int browserId cdef object callback try: Debug("LifespanHandler_OnBeforeClose") @@ -126,14 +127,29 @@ cdef public void LifespanHandler_OnBeforeClose( callback = pyBrowser.GetClientCallback("OnBeforeClose") if callback: callback(browser=pyBrowser) - RemovePythonCallbacksForBrowser(pyBrowser.GetIdentifier()) - RemovePyFramesForBrowser(pyBrowser.GetIdentifier()) - RemovePyBrowser(pyBrowser.GetIdentifier()) + + # Flush cookies to disk. Temporary solution for Issue #365. + # A similar call is made in Browser.CloseBrowser. If using + # GetCookieManager to implement custom cookie managers then + # flushing of cookies would need to be handled manually. + cefBrowser.get().GetHost().get().GetRequestContext().get() \ + .GetDefaultCookieManager( + NULL) \ + .get().FlushStore(NULL) + + browserId = pyBrowser.GetIdentifier() + pyBrowser.cefBrowser.Assign(NULL) + cefBrowser.Assign(NULL) + del pyBrowser + + RemovePythonCallbacksForBrowser(browserId) + RemovePyFramesForBrowser(browserId) + RemovePyBrowser(browserId) + if g_MessageLoop_called and not len(g_pyBrowsers): # Automatically quit message loop when last browser was closed. # This is required for hello_world.py example to work. - QuitMessageLoop() - + PostTask(TID_UI, QuitMessageLoop) except: (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) diff --git a/src/handlers/render_handler.pyx b/src/handlers/render_handler.pyx index 1594d6bd6..a8ad49124 100644 --- a/src/handlers/render_handler.pyx +++ b/src/handlers/render_handler.pyx @@ -4,8 +4,10 @@ include "../cefpython.pyx" include "../browser.pyx" +include "../string_utils.pyx" cimport cef_types +from cef_types cimport CefRange # cef_paint_element_type_t, PaintElementType PET_VIEW = cef_types.PET_VIEW @@ -288,3 +290,20 @@ cdef public void RenderHandler_UpdateDragCursor( (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) +cdef public void RenderHandler_OnTextSelectionChanged( + CefRefPtr[CefBrowser] cef_browser, + const CefString& selected_text, + const CefRange& selected_range + ) except * with gil: + cdef PyBrowser browser + try: + browser = GetPyBrowser(cef_browser, "OnTextSelectionChanged") + callback = browser.GetClientCallback("OnTextSelectionChanged") + if callback: + callback(browser=browser, + selected_text=CefToPyString(selected_text), + selected_range=[selected_range.from_val, + selected_range.to_val]) + except: + (exc_type, exc_value, exc_trace) = sys.exc_info() + sys.excepthook(exc_type, exc_value, exc_trace) diff --git a/src/handlers/request_handler.pyx b/src/handlers/request_handler.pyx index 0df1d8670..866942bfd 100644 --- a/src/handlers/request_handler.pyx +++ b/src/handlers/request_handler.pyx @@ -4,6 +4,7 @@ include "../cefpython.pyx" include "../browser.pyx" +include "../cookie.pyx" # cef_termination_status_t cimport cef_types @@ -59,26 +60,31 @@ cdef public cpp_bool RequestHandler_OnBeforeBrowse( CefRefPtr[CefBrowser] cefBrowser, CefRefPtr[CefFrame] cefFrame, CefRefPtr[CefRequest] cefRequest, - cpp_bool cefIsRedirect + cpp_bool user_gesture, + cpp_bool is_redirect ) except * with gil: cdef PyBrowser pyBrowser cdef PyFrame pyFrame cdef PyRequest pyRequest - cdef py_bool pyIsRedirect cdef object clientCallback cdef py_bool returnValue try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return False + pyBrowser = GetPyBrowser(cefBrowser, "OnBeforeBrowse") pyFrame = GetPyFrame(cefFrame) pyRequest = CreatePyRequest(cefRequest) - pyIsRedirect = bool(cefIsRedirect) clientCallback = pyBrowser.GetClientCallback("OnBeforeBrowse") if clientCallback: returnValue = clientCallback( browser=pyBrowser, frame=pyFrame, request=pyRequest, - is_redirect=pyIsRedirect) + user_gesture=user_gesture, + is_redirect=is_redirect) return bool(returnValue) else: return False @@ -98,6 +104,11 @@ cdef public cpp_bool RequestHandler_OnBeforeResourceLoad( cdef object clientCallback cdef py_bool returnValue try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return False + pyBrowser = GetPyBrowser(cefBrowser, "OnBeforeResourceLoad") pyFrame = GetPyFrame(cefFrame) pyRequest = CreatePyRequest(cefRequest) @@ -126,6 +137,11 @@ cdef public CefRefPtr[CefResourceHandler] RequestHandler_GetResourceHandler( cdef object clientCallback cdef object returnValue try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return NULL + pyBrowser = GetPyBrowser(cefBrowser, "GetResourceHandler") pyFrame = GetPyFrame(cefFrame) pyRequest = CreatePyRequest(cefRequest) @@ -162,6 +178,11 @@ cdef public void RequestHandler_OnResourceRedirect( cdef PyResponse pyResponse cdef object clientCallback try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return + pyBrowser = GetPyBrowser(cefBrowser, "OnResourceRedirect") pyFrame = GetPyFrame(cefFrame) pyOldUrl = CefToPyString(cefOldUrl) @@ -207,6 +228,11 @@ cdef public cpp_bool RequestHandler_GetAuthCredentials( cdef list pyPasswordOut cdef object clientCallback try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return False + pyBrowser = GetPyBrowser(cefBrowser, "GetAuthCredentials") pyFrame = GetPyFrame(cefFrame) pyIsProxy = bool(cefIsProxy) @@ -261,6 +287,11 @@ cdef public cpp_bool RequestHandler_OnQuotaRequest( cdef py_bool returnValue cdef object clientCallback try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return False + pyBrowser = GetPyBrowser(cefBrowser, "OnQuotaRequest") pyOriginUrl = CefToPyString(cefOriginUrl) clientCallback = pyBrowser.GetClientCallback("OnQuotaRequest") @@ -291,11 +322,19 @@ cdef public CefRefPtr[CefCookieManager] RequestHandler_GetCookieManager( cdef object clientCallback cdef PyCookieManager returnValue try: + # Issue #429: in some cases due to a race condition the browser + # may be NULL. + if not cefBrowser.get(): + return NULL + + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return NULL + pyBrowser = GetPyBrowser(cefBrowser, "GetCookieManager") pyMainUrl = CefToPyString(cefMainUrl) - if pyBrowser: - # Browser may be empty. - clientCallback = pyBrowser.GetClientCallback("GetCookieManager") + clientCallback = pyBrowser.GetClientCallback("GetCookieManager") if clientCallback: returnValue = clientCallback( browser=pyBrowser, @@ -323,6 +362,11 @@ cdef public void RequestHandler_OnProtocolExecution( cdef list pyAllowOSExecutionOut cdef object clientCallback try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return + pyBrowser = GetPyBrowser(cefBrowser, "OnProtocolExecution") pyUrl = CefToPyString(cefUrl) pyAllowOSExecutionOut = [bool(cefAllowOSExecution)] @@ -367,6 +411,12 @@ cdef public cpp_bool RequestHandler_OnBeforePluginLoad( Debug("WARNING: RequestHandler_OnBeforePluginLoad() failed," " Browser object is not available") return False + + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(browser): + return False + py_browser = GetPyBrowser(browser, "OnBeforePluginLoad") py_plugin_info = CreatePyWebPluginInfo(plugin_info) clientCallback = GetGlobalClientCallback("OnBeforePluginLoad") @@ -422,6 +472,11 @@ cdef public void RequestHandler_OnRendererProcessTerminated( cdef PyBrowser pyBrowser cdef object clientCallback try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return + pyBrowser = GetPyBrowser(cefBrowser, "OnRendererProcessTerminated") clientCallback = pyBrowser.GetClientCallback( "OnRendererProcessTerminated") @@ -437,13 +492,18 @@ cdef public void RequestHandler_OnPluginCrashed( const CefString& cefPluginPath ) except * with gil: # TODO: plugin may crash during browser creation. Let this callback - # to be set either through cefpython.SetGlobalClientCallback() + # to be set either through cefpython.SetGlobalClientCallback() # or PyBrowser.SetClientCallback(). Modify the # PyBrowser.GetClientCallback() implementation to return a global # callback first if set. cdef PyBrowser pyBrowser cdef object clientCallback try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cefBrowser): + return + pyBrowser = GetPyBrowser(cefBrowser, "OnPluginCrashed") clientCallback = pyBrowser.GetClientCallback("OnPluginCrashed") if clientCallback: @@ -453,3 +513,75 @@ cdef public void RequestHandler_OnPluginCrashed( except: (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) + + +cdef public cpp_bool RequestHandler_CanGetCookies( + CefRefPtr[CefBrowser] cef_browser, + CefRefPtr[CefFrame] cef_frame, + CefRefPtr[CefRequest] cef_request + ) except * with gil: + cdef PyBrowser browser + cdef PyFrame frame + cdef PyRequest request + cdef object callback + cdef py_bool retval + try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cef_browser): + return False + + browser = GetPyBrowser(cef_browser, "CanGetCookies") + frame = GetPyFrame(cef_frame) + request = CreatePyRequest(cef_request) + callback = browser.GetClientCallback("CanGetCookies") + if callback: + retval = callback( + browser=browser, + frame=frame, + request=request) + return bool(retval) + else: + # Return True by default + return True + except: + (exc_type, exc_value, exc_trace) = sys.exc_info() + sys.excepthook(exc_type, exc_value, exc_trace) + + +cdef public cpp_bool RequestHandler_CanSetCookie( + CefRefPtr[CefBrowser] cef_browser, + CefRefPtr[CefFrame] cef_frame, + CefRefPtr[CefRequest] cef_request, + const CefCookie& cef_cookie + ) except * with gil: + cdef PyBrowser browser + cdef PyFrame frame + cdef PyRequest request + cdef PyCookie cookie + cdef object callback + cdef py_bool retval + try: + # Issue #455: CefRequestHandler callbacks still executed after + # browser was closed. + if IsBrowserClosed(cef_browser): + return False + + browser = GetPyBrowser(cef_browser, "CanSetCookie") + frame = GetPyFrame(cef_frame) + request = CreatePyRequest(cef_request) + cookie = CreatePyCookie(cef_cookie) + callback = browser.GetClientCallback("CanSetCookie") + if callback: + retval = callback( + browser=browser, + frame=frame, + request=request, + cookie=cookie) + return bool(retval) + else: + # Return True by default + return True + except: + (exc_type, exc_value, exc_trace) = sys.exc_info() + sys.excepthook(exc_type, exc_value, exc_trace) diff --git a/src/handlers/v8context_handler.pyx b/src/handlers/v8context_handler.pyx index 704f6ad92..fccdad562 100644 --- a/src/handlers/v8context_handler.pyx +++ b/src/handlers/v8context_handler.pyx @@ -10,6 +10,7 @@ include "../cefpython.pyx" include "../browser.pyx" +include "../frame.pyx" cdef public void V8ContextHandler_OnContextCreated( CefRefPtr[CefBrowser] cefBrowser, @@ -23,7 +24,7 @@ cdef public void V8ContextHandler_OnContextCreated( pyBrowser = GetPyBrowser(cefBrowser, "OnContextCreated") pyBrowser.SetUserData("__v8ContextCreated", True) pyFrame = GetPyFrame(cefFrame) - # User defined callback. + # User defined callback clientCallback = pyBrowser.GetClientCallback("OnContextCreated") if clientCallback: clientCallback(browser=pyBrowser, frame=pyFrame) @@ -52,19 +53,15 @@ cdef public void V8ContextHandler_OnContextReleased( if not pyBrowser: Debug("OnContextReleased: Browser doesn't exist anymore, id={id}" .format(id=str(browserId))) + RemovePyFrame(browserId, frameId) return pyFrame = GetPyFrameById(browserId, frameId) - if pyBrowser and pyFrame: + # Frame may already be destroyed while IPC messaging was executing + # (Issue #431). + if pyFrame: clientCallback = pyBrowser.GetClientCallback("OnContextReleased") if clientCallback: clientCallback(browser=pyBrowser, frame=pyFrame) - else: - if not pyBrowser: - Debug("V8ContextHandler_OnContextReleased() WARNING: " - "PyBrowser not found") - if not pyFrame: - Debug("V8ContextHandler_OnContextReleased() WARNING: " - "PyFrame not found") RemovePyFrame(browserId, frameId) except: (exc_type, exc_value, exc_trace) = sys.exc_info() diff --git a/src/handlers/v8function_handler.pyx b/src/handlers/v8function_handler.pyx index 2c9b3f1cf..ee73619f8 100644 --- a/src/handlers/v8function_handler.pyx +++ b/src/handlers/v8function_handler.pyx @@ -4,46 +4,48 @@ include "../cefpython.pyx" include "../browser.pyx" +include "../frame.pyx" cdef public void V8FunctionHandler_Execute( CefRefPtr[CefBrowser] cefBrowser, - CefRefPtr[CefFrame] cefFrame, - CefString& cefFunctionName, - CefRefPtr[CefListValue] cefFunctionArguments + int64 frameId, + CefString& cefFuncName, + CefRefPtr[CefListValue] cefFuncArgs ) except * with gil: cdef PyBrowser pyBrowser - cdef PyFrame pyFrame - cdef py_string functionName - cdef object function - cdef list functionArguments + cdef CefRefPtr[CefFrame] cefFrame + cdef PyFrame pyFrame # may be None + cdef py_string funcName + cdef object func + cdef list funcArgs cdef object returnValue - cdef py_string jsErrorMessage + cdef py_string errorMessage try: pyBrowser = GetPyBrowser(cefBrowser, "V8FunctionHandler_Execute") - pyFrame = GetPyFrame(cefFrame) - functionName = CefToPyString(cefFunctionName) - Debug("V8FunctionHandler_Execute(): functionName=%s" % functionName) + cefFrame = cefBrowser.get().GetFrame(frameId) + if cefFrame.get(): + pyFrame = GetPyFrame(cefFrame) + else: + pyFrame = None + funcName = CefToPyString(cefFuncName) + Debug("V8FunctionHandler_Execute(): funcName=%s" % funcName) jsBindings = pyBrowser.GetJavascriptBindings() - function = jsBindings.GetFunctionOrMethod(functionName) - if not function: + func = jsBindings.GetFunctionOrMethod(funcName) + if not func: # The Renderer process already checks whether function # name is valid before calling V8FunctionHandler_Execute(), # but it is possible for the javascript bindings to change # during execution, so it's possible for the Browser/Renderer # bindings to be out of sync due to delay in process messaging. - jsErrorMessage = "V8FunctionHandler_Execute() FAILED: " \ - "python function not found: %s" % functionName - Debug(jsErrorMessage) - # Raise a javascript exception in that frame. - pyFrame.ExecuteJavascript("throw '%s';" % jsErrorMessage) + errorMessage = "V8FunctionHandler_Execute() FAILED: " \ + "python function not found: %s" % funcName + NonCriticalError(errorMessage) + # Raise a javascript exception in that frame if it still exists + if pyFrame: + pyFrame.ExecuteJavascript("throw '%s';" % errorMessage) return - functionArguments = CefListValueToPyList(cefBrowser, - cefFunctionArguments) - returnValue = function(*functionArguments) - if returnValue is not None: - Debug("V8FunctionHandler_Execute() WARNING: function returned" \ - "value, but returning values to javascript is not " \ - "supported, functionName=%s" % functionName) + funcArgs = CefListValueToPyList(cefBrowser, cefFuncArgs) + func(*funcArgs) except: (exc_type, exc_value, exc_trace) = sys.exc_info() sys.excepthook(exc_type, exc_value, exc_trace) diff --git a/src/include/base/cef_atomic_ref_count.h b/src/include/base/cef_atomic_ref_count.h index bdbad6c92..4d6777970 100644 --- a/src/include/base/cef_atomic_ref_count.h +++ b/src/include/base/cef_atomic_ref_count.h @@ -39,14 +39,49 @@ #define CEF_INCLUDE_BASE_CEF_ATOMIC_REF_COUNT_H_ #pragma once -#if defined(BASE_ATOMIC_REF_COUNT_H_) -// Do nothing if the Chromium header has already been included. -// This can happen in cases where Chromium code is used directly by the -// client application. When using Chromium code directly always include -// the Chromium header first to avoid type conflicts. -#elif defined(USING_CHROMIUM_INCLUDES) +#if defined(USING_CHROMIUM_INCLUDES) // When building CEF include the Chromium header directly. #include "base/atomic_ref_count.h" + +// Used when declaring a base::AtomicRefCount value. This is an object type with +// Chromium headers. +#define ATOMIC_DECLARATION (0) + +// Maintaining compatibility with AtompicRefCount* functions that were removed +// from Chromium in http://crrev.com/ee96d561. +namespace base { + +// Increment a reference count by 1. +inline void AtomicRefCountInc(volatile AtomicRefCount* ptr) { + const_cast(ptr)->Increment(); +} + +// Decrement a reference count by 1 and return whether the result is non-zero. +// Insert barriers to ensure that state written before the reference count +// became zero will be visible to a thread that has just made the count zero. +inline bool AtomicRefCountDec(volatile AtomicRefCount* ptr) { + return const_cast(ptr)->Decrement(); +} + +// Return whether the reference count is one. If the reference count is used +// in the conventional way, a refrerence count of 1 implies that the current +// thread owns the reference and no other thread shares it. This call performs +// the test for a reference count of one, and performs the memory barrier +// needed for the owning thread to act on the object, knowing that it has +// exclusive access to the object. +inline bool AtomicRefCountIsOne(volatile AtomicRefCount* ptr) { + return const_cast(ptr)->IsOne(); +} + +// Return whether the reference count is zero. With conventional object +// referencing counting, the object will be destroyed, so the reference count +// should never be zero. Hence this is generally used for a debug check. +inline bool AtomicRefCountIsZero(volatile AtomicRefCount* ptr) { + return const_cast(ptr)->IsZero(); +} + +} // namespace base + #else // !USING_CHROMIUM_INCLUDES // The following is substantially similar to the Chromium implementation. // If the Chromium implementation diverges the below implementation should be @@ -56,14 +91,18 @@ // Annotations are not currently supported. #define ANNOTATE_HAPPENS_BEFORE(obj) /* empty */ -#define ANNOTATE_HAPPENS_AFTER(obj) /* empty */ +#define ANNOTATE_HAPPENS_AFTER(obj) /* empty */ + +// Used when declaring a base::AtomicRefCount value. This is an integer/ptr type +// with CEF headers. +#define ATOMIC_DECLARATION = 0 namespace base { typedef subtle::Atomic32 AtomicRefCount; // Increment a reference count by "increment", which must exceed 0. -inline void AtomicRefCountIncN(volatile AtomicRefCount *ptr, +inline void AtomicRefCountIncN(volatile AtomicRefCount* ptr, AtomicRefCount increment) { subtle::NoBarrier_AtomicIncrement(ptr, increment); } @@ -72,7 +111,7 @@ inline void AtomicRefCountIncN(volatile AtomicRefCount *ptr, // and return whether the result is non-zero. // Insert barriers to ensure that state written before the reference count // became zero will be visible to a thread that has just made the count zero. -inline bool AtomicRefCountDecN(volatile AtomicRefCount *ptr, +inline bool AtomicRefCountDecN(volatile AtomicRefCount* ptr, AtomicRefCount decrement) { ANNOTATE_HAPPENS_BEFORE(ptr); bool res = (subtle::Barrier_AtomicIncrement(ptr, -decrement) != 0); @@ -83,14 +122,14 @@ inline bool AtomicRefCountDecN(volatile AtomicRefCount *ptr, } // Increment a reference count by 1. -inline void AtomicRefCountInc(volatile AtomicRefCount *ptr) { +inline void AtomicRefCountInc(volatile AtomicRefCount* ptr) { base::AtomicRefCountIncN(ptr, 1); } // Decrement a reference count by 1 and return whether the result is non-zero. // Insert barriers to ensure that state written before the reference count // became zero will be visible to a thread that has just made the count zero. -inline bool AtomicRefCountDec(volatile AtomicRefCount *ptr) { +inline bool AtomicRefCountDec(volatile AtomicRefCount* ptr) { return base::AtomicRefCountDecN(ptr, 1); } @@ -100,7 +139,7 @@ inline bool AtomicRefCountDec(volatile AtomicRefCount *ptr) { // the test for a reference count of one, and performs the memory barrier // needed for the owning thread to act on the object, knowing that it has // exclusive access to the object. -inline bool AtomicRefCountIsOne(volatile AtomicRefCount *ptr) { +inline bool AtomicRefCountIsOne(volatile AtomicRefCount* ptr) { bool res = (subtle::Acquire_Load(ptr) == 1); if (res) { ANNOTATE_HAPPENS_AFTER(ptr); @@ -111,7 +150,7 @@ inline bool AtomicRefCountIsOne(volatile AtomicRefCount *ptr) { // Return whether the reference count is zero. With conventional object // referencing counting, the object will be destroyed, so the reference count // should never be zero. Hence this is generally used for a debug check. -inline bool AtomicRefCountIsZero(volatile AtomicRefCount *ptr) { +inline bool AtomicRefCountIsZero(volatile AtomicRefCount* ptr) { bool res = (subtle::Acquire_Load(ptr) == 0); if (res) { ANNOTATE_HAPPENS_AFTER(ptr); diff --git a/src/include/base/cef_atomicops.h b/src/include/base/cef_atomicops.h index ae74802f2..96aebabf8 100644 --- a/src/include/base/cef_atomicops.h +++ b/src/include/base/cef_atomicops.h @@ -122,8 +122,7 @@ Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value); // *ptr with the increment applied. This routine implies no memory barriers. Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); -Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, - Atomic32 increment); +Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); // These following lower-level operations are typically useful only to people // implementing higher-level synchronization operations like spinlocks, diff --git a/src/include/base/cef_basictypes.h b/src/include/base/cef_basictypes.h index 193e910f8..e38f4f729 100644 --- a/src/include/base/cef_basictypes.h +++ b/src/include/base/cef_basictypes.h @@ -32,8 +32,8 @@ #define CEF_INCLUDE_BASE_CEF_BASICTYPES_H_ #pragma once -#include // For UINT_MAX -#include // For size_t +#include // For UINT_MAX +#include // For size_t #include "include/base/cef_build.h" @@ -43,34 +43,44 @@ // On Mac OS X, |long long| is used for 64-bit types for compatibility with // format macros even in the LP64 model. #if defined(__LP64__) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) -typedef long int64; // NOLINT(runtime/int) -typedef unsigned long uint64; // NOLINT(runtime/int) +typedef long int64; +typedef unsigned long uint64; #else -typedef long long int64; // NOLINT(runtime/int) -typedef unsigned long long uint64; // NOLINT(runtime/int) +typedef long long int64; +typedef unsigned long long uint64; #endif // TODO: Remove these type guards. These are to avoid conflicts with // obsolete/protypes.h in the Gecko SDK. #ifndef _INT32 #define _INT32 -typedef int int32; +typedef int int32; #endif // TODO: Remove these type guards. These are to avoid conflicts with // obsolete/protypes.h in the Gecko SDK. #ifndef _UINT32 #define _UINT32 -typedef unsigned int uint32; +typedef unsigned int uint32; +#endif + +#ifndef _INT16 +#define _INT16 +typedef short int16; +#endif + +#ifndef _UINT16 +#define _UINT16 +typedef unsigned short uint16; #endif // UTF-16 character type. // This should be kept synchronized with base/strings/string16.h #ifndef char16 #if defined(WCHAR_T_IS_UTF16) -typedef wchar_t char16; +typedef wchar_t char16; #elif defined(WCHAR_T_IS_UTF32) -typedef unsigned short char16; +typedef unsigned short char16; #endif #endif diff --git a/src/include/base/cef_bind.h b/src/include/base/cef_bind.h index 8ee406d75..77c9c5573 100644 --- a/src/include/base/cef_bind.h +++ b/src/include/base/cef_bind.h @@ -89,34 +89,32 @@ namespace base { template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void()> - ::UnboundRunType> +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void()>::UnboundRunType> Bind(Functor functor) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; typedef cef_internal::BindState BindState; - return Callback( new BindState(cef_internal::MakeRunnable(functor))); } template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void(typename cef_internal::CallbackParamTraits::StorageType)> - ::UnboundRunType> +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType)>:: + UnboundRunType> Bind(Functor functor, const P1& p1) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; // Use RunnableType::RunType instead of RunType above because our @@ -131,39 +129,39 @@ Bind(Functor functor, const P1& p1) { // invoked function will receive a reference to the stored copy of the // argument and not the original. COMPILE_ASSERT( - !(is_non_const_reference::value ), + !(is_non_const_reference::value), do_not_bind_functions_with_nonconst_ref); // For methods, we need to be careful for parameter 1. We do not require // a scoped_refptr because BindState<> itself takes care of AddRef() for // methods. We also disallow binding of an array as the method's target // object. - COMPILE_ASSERT( - cef_internal::HasIsMethodTag::value || - !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, - p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || !is_array::value, first_bound_argument_to_method_cannot_be_array); - typedef cef_internal::BindState::StorageType)> BindState; - + typedef cef_internal::BindState< + RunnableType, RunType, + void(typename cef_internal::CallbackParamTraits::StorageType)> + BindState; return Callback( new BindState(cef_internal::MakeRunnable(functor), p1)); } template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void(typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> - ::UnboundRunType> +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)>:: + UnboundRunType> Bind(Functor functor, const P1& p1, const P2& p2) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; // Use RunnableType::RunType instead of RunType above because our @@ -179,43 +177,43 @@ Bind(Functor functor, const P1& p1, const P2& p2) { // argument and not the original. COMPILE_ASSERT( !(is_non_const_reference::value || - is_non_const_reference::value ), + is_non_const_reference::value), do_not_bind_functions_with_nonconst_ref); // For methods, we need to be careful for parameter 1. We do not require // a scoped_refptr because BindState<> itself takes care of AddRef() for // methods. We also disallow binding of an array as the method's target // object. - COMPILE_ASSERT( - cef_internal::HasIsMethodTag::value || - !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, - p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || !is_array::value, first_bound_argument_to_method_cannot_be_array); COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, p2_is_refcounted_type_and_needs_scoped_refptr); - typedef cef_internal::BindState::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> BindState; - + typename cef_internal::CallbackParamTraits::StorageType)> + BindState; return Callback( new BindState(cef_internal::MakeRunnable(functor), p1, p2)); } template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void(typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> - ::UnboundRunType> +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)>:: + UnboundRunType> Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; // Use RunnableType::RunType instead of RunType above because our @@ -231,18 +229,17 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3) { // argument and not the original. COMPILE_ASSERT( !(is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value ), + is_non_const_reference::value || + is_non_const_reference::value), do_not_bind_functions_with_nonconst_ref); // For methods, we need to be careful for parameter 1. We do not require // a scoped_refptr because BindState<> itself takes care of AddRef() for // methods. We also disallow binding of an array as the method's target // object. - COMPILE_ASSERT( - cef_internal::HasIsMethodTag::value || - !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, - p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || !is_array::value, first_bound_argument_to_method_cannot_be_array); @@ -250,29 +247,30 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3) { p2_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, p3_is_refcounted_type_and_needs_scoped_refptr); - typedef cef_internal::BindState::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> BindState; - + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + BindState; return Callback( new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3)); } template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void(typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> - ::UnboundRunType> +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)>:: + UnboundRunType> Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; // Use RunnableType::RunType instead of RunType above because our @@ -288,19 +286,18 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4) { // argument and not the original. COMPILE_ASSERT( !(is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value ), + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value), do_not_bind_functions_with_nonconst_ref); // For methods, we need to be careful for parameter 1. We do not require // a scoped_refptr because BindState<> itself takes care of AddRef() for // methods. We also disallow binding of an array as the method's target // object. - COMPILE_ASSERT( - cef_internal::HasIsMethodTag::value || - !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, - p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || !is_array::value, first_bound_argument_to_method_cannot_be_array); @@ -310,33 +307,42 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4) { p3_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, p4_is_refcounted_type_and_needs_scoped_refptr); - typedef cef_internal::BindState::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> BindState; - + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + BindState; return Callback( new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4)); } -template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void(typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> - ::UnboundRunType> -Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, - const P5& p5) { +template +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)>:: + UnboundRunType> +Bind(Functor functor, + const P1& p1, + const P2& p2, + const P3& p3, + const P4& p4, + const P5& p5) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; // Use RunnableType::RunType instead of RunType above because our @@ -352,20 +358,19 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, // argument and not the original. COMPILE_ASSERT( !(is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value ), + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value), do_not_bind_functions_with_nonconst_ref); // For methods, we need to be careful for parameter 1. We do not require // a scoped_refptr because BindState<> itself takes care of AddRef() for // methods. We also disallow binding of an array as the method's target // object. - COMPILE_ASSERT( - cef_internal::HasIsMethodTag::value || - !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, - p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || !is_array::value, first_bound_argument_to_method_cannot_be_array); @@ -377,35 +382,46 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, p4_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, p5_is_refcounted_type_and_needs_scoped_refptr); - typedef cef_internal::BindState::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> BindState; - + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + BindState; return Callback( new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5)); } -template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void(typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> - ::UnboundRunType> -Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, - const P5& p5, const P6& p6) { +template +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)>:: + UnboundRunType> +Bind(Functor functor, + const P1& p1, + const P2& p2, + const P3& p3, + const P4& p4, + const P5& p5, + const P6& p6) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; // Use RunnableType::RunType instead of RunType above because our @@ -421,21 +437,20 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, // argument and not the original. COMPILE_ASSERT( !(is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value ), + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value), do_not_bind_functions_with_nonconst_ref); // For methods, we need to be careful for parameter 1. We do not require // a scoped_refptr because BindState<> itself takes care of AddRef() for // methods. We also disallow binding of an array as the method's target // object. - COMPILE_ASSERT( - cef_internal::HasIsMethodTag::value || - !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, - p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || !is_array::value, first_bound_argument_to_method_cannot_be_array); @@ -449,37 +464,50 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, p5_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, p6_is_refcounted_type_and_needs_scoped_refptr); - typedef cef_internal::BindState::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> BindState; - - - return Callback( - new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6)); + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + BindState; + + return Callback(new BindState( + cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6)); } -template -base::Callback< - typename cef_internal::BindState< - typename cef_internal::FunctorTraits::RunnableType, - typename cef_internal::FunctorTraits::RunType, - void(typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> - ::UnboundRunType> -Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, - const P5& p5, const P6& p6, const P7& p7) { +template +base::Callback::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)>:: + UnboundRunType> +Bind(Functor functor, + const P1& p1, + const P2& p2, + const P3& p3, + const P4& p4, + const P5& p5, + const P6& p6, + const P7& p7) { // Typedefs for how to store and run the functor. - typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef + typename cef_internal::FunctorTraits::RunnableType RunnableType; typedef typename cef_internal::FunctorTraits::RunType RunType; // Use RunnableType::RunType instead of RunType above because our @@ -495,22 +523,21 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, // argument and not the original. COMPILE_ASSERT( !(is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value || - is_non_const_reference::value ), + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value), do_not_bind_functions_with_nonconst_ref); // For methods, we need to be careful for parameter 1. We do not require // a scoped_refptr because BindState<> itself takes care of AddRef() for // methods. We also disallow binding of an array as the method's target // object. - COMPILE_ASSERT( - cef_internal::HasIsMethodTag::value || - !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, - p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || !is_array::value, first_bound_argument_to_method_cannot_be_array); @@ -526,19 +553,19 @@ Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, p6_is_refcounted_type_and_needs_scoped_refptr); COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, p7_is_refcounted_type_and_needs_scoped_refptr); - typedef cef_internal::BindState::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType, - typename cef_internal::CallbackParamTraits::StorageType)> BindState; - - - return Callback( - new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6, - p7)); + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + BindState; + + return Callback(new BindState( + cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6, p7)); } } // namespace base diff --git a/src/include/base/cef_bind_helpers.h b/src/include/base/cef_bind_helpers.h index dde1d0dc0..2b4798b2c 100644 --- a/src/include/base/cef_bind_helpers.h +++ b/src/include/base/cef_bind_helpers.h @@ -274,20 +274,20 @@ class SupportsAddRefAndRelease { // instantiate Base is made. We disable the warning for this definition. #if defined(OS_WIN) #pragma warning(push) -#pragma warning(disable:4624) +#pragma warning(disable : 4624) #endif - struct Base : public T, public BaseMixin { - }; + struct Base : public T, public BaseMixin {}; #if defined(OS_WIN) #pragma warning(pop) #endif - template struct Helper {}; + template + struct Helper {}; template static No& Check(Helper<&C::AddRef>*); - template + template static Yes& Check(...); public: @@ -297,22 +297,18 @@ class SupportsAddRefAndRelease { // Helpers to assert that arguments of a recounted type are bound with a // scoped_refptr. template -struct UnsafeBindtoRefCountedArgHelper : false_type { -}; +struct UnsafeBindtoRefCountedArgHelper : false_type {}; template struct UnsafeBindtoRefCountedArgHelper - : integral_constant::value> { -}; + : integral_constant::value> {}; template -struct UnsafeBindtoRefCountedArg : false_type { -}; +struct UnsafeBindtoRefCountedArg : false_type {}; template struct UnsafeBindtoRefCountedArg - : UnsafeBindtoRefCountedArgHelper::value, T> { -}; + : UnsafeBindtoRefCountedArgHelper::value, T> {}; template class HasIsMethodTag { @@ -334,6 +330,7 @@ class UnretainedWrapper { public: explicit UnretainedWrapper(T* o) : ptr_(o) {} T* get() const { return ptr_; } + private: T* ptr_; }; @@ -343,6 +340,7 @@ class ConstRefWrapper { public: explicit ConstRefWrapper(const T& o) : ptr_(&o) {} const T& get() const { return *ptr_; } + private: const T* ptr_; }; @@ -355,7 +353,7 @@ struct IgnoreResultHelper { }; template -struct IgnoreResultHelper > { +struct IgnoreResultHelper> { explicit IgnoreResultHelper(const Callback& functor) : functor_(functor) {} const Callback& functor_; @@ -409,8 +407,7 @@ class PassedWrapper { public: explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {} PassedWrapper(const PassedWrapper& other) - : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) { - } + : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) {} T Pass() const { CHECK(is_valid_); is_valid_ = false; @@ -430,7 +427,7 @@ struct UnwrapTraits { }; template -struct UnwrapTraits > { +struct UnwrapTraits> { typedef T* ForwardType; static ForwardType Unwrap(UnretainedWrapper unretained) { return unretained.get(); @@ -438,7 +435,7 @@ struct UnwrapTraits > { }; template -struct UnwrapTraits > { +struct UnwrapTraits> { typedef const T& ForwardType; static ForwardType Unwrap(ConstRefWrapper const_ref) { return const_ref.get(); @@ -446,31 +443,27 @@ struct UnwrapTraits > { }; template -struct UnwrapTraits > { +struct UnwrapTraits> { typedef T* ForwardType; static ForwardType Unwrap(const scoped_refptr& o) { return o.get(); } }; template -struct UnwrapTraits > { +struct UnwrapTraits> { typedef const WeakPtr& ForwardType; static ForwardType Unwrap(const WeakPtr& o) { return o; } }; template -struct UnwrapTraits > { +struct UnwrapTraits> { typedef T* ForwardType; - static ForwardType Unwrap(const OwnedWrapper& o) { - return o.get(); - } + static ForwardType Unwrap(const OwnedWrapper& o) { return o.get(); } }; template -struct UnwrapTraits > { +struct UnwrapTraits> { typedef T ForwardType; - static T Unwrap(PassedWrapper& o) { - return o.Pass(); - } + static T Unwrap(PassedWrapper& o) { return o.Pass(); } }; // Utility for handling different refcounting semantics in the Bind() @@ -505,7 +498,7 @@ struct MaybeRefcount { // No need to additionally AddRef() and Release() since we are storing a // scoped_refptr<> inside the storage object already. template -struct MaybeRefcount > { +struct MaybeRefcount> { static void AddRef(const scoped_refptr& o) {} static void Release(const scoped_refptr& o) {} }; @@ -526,10 +519,10 @@ template struct IsWeakMethod : public false_type {}; template -struct IsWeakMethod > : public true_type {}; +struct IsWeakMethod> : public true_type {}; template -struct IsWeakMethod > > : public true_type {}; +struct IsWeakMethod>> : public true_type {}; } // namespace cef_internal @@ -567,14 +560,14 @@ static inline cef_internal::IgnoreResultHelper IgnoreResult(T data) { } template -static inline cef_internal::IgnoreResultHelper > -IgnoreResult(const Callback& data) { - return cef_internal::IgnoreResultHelper >(data); +static inline cef_internal::IgnoreResultHelper> IgnoreResult( + const Callback& data) { + return cef_internal::IgnoreResultHelper>(data); } void DoNothing(); -template +template void DeletePointer(T* obj) { delete obj; } diff --git a/src/include/base/cef_build.h b/src/include/base/cef_build.h index 81ee851f5..1e2065ce3 100644 --- a/src/include/base/cef_build.h +++ b/src/include/base/cef_build.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #ifndef CEF_INCLUDE_BASE_CEF_BUILD_H_ #define CEF_INCLUDE_BASE_CEF_BUILD_H_ #pragma once @@ -116,12 +115,10 @@ // Type detection for wchar_t. #if defined(OS_WIN) #define WCHAR_T_IS_UTF16 -#elif defined(OS_POSIX) && defined(COMPILER_GCC) && \ - defined(__WCHAR_MAX__) && \ +#elif defined(OS_POSIX) && defined(COMPILER_GCC) && defined(__WCHAR_MAX__) && \ (__WCHAR_MAX__ == 0x7fffffff || __WCHAR_MAX__ == 0xffffffff) #define WCHAR_T_IS_UTF32 -#elif defined(OS_POSIX) && defined(COMPILER_GCC) && \ - defined(__WCHAR_MAX__) && \ +#elif defined(OS_POSIX) && defined(COMPILER_GCC) && defined(__WCHAR_MAX__) && \ (__WCHAR_MAX__ == 0x7fff || __WCHAR_MAX__ == 0xffff) // On Posix, we'll detect short wchar_t, but projects aren't guaranteed to // compile in this mode (in particular, Chrome doesn't). This is intended for @@ -181,7 +178,7 @@ // Visual Studio 2010 and later support override. #define OVERRIDE override #elif defined(COMPILER_GCC) && __cplusplus >= 201103 && \ - (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= 40700 + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= 40700 // GCC 4.7 supports explicit virtual overrides when C++11 support is enabled. #define OVERRIDE override #else @@ -191,10 +188,9 @@ // Check for C++11 template alias support which was added in VS2013 and GCC4.7. // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf -#if __cplusplus > 199711L || \ - (defined(_MSC_VER) && _MSC_VER >= 1800) || \ - (defined(__GNUC__) && \ - (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ >= 40700)) +#if __cplusplus > 199711L || (defined(_MSC_VER) && _MSC_VER >= 1800) || \ + (defined(__GNUC__) && \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ >= 40700)) #define HAS_CPP11_TEMPLATE_ALIAS_SUPPORT #endif diff --git a/src/include/base/cef_callback.h b/src/include/base/cef_callback.h index 611fba50d..16e238a97 100644 --- a/src/include/base/cef_callback.h +++ b/src/include/base/cef_callback.h @@ -45,9 +45,9 @@ // If the Chromium implementation diverges the below implementation should be // updated to match. -#include "include/base/internal/cef_callback_internal.h" #include "include/base/cef_callback_forward.h" #include "include/base/cef_template_util.h" +#include "include/base/internal/cef_callback_internal.h" // NOTE: Header files that do not require the full definition of Callback or // Closure should #include "base/cef_callback_forward.h" instead of this file. @@ -407,21 +407,20 @@ class Callback : public cef_internal::CallbackBase { public: typedef R(RunType)(); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -437,9 +436,7 @@ class Callback : public cef_internal::CallbackBase { } private: - typedef R(*PolymorphicInvoke)( - cef_internal::BindStateBase*); - + typedef R (*PolymorphicInvoke)(cef_internal::BindStateBase*); }; template @@ -447,21 +444,20 @@ class Callback : public cef_internal::CallbackBase { public: typedef R(RunType)(A1); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -477,10 +473,9 @@ class Callback : public cef_internal::CallbackBase { } private: - typedef R(*PolymorphicInvoke)( + typedef R (*PolymorphicInvoke)( cef_internal::BindStateBase*, - typename cef_internal::CallbackParamTraits::ForwardType); - + typename cef_internal::CallbackParamTraits::ForwardType); }; template @@ -488,21 +483,20 @@ class Callback : public cef_internal::CallbackBase { public: typedef R(RunType)(A1, A2); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -520,11 +514,10 @@ class Callback : public cef_internal::CallbackBase { } private: - typedef R(*PolymorphicInvoke)( + typedef R (*PolymorphicInvoke)( cef_internal::BindStateBase*, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType); - + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); }; template @@ -532,21 +525,20 @@ class Callback : public cef_internal::CallbackBase { public: typedef R(RunType)(A1, A2, A3); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -566,12 +558,11 @@ class Callback : public cef_internal::CallbackBase { } private: - typedef R(*PolymorphicInvoke)( + typedef R (*PolymorphicInvoke)( cef_internal::BindStateBase*, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType); - + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); }; template @@ -579,21 +570,20 @@ class Callback : public cef_internal::CallbackBase { public: typedef R(RunType)(A1, A2, A3, A4); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -615,36 +605,38 @@ class Callback : public cef_internal::CallbackBase { } private: - typedef R(*PolymorphicInvoke)( + typedef R (*PolymorphicInvoke)( cef_internal::BindStateBase*, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType); - + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); }; -template +template class Callback : public cef_internal::CallbackBase { public: typedef R(RunType)(A1, A2, A3, A4, A5); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -660,45 +652,47 @@ class Callback : public cef_internal::CallbackBase { PolymorphicInvoke f = reinterpret_cast(polymorphic_invoke_); - return f(bind_state_.get(), cef_internal::CallbackForward(a1), - cef_internal::CallbackForward(a2), - cef_internal::CallbackForward(a3), - cef_internal::CallbackForward(a4), - cef_internal::CallbackForward(a5)); + return f( + bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), cef_internal::CallbackForward(a3), + cef_internal::CallbackForward(a4), cef_internal::CallbackForward(a5)); } private: - typedef R(*PolymorphicInvoke)( + typedef R (*PolymorphicInvoke)( cef_internal::BindStateBase*, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType); - + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); }; -template +template class Callback : public cef_internal::CallbackBase { public: typedef R(RunType)(A1, A2, A3, A4, A5, A6); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -715,47 +709,51 @@ class Callback : public cef_internal::CallbackBase { PolymorphicInvoke f = reinterpret_cast(polymorphic_invoke_); - return f(bind_state_.get(), cef_internal::CallbackForward(a1), - cef_internal::CallbackForward(a2), - cef_internal::CallbackForward(a3), - cef_internal::CallbackForward(a4), - cef_internal::CallbackForward(a5), - cef_internal::CallbackForward(a6)); + return f( + bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), cef_internal::CallbackForward(a3), + cef_internal::CallbackForward(a4), cef_internal::CallbackForward(a5), + cef_internal::CallbackForward(a6)); } private: - typedef R(*PolymorphicInvoke)( + typedef R (*PolymorphicInvoke)( cef_internal::BindStateBase*, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType); - + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); }; -template -class Callback : public cef_internal::CallbackBase { +template +class Callback + : public cef_internal::CallbackBase { public: typedef R(RunType)(A1, A2, A3, A4, A5, A6, A7); - Callback() : CallbackBase(NULL) { } + Callback() : CallbackBase(NULL) {} // Note that this constructor CANNOT be explicit, and that Bind() CANNOT // return the exact Callback<> type. See base/bind.h for details. template - Callback(cef_internal::BindState* bind_state) + Callback( + cef_internal::BindState* bind_state) : CallbackBase(bind_state) { - // Force the assignment to a local variable of PolymorphicInvoke // so the compiler will typecheck that the passed in Run() method has // the correct type. PolymorphicInvoke invoke_func = - &cef_internal::BindState - ::InvokerType::Run; + &cef_internal::BindState::InvokerType::Run; polymorphic_invoke_ = reinterpret_cast(invoke_func); } @@ -773,29 +771,25 @@ class Callback : public cef_internal::CallbackBas PolymorphicInvoke f = reinterpret_cast(polymorphic_invoke_); - return f(bind_state_.get(), cef_internal::CallbackForward(a1), - cef_internal::CallbackForward(a2), - cef_internal::CallbackForward(a3), - cef_internal::CallbackForward(a4), - cef_internal::CallbackForward(a5), - cef_internal::CallbackForward(a6), - cef_internal::CallbackForward(a7)); + return f( + bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), cef_internal::CallbackForward(a3), + cef_internal::CallbackForward(a4), cef_internal::CallbackForward(a5), + cef_internal::CallbackForward(a6), cef_internal::CallbackForward(a7)); } private: - typedef R(*PolymorphicInvoke)( + typedef R (*PolymorphicInvoke)( cef_internal::BindStateBase*, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType, - typename cef_internal::CallbackParamTraits::ForwardType); - + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); }; - // Syntactic sugar to make Callbacks easier to declare since it // will be used in a lot of APIs with delayed execution. typedef Callback Closure; diff --git a/src/include/base/cef_callback_list.h b/src/include/base/cef_callback_list.h index 73dd9f757..e0ef3665b 100644 --- a/src/include/base/cef_callback_list.h +++ b/src/include/base/cef_callback_list.h @@ -48,12 +48,12 @@ #include #include "include/base/cef_basictypes.h" -#include "include/base/cef_callback.h" -#include "include/base/internal/cef_callback_internal.h" #include "include/base/cef_build.h" +#include "include/base/cef_callback.h" #include "include/base/cef_logging.h" #include "include/base/cef_macros.h" #include "include/base/cef_scoped_ptr.h" +#include "include/base/internal/cef_callback_internal.h" // OVERVIEW: // @@ -120,9 +120,7 @@ class CallbackListBase { public: Subscription(CallbackListBase* list, typename std::list::iterator iter) - : list_(list), - iter_(iter) { - } + : list_(list), iter_(iter) {} ~Subscription() { if (list_->active_iterator_count_) { @@ -167,14 +165,12 @@ class CallbackListBase { class Iterator { public: explicit Iterator(CallbackListBase* list) - : list_(list), - list_iter_(list_->callbacks_.begin()) { + : list_(list), list_iter_(list_->callbacks_.begin()) { ++list_->active_iterator_count_; } Iterator(const Iterator& iter) - : list_(iter.list_), - list_iter_(iter.list_iter_) { + : list_(iter.list_), list_iter_(iter.list_iter_) { ++list_->active_iterator_count_; } @@ -210,9 +206,7 @@ class CallbackListBase { // Returns an instance of a CallbackListBase::Iterator which can be used // to run callbacks. - Iterator GetIterator() { - return Iterator(this); - } + Iterator GetIterator() { return Iterator(this); } // Compact the list: remove any entries which were NULLed out during // iteration. @@ -242,11 +236,12 @@ class CallbackListBase { } // namespace cef_internal -template class CallbackList; +template +class CallbackList; template <> class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase> { public: typedef Callback CallbackType; @@ -267,7 +262,7 @@ class CallbackList template class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase> { public: typedef Callback CallbackType; @@ -288,7 +283,7 @@ class CallbackList template class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase> { public: typedef Callback CallbackType; @@ -310,7 +305,7 @@ class CallbackList template class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase> { public: typedef Callback CallbackType; @@ -333,7 +328,7 @@ class CallbackList template class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase> { public: typedef Callback CallbackType; @@ -357,7 +352,8 @@ class CallbackList template class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase< + Callback> { public: typedef Callback CallbackType; @@ -380,11 +376,15 @@ class CallbackList DISALLOW_COPY_AND_ASSIGN(CallbackList); }; -template +template class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase< + Callback> { public: typedef Callback CallbackType; @@ -408,11 +408,16 @@ class CallbackList DISALLOW_COPY_AND_ASSIGN(CallbackList); }; -template +template class CallbackList - : public cef_internal::CallbackListBase > { + : public cef_internal::CallbackListBase< + Callback> { public: typedef Callback CallbackType; diff --git a/src/include/base/cef_cancelable_callback.h b/src/include/base/cef_cancelable_callback.h index 8f5979eb4..febce3a32 100644 --- a/src/include/base/cef_cancelable_callback.h +++ b/src/include/base/cef_cancelable_callback.h @@ -83,8 +83,8 @@ // updated to match. #include "include/base/cef_bind.h" -#include "include/base/cef_callback.h" #include "include/base/cef_build.h" +#include "include/base/cef_callback.h" #include "include/base/cef_logging.h" #include "include/base/cef_macros.h" #include "include/base/cef_weak_ptr.h" @@ -102,8 +102,7 @@ class CancelableCallback { // |callback| must not be null. explicit CancelableCallback(const base::Callback& callback) - : weak_factory_(this), - callback_(callback) { + : weak_factory_(this), callback_(callback) { DCHECK(!callback.is_null()); InitializeForwarder(); } @@ -118,9 +117,7 @@ class CancelableCallback { } // Returns true if the wrapped callback has been cancelled. - bool IsCancelled() const { - return callback_.is_null(); - } + bool IsCancelled() const { return callback_.is_null(); } // Sets |callback| as the closure that may be cancelled. |callback| may not // be null. Outstanding and any previously wrapped callbacks are cancelled. @@ -137,14 +134,10 @@ class CancelableCallback { } // Returns a callback that can be disabled by calling Cancel(). - const base::Callback& callback() const { - return forwarder_; - } + const base::Callback& callback() const { return forwarder_; } private: - void Forward() { - callback_.Run(); - } + void Forward() { callback_.Run(); } // Helper method to bind |forwarder_| using a weak pointer from // |weak_factory_|. @@ -154,7 +147,7 @@ class CancelableCallback { } // Used to ensure Forward() is not run when this object is destroyed. - base::WeakPtrFactory > weak_factory_; + base::WeakPtrFactory> weak_factory_; // The wrapper closure. base::Callback forwarder_; @@ -172,8 +165,7 @@ class CancelableCallback { // |callback| must not be null. explicit CancelableCallback(const base::Callback& callback) - : weak_factory_(this), - callback_(callback) { + : weak_factory_(this), callback_(callback) { DCHECK(!callback.is_null()); InitializeForwarder(); } @@ -188,9 +180,7 @@ class CancelableCallback { } // Returns true if the wrapped callback has been cancelled. - bool IsCancelled() const { - return callback_.is_null(); - } + bool IsCancelled() const { return callback_.is_null(); } // Sets |callback| as the closure that may be cancelled. |callback| may not // be null. Outstanding and any previously wrapped callbacks are cancelled. @@ -207,14 +197,10 @@ class CancelableCallback { } // Returns a callback that can be disabled by calling Cancel(). - const base::Callback& callback() const { - return forwarder_; - } + const base::Callback& callback() const { return forwarder_; } private: - void Forward(A1 a1) const { - callback_.Run(a1); - } + void Forward(A1 a1) const { callback_.Run(a1); } // Helper method to bind |forwarder_| using a weak pointer from // |weak_factory_|. @@ -224,7 +210,7 @@ class CancelableCallback { } // Used to ensure Forward() is not run when this object is destroyed. - base::WeakPtrFactory > weak_factory_; + base::WeakPtrFactory> weak_factory_; // The wrapper closure. base::Callback forwarder_; @@ -242,8 +228,7 @@ class CancelableCallback { // |callback| must not be null. explicit CancelableCallback(const base::Callback& callback) - : weak_factory_(this), - callback_(callback) { + : weak_factory_(this), callback_(callback) { DCHECK(!callback.is_null()); InitializeForwarder(); } @@ -258,9 +243,7 @@ class CancelableCallback { } // Returns true if the wrapped callback has been cancelled. - bool IsCancelled() const { - return callback_.is_null(); - } + bool IsCancelled() const { return callback_.is_null(); } // Sets |callback| as the closure that may be cancelled. |callback| may not // be null. Outstanding and any previously wrapped callbacks are cancelled. @@ -277,14 +260,10 @@ class CancelableCallback { } // Returns a callback that can be disabled by calling Cancel(). - const base::Callback& callback() const { - return forwarder_; - } + const base::Callback& callback() const { return forwarder_; } private: - void Forward(A1 a1, A2 a2) const { - callback_.Run(a1, a2); - } + void Forward(A1 a1, A2 a2) const { callback_.Run(a1, a2); } // Helper method to bind |forwarder_| using a weak pointer from // |weak_factory_|. @@ -294,7 +273,7 @@ class CancelableCallback { } // Used to ensure Forward() is not run when this object is destroyed. - base::WeakPtrFactory > weak_factory_; + base::WeakPtrFactory> weak_factory_; // The wrapper closure. base::Callback forwarder_; diff --git a/src/include/base/cef_lock.h b/src/include/base/cef_lock.h index 9f872bb58..6909bd6f2 100644 --- a/src/include/base/cef_lock.h +++ b/src/include/base/cef_lock.h @@ -125,9 +125,7 @@ class AutoLock { public: struct AlreadyAcquired {}; - explicit AutoLock(Lock& lock) : lock_(lock) { - lock_.Acquire(); - } + explicit AutoLock(Lock& lock) : lock_(lock) { lock_.Acquire(); } AutoLock(Lock& lock, const AlreadyAcquired&) : lock_(lock) { lock_.AssertAcquired(); @@ -153,9 +151,7 @@ class AutoUnlock { lock_.Release(); } - ~AutoUnlock() { - lock_.Acquire(); - } + ~AutoUnlock() { lock_.Acquire(); } private: Lock& lock_; diff --git a/src/include/base/cef_logging.h b/src/include/base/cef_logging.h index 75e35d961..8d8bb889e 100644 --- a/src/include/base/cef_logging.h +++ b/src/include/base/cef_logging.h @@ -158,9 +158,9 @@ // updated to match. #include -#include #include #include +#include #include "include/base/cef_build.h" #include "include/base/cef_macros.h" @@ -201,32 +201,27 @@ const LogSeverity LOG_DFATAL = LOG_FATAL; // A few definitions of macros that don't generate much code. These are used // by LOG() and LOG_IF, etc. Since these are used all over our code, it's // better to have compact code for these operations. -#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \ - cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_INFO , \ - ##__VA_ARGS__) -#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \ - cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_WARNING , \ - ##__VA_ARGS__) -#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \ - cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_ERROR , \ - ##__VA_ARGS__) -#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \ - cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_FATAL , \ - ##__VA_ARGS__) -#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \ - cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_DFATAL , \ - ##__VA_ARGS__) - -#define COMPACT_GOOGLE_LOG_INFO \ - COMPACT_GOOGLE_LOG_EX_INFO(LogMessage) -#define COMPACT_GOOGLE_LOG_WARNING \ - COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage) -#define COMPACT_GOOGLE_LOG_ERROR \ - COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage) -#define COMPACT_GOOGLE_LOG_FATAL \ - COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage) -#define COMPACT_GOOGLE_LOG_DFATAL \ - COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage) +#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_INFO, \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_WARNING, \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_ERROR, \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_FATAL, \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_DFATAL, \ + ##__VA_ARGS__) + +#define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage) +#define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage) +#define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage) +#define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage) +#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage) #if defined(OS_WIN) // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets @@ -236,7 +231,7 @@ const LogSeverity LOG_DFATAL = LOG_FATAL; // the Windows SDK does for consistency. #define ERROR 0 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \ - COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__) + COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR // Needed for LOG_IS_ON(ERROR). const LogSeverity LOG_0 = LOG_ERROR; @@ -246,7 +241,7 @@ const LogSeverity LOG_0 = LOG_ERROR; // LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will // always fire if they fail. #define LOG_IS_ON(severity) \ - ((::cef::logging::LOG_ ## severity) >= ::cef::logging::GetMinLogLevel()) + ((::cef::logging::LOG_##severity) >= ::cef::logging::GetMinLogLevel()) // We can't do any caching tricks with VLOG_IS_ON() like the // google-glog version since it requires GCC extensions. This means @@ -257,8 +252,8 @@ const LogSeverity LOG_0 = LOG_ERROR; // Helper macro which avoids evaluating the arguments to a stream if // the condition doesn't hold. -#define LAZY_STREAM(stream, condition) \ - !(condition) ? (void) 0 : ::cef::logging::LogMessageVoidify() & (stream) +#define LAZY_STREAM(stream, condition) \ + !(condition) ? (void)0 : ::cef::logging::LogMessageVoidify() & (stream) // We use the preprocessor's merging operator, "##", so that, e.g., // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny @@ -268,7 +263,7 @@ const LogSeverity LOG_0 = LOG_ERROR; // impossible to stream something like a string directly to an unnamed // ostream. We employ a neat hack by calling the stream() member // function of LogMessage which seems to avoid the problem. -#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() +#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_##severity.stream() #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity)) #define LOG_IF(severity, condition) \ @@ -286,16 +281,18 @@ const LogSeverity LOG_0 = LOG_ERROR; #define VLOG_IF(verbose_level, condition) \ LAZY_STREAM(VLOG_STREAM(verbose_level), \ - VLOG_IS_ON(verbose_level) && (condition)) + VLOG_IS_ON(verbose_level) && (condition)) -#if defined (OS_WIN) -#define VPLOG_STREAM(verbose_level) \ - cef::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \ - ::cef::logging::GetLastSystemErrorCode()).stream() +#if defined(OS_WIN) +#define VPLOG_STREAM(verbose_level) \ + cef::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \ + ::cef::logging::GetLastSystemErrorCode()) \ + .stream() #elif defined(OS_POSIX) -#define VPLOG_STREAM(verbose_level) \ - cef::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \ - ::cef::logging::GetLastSystemErrorCode()).stream() +#define VPLOG_STREAM(verbose_level) \ + cef::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \ + ::cef::logging::GetLastSystemErrorCode()) \ + .stream() #endif #define VPLOG(verbose_level) \ @@ -303,34 +300,35 @@ const LogSeverity LOG_0 = LOG_ERROR; #define VPLOG_IF(verbose_level, condition) \ LAZY_STREAM(VPLOG_STREAM(verbose_level), \ - VLOG_IS_ON(verbose_level) && (condition)) + VLOG_IS_ON(verbose_level) && (condition)) // TODO(akalin): Add more VLOG variants, e.g. VPLOG. -#define LOG_ASSERT(condition) \ +#define LOG_ASSERT(condition) \ LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " #define SYSLOG_ASSERT(condition) \ SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " #if defined(OS_WIN) -#define PLOG_STREAM(severity) \ - COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \ - ::cef::logging::GetLastSystemErrorCode()).stream() +#define PLOG_STREAM(severity) \ + COMPACT_GOOGLE_LOG_EX_##severity(Win32ErrorLogMessage, \ + ::cef::logging::GetLastSystemErrorCode()) \ + .stream() #elif defined(OS_POSIX) -#define PLOG_STREAM(severity) \ - COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \ - ::cef::logging::GetLastSystemErrorCode()).stream() +#define PLOG_STREAM(severity) \ + COMPACT_GOOGLE_LOG_EX_##severity(ErrnoLogMessage, \ + ::cef::logging::GetLastSystemErrorCode()) \ + .stream() #endif -#define PLOG(severity) \ - LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity)) +#define PLOG(severity) LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity)) #define PLOG_IF(severity, condition) \ LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition)) // The actual stream used isn't important. -#define EAT_STREAM_PARAMETERS \ - true ? (void) 0 : ::cef::logging::LogMessageVoidify() & LOG_STREAM(FATAL) +#define EAT_STREAM_PARAMETERS \ + true ? (void)0 : ::cef::logging::LogMessageVoidify() & LOG_STREAM(FATAL) // CHECK dies with a fatal error if condition is not true. It is *not* // controlled by NDEBUG, so the check will be executed regardless of @@ -341,28 +339,27 @@ const LogSeverity LOG_0 = LOG_ERROR; #define CHECK(condition) \ LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \ - << "Check failed: " #condition ". " + << "Check failed: " #condition ". " -#define PCHECK(condition) \ +#define PCHECK(condition) \ LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \ - << "Check failed: " #condition ". " + << "Check failed: " #condition ". " // Helper macro for binary operators. // Don't use this macro directly in your code, use CHECK_EQ et al below. // // TODO(akalin): Rewrite this so that constructs like if (...) // CHECK_EQ(...) else { ... } work properly. -#define CHECK_OP(name, op, val1, val2) \ - if (std::string* _result = \ - cef::logging::Check##name##Impl((val1), (val2), \ - #val1 " " #op " " #val2)) \ - cef::logging::LogMessage(__FILE__, __LINE__, _result).stream() +#define CHECK_OP(name, op, val1, val2) \ + if (std::string* _result = cef::logging::Check##name##Impl( \ + (val1), (val2), #val1 " " #op " " #val2)) \ + cef::logging::LogMessage(__FILE__, __LINE__, _result).stream() // Build the error message string. This is separate from the "Impl" // function template because it is not performance critical and so can // be out of line, while the "Impl" code should be inline. Caller // takes ownership of the returned string. -template +template std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) { std::ostringstream ss; ss << names << " (" << v1 << " vs. " << v2 << ")"; @@ -374,51 +371,60 @@ std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) { #if !defined(COMPILER_MSVC) // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated // in logging.cc. -extern template std::string* MakeCheckOpString( - const int&, const int&, const char* names); -extern template -std::string* MakeCheckOpString( - const unsigned long&, const unsigned long&, const char* names); -extern template -std::string* MakeCheckOpString( - const unsigned long&, const unsigned int&, const char* names); -extern template -std::string* MakeCheckOpString( - const unsigned int&, const unsigned long&, const char* names); -extern template -std::string* MakeCheckOpString( - const std::string&, const std::string&, const char* name); +extern template std::string* MakeCheckOpString(const int&, + const int&, + const char* names); +extern template std::string* MakeCheckOpString( + const unsigned long&, + const unsigned long&, + const char* names); +extern template std::string* MakeCheckOpString( + const unsigned long&, + const unsigned int&, + const char* names); +extern template std::string* MakeCheckOpString( + const unsigned int&, + const unsigned long&, + const char* names); +extern template std::string* MakeCheckOpString( + const std::string&, + const std::string&, + const char* name); #endif // Helper functions for CHECK_OP macro. // The (int, int) specialization works around the issue that the compiler // will not instantiate the template version of the function on values of // unnamed enum type - see comment below. -#define DEFINE_CHECK_OP_IMPL(name, op) \ - template \ - inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \ - const char* names) { \ - if (v1 op v2) return NULL; \ - else return MakeCheckOpString(v1, v2, names); \ - } \ +#define DEFINE_CHECK_OP_IMPL(name, op) \ + template \ + inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \ + const char* names) { \ + if (v1 op v2) \ + return NULL; \ + else \ + return MakeCheckOpString(v1, v2, names); \ + } \ inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \ - if (v1 op v2) return NULL; \ - else return MakeCheckOpString(v1, v2, names); \ + if (v1 op v2) \ + return NULL; \ + else \ + return MakeCheckOpString(v1, v2, names); \ } DEFINE_CHECK_OP_IMPL(EQ, ==) DEFINE_CHECK_OP_IMPL(NE, !=) DEFINE_CHECK_OP_IMPL(LE, <=) -DEFINE_CHECK_OP_IMPL(LT, < ) +DEFINE_CHECK_OP_IMPL(LT, <) DEFINE_CHECK_OP_IMPL(GE, >=) -DEFINE_CHECK_OP_IMPL(GT, > ) +DEFINE_CHECK_OP_IMPL(GT, >) #undef DEFINE_CHECK_OP_IMPL #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2) #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2) #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2) -#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2) +#define CHECK_LT(val1, val2) CHECK_OP(LT, <, val1, val2) #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2) -#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2) +#define CHECK_GT(val1, val2) CHECK_OP(GT, >, val1, val2) #if defined(NDEBUG) #define ENABLE_DLOG 0 @@ -471,11 +477,9 @@ enum { DEBUG_MODE = ENABLE_DLOG }; #undef ENABLE_DLOG -#define DLOG(severity) \ - LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity)) +#define DLOG(severity) LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity)) -#define DPLOG(severity) \ - LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity)) +#define DPLOG(severity) LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity)) #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel)) @@ -486,7 +490,7 @@ enum { DEBUG_MODE = ENABLE_DLOG }; #if DCHECK_IS_ON() #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ - COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__) + COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL const LogSeverity LOG_DCHECK = LOG_FATAL; @@ -494,7 +498,7 @@ const LogSeverity LOG_DCHECK = LOG_FATAL; // These are just dummy values. #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ - COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__) + COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO const LogSeverity LOG_DCHECK = LOG_INFO; @@ -505,22 +509,23 @@ const LogSeverity LOG_DCHECK = LOG_INFO; // variable warnings if the only use of a variable is in a DCHECK. // This behavior is different from DLOG_IF et al. -#define DCHECK(condition) \ - LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \ +#define DCHECK(condition) \ + LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \ << "Check failed: " #condition ". " -#define DPCHECK(condition) \ - LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \ +#define DPCHECK(condition) \ + LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \ << "Check failed: " #condition ". " // Helper macro for binary operators. // Don't use this macro directly in your code, use DCHECK_EQ et al below. -#define DCHECK_OP(name, op, val1, val2) \ - if (DCHECK_IS_ON()) \ - if (std::string* _result = cef::logging::Check##name##Impl( \ - (val1), (val2), #val1 " " #op " " #val2)) \ - cef::logging::LogMessage(__FILE__, __LINE__, \ - ::cef::logging::LOG_DCHECK, _result).stream() +#define DCHECK_OP(name, op, val1, val2) \ + if (DCHECK_IS_ON()) \ + if (std::string* _result = cef::logging::Check##name##Impl( \ + (val1), (val2), #val1 " " #op " " #val2)) \ + cef::logging::LogMessage(__FILE__, __LINE__, ::cef::logging::LOG_DCHECK, \ + _result) \ + .stream() // Equality/Inequality checks - compare two values, and log a // LOG_DCHECK message including the two values when the result is not @@ -544,13 +549,13 @@ const LogSeverity LOG_DCHECK = LOG_INFO; #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2) #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2) #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2) -#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2) +#define DCHECK_LT(val1, val2) DCHECK_OP(LT, <, val1, val2) #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2) -#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2) +#define DCHECK_GT(val1, val2) DCHECK_OP(GT, >, val1, val2) #if defined(NDEBUG) && defined(OS_CHROMEOS) -#define NOTREACHED() LOG(ERROR) << "NOTREACHED() hit in " << \ - __FUNCTION__ << ". " +#define NOTREACHED() \ + LOG(ERROR) << "NOTREACHED() hit in " << __FUNCTION__ << ". " #else #define NOTREACHED() DCHECK(false) #endif @@ -577,7 +582,9 @@ class LogMessage { LogMessage(const char* file, int line, std::string* result); // Used for DCHECK_EQ(), etc. Takes ownership of the given string. - LogMessage(const char* file, int line, LogSeverity severity, + LogMessage(const char* file, + int line, + LogSeverity severity, std::string* result); ~LogMessage(); @@ -617,7 +624,7 @@ class LogMessage { // A non-macro interface to the log facility; (useful // when the logging level is not a compile-time constant). -inline void LogAtLevel(int const log_level, std::string const &msg) { +inline void LogAtLevel(int const log_level, std::string const& msg) { LogMessage(__FILE__, __LINE__, log_level).stream() << msg; } @@ -626,10 +633,10 @@ inline void LogAtLevel(int const log_level, std::string const &msg) { // is not used" and "statement has no effect". class LogMessageVoidify { public: - LogMessageVoidify() { } + LogMessageVoidify() {} // This has to be an operator with a precedence lower than << but // higher than ?: - void operator&(std::ostream&) { } + void operator&(std::ostream&) {} }; #if defined(OS_WIN) @@ -739,12 +746,13 @@ inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) { #elif NOTIMPLEMENTED_POLICY == 4 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG #elif NOTIMPLEMENTED_POLICY == 5 -#define NOTIMPLEMENTED() do {\ - static bool logged_once = false;\ - LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\ - logged_once = true;\ -} while(0);\ -EAT_STREAM_PARAMETERS +#define NOTIMPLEMENTED() \ + do { \ + static bool logged_once = false; \ + LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG; \ + logged_once = true; \ + } while (0); \ + EAT_STREAM_PARAMETERS #endif #endif // !USING_CHROMIUM_INCLUDES diff --git a/src/include/base/cef_macros.h b/src/include/base/cef_macros.h index df3f9b7c5..e714529cd 100644 --- a/src/include/base/cef_macros.h +++ b/src/include/base/cef_macros.h @@ -41,7 +41,7 @@ // If the Chromium implementation diverges the below implementation should be // updated to match. -#include // For size_t. +#include // For size_t. #include "include/base/cef_build.h" // For COMPILER_MSVC #if !defined(arraysize) @@ -126,14 +126,13 @@ char (&ArraySizeHelper(const T (&array)[N]))[N]; namespace cef { template -struct CompileAssert { -}; +struct CompileAssert {}; } // namespace cef -#define COMPILE_ASSERT(expr, msg) \ - typedef cef::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] \ - ALLOW_UNUSED_TYPE +#define COMPILE_ASSERT(expr, msg) \ + typedef cef::CompileAssert<(bool(expr))> \ + msg[bool(expr) ? 1 : -1] ALLOW_UNUSED_TYPE // Implementation details of COMPILE_ASSERT: // @@ -182,13 +181,12 @@ struct CompileAssert { #endif // !USING_CHROMIUM_INCLUDES -#if !defined(ALLOW_THIS_IN_INITIALIZER_LIST) -#if defined(COMPILER_MSVC) +#if !defined(MSVC_PUSH_DISABLE_WARNING) && defined(COMPILER_MSVC) // MSVC_PUSH_DISABLE_WARNING pushes |n| onto a stack of warnings to be disabled. // The warning remains disabled until popped by MSVC_POP_WARNING. -#define MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \ - __pragma(warning(disable:n)) +#define MSVC_PUSH_DISABLE_WARNING(n) \ + __pragma(warning(push)) __pragma(warning(disable : n)) // MSVC_PUSH_WARNING_LEVEL pushes |n| as the global warning level. The level // remains in effect until popped by MSVC_POP_WARNING(). Use 0 to disable all @@ -198,6 +196,10 @@ struct CompileAssert { // Pop effects of innermost MSVC_PUSH_* macro. #define MSVC_POP_WARNING() __pragma(warning(pop)) +#endif // !defined(MSVC_PUSH_DISABLE_WARNING) && defined(COMPILER_MSVC) + +#if !defined(ALLOW_THIS_IN_INITIALIZER_LIST) +#if defined(COMPILER_MSVC) // Allows |this| to be passed as an argument in constructor initializer lists. // This uses push/pop instead of the seemingly simpler suppress feature to avoid // having the warning be disabled for more than just |code|. @@ -207,13 +209,11 @@ struct CompileAssert { // // Compiler warning C4355: 'this': used in base member initializer list: // http://msdn.microsoft.com/en-us/library/3c594ae3(VS.80).aspx -#define ALLOW_THIS_IN_INITIALIZER_LIST(code) MSVC_PUSH_DISABLE_WARNING(4355) \ - code \ - MSVC_POP_WARNING() +#define ALLOW_THIS_IN_INITIALIZER_LIST(code) \ + MSVC_PUSH_DISABLE_WARNING(4355) \ + code MSVC_POP_WARNING() #else // !COMPILER_MSVC - #define ALLOW_THIS_IN_INITIALIZER_LIST(code) code - #endif // !COMPILER_MSVC #endif // !ALLOW_THIS_IN_INITIALIZER_LIST diff --git a/src/include/base/cef_move.h b/src/include/base/cef_move.h index 3c3c4913f..da47d2d32 100644 --- a/src/include/base/cef_move.h +++ b/src/include/base/cef_move.h @@ -240,20 +240,22 @@ // // The workaround is to explicitly declare your copy constructor. // -#define MOVE_ONLY_TYPE_FOR_CPP_03(type, rvalue_type) \ - private: \ - struct rvalue_type { \ +#define MOVE_ONLY_TYPE_FOR_CPP_03(type, rvalue_type) \ + private: \ + struct rvalue_type { \ explicit rvalue_type(type* object) : object(object) {} \ - type* object; \ - }; \ - type(type&); \ - void operator=(type&); \ - public: \ - operator rvalue_type() { return rvalue_type(this); } \ - type Pass() { return type(rvalue_type(this)); } \ - typedef void MoveOnlyTypeForCPP03; \ + type* object; \ + }; \ + type(type&); \ + void operator=(type&); \ + \ + public: \ + operator rvalue_type() { return rvalue_type(this); } \ + type Pass() { return type(rvalue_type(this)); } \ + typedef void MoveOnlyTypeForCPP03; \ + \ private: - + #endif // !USING_CHROMIUM_INCLUDES #endif // CEF_INCLUDE_BASE_CEF_MOVE_H_ diff --git a/src/include/base/cef_platform_thread.h b/src/include/base/cef_platform_thread.h index 916113606..d3fdd798e 100644 --- a/src/include/base/cef_platform_thread.h +++ b/src/include/base/cef_platform_thread.h @@ -69,21 +69,14 @@ class PlatformThreadRef { public: typedef cef_platform_thread_handle_t RefType; - PlatformThreadRef() - : id_(0) { - } + PlatformThreadRef() : id_(0) {} - explicit PlatformThreadRef(RefType id) - : id_(id) { - } + explicit PlatformThreadRef(RefType id) : id_(id) {} - bool operator==(PlatformThreadRef other) const { - return id_ == other.id_; - } + bool operator==(PlatformThreadRef other) const { return id_ == other.id_; } + + bool is_null() const { return id_ == 0; } - bool is_null() const { - return id_ == 0; - } private: RefType id_; }; diff --git a/src/include/base/cef_ref_counted.h b/src/include/base/cef_ref_counted.h index 61d4de686..480b1ce9d 100644 --- a/src/include/base/cef_ref_counted.h +++ b/src/include/base/cef_ref_counted.h @@ -64,43 +64,43 @@ class RefCountedBase { protected: RefCountedBase() : ref_count_(0) - #if DCHECK_IS_ON() - , in_dtor_(false) - #endif - { +#if DCHECK_IS_ON() + , + in_dtor_(false) +#endif + { } ~RefCountedBase() { - #if DCHECK_IS_ON() +#if DCHECK_IS_ON() DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()"; - #endif +#endif } - void AddRef() const { - // TODO(maruel): Add back once it doesn't assert 500 times/sec. - // Current thread books the critical section "AddRelease" - // without release it. - // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); - #if DCHECK_IS_ON() +// TODO(maruel): Add back once it doesn't assert 500 times/sec. +// Current thread books the critical section "AddRelease" +// without release it. +// DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); +#if DCHECK_IS_ON() DCHECK(!in_dtor_); - #endif +#endif ++ref_count_; } // Returns true if the object should self-delete. bool Release() const { - // TODO(maruel): Add back once it doesn't assert 500 times/sec. - // Current thread books the critical section "AddRelease" - // without release it. - // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); - #if DCHECK_IS_ON() +// TODO(maruel): Add back once it doesn't assert 500 times/sec. +// Current thread books the critical section "AddRelease" +// without release it. +// DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); +#if DCHECK_IS_ON() DCHECK(!in_dtor_); - #endif +#endif if (--ref_count_ == 0) { - #if DCHECK_IS_ON() +#if DCHECK_IS_ON() in_dtor_ = true; - #endif +#endif return true; } return false; @@ -160,9 +160,7 @@ class RefCounted : public cef_subtle::RefCountedBase { public: RefCounted() {} - void AddRef() const { - cef_subtle::RefCountedBase::AddRef(); - } + void AddRef() const { cef_subtle::RefCountedBase::AddRef(); } void Release() const { if (cef_subtle::RefCountedBase::Release()) { @@ -178,18 +176,19 @@ class RefCounted : public cef_subtle::RefCountedBase { }; // Forward declaration. -template class RefCountedThreadSafe; +template +class RefCountedThreadSafe; // Default traits for RefCountedThreadSafe. Deletes the object when its ref // count reaches 0. Overload to delete it on a different thread etc. -template +template struct DefaultRefCountedThreadSafeTraits { static void Destruct(const T* x) { // Delete through RefCountedThreadSafe to make child classes only need to be // friend with RefCountedThreadSafe instead of this struct, which is an // implementation detail. - RefCountedThreadSafe::DeleteInternal(x); + RefCountedThreadSafe::DeleteInternal( + x); } }; @@ -205,14 +204,12 @@ struct DefaultRefCountedThreadSafeTraits { // private: // friend class base::RefCountedThreadSafe; // ~MyFoo(); -template > +template > class RefCountedThreadSafe : public cef_subtle::RefCountedThreadSafeBase { public: RefCountedThreadSafe() {} - void AddRef() const { - cef_subtle::RefCountedThreadSafeBase::AddRef(); - } + void AddRef() const { cef_subtle::RefCountedThreadSafeBase::AddRef(); } void Release() const { if (cef_subtle::RefCountedThreadSafeBase::Release()) { @@ -234,9 +231,9 @@ class RefCountedThreadSafe : public cef_subtle::RefCountedThreadSafeBase { // A thread-safe wrapper for some piece of data so we can place other // things in scoped_refptrs<>. // -template +template class RefCountedData - : public base::RefCountedThreadSafe< base::RefCountedData > { + : public base::RefCountedThreadSafe> { public: RefCountedData() : data() {} RefCountedData(const T& in_value) : data(in_value) {} @@ -244,7 +241,7 @@ class RefCountedData T data; private: - friend class base::RefCountedThreadSafe >; + friend class base::RefCountedThreadSafe>; ~RefCountedData() {} }; @@ -303,8 +300,7 @@ class scoped_refptr { public: typedef T element_type; - scoped_refptr() : ptr_(NULL) { - } + scoped_refptr() : ptr_(NULL) {} scoped_refptr(T* p) : ptr_(p) { if (ptr_) @@ -364,9 +360,7 @@ class scoped_refptr { *pp = p; } - void swap(scoped_refptr& r) { - swap(&r.ptr_); - } + void swap(scoped_refptr& r) { swap(&r.ptr_); } protected: T* ptr_; diff --git a/src/include/base/cef_scoped_ptr.h b/src/include/base/cef_scoped_ptr.h index 563558979..eb9e0e29b 100644 --- a/src/include/base/cef_scoped_ptr.h +++ b/src/include/base/cef_scoped_ptr.h @@ -154,7 +154,8 @@ class RefCountedThreadSafeBase; template struct DefaultDeleter { DefaultDeleter() {} - template DefaultDeleter(const DefaultDeleter& other) { + template + DefaultDeleter(const DefaultDeleter& other) { // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor // if U* is implicitly convertible to T* and U is not an array type. // @@ -194,7 +195,8 @@ struct DefaultDeleter { // References: // C++98 [expr.delete]p3 // http://cplusplus.github.com/LWG/lwg-defects.html#938 - template void operator()(U* array) const; + template + void operator()(U* array) const; }; template @@ -209,18 +211,18 @@ struct DefaultDeleter { // scoped_ptr foo_ptr( // static_cast(malloc(sizeof(int)))); struct FreeDeleter { - inline void operator()(void* ptr) const { - free(ptr); - } + inline void operator()(void* ptr) const { free(ptr); } }; namespace cef_internal { -template struct IsNotRefCounted { +template +struct IsNotRefCounted { enum { - value = !base::is_convertible::value && - !base::is_convertible:: - value + value = + !base::is_convertible::value && + !base::is_convertible::value }; }; @@ -229,7 +231,7 @@ template struct IsNotRefCounted { template class scoped_ptr_impl { public: - explicit scoped_ptr_impl(T* p) : data_(p) { } + explicit scoped_ptr_impl(T* p) : data_(p) {} // Initializer for deleters that have data parameters. scoped_ptr_impl(T* p, const D& d) : data_(p, d) {} @@ -309,7 +311,8 @@ class scoped_ptr_impl { private: // Needed to allow type-converting constructor. - template friend class scoped_ptr_impl; + template + friend class scoped_ptr_impl; // Use the empty base class optimization to allow us to have a D // member, while avoiding any space overhead for it when D is an @@ -346,7 +349,7 @@ class scoped_ptr_impl { // unique_ptr<> features. Known deficiencies include not supporting move-only // deleteres, function pointers as deleters, and deleters with reference // types. -template > +template > class scoped_ptr { MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) @@ -359,13 +362,13 @@ class scoped_ptr { typedef D deleter_type; // Constructor. Defaults to initializing with NULL. - scoped_ptr() : impl_(NULL) { } + scoped_ptr() : impl_(NULL) {} // Constructor. Takes ownership of p. - explicit scoped_ptr(element_type* p) : impl_(p) { } + explicit scoped_ptr(element_type* p) : impl_(p) {} // Constructor. Allows initialization of a stateful deleter. - scoped_ptr(element_type* p, const D& d) : impl_(p, d) { } + scoped_ptr(element_type* p, const D& d) : impl_(p, d) {} // Constructor. Allows construction from a scoped_ptr rvalue for a // convertible type and deleter. @@ -383,7 +386,7 @@ class scoped_ptr { } // Constructor. Move constructor for C++03 move emulation of this type. - scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } + scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) {} // operator=. Allows assignment from a scoped_ptr rvalue for a convertible // type and deleter. @@ -412,7 +415,7 @@ class scoped_ptr { assert(impl_.get() != NULL); return *impl_.get(); } - element_type* operator->() const { + element_type* operator->() const { assert(impl_.get() != NULL); return impl_.get(); } @@ -443,18 +446,14 @@ class scoped_ptr { bool operator!=(const element_type* p) const { return impl_.get() != p; } // Swap two scoped pointers. - void swap(scoped_ptr& p2) { - impl_.swap(p2.impl_); - } + void swap(scoped_ptr& p2) { impl_.swap(p2.impl_); } // Release a pointer. // The return value is the current pointer held by this object. // If this object holds a NULL pointer, the return value is NULL. // After this operation, this object will hold a NULL pointer, // and will not own the object any more. - element_type* release() WARN_UNUSED_RESULT { - return impl_.release(); - } + element_type* release() WARN_UNUSED_RESULT { return impl_.release(); } // C++98 doesn't support functions templates with default parameters which // makes it hard to write a PassAs() that understands converting the deleter @@ -469,7 +468,8 @@ class scoped_ptr { private: // Needed to reach into |impl_| in the constructor. - template friend class scoped_ptr; + template + friend class scoped_ptr; base::cef_internal::scoped_ptr_impl impl_; // Forbidden for API compatibility with std::unique_ptr. @@ -479,8 +479,10 @@ class scoped_ptr { // doesn't make sense, and if U == T, it still doesn't make sense // because you should never have the same object owned by two different // scoped_ptrs. - template bool operator==(scoped_ptr const& p2) const; - template bool operator!=(scoped_ptr const& p2) const; + template + bool operator==(scoped_ptr const& p2) const; + template + bool operator!=(scoped_ptr const& p2) const; }; template @@ -493,7 +495,7 @@ class scoped_ptr { typedef D deleter_type; // Constructor. Defaults to initializing with NULL. - scoped_ptr() : impl_(NULL) { } + scoped_ptr() : impl_(NULL) {} // Constructor. Stores the given array. Note that the argument's type // must exactly match T*. In particular: @@ -511,10 +513,10 @@ class scoped_ptr { // to work around this may use implicit_cast(). // However, because of the first bullet in this comment, users MUST // NOT use implicit_cast() to upcast the static type of the array. - explicit scoped_ptr(element_type* array) : impl_(array) { } + explicit scoped_ptr(element_type* array) : impl_(array) {} // Constructor. Move constructor for C++03 move emulation of this type. - scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } + scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) {} // operator=. Move operator= for C++03 move emulation of this type. scoped_ptr& operator=(RValue rhs) { @@ -553,18 +555,14 @@ class scoped_ptr { bool operator!=(element_type* array) const { return impl_.get() != array; } // Swap two scoped pointers. - void swap(scoped_ptr& p2) { - impl_.swap(p2.impl_); - } + void swap(scoped_ptr& p2) { impl_.swap(p2.impl_); } // Release a pointer. // The return value is the current pointer held by this object. // If this object holds a NULL pointer, the return value is NULL. // After this operation, this object will hold a NULL pointer, // and will not own the object any more. - element_type* release() WARN_UNUSED_RESULT { - return impl_.release(); - } + element_type* release() WARN_UNUSED_RESULT { return impl_.release(); } private: // Force element_type to be a complete type. @@ -578,20 +576,24 @@ class scoped_ptr { // private and has no definition. This is disabled because it is not safe to // call delete[] on an array whose static type does not match its dynamic // type. - template explicit scoped_ptr(U* array); + template + explicit scoped_ptr(U* array); explicit scoped_ptr(int disallow_construction_from_null); // Disable reset() from any type other than element_type*, for the same // reasons as the constructor above. - template void reset(U* array); + template + void reset(U* array); void reset(int disallow_reset_from_null); // Forbid comparison of scoped_ptr types. If U != T, it totally // doesn't make sense, and if U == T, it still doesn't make sense // because you should never have the same object owned by two different // scoped_ptrs. - template bool operator==(scoped_ptr const& p2) const; - template bool operator!=(scoped_ptr const& p2) const; + template + bool operator==(scoped_ptr const& p2) const; + template + bool operator!=(scoped_ptr const& p2) const; }; // Free functions diff --git a/src/include/base/cef_string16.h b/src/include/base/cef_string16.h index 51760f435..427564073 100644 --- a/src/include/base/cef_string16.h +++ b/src/include/base/cef_string16.h @@ -112,26 +112,19 @@ struct string16_char_traits { typedef mbstate_t state_type; typedef std::fpos pos_type; - static void assign(char_type& c1, const char_type& c2) { - c1 = c2; - } + static void assign(char_type& c1, const char_type& c2) { c1 = c2; } - static bool eq(const char_type& c1, const char_type& c2) { - return c1 == c2; - } - static bool lt(const char_type& c1, const char_type& c2) { - return c1 < c2; - } + static bool eq(const char_type& c1, const char_type& c2) { return c1 == c2; } + static bool lt(const char_type& c1, const char_type& c2) { return c1 < c2; } static int compare(const char_type* s1, const char_type* s2, size_t n) { return c16memcmp(s1, s2, n); } - static size_t length(const char_type* s) { - return c16len(s); - } + static size_t length(const char_type* s) { return c16len(s); } - static const char_type* find(const char_type* s, size_t n, + static const char_type* find(const char_type* s, + size_t n, const char_type& a) { return c16memchr(s, a, n); } @@ -152,21 +145,15 @@ struct string16_char_traits { return eq_int_type(c, eof()) ? 0 : c; } - static char_type to_char_type(const int_type& c) { - return char_type(c); - } + static char_type to_char_type(const int_type& c) { return char_type(c); } - static int_type to_int_type(const char_type& c) { - return int_type(c); - } + static int_type to_int_type(const char_type& c) { return int_type(c); } static bool eq_int_type(const int_type& c1, const int_type& c2) { return c1 == c2; } - static int_type eof() { - return static_cast(EOF); - } + static int_type eof() { return static_cast(EOF); } }; typedef std::basic_string string16; @@ -217,8 +204,8 @@ extern void PrintTo(const string16& str, std::ostream* out); // // TODO(mark): File this bug with Apple and update this note with a bug number. -extern template -class std::basic_string; +extern template class std::basic_string; #endif // WCHAR_T_IS_UTF32 diff --git a/src/include/base/cef_template_util.h b/src/include/base/cef_template_util.h index 098bf463e..38fa5839c 100644 --- a/src/include/base/cef_template_util.h +++ b/src/include/base/cef_template_util.h @@ -53,70 +53,92 @@ namespace base { // template definitions from tr1 -template +template struct integral_constant { static const T value = v; typedef T value_type; typedef integral_constant type; }; -template const T integral_constant::value; +template +const T integral_constant::value; typedef integral_constant true_type; typedef integral_constant false_type; -template struct is_pointer : false_type {}; -template struct is_pointer : true_type {}; +template +struct is_pointer : false_type {}; +template +struct is_pointer : true_type {}; // Member function pointer detection up to four params. Add more as needed // below. This is built-in to C++ 11, and we can remove this when we switch. -template +template struct is_member_function_pointer : false_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; template -struct is_member_function_pointer : true_type {}; +struct is_member_function_pointer : true_type {}; -template -struct is_member_function_pointer : true_type {}; -template : true_type {}; +template -struct is_member_function_pointer : true_type {}; - - -template struct is_same : public false_type {}; -template struct is_same : true_type {}; - -template struct is_array : public false_type {}; -template struct is_array : public true_type {}; -template struct is_array : public true_type {}; - -template struct is_non_const_reference : false_type {}; -template struct is_non_const_reference : true_type {}; -template struct is_non_const_reference : false_type {}; - -template struct is_const : false_type {}; -template struct is_const : true_type {}; - -template struct is_void : false_type {}; -template <> struct is_void : true_type {}; +struct is_member_function_pointer : true_type {}; + +template +struct is_same : public false_type {}; +template +struct is_same : true_type {}; + +template +struct is_array : public false_type {}; +template +struct is_array : public true_type {}; +template +struct is_array : public true_type {}; + +template +struct is_non_const_reference : false_type {}; +template +struct is_non_const_reference : true_type {}; +template +struct is_non_const_reference : false_type {}; + +template +struct is_const : false_type {}; +template +struct is_const : true_type {}; + +template +struct is_void : false_type {}; +template <> +struct is_void : true_type {}; namespace cef_internal { @@ -152,7 +174,7 @@ struct ConvertHelper { // is_class type_trait implementation. struct IsClassHelper { template - static YesType Test(void(C::*)(void)); + static YesType Test(void (C::*)(void)); template static NoType Test(...); @@ -168,22 +190,22 @@ template struct is_convertible : integral_constant( - cef_internal::ConvertHelper::Create())) == - sizeof(cef_internal::YesType)> { -}; + cef_internal::ConvertHelper::Create())) == + sizeof(cef_internal::YesType)> {}; template struct is_class : integral_constant(0)) == - sizeof(cef_internal::YesType)> { -}; + sizeof(cef_internal::YesType)> {}; -template +template struct enable_if {}; -template -struct enable_if { typedef T type; }; +template +struct enable_if { + typedef T type; +}; } // namespace base diff --git a/src/include/base/cef_thread_checker.h b/src/include/base/cef_thread_checker.h index 42bac7fc0..e48c8d033 100644 --- a/src/include/base/cef_thread_checker.h +++ b/src/include/base/cef_thread_checker.h @@ -58,7 +58,6 @@ #define ENABLE_THREAD_CHECKER 0 #endif - namespace base { namespace cef_internal { @@ -69,9 +68,7 @@ namespace cef_internal { // right version for your build configuration. class ThreadCheckerDoNothing { public: - bool CalledOnValidThread() const { - return true; - } + bool CalledOnValidThread() const { return true; } void DetachFromThread() {} }; @@ -110,11 +107,9 @@ class ThreadCheckerDoNothing { // // In Release mode, CalledOnValidThread will always return true. #if ENABLE_THREAD_CHECKER -class ThreadChecker : public cef_internal::ThreadCheckerImpl { -}; +class ThreadChecker : public cef_internal::ThreadCheckerImpl {}; #else -class ThreadChecker : public cef_internal::ThreadCheckerDoNothing { -}; +class ThreadChecker : public cef_internal::ThreadCheckerDoNothing {}; #endif // ENABLE_THREAD_CHECKER #undef ENABLE_THREAD_CHECKER diff --git a/src/include/base/cef_thread_collision_warner.h b/src/include/base/cef_thread_collision_warner.h index 8f60a546d..53f6ef6d5 100644 --- a/src/include/base/cef_thread_collision_warner.h +++ b/src/include/base/cef_thread_collision_warner.h @@ -139,24 +139,22 @@ // DFAKE_MUTEX(shareable_section_); // }; - #if DCHECK_IS_ON() // Defines a class member that acts like a mutex. It is used only as a // verification tool. -#define DFAKE_MUTEX(obj) \ - mutable base::ThreadCollisionWarner obj +#define DFAKE_MUTEX(obj) mutable base::ThreadCollisionWarner obj // Asserts the call is never called simultaneously in two threads. Used at // member function scope. #define DFAKE_SCOPED_LOCK(obj) \ - base::ThreadCollisionWarner::ScopedCheck s_check_##obj(&obj) + base::ThreadCollisionWarner::ScopedCheck s_check_##obj(&obj) // Asserts the call is never called simultaneously in two threads. Used at // member function scope. Same as DFAKE_SCOPED_LOCK but allows recursive locks. #define DFAKE_SCOPED_RECURSIVE_LOCK(obj) \ - base::ThreadCollisionWarner::ScopedRecursiveCheck sr_check_##obj(&obj) + base::ThreadCollisionWarner::ScopedRecursiveCheck sr_check_##obj(&obj) // Asserts the code is always executed in the same thread. #define DFAKE_SCOPED_LOCK_THREAD_LOCKED(obj) \ - base::ThreadCollisionWarner::Check check_##obj(&obj) + base::ThreadCollisionWarner::Check check_##obj(&obj) #else @@ -187,13 +185,9 @@ class ThreadCollisionWarner { public: // The parameter asserter is there only for test purpose explicit ThreadCollisionWarner(AsserterBase* asserter = new DCheckAsserter()) - : valid_thread_id_(0), - counter_(0), - asserter_(asserter) {} + : valid_thread_id_(0), counter_(0), asserter_(asserter) {} - ~ThreadCollisionWarner() { - delete asserter_; - } + ~ThreadCollisionWarner() { delete asserter_; } // This class is meant to be used through the macro // DFAKE_SCOPED_LOCK_THREAD_LOCKED @@ -202,8 +196,7 @@ class ThreadCollisionWarner { // from one thread class Check { public: - explicit Check(ThreadCollisionWarner* warner) - : warner_(warner) { + explicit Check(ThreadCollisionWarner* warner) : warner_(warner) { warner_->EnterSelf(); } @@ -219,14 +212,11 @@ class ThreadCollisionWarner { // DFAKE_SCOPED_LOCK class ScopedCheck { public: - explicit ScopedCheck(ThreadCollisionWarner* warner) - : warner_(warner) { + explicit ScopedCheck(ThreadCollisionWarner* warner) : warner_(warner) { warner_->Enter(); } - ~ScopedCheck() { - warner_->Leave(); - } + ~ScopedCheck() { warner_->Leave(); } private: ThreadCollisionWarner* warner_; @@ -243,9 +233,7 @@ class ThreadCollisionWarner { warner_->EnterSelf(); } - ~ScopedRecursiveCheck() { - warner_->Leave(); - } + ~ScopedRecursiveCheck() { warner_->Leave(); } private: ThreadCollisionWarner* warner_; diff --git a/src/include/base/cef_trace_event.h b/src/include/base/cef_trace_event.h index 20723fbb9..1b2cad014 100644 --- a/src/include/base/cef_trace_event.h +++ b/src/include/base/cef_trace_event.h @@ -160,32 +160,29 @@ // enabled, then this does nothing. // - category and name strings must have application lifetime (statics or // literals). They may not include " chars. -#define TRACE_EVENT0(category, name) \ +#define TRACE_EVENT0(category, name) \ cef_trace_event_begin(category, name, NULL, 0, NULL, 0, false); \ CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) -#define TRACE_EVENT1(category, name, arg1_name, arg1_val) \ +#define TRACE_EVENT1(category, name, arg1_name, arg1_val) \ cef_trace_event_begin(category, name, arg1_name, arg1_val, NULL, 0, false); \ CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) -#define TRACE_EVENT2(category, name, arg1_name, arg1_val, arg2_name, \ - arg2_val) \ - cef_trace_event_begin(category, name, arg1_name, arg1_val, \ - arg2_name, arg2_val, false); \ +#define TRACE_EVENT2(category, name, arg1_name, arg1_val, arg2_name, arg2_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, false); \ CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) // Implementation detail: trace event macros create temporary variable names. // These macros give each temporary variable a unique name based on the line // number to prevent name collisions. -#define CEF_INTERNAL_TRACE_EVENT_UID3(a,b) \ - cef_trace_event_unique_##a##b -#define CEF_INTERNAL_TRACE_EVENT_UID2(a,b) \ - CEF_INTERNAL_TRACE_EVENT_UID3(a,b) +#define CEF_INTERNAL_TRACE_EVENT_UID3(a, b) cef_trace_event_unique_##a##b +#define CEF_INTERNAL_TRACE_EVENT_UID2(a, b) CEF_INTERNAL_TRACE_EVENT_UID3(a, b) #define CEF_INTERNAL_TRACE_EVENT_UID(name_prefix) \ CEF_INTERNAL_TRACE_EVENT_UID2(name_prefix, __LINE__) // Implementation detail: internal macro to end end event when the scope ends. -#define CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) \ - cef_trace_event::CefTraceEndOnScopeClose \ - CEF_INTERNAL_TRACE_EVENT_UID(profileScope)(category, name) +#define CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) \ + cef_trace_event::CefTraceEndOnScopeClose CEF_INTERNAL_TRACE_EVENT_UID( \ + profileScope)(category, name) // Records a single event called "name" immediately, with 0, 1 or 2 // associated arguments. If the category is not enabled, then this @@ -196,18 +193,18 @@ cef_trace_event_instant(category, name, NULL, 0, NULL, 0, false) #define TRACE_EVENT_INSTANT1(category, name, arg1_name, arg1_val) \ cef_trace_event_instant(category, name, arg1_name, arg1_val, NULL, 0, false) -#define TRACE_EVENT_INSTANT2(category, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - cef_trace_event_instant(category, name, arg1_name, arg1_val, arg2_name, \ - arg2_val, false) +#define TRACE_EVENT_INSTANT2(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val) \ + cef_trace_event_instant(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, false) #define TRACE_EVENT_COPY_INSTANT0(category, name) \ cef_trace_event_instant(category, name, NULL, 0, NULL, 0, true) #define TRACE_EVENT_COPY_INSTANT1(category, name, arg1_name, arg1_val) \ cef_trace_event_instant(category, name, arg1_name, arg1_val, NULL, 0, true) -#define TRACE_EVENT_COPY_INSTANT2(category, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ +#define TRACE_EVENT_COPY_INSTANT2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ cef_trace_event_instant(category, name, arg1_name, arg1_val, arg2_name, \ - arg2_val, true) + arg2_val, true) // Records a single BEGIN event called "name" immediately, with 0, 1 or 2 // associated arguments. If the category is not enabled, then this @@ -218,18 +215,18 @@ cef_trace_event_begin(category, name, NULL, 0, NULL, 0, false) #define TRACE_EVENT_BEGIN1(category, name, arg1_name, arg1_val) \ cef_trace_event_begin(category, name, arg1_name, arg1_val, NULL, 0, false) -#define TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - cef_trace_event_begin(category, name, arg1_name, arg1_val, arg2_name, \ - arg2_val, false) +#define TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, false) #define TRACE_EVENT_COPY_BEGIN0(category, name) \ cef_trace_event_begin(category, name, NULL, 0, NULL, 0, true) #define TRACE_EVENT_COPY_BEGIN1(category, name, arg1_name, arg1_val) \ cef_trace_event_begin(category, name, arg1_name, arg1_val, NULL, 0, true) -#define TRACE_EVENT_COPY_BEGIN2(category, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ +#define TRACE_EVENT_COPY_BEGIN2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ cef_trace_event_begin(category, name, arg1_name, arg1_val, arg2_name, \ - arg2_val, true) + arg2_val, true) // Records a single END event for "name" immediately. If the category // is not enabled, then this does nothing. @@ -239,18 +236,18 @@ cef_trace_event_end(category, name, NULL, 0, NULL, 0, false) #define TRACE_EVENT_END1(category, name, arg1_name, arg1_val) \ cef_trace_event_end(category, name, arg1_name, arg1_val, NULL, 0, false) -#define TRACE_EVENT_END2(category, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - cef_trace_event_end(category, name, arg1_name, arg1_val, arg2_name, \ - arg2_val, false) +#define TRACE_EVENT_END2(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val) \ + cef_trace_event_end(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, false) #define TRACE_EVENT_COPY_END0(category, name) \ cef_trace_event_end(category, name, NULL, 0, NULL, 0, true) #define TRACE_EVENT_COPY_END1(category, name, arg1_name, arg1_val) \ cef_trace_event_end(category, name, arg1_name, arg1_val, NULL, 0, true) -#define TRACE_EVENT_COPY_END2(category, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - cef_trace_event_end(category, name, arg1_name, arg1_val, arg2_name, \ - arg2_val, true) +#define TRACE_EVENT_COPY_END2(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val) \ + cef_trace_event_end(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, true) // Records the value of a counter called "name" immediately. Value // must be representable as a 32 bit integer. @@ -266,14 +263,14 @@ // values as a stacked-bar chart. // - category and name strings must have application lifetime (statics or // literals). They may not include " chars. -#define TRACE_COUNTER2(category, name, value1_name, value1_val, \ - value2_name, value2_val) \ - cef_trace_counter(category, name, value1_name, value1_val, value2_name, \ - value2_val, false) -#define TRACE_COPY_COUNTER2(category, name, value1_name, value1_val, \ - value2_name, value2_val) \ +#define TRACE_COUNTER2(category, name, value1_name, value1_val, value2_name, \ + value2_val) \ + cef_trace_counter(category, name, value1_name, value1_val, value2_name, \ + value2_val, false) +#define TRACE_COPY_COUNTER2(category, name, value1_name, value1_val, \ + value2_name, value2_val) \ cef_trace_counter(category, name, value1_name, value1_val, value2_name, \ - value2_val, true) + value2_val, true) // Records the value of a counter called "name" immediately. Value // must be representable as a 32 bit integer. @@ -298,14 +295,13 @@ // bits will be xored with a hash of the process ID so that the same pointer // on two different processes will not collide. #define TRACE_COUNTER_ID2(category, name, id, value1_name, value1_val, \ - value2_name, value2_val) \ - cef_trace_counter_id(category, name, id, value1_name, value1_val, \ - value2_name, value2_val, false) -#define TRACE_COPY_COUNTER_ID2(category, name, id, value1_name, \ - value1_val, value2_name, value2_val) \ - cef_trace_counter_id(category, name, id, value1_name, value1_val, \ - value2_name, value2_val, true) - + value2_name, value2_val) \ + cef_trace_counter_id(category, name, id, value1_name, value1_val, \ + value2_name, value2_val, false) +#define TRACE_COPY_COUNTER_ID2(category, name, id, value1_name, value1_val, \ + value2_name, value2_val) \ + cef_trace_counter_id(category, name, id, value1_name, value1_val, \ + value2_name, value2_val, true) // Records a single ASYNC_BEGIN event called "name" immediately, with 0, 1 or 2 // associated arguments. If the category is not enabled, then this @@ -325,23 +321,22 @@ // args. #define TRACE_EVENT_ASYNC_BEGIN0(category, name, id) \ cef_trace_event_async_begin(category, name, id, NULL, 0, NULL, 0, false) -#define TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \ +#define TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \ cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, NULL, \ - 0, false) + 0, false) #define TRACE_EVENT_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, \ - arg2_name, arg2_val, false) + arg2_name, arg2_val) \ + cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, false) #define TRACE_EVENT_COPY_ASYNC_BEGIN0(category, name, id) \ cef_trace_event_async_begin(category, name, id, NULL, 0, NULL, 0, true) -#define TRACE_EVENT_COPY_ASYNC_BEGIN1(category, name, id, arg1_name, \ - arg1_val) \ - cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, NULL, \ - 0, true) -#define TRACE_EVENT_COPY_ASYNC_BEGIN2(category, name, id, arg1_name, \ - arg1_val, arg2_name, arg2_val) \ - cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, \ - arg2_name, arg2_val, true) +#define TRACE_EVENT_COPY_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \ + cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, NULL, \ + 0, true) +#define TRACE_EVENT_COPY_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, true) // Records a single ASYNC_STEP_INTO event for |step| immediately. If the // category is not enabled, then this does nothing. The |name| and |id| must @@ -351,16 +346,16 @@ // ASYNC_STEP_PAST events. #define TRACE_EVENT_ASYNC_STEP_INTO0(category, name, id, step) \ cef_trace_event_async_step_into(category, name, id, step, NULL, 0, false) -#define TRACE_EVENT_ASYNC_STEP_INTO1(category, name, id, step, \ - arg1_name, arg1_val) \ - cef_trace_event_async_step_into(category, name, id, step, arg1_name, \ - arg1_val, false) +#define TRACE_EVENT_ASYNC_STEP_INTO1(category, name, id, step, arg1_name, \ + arg1_val) \ + cef_trace_event_async_step_into(category, name, id, step, arg1_name, \ + arg1_val, false) #define TRACE_EVENT_COPY_ASYNC_STEP_INTO0(category, name, id, step) \ cef_trace_event_async_step_into(category, name, id, step, NULL, 0, true) -#define TRACE_EVENT_COPY_ASYNC_STEP_INTO1(category, name, id, step, \ - arg1_name, arg1_val) \ - cef_trace_event_async_step_into(category, name, id, step, arg1_name, \ - arg1_val, true) +#define TRACE_EVENT_COPY_ASYNC_STEP_INTO1(category, name, id, step, arg1_name, \ + arg1_val) \ + cef_trace_event_async_step_into(category, name, id, step, arg1_name, \ + arg1_val, true) // Records a single ASYNC_STEP_PAST event for |step| immediately. If the // category is not enabled, then this does nothing. The |name| and |id| must @@ -370,38 +365,37 @@ // ASYNC_STEP_INTO events. #define TRACE_EVENT_ASYNC_STEP_PAST0(category, name, id, step) \ cef_trace_event_async_step_past(category, name, id, step, NULL, 0, false) -#define TRACE_EVENT_ASYNC_STEP_PAST1(category, name, id, step, \ - arg1_name, arg1_val) \ - cef_trace_event_async_step_past(category, name, id, step, arg1_name, \ - arg1_val, false) +#define TRACE_EVENT_ASYNC_STEP_PAST1(category, name, id, step, arg1_name, \ + arg1_val) \ + cef_trace_event_async_step_past(category, name, id, step, arg1_name, \ + arg1_val, false) #define TRACE_EVENT_COPY_ASYNC_STEP_PAST0(category, name, id, step) \ cef_trace_event_async_step_past(category, name, id, step, NULL, 0, true) -#define TRACE_EVENT_COPY_ASYNC_STEP_PAST1(category, name, id, step, \ - arg1_name, arg1_val) \ - cef_trace_event_async_step_past(category, name, id, step, arg1_name, \ - arg1_val, true) +#define TRACE_EVENT_COPY_ASYNC_STEP_PAST1(category, name, id, step, arg1_name, \ + arg1_val) \ + cef_trace_event_async_step_past(category, name, id, step, arg1_name, \ + arg1_val, true) // Records a single ASYNC_END event for "name" immediately. If the category // is not enabled, then this does nothing. #define TRACE_EVENT_ASYNC_END0(category, name, id) \ cef_trace_event_async_end(category, name, id, NULL, 0, NULL, 0, false) -#define TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name, arg1_val) \ +#define TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name, arg1_val) \ cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, NULL, 0, \ - false) + false) #define TRACE_EVENT_ASYNC_END2(category, name, id, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, \ - arg2_name, arg2_val, false) + arg2_name, arg2_val) \ + cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, false) #define TRACE_EVENT_COPY_ASYNC_END0(category, name, id) \ cef_trace_event_async_end(category, name, id, NULL, 0, NULL, 0, true) -#define TRACE_EVENT_COPY_ASYNC_END1(category, name, id, arg1_name, \ - arg1_val) \ +#define TRACE_EVENT_COPY_ASYNC_END1(category, name, id, arg1_name, arg1_val) \ cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, NULL, 0, \ - true) -#define TRACE_EVENT_COPY_ASYNC_END2(category, name, id, arg1_name, \ - arg1_val, arg2_name, arg2_val) \ - cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, \ - arg2_name, arg2_val, true) + true) +#define TRACE_EVENT_COPY_ASYNC_END2(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, true) namespace cef_trace_event { @@ -409,8 +403,7 @@ namespace cef_trace_event { class CefTraceEndOnScopeClose { public: CefTraceEndOnScopeClose(const char* category, const char* name) - : category_(category), name_(name) { - } + : category_(category), name_(name) {} ~CefTraceEndOnScopeClose() { cef_trace_event_end(category_, name_, NULL, 0, NULL, 0, false); } diff --git a/src/include/base/cef_tuple.h b/src/include/base/cef_tuple.h index 2268792dd..aeb6e9cea 100644 --- a/src/include/base/cef_tuple.h +++ b/src/include/base/cef_tuple.h @@ -96,7 +96,7 @@ struct TupleTraits { }; template -struct TupleTypes { }; +struct TupleTypes {}; // Tuple ----------------------------------------------------------------------- // @@ -138,8 +138,7 @@ struct Tuple2 { Tuple2() {} Tuple2(typename TupleTraits::ParamType a, typename TupleTraits::ParamType b) - : a(a), b(b) { - } + : a(a), b(b) {} A a; B b; @@ -156,8 +155,7 @@ struct Tuple3 { Tuple3(typename TupleTraits::ParamType a, typename TupleTraits::ParamType b, typename TupleTraits::ParamType c) - : a(a), b(b), c(c){ - } + : a(a), b(b), c(c) {} A a; B b; @@ -177,8 +175,7 @@ struct Tuple4 { typename TupleTraits::ParamType b, typename TupleTraits::ParamType c, typename TupleTraits::ParamType d) - : a(a), b(b), c(c), d(d) { - } + : a(a), b(b), c(c), d(d) {} A a; B b; @@ -197,12 +194,11 @@ struct Tuple5 { Tuple5() {} Tuple5(typename TupleTraits::ParamType a, - typename TupleTraits::ParamType b, - typename TupleTraits::ParamType c, - typename TupleTraits::ParamType d, - typename TupleTraits::ParamType e) - : a(a), b(b), c(c), d(d), e(e) { - } + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e) + : a(a), b(b), c(c), d(d), e(e) {} A a; B b; @@ -223,13 +219,12 @@ struct Tuple6 { Tuple6() {} Tuple6(typename TupleTraits::ParamType a, - typename TupleTraits::ParamType b, - typename TupleTraits::ParamType c, - typename TupleTraits::ParamType d, - typename TupleTraits::ParamType e, - typename TupleTraits::ParamType f) - : a(a), b(b), c(c), d(d), e(e), f(f) { - } + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e, + typename TupleTraits::ParamType f) + : a(a), b(b), c(c), d(d), e(e), f(f) {} A a; B b; @@ -252,14 +247,13 @@ struct Tuple7 { Tuple7() {} Tuple7(typename TupleTraits::ParamType a, - typename TupleTraits::ParamType b, - typename TupleTraits::ParamType c, - typename TupleTraits::ParamType d, - typename TupleTraits::ParamType e, - typename TupleTraits::ParamType f, - typename TupleTraits::ParamType g) - : a(a), b(b), c(c), d(d), e(e), f(f), g(g) { - } + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e, + typename TupleTraits::ParamType f, + typename TupleTraits::ParamType g) + : a(a), b(b), c(c), d(d), e(e), f(f), g(g) {} A a; B b; @@ -270,7 +264,13 @@ struct Tuple7 { G g; }; -template struct Tuple8 { public: @@ -285,15 +285,14 @@ struct Tuple8 { Tuple8() {} Tuple8(typename TupleTraits::ParamType a, - typename TupleTraits::ParamType b, - typename TupleTraits::ParamType c, - typename TupleTraits::ParamType d, - typename TupleTraits::ParamType e, - typename TupleTraits::ParamType f, - typename TupleTraits::ParamType g, - typename TupleTraits::ParamType h) - : a(a), b(b), c(c), d(d), e(e), f(f), g(g), h(h) { - } + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e, + typename TupleTraits::ParamType f, + typename TupleTraits::ParamType g, + typename TupleTraits::ParamType h) + : a(a), b(b), c(c), d(d), e(e), f(f), g(g), h(h) {} A a; B b; @@ -311,127 +310,151 @@ struct Tuple8 { // definitions of class types the tuple takes as parameters. template <> -struct TupleTypes< Tuple0 > { +struct TupleTypes { typedef Tuple0 ValueTuple; typedef Tuple0 RefTuple; typedef Tuple0 ParamTuple; }; template -struct TupleTypes< Tuple1 > { +struct TupleTypes> { typedef Tuple1::ValueType> ValueTuple; typedef Tuple1::RefType> RefTuple; typedef Tuple1::ParamType> ParamTuple; }; template -struct TupleTypes< Tuple2 > { +struct TupleTypes> { typedef Tuple2::ValueType, - typename TupleTraits::ValueType> ValueTuple; -typedef Tuple2::RefType, - typename TupleTraits::RefType> RefTuple; + typename TupleTraits::ValueType> + ValueTuple; + typedef Tuple2::RefType, + typename TupleTraits::RefType> + RefTuple; typedef Tuple2::ParamType, - typename TupleTraits::ParamType> ParamTuple; + typename TupleTraits::ParamType> + ParamTuple; }; template -struct TupleTypes< Tuple3 > { +struct TupleTypes> { typedef Tuple3::ValueType, typename TupleTraits::ValueType, - typename TupleTraits::ValueType> ValueTuple; -typedef Tuple3::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType> RefTuple; + typename TupleTraits::ValueType> + ValueTuple; + typedef Tuple3::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> + RefTuple; typedef Tuple3::ParamType, typename TupleTraits::ParamType, - typename TupleTraits::ParamType> ParamTuple; + typename TupleTraits::ParamType> + ParamTuple; }; template -struct TupleTypes< Tuple4 > { +struct TupleTypes> { typedef Tuple4::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, - typename TupleTraits::ValueType> ValueTuple; -typedef Tuple4::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType> RefTuple; + typename TupleTraits::ValueType> + ValueTuple; + typedef Tuple4::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> + RefTuple; typedef Tuple4::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, - typename TupleTraits::ParamType> ParamTuple; + typename TupleTraits::ParamType> + ParamTuple; }; template -struct TupleTypes< Tuple5 > { +struct TupleTypes> { typedef Tuple5::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, - typename TupleTraits::ValueType> ValueTuple; -typedef Tuple5::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType> RefTuple; + typename TupleTraits::ValueType> + ValueTuple; + typedef Tuple5::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> + RefTuple; typedef Tuple5::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, - typename TupleTraits::ParamType> ParamTuple; + typename TupleTraits::ParamType> + ParamTuple; }; template -struct TupleTypes< Tuple6 > { +struct TupleTypes> { typedef Tuple6::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, - typename TupleTraits::ValueType> ValueTuple; -typedef Tuple6::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType> RefTuple; + typename TupleTraits::ValueType> + ValueTuple; + typedef Tuple6::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> + RefTuple; typedef Tuple6::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, - typename TupleTraits::ParamType> ParamTuple; + typename TupleTraits::ParamType> + ParamTuple; }; template -struct TupleTypes< Tuple7 > { +struct TupleTypes> { typedef Tuple7::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, - typename TupleTraits::ValueType> ValueTuple; -typedef Tuple7::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType> RefTuple; + typename TupleTraits::ValueType> + ValueTuple; + typedef Tuple7::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> + RefTuple; typedef Tuple7::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, - typename TupleTraits::ParamType> ParamTuple; + typename TupleTraits::ParamType> + ParamTuple; }; -template -struct TupleTypes< Tuple8 > { +struct TupleTypes> { typedef Tuple8::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, @@ -439,15 +462,17 @@ struct TupleTypes< Tuple8 > { typename TupleTraits::ValueType, typename TupleTraits::ValueType, typename TupleTraits::ValueType, - typename TupleTraits::ValueType> ValueTuple; -typedef Tuple8::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType, - typename TupleTraits::RefType> RefTuple; + typename TupleTraits::ValueType> + ValueTuple; + typedef Tuple8::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> + RefTuple; typedef Tuple8::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, @@ -455,7 +480,8 @@ typedef Tuple8::RefType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, typename TupleTraits::ParamType, - typename TupleTraits::ParamType> ParamTuple; + typename TupleTraits::ParamType> + ParamTuple; }; // Tuple creators ------------------------------------------------------------- @@ -483,36 +509,59 @@ inline Tuple3 MakeTuple(const A& a, const B& b, const C& c) { } template -inline Tuple4 MakeTuple(const A& a, const B& b, const C& c, +inline Tuple4 MakeTuple(const A& a, + const B& b, + const C& c, const D& d) { return Tuple4(a, b, c, d); } template -inline Tuple5 MakeTuple(const A& a, const B& b, const C& c, - const D& d, const E& e) { +inline Tuple5 MakeTuple(const A& a, + const B& b, + const C& c, + const D& d, + const E& e) { return Tuple5(a, b, c, d, e); } template -inline Tuple6 MakeTuple(const A& a, const B& b, const C& c, - const D& d, const E& e, const F& f) { +inline Tuple6 MakeTuple(const A& a, + const B& b, + const C& c, + const D& d, + const E& e, + const F& f) { return Tuple6(a, b, c, d, e, f); } template -inline Tuple7 MakeTuple(const A& a, const B& b, const C& c, - const D& d, const E& e, const F& f, +inline Tuple7 MakeTuple(const A& a, + const B& b, + const C& c, + const D& d, + const E& e, + const F& f, const G& g) { return Tuple7(a, b, c, d, e, f, g); } -template -inline Tuple8 MakeTuple(const A& a, const B& b, - const C& c, const D& d, - const E& e, const F& f, - const G& g, const H& h) { +inline Tuple8 MakeTuple(const A& a, + const B& b, + const C& c, + const D& d, + const E& e, + const F& f, + const G& g, + const H& h) { return Tuple8(a, b, c, d, e, f, g, h); } @@ -545,22 +594,31 @@ inline Tuple5 MakeRefTuple(A& a, B& b, C& c, D& d, E& e) { } template -inline Tuple6 MakeRefTuple(A& a, B& b, C& c, D& d, E& e, +inline Tuple6 MakeRefTuple(A& a, + B& b, + C& c, + D& d, + E& e, F& f) { return Tuple6(a, b, c, d, e, f); } template -inline Tuple7 MakeRefTuple(A& a, B& b, C& c, D& d, - E& e, F& f, G& g) { +inline Tuple7 +MakeRefTuple(A& a, B& b, C& c, D& d, E& e, F& f, G& g) { return Tuple7(a, b, c, d, e, f, g); } -template -inline Tuple8 MakeRefTuple(A& a, B& b, C& c, - D& d, E& e, F& f, - G& g, H& h) { +inline Tuple8 +MakeRefTuple(A& a, B& b, C& c, D& d, E& e, F& f, G& g, H& h) { return Tuple8(a, b, c, d, e, f, g, h); } @@ -590,7 +648,7 @@ inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1& arg) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a)); } -template +template inline void DispatchToMethod(ObjT* obj, Method method, const Tuple2& arg) { @@ -598,16 +656,18 @@ inline void DispatchToMethod(ObjT* obj, base::cef_internal::UnwrapTraits::Unwrap(arg.b)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple3& arg) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), base::cef_internal::UnwrapTraits::Unwrap(arg.c)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple4& arg) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), @@ -615,8 +675,9 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(arg.d)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple5& arg) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), @@ -625,9 +686,16 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(arg.e)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple6& arg) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), @@ -637,9 +705,17 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(arg.f)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple7& arg) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), @@ -650,9 +726,18 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(arg.g)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple8& arg) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), @@ -681,20 +766,20 @@ inline void DispatchToFunction(Function function, const Tuple1& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a)); } -template +template inline void DispatchToFunction(Function function, const Tuple2& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b)); } -template +template inline void DispatchToFunction(Function function, const Tuple3& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), base::cef_internal::UnwrapTraits::Unwrap(arg.c)); } -template +template inline void DispatchToFunction(Function function, const Tuple4& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), @@ -703,7 +788,7 @@ inline void DispatchToFunction(Function function, base::cef_internal::UnwrapTraits::Unwrap(arg.d)); } -template +template inline void DispatchToFunction(Function function, const Tuple5& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), @@ -713,7 +798,7 @@ inline void DispatchToFunction(Function function, base::cef_internal::UnwrapTraits::Unwrap(arg.e)); } -template +template inline void DispatchToFunction(Function function, const Tuple6& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), @@ -724,8 +809,14 @@ inline void DispatchToFunction(Function function, base::cef_internal::UnwrapTraits::Unwrap(arg.f)); } -template +template inline void DispatchToFunction(Function function, const Tuple7& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), @@ -737,8 +828,15 @@ inline void DispatchToFunction(Function function, base::cef_internal::UnwrapTraits::Unwrap(arg.g)); } -template +template inline void DispatchToFunction(Function function, const Tuple8& arg) { (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), @@ -756,7 +854,8 @@ inline void DispatchToFunction(Function function, template inline void DispatchToMethod(ObjT* obj, Method method, - const Tuple0& arg, Tuple0*) { + const Tuple0& arg, + Tuple0*) { (obj->*method)(); } @@ -768,38 +867,46 @@ inline void DispatchToMethod(ObjT* obj, Method method, const A& arg, Tuple0*) { template inline void DispatchToMethod(ObjT* obj, Method method, - const Tuple1& arg, Tuple0*) { + const Tuple1& arg, + Tuple0*) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a)); } -template +template inline void DispatchToMethod(ObjT* obj, Method method, - const Tuple2& arg, Tuple0*) { + const Tuple2& arg, + Tuple0*) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, - const Tuple3& arg, Tuple0*) { +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple3& arg, + Tuple0*) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), base::cef_internal::UnwrapTraits::Unwrap(arg.c)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, - const Tuple4& arg, Tuple0*) { +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple4& arg, + Tuple0*) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), base::cef_internal::UnwrapTraits::Unwrap(arg.c), base::cef_internal::UnwrapTraits::Unwrap(arg.d)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, - const Tuple5& arg, Tuple0*) { +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple5& arg, + Tuple0*) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), base::cef_internal::UnwrapTraits::Unwrap(arg.c), @@ -807,10 +914,18 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(arg.e)); } -template -inline void DispatchToMethod(ObjT* obj, Method method, - const Tuple6& arg, Tuple0*) { +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple6& arg, + Tuple0*) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), base::cef_internal::UnwrapTraits::Unwrap(arg.b), base::cef_internal::UnwrapTraits::Unwrap(arg.c), @@ -821,80 +936,96 @@ inline void DispatchToMethod(ObjT* obj, Method method, // Dispatchers with 1 out param. -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple0& in, Tuple1* out) { (obj->*method)(&out->a); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const InA& in, Tuple1* out) { (obj->*method)(in, &out->a); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple1& in, Tuple1* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple2& in, Tuple1* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - base::cef_internal::UnwrapTraits::Unwrap(in.b), - &out->a); + base::cef_internal::UnwrapTraits::Unwrap(in.b), &out->a); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple3& in, Tuple1* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), - base::cef_internal::UnwrapTraits::Unwrap(in.c), - &out->a); + base::cef_internal::UnwrapTraits::Unwrap(in.c), &out->a); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple4& in, Tuple1* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), - base::cef_internal::UnwrapTraits::Unwrap(in.d), - &out->a); + base::cef_internal::UnwrapTraits::Unwrap(in.d), &out->a); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple5& in, Tuple1* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), - base::cef_internal::UnwrapTraits::Unwrap(in.e), - &out->a); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.e), &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple6& in, Tuple1* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), @@ -902,92 +1033,120 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), base::cef_internal::UnwrapTraits::Unwrap(in.e), - base::cef_internal::UnwrapTraits::Unwrap(in.f), - &out->a); + base::cef_internal::UnwrapTraits::Unwrap(in.f), &out->a); } // Dispatchers with 2 out params. -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple0& in, Tuple2* out) { (obj->*method)(&out->a, &out->b); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const InA& in, Tuple2* out) { (obj->*method)(in, &out->a, &out->b); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple1& in, Tuple2* out) { - (obj->*method)( - base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a, &out->b); + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a, + &out->b); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple2& in, Tuple2* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - base::cef_internal::UnwrapTraits::Unwrap(in.b), - &out->a, + base::cef_internal::UnwrapTraits::Unwrap(in.b), &out->a, &out->b); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple3& in, Tuple2* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), - base::cef_internal::UnwrapTraits::Unwrap(in.c), - &out->a, + base::cef_internal::UnwrapTraits::Unwrap(in.c), &out->a, &out->b); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple4& in, Tuple2* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), - base::cef_internal::UnwrapTraits::Unwrap(in.d), - &out->a, + base::cef_internal::UnwrapTraits::Unwrap(in.d), &out->a, &out->b); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple5& in, Tuple2* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), - base::cef_internal::UnwrapTraits::Unwrap(in.e), - &out->a, + base::cef_internal::UnwrapTraits::Unwrap(in.e), &out->a, &out->b); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple6& in, Tuple2* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), @@ -995,99 +1154,136 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), base::cef_internal::UnwrapTraits::Unwrap(in.e), - base::cef_internal::UnwrapTraits::Unwrap(in.f), - &out->a, + base::cef_internal::UnwrapTraits::Unwrap(in.f), &out->a, &out->b); } // Dispatchers with 3 out params. -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple0& in, Tuple3* out) { (obj->*method)(&out->a, &out->b, &out->c); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const InA& in, Tuple3* out) { (obj->*method)(in, &out->a, &out->b, &out->c); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple1& in, Tuple3* out) { - (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - &out->a, - &out->b, - &out->c); + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a, + &out->b, &out->c); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple2& in, Tuple3* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - base::cef_internal::UnwrapTraits::Unwrap(in.b), - &out->a, - &out->b, - &out->c); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.b), &out->a, + &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple3& in, Tuple3* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), - base::cef_internal::UnwrapTraits::Unwrap(in.c), - &out->a, - &out->b, - &out->c); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.c), &out->a, + &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple4& in, Tuple3* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), - base::cef_internal::UnwrapTraits::Unwrap(in.d), - &out->a, - &out->b, - &out->c); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.d), &out->a, + &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple5& in, Tuple3* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), - base::cef_internal::UnwrapTraits::Unwrap(in.e), - &out->a, - &out->b, - &out->c); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.e), &out->a, + &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple6& in, Tuple3* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), @@ -1095,109 +1291,149 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), base::cef_internal::UnwrapTraits::Unwrap(in.e), - base::cef_internal::UnwrapTraits::Unwrap(in.f), - &out->a, - &out->b, - &out->c); + base::cef_internal::UnwrapTraits::Unwrap(in.f), &out->a, + &out->b, &out->c); } // Dispatchers with 4 out params. -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple0& in, Tuple4* out) { (obj->*method)(&out->a, &out->b, &out->c, &out->d); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const InA& in, Tuple4* out) { - (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in), - &out->a, - &out->b, - &out->c, - &out->d); + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in), &out->a, + &out->b, &out->c, &out->d); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple1& in, Tuple4* out) { - (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - &out->a, - &out->b, - &out->c, - &out->d); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a, + &out->b, &out->c, &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple2& in, Tuple4* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - base::cef_internal::UnwrapTraits::Unwrap(in.b), - &out->a, - &out->b, - &out->c, - &out->d); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.b), &out->a, + &out->b, &out->c, &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple3& in, Tuple4* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), - base::cef_internal::UnwrapTraits::Unwrap(in.c), - &out->a, - &out->b, - &out->c, - &out->d); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.c), &out->a, + &out->b, &out->c, &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple4& in, Tuple4* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), - base::cef_internal::UnwrapTraits::Unwrap(in.d), - &out->a, - &out->b, - &out->c, - &out->d); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.d), &out->a, + &out->b, &out->c, &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple5& in, Tuple4* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), - base::cef_internal::UnwrapTraits::Unwrap(in.e), - &out->a, - &out->b, - &out->c, - &out->d); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.e), &out->a, + &out->b, &out->c, &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple6& in, Tuple4* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), @@ -1205,116 +1441,157 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), base::cef_internal::UnwrapTraits::Unwrap(in.e), - base::cef_internal::UnwrapTraits::Unwrap(in.f), - &out->a, - &out->b, - &out->c, - &out->d); + base::cef_internal::UnwrapTraits::Unwrap(in.f), &out->a, + &out->b, &out->c, &out->d); } // Dispatchers with 5 out params. -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple0& in, Tuple5* out) { (obj->*method)(&out->a, &out->b, &out->c, &out->d, &out->e); } -template -inline void DispatchToMethod(ObjT* obj, Method method, +template +inline void DispatchToMethod(ObjT* obj, + Method method, const InA& in, Tuple5* out) { - (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in), - &out->a, - &out->b, - &out->c, - &out->d, - &out->e); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in), &out->a, + &out->b, &out->c, &out->d, &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple1& in, Tuple5* out) { - (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - &out->a, - &out->b, - &out->c, - &out->d, - &out->e); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a, + &out->b, &out->c, &out->d, &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple2& in, Tuple5* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), - base::cef_internal::UnwrapTraits::Unwrap(in.b), - &out->a, - &out->b, - &out->c, - &out->d, - &out->e); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.b), &out->a, + &out->b, &out->c, &out->d, &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple3& in, Tuple5* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), - base::cef_internal::UnwrapTraits::Unwrap(in.c), - &out->a, - &out->b, - &out->c, - &out->d, - &out->e); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.c), &out->a, + &out->b, &out->c, &out->d, &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple4& in, Tuple5* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), - base::cef_internal::UnwrapTraits::Unwrap(in.d), - &out->a, - &out->b, - &out->c, - &out->d, - &out->e); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.d), &out->a, + &out->b, &out->c, &out->d, &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple5& in, Tuple5* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), base::cef_internal::UnwrapTraits::Unwrap(in.b), base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), - base::cef_internal::UnwrapTraits::Unwrap(in.e), - &out->a, - &out->b, - &out->c, - &out->d, - &out->e); -} - -template -inline void DispatchToMethod(ObjT* obj, Method method, + base::cef_internal::UnwrapTraits::Unwrap(in.e), &out->a, + &out->b, &out->c, &out->d, &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, const Tuple6& in, Tuple5* out) { (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), @@ -1322,16 +1599,12 @@ inline void DispatchToMethod(ObjT* obj, Method method, base::cef_internal::UnwrapTraits::Unwrap(in.c), base::cef_internal::UnwrapTraits::Unwrap(in.d), base::cef_internal::UnwrapTraits::Unwrap(in.e), - base::cef_internal::UnwrapTraits::Unwrap(in.f), - &out->a, - &out->b, - &out->c, - &out->d, - &out->e); + base::cef_internal::UnwrapTraits::Unwrap(in.f), &out->a, + &out->b, &out->c, &out->d, &out->e); } } // namespace base -#endif // !USING_CHROMIUM_INCLUDES +#endif // !USING_CHROMIUM_INCLUDES #endif // CEF_INCLUDE_BASE_CEF_TUPLE_H_ diff --git a/src/include/base/cef_weak_ptr.h b/src/include/base/cef_weak_ptr.h index 217f12cf5..1ba34b9db 100644 --- a/src/include/base/cef_weak_ptr.h +++ b/src/include/base/cef_weak_ptr.h @@ -117,8 +117,10 @@ namespace base { -template class SupportsWeakPtr; -template class WeakPtr; +template +class SupportsWeakPtr; +template +class WeakPtr; namespace cef_internal { // These classes are part of the WeakPtr implementation. @@ -164,9 +166,7 @@ class WeakReferenceOwner { WeakReference GetRef() const; - bool HasRefs() const { - return flag_.get() && !flag_->HasOneRef(); - } + bool HasRefs() const { return flag_.get() && !flag_->HasOneRef(); } void Invalidate(); @@ -198,10 +198,10 @@ class SupportsWeakPtrBase { // conversion will only compile if there is exists a Base which inherits // from SupportsWeakPtr. See base::AsWeakPtr() below for a helper // function that makes calling this easier. - template + template static WeakPtr StaticAsWeakPtr(Derived* t) { - typedef - is_convertible convertible; + typedef is_convertible + convertible; COMPILE_ASSERT(convertible::value, AsWeakPtr_argument_inherits_from_SupportsWeakPtr); return AsWeakPtrImpl(t, *t); @@ -212,8 +212,8 @@ class SupportsWeakPtrBase { // which is an instance of SupportsWeakPtr. We can then safely // static_cast the Base* to a Derived*. template - static WeakPtr AsWeakPtrImpl( - Derived* t, const SupportsWeakPtr&) { + static WeakPtr AsWeakPtrImpl(Derived* t, + const SupportsWeakPtr&) { WeakPtr ptr = t->Base::AsWeakPtr(); return WeakPtr(ptr.ref_, static_cast(ptr.ptr_)); } @@ -221,7 +221,8 @@ class SupportsWeakPtrBase { } // namespace cef_internal -template class WeakPtrFactory; +template +class WeakPtrFactory; // The WeakPtr class holds a weak reference to |T*|. // @@ -239,14 +240,12 @@ template class WeakPtrFactory; template class WeakPtr : public cef_internal::WeakPtrBase { public: - WeakPtr() : ptr_(NULL) { - } + WeakPtr() : ptr_(NULL) {} // Allow conversion from U to T provided U "is a" T. Note that this // is separate from the (implicit) copy constructor. template - WeakPtr(const WeakPtr& other) : WeakPtrBase(other), ptr_(other.ptr_) { - } + WeakPtr(const WeakPtr& other) : WeakPtrBase(other), ptr_(other.ptr_) {} T* get() const { return ref_.is_valid() ? ptr_ : NULL; } @@ -280,18 +279,19 @@ class WeakPtr : public cef_internal::WeakPtrBase { private: // Explicitly declare comparison operators as required by the bool // trick, but keep them private. - template bool operator==(WeakPtr const&) const; - template bool operator!=(WeakPtr const&) const; + template + bool operator==(WeakPtr const&) const; + template + bool operator!=(WeakPtr const&) const; friend class cef_internal::SupportsWeakPtrBase; - template friend class WeakPtr; + template + friend class WeakPtr; friend class SupportsWeakPtr; friend class WeakPtrFactory; WeakPtr(const cef_internal::WeakReference& ref, T* ptr) - : WeakPtrBase(ref), - ptr_(ptr) { - } + : WeakPtrBase(ref), ptr_(ptr) {} // This pointer is only valid when ref_.is_valid() is true. Otherwise, its // value is undefined (as opposed to NULL). @@ -306,12 +306,9 @@ class WeakPtr : public cef_internal::WeakPtrBase { template class WeakPtrFactory { public: - explicit WeakPtrFactory(T* ptr) : ptr_(ptr) { - } + explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {} - ~WeakPtrFactory() { - ptr_ = NULL; - } + ~WeakPtrFactory() { ptr_ = NULL; } WeakPtr GetWeakPtr() { DCHECK(ptr_); diff --git a/src/include/base/internal/cef_atomicops_arm_gcc.h b/src/include/base/internal/cef_atomicops_arm_gcc.h index c228b6af0..2e39ce3c2 100644 --- a/src/include/base/internal/cef_atomicops_arm_gcc.h +++ b/src/include/base/internal/cef_atomicops_arm_gcc.h @@ -85,9 +85,9 @@ inline void MemoryBarrier() { // variant of the target architecture is being used. This tests against // any known ARMv6 or ARMv7 variant, where it is possible to directly // use ldrex/strex instructions to implement fast atomic operations. -#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \ +#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \ defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || \ - defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \ + defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \ defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || \ defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) @@ -103,16 +103,17 @@ inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, // reloop = 0 // if (prev_value != old_value) // reloop = STREX(ptr, new_value) - __asm__ __volatile__(" ldrex %0, [%3]\n" - " mov %1, #0\n" - " cmp %0, %4\n" + __asm__ __volatile__( + " ldrex %0, [%3]\n" + " mov %1, #0\n" + " cmp %0, %4\n" #ifdef __thumb2__ - " it eq\n" + " it eq\n" #endif - " strexeq %1, %5, [%3]\n" - : "=&r"(prev_value), "=&r"(reloop), "+m"(*ptr) - : "r"(ptr), "r"(old_value), "r"(new_value) - : "cc", "memory"); + " strexeq %1, %5, [%3]\n" + : "=&r"(prev_value), "=&r"(reloop), "+m"(*ptr) + : "r"(ptr), "r"(old_value), "r"(new_value) + : "cc", "memory"); } while (reloop != 0); return prev_value; } @@ -143,12 +144,13 @@ inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, // value += increment // reloop = STREX(ptr, value) // - __asm__ __volatile__(" ldrex %0, [%3]\n" - " add %0, %0, %4\n" - " strex %1, %0, [%3]\n" - : "=&r"(value), "=&r"(reloop), "+m"(*ptr) - : "r"(ptr), "r"(increment) - : "cc", "memory"); + __asm__ __volatile__( + " ldrex %0, [%3]\n" + " add %0, %0, %4\n" + " strex %1, %0, [%3]\n" + : "=&r"(value), "=&r"(reloop), "+m"(*ptr) + : "r"(ptr), "r"(increment) + : "cc", "memory"); } while (reloop); return value; } @@ -171,18 +173,19 @@ inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, do { // old_value = LDREX(ptr) // reloop = STREX(ptr, new_value) - __asm__ __volatile__(" ldrex %0, [%3]\n" - " strex %1, %4, [%3]\n" - : "=&r"(old_value), "=&r"(reloop), "+m"(*ptr) - : "r"(ptr), "r"(new_value) - : "cc", "memory"); + __asm__ __volatile__( + " ldrex %0, [%3]\n" + " strex %1, %4, [%3]\n" + : "=&r"(old_value), "=&r"(reloop), "+m"(*ptr) + : "r"(ptr), "r"(new_value) + : "cc", "memory"); } while (reloop != 0); return old_value; } // This tests against any known ARMv5 variant. #elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) || \ - defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5TEJ__) + defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5TEJ__) // The kernel also provides a helper function to perform an atomic // compare-and-swap operation at the hard-wired address 0xffff0fc0. @@ -281,7 +284,7 @@ inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, } #else -# error "Your CPU's ARM architecture is not supported yet" +#error "Your CPU's ARM architecture is not supported yet" #endif // NOTE: Atomicity of the following load and store operations is only @@ -301,7 +304,9 @@ inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { *ptr = value; } -inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { return *ptr; } +inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { + return *ptr; +} inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { Atomic32 value = *ptr; diff --git a/src/include/base/internal/cef_atomicops_atomicword_compat.h b/src/include/base/internal/cef_atomicops_atomicword_compat.h index 985f0f9b9..f905de85f 100644 --- a/src/include/base/internal/cef_atomicops_atomicword_compat.h +++ b/src/include/base/internal/cef_atomicops_atomicword_compat.h @@ -52,26 +52,26 @@ namespace subtle { inline AtomicWord NoBarrier_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { - return NoBarrier_CompareAndSwap( - reinterpret_cast(ptr), old_value, new_value); + return NoBarrier_CompareAndSwap(reinterpret_cast(ptr), + old_value, new_value); } inline AtomicWord NoBarrier_AtomicExchange(volatile AtomicWord* ptr, AtomicWord new_value) { - return NoBarrier_AtomicExchange( - reinterpret_cast(ptr), new_value); + return NoBarrier_AtomicExchange(reinterpret_cast(ptr), + new_value); } inline AtomicWord NoBarrier_AtomicIncrement(volatile AtomicWord* ptr, AtomicWord increment) { - return NoBarrier_AtomicIncrement( - reinterpret_cast(ptr), increment); + return NoBarrier_AtomicIncrement(reinterpret_cast(ptr), + increment); } inline AtomicWord Barrier_AtomicIncrement(volatile AtomicWord* ptr, AtomicWord increment) { - return Barrier_AtomicIncrement( - reinterpret_cast(ptr), increment); + return Barrier_AtomicIncrement(reinterpret_cast(ptr), + increment); } inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr, @@ -88,24 +88,22 @@ inline AtomicWord Release_CompareAndSwap(volatile AtomicWord* ptr, reinterpret_cast(ptr), old_value, new_value); } -inline void NoBarrier_Store(volatile AtomicWord *ptr, AtomicWord value) { - NoBarrier_Store( - reinterpret_cast(ptr), value); +inline void NoBarrier_Store(volatile AtomicWord* ptr, AtomicWord value) { + NoBarrier_Store(reinterpret_cast(ptr), value); } inline void Acquire_Store(volatile AtomicWord* ptr, AtomicWord value) { - return base::subtle::Acquire_Store( - reinterpret_cast(ptr), value); + return base::subtle::Acquire_Store(reinterpret_cast(ptr), + value); } inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) { - return base::subtle::Release_Store( - reinterpret_cast(ptr), value); + return base::subtle::Release_Store(reinterpret_cast(ptr), + value); } -inline AtomicWord NoBarrier_Load(volatile const AtomicWord *ptr) { - return NoBarrier_Load( - reinterpret_cast(ptr)); +inline AtomicWord NoBarrier_Load(volatile const AtomicWord* ptr) { + return NoBarrier_Load(reinterpret_cast(ptr)); } inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) { @@ -118,8 +116,8 @@ inline AtomicWord Release_Load(volatile const AtomicWord* ptr) { reinterpret_cast(ptr)); } -} // namespace base::subtle -} // namespace base +} // namespace base::subtle +} // namespace base #endif // !defined(ARCH_CPU_64_BITS) diff --git a/src/include/base/internal/cef_atomicops_mac.h b/src/include/base/internal/cef_atomicops_mac.h index 9f268dd67..374ae35d6 100644 --- a/src/include/base/internal/cef_atomicops_mac.h +++ b/src/include/base/internal/cef_atomicops_mac.h @@ -170,7 +170,7 @@ inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, Atomic64 prev_value; do { if (OSAtomicCompareAndSwap64Barrier( - old_value, new_value, reinterpret_cast(ptr))) { + old_value, new_value, reinterpret_cast(ptr))) { return old_value; } prev_value = *ptr; @@ -217,7 +217,7 @@ inline Atomic64 Release_Load(volatile const Atomic64* ptr) { #endif // defined(__LP64__) -} // namespace base::subtle -} // namespace base +} // namespace base::subtle +} // namespace base #endif // CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_MAC_H_ diff --git a/src/include/base/internal/cef_atomicops_x86_gcc.h b/src/include/base/internal/cef_atomicops_x86_gcc.h index 0e2139d95..b93df21b0 100644 --- a/src/include/base/internal/cef_atomicops_x86_gcc.h +++ b/src/include/base/internal/cef_atomicops_x86_gcc.h @@ -38,11 +38,10 @@ // Features of this x86. Values may not be correct before main() is run, // but are set conservatively. struct AtomicOps_x86CPUFeatureStruct { - bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence - // after acquire compare-and-swap. + bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence + // after acquire compare-and-swap. }; -extern struct AtomicOps_x86CPUFeatureStruct - AtomicOps_Internalx86CPUFeatures; +extern struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures; #define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") @@ -56,8 +55,8 @@ inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, Atomic32 new_value) { Atomic32 prev; __asm__ __volatile__("lock; cmpxchgl %1,%2" - : "=a" (prev) - : "q" (new_value), "m" (*ptr), "0" (old_value) + : "=a"(prev) + : "q"(new_value), "m"(*ptr), "0"(old_value) : "memory"); return prev; } @@ -65,8 +64,8 @@ inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value) { __asm__ __volatile__("xchgl %1,%0" // The lock prefix is implicit for xchg. - : "=r" (new_value) - : "m" (*ptr), "0" (new_value) + : "=r"(new_value) + : "m"(*ptr), "0"(new_value) : "memory"); return new_value; // Now it's the previous value. } @@ -75,8 +74,9 @@ inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { Atomic32 temp = increment; __asm__ __volatile__("lock; xaddl %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); + : "+r"(temp), "+m"(*ptr) + : + : "memory"); // temp now holds the old value of *ptr return temp + increment; } @@ -85,8 +85,9 @@ inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { Atomic32 temp = increment; __asm__ __volatile__("lock; xaddl %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); + : "+r"(temp), "+m"(*ptr) + : + : "memory"); // temp now holds the old value of *ptr if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { __asm__ __volatile__("lfence" : : : "memory"); @@ -125,7 +126,7 @@ inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { ATOMICOPS_COMPILER_BARRIER(); - *ptr = value; // An x86 store acts as a release barrier. + *ptr = value; // An x86 store acts as a release barrier. // See comments in Atomic64 version of Release_Store(), below. } @@ -134,7 +135,7 @@ inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { } inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { - Atomic32 value = *ptr; // An x86 load acts as a acquire barrier. + Atomic32 value = *ptr; // An x86 load acts as a acquire barrier. // See comments in Atomic64 version of Release_Store(), below. ATOMICOPS_COMPILER_BARRIER(); return value; @@ -154,8 +155,8 @@ inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, Atomic64 new_value) { Atomic64 prev; __asm__ __volatile__("lock; cmpxchgq %1,%2" - : "=a" (prev) - : "q" (new_value), "m" (*ptr), "0" (old_value) + : "=a"(prev) + : "q"(new_value), "m"(*ptr), "0"(old_value) : "memory"); return prev; } @@ -163,8 +164,8 @@ inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value) { __asm__ __volatile__("xchgq %1,%0" // The lock prefix is implicit for xchg. - : "=r" (new_value) - : "m" (*ptr), "0" (new_value) + : "=r"(new_value) + : "m"(*ptr), "0"(new_value) : "memory"); return new_value; // Now it's the previous value. } @@ -173,8 +174,9 @@ inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { Atomic64 temp = increment; __asm__ __volatile__("lock; xaddq %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); + : "+r"(temp), "+m"(*ptr) + : + : "memory"); // temp now contains the previous value of *ptr return temp + increment; } @@ -183,8 +185,9 @@ inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { Atomic64 temp = increment; __asm__ __volatile__("lock; xaddq %0,%1" - : "+r" (temp), "+m" (*ptr) - : : "memory"); + : "+r"(temp), "+m"(*ptr) + : + : "memory"); // temp now contains the previous value of *ptr if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { __asm__ __volatile__("lfence" : : : "memory"); @@ -204,9 +207,9 @@ inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { ATOMICOPS_COMPILER_BARRIER(); - *ptr = value; // An x86 store acts as a release barrier - // for current AMD/Intel chips as of Jan 2008. - // See also Acquire_Load(), below. + *ptr = value; // An x86 store acts as a release barrier + // for current AMD/Intel chips as of Jan 2008. + // See also Acquire_Load(), below. // When new chips come out, check: // IA-32 Intel Architecture Software Developer's Manual, Volume 3: @@ -227,9 +230,9 @@ inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { } inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { - Atomic64 value = *ptr; // An x86 load acts as a acquire barrier, - // for current AMD/Intel chips as of Jan 2008. - // See also Release_Store(), above. + Atomic64 value = *ptr; // An x86 load acts as a acquire barrier, + // for current AMD/Intel chips as of Jan 2008. + // See also Release_Store(), above. ATOMICOPS_COMPILER_BARRIER(); return value; } @@ -257,8 +260,8 @@ inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, #endif // defined(__x86_64__) -} // namespace base::subtle -} // namespace base +} // namespace base::subtle +} // namespace base #undef ATOMICOPS_COMPILER_BARRIER diff --git a/src/include/base/internal/cef_atomicops_x86_msvc.h b/src/include/base/internal/cef_atomicops_x86_msvc.h index 12bb0f468..a262c81f1 100644 --- a/src/include/base/internal/cef_atomicops_x86_msvc.h +++ b/src/include/base/internal/cef_atomicops_x86_msvc.h @@ -55,25 +55,23 @@ inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { LONG result = _InterlockedCompareExchange( - reinterpret_cast(ptr), - static_cast(new_value), + reinterpret_cast(ptr), static_cast(new_value), static_cast(old_value)); return static_cast(result); } inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value) { - LONG result = _InterlockedExchange( - reinterpret_cast(ptr), - static_cast(new_value)); + LONG result = _InterlockedExchange(reinterpret_cast(ptr), + static_cast(new_value)); return static_cast(result); } inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment) { - return _InterlockedExchangeAdd( - reinterpret_cast(ptr), - static_cast(increment)) + increment; + return _InterlockedExchangeAdd(reinterpret_cast(ptr), + static_cast(increment)) + + increment; } inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, @@ -112,11 +110,11 @@ inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier in this implementation + // acts as a barrier in this implementation } inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { - *ptr = value; // works w/o barrier for current Intel chips as of June 2005 + *ptr = value; // works w/o barrier for current Intel chips as of June 2005 // See comments in Atomic64 version of Release_Store() below. } @@ -144,24 +142,24 @@ inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value) { PVOID result = InterlockedCompareExchangePointer( - reinterpret_cast(ptr), - reinterpret_cast(new_value), reinterpret_cast(old_value)); + reinterpret_cast(ptr), + reinterpret_cast(new_value), reinterpret_cast(old_value)); return reinterpret_cast(result); } inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value) { - PVOID result = InterlockedExchangePointer( - reinterpret_cast(ptr), - reinterpret_cast(new_value)); + PVOID result = + InterlockedExchangePointer(reinterpret_cast(ptr), + reinterpret_cast(new_value)); return reinterpret_cast(result); } inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment) { - return InterlockedExchangeAdd64( - reinterpret_cast(ptr), - static_cast(increment)) + increment; + return InterlockedExchangeAdd64(reinterpret_cast(ptr), + static_cast(increment)) + + increment; } inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, @@ -175,11 +173,11 @@ inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { NoBarrier_AtomicExchange(ptr, value); - // acts as a barrier in this implementation + // acts as a barrier in this implementation } inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { - *ptr = value; // works w/o barrier for current Intel chips as of June 2005 + *ptr = value; // works w/o barrier for current Intel chips as of June 2005 // When new chips come out, check: // IA-32 Intel Architecture Software Developer's Manual, Volume 3: @@ -215,7 +213,6 @@ inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, return NoBarrier_CompareAndSwap(ptr, old_value, new_value); } - #endif // defined(_WIN64) } // namespace base::subtle diff --git a/src/include/base/internal/cef_bind_internal.h b/src/include/base/internal/cef_bind_internal.h index a097978be..64eeb3f3b 100644 --- a/src/include/base/internal/cef_bind_internal.h +++ b/src/include/base/internal/cef_bind_internal.h @@ -125,17 +125,13 @@ class RunnableAdapter; // Function: Arity 0. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(); + typedef R(RunType)(); - explicit RunnableAdapter(R(*function)()) - : function_(function) { - } + explicit RunnableAdapter(R (*function)()) : function_(function) {} - R Run() { - return function_(); - } + R Run() { return function_(); } private: R (*function_)(); @@ -143,18 +139,14 @@ class RunnableAdapter { // Method: Arity 0. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(T*); + typedef R(RunType)(T*); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)()) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)()) : method_(method) {} - R Run(T* object) { - return (object->*method_)(); - } + R Run(T* object) { return (object->*method_)(); } private: R (T::*method_)(); @@ -162,18 +154,14 @@ class RunnableAdapter { // Const Method: Arity 0. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(const T*); + typedef R(RunType)(const T*); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)() const) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)() const) : method_(method) {} - R Run(const T* object) { - return (object->*method_)(); - } + R Run(const T* object) { return (object->*method_)(); } private: R (T::*method_)() const; @@ -181,13 +169,11 @@ class RunnableAdapter { // Function: Arity 1. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1); + typedef R(RunType)(A1); - explicit RunnableAdapter(R(*function)(A1)) - : function_(function) { - } + explicit RunnableAdapter(R (*function)(A1)) : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1) { return function_(CallbackForward(a1)); @@ -199,14 +185,12 @@ class RunnableAdapter { // Method: Arity 1. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(T*, A1); + typedef R(RunType)(T*, A1); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1)) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1)) : method_(method) {} R Run(T* object, typename CallbackParamTraits::ForwardType a1) { return (object->*method_)(CallbackForward(a1)); @@ -218,14 +202,12 @@ class RunnableAdapter { // Const Method: Arity 1. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(const T*, A1); + typedef R(RunType)(const T*, A1); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1) const) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1) const) : method_(method) {} R Run(const T* object, typename CallbackParamTraits::ForwardType a1) { return (object->*method_)(CallbackForward(a1)); @@ -237,16 +219,14 @@ class RunnableAdapter { // Function: Arity 2. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2); + typedef R(RunType)(A1, A2); - explicit RunnableAdapter(R(*function)(A1, A2)) - : function_(function) { - } + explicit RunnableAdapter(R (*function)(A1, A2)) : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2) { + typename CallbackParamTraits::ForwardType a2) { return function_(CallbackForward(a1), CallbackForward(a2)); } @@ -256,17 +236,16 @@ class RunnableAdapter { // Method: Arity 2. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(T*, A1, A2); + typedef R(RunType)(T*, A1, A2); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2)) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2)) : method_(method) {} - R Run(T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2) { + R Run(T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2)); } @@ -276,17 +255,16 @@ class RunnableAdapter { // Const Method: Arity 2. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(const T*, A1, A2); + typedef R(RunType)(const T*, A1, A2); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2) const) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2) const) : method_(method) {} - R Run(const T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2) { + R Run(const T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2)); } @@ -296,19 +274,17 @@ class RunnableAdapter { // Function: Arity 3. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3); + typedef R(RunType)(A1, A2, A3); - explicit RunnableAdapter(R(*function)(A1, A2, A3)) - : function_(function) { - } + explicit RunnableAdapter(R (*function)(A1, A2, A3)) : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { return function_(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3)); + CallbackForward(a3)); } private: @@ -317,20 +293,19 @@ class RunnableAdapter { // Method: Arity 3. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(T*, A1, A2, A3); + typedef R(RunType)(T*, A1, A2, A3); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3)) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3)) : method_(method) {} - R Run(T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3) { + R Run(T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3)); + CallbackForward(a3)); } private: @@ -339,20 +314,20 @@ class RunnableAdapter { // Const Method: Arity 3. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(const T*, A1, A2, A3); + typedef R(RunType)(const T*, A1, A2, A3); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3) const) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3) const) + : method_(method) {} - R Run(const T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3) { + R Run(const T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3)); + CallbackForward(a3)); } private: @@ -361,20 +336,19 @@ class RunnableAdapter { // Function: Arity 4. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4); + typedef R(RunType)(A1, A2, A3, A4); - explicit RunnableAdapter(R(*function)(A1, A2, A3, A4)) - : function_(function) { - } + explicit RunnableAdapter(R (*function)(A1, A2, A3, A4)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { return function_(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4)); + CallbackForward(a3), CallbackForward(a4)); } private: @@ -382,23 +356,26 @@ class RunnableAdapter { }; // Method: Arity 4. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(T*, A1, A2, A3, A4); + typedef R(RunType)(T*, A1, A2, A3, A4); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4)) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4)) : method_(method) {} - R Run(T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4) { + R Run(T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4)); + CallbackForward(a3), CallbackForward(a4)); } private: @@ -406,23 +383,27 @@ class RunnableAdapter { }; // Const Method: Arity 4. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(const T*, A1, A2, A3, A4); + typedef R(RunType)(const T*, A1, A2, A3, A4); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4) const) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4) const) + : method_(method) {} - R Run(const T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4) { + R Run(const T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4)); + CallbackForward(a3), CallbackForward(a4)); } private: @@ -430,23 +411,27 @@ class RunnableAdapter { }; // Function: Arity 5. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5); + typedef R(RunType)(A1, A2, A3, A4, A5); - explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5)) - : function_(function) { - } + explicit RunnableAdapter(R (*function)(A1, A2, A3, A4, A5)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { return function_(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5)); } private: @@ -454,24 +439,30 @@ class RunnableAdapter { }; // Method: Arity 5. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(T*, A1, A2, A3, A4, A5); + typedef R(RunType)(T*, A1, A2, A3, A4, A5); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5)) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4, A5)) + : method_(method) {} - R Run(T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5) { + R Run(T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5)); } private: @@ -479,24 +470,30 @@ class RunnableAdapter { }; // Const Method: Arity 5. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(const T*, A1, A2, A3, A4, A5); + typedef R(RunType)(const T*, A1, A2, A3, A4, A5); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5) const) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4, A5) const) + : method_(method) {} - R Run(const T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5) { + R Run(const T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5)); } private: @@ -504,25 +501,29 @@ class RunnableAdapter { }; // Function: Arity 6. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5, A6); + typedef R(RunType)(A1, A2, A3, A4, A5, A6); - explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5, A6)) - : function_(function) { - } + explicit RunnableAdapter(R (*function)(A1, A2, A3, A4, A5, A6)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { return function_(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6)); } private: @@ -530,26 +531,32 @@ class RunnableAdapter { }; // Method: Arity 6. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(T*, A1, A2, A3, A4, A5, A6); + typedef R(RunType)(T*, A1, A2, A3, A4, A5, A6); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6)) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4, A5, A6)) + : method_(method) {} - R Run(T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6) { + R Run(T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6)); } private: @@ -557,26 +564,32 @@ class RunnableAdapter { }; // Const Method: Arity 6. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(const T*, A1, A2, A3, A4, A5, A6); + typedef R(RunType)(const T*, A1, A2, A3, A4, A5, A6); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6) const) - : method_(method) { - } + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4, A5, A6) const) + : method_(method) {} - R Run(const T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6) { + R Run(const T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6)); } private: @@ -584,26 +597,32 @@ class RunnableAdapter { }; // Function: Arity 7. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5, A6, A7); + typedef R(RunType)(A1, A2, A3, A4, A5, A6, A7); - explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5, A6, A7)) - : function_(function) { - } + explicit RunnableAdapter(R (*function)(A1, A2, A3, A4, A5, A6, A7)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6, - typename CallbackParamTraits::ForwardType a7) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { return function_(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6), CallbackForward(a7)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); } private: @@ -611,27 +630,35 @@ class RunnableAdapter { }; // Method: Arity 7. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(T*, A1, A2, A3, A4, A5, A6, A7); + typedef R(RunType)(T*, A1, A2, A3, A4, A5, A6, A7); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6, A7)) - : method_(method) { - } - - R Run(T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6, - typename CallbackParamTraits::ForwardType a7) { + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4, A5, A6, A7)) + : method_(method) {} + + R Run(T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6), CallbackForward(a7)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); } private: @@ -639,34 +666,41 @@ class RunnableAdapter { }; // Const Method: Arity 7. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(const T*, A1, A2, A3, A4, A5, A6, A7); + typedef R(RunType)(const T*, A1, A2, A3, A4, A5, A6, A7); typedef true_type IsMethod; - explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6, A7) const) - : method_(method) { - } - - R Run(const T* object, typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6, - typename CallbackParamTraits::ForwardType a7) { + explicit RunnableAdapter(R (T::*method)(A1, A2, A3, A4, A5, A6, A7) const) + : method_(method) {} + + R Run(const T* object, + typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { return (object->*method_)(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6), CallbackForward(a7)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); } private: R (T::*method_)(A1, A2, A3, A4, A5, A6, A7) const; }; - // FunctionTraits<> // // Breaks a function signature apart into typedefs for easier introspection. @@ -708,8 +742,12 @@ struct FunctionTraits { typedef A4 A4Type; }; -template +template struct FunctionTraits { typedef R ReturnType; typedef A1 A1Type; @@ -719,8 +757,13 @@ struct FunctionTraits { typedef A5 A5Type; }; -template +template struct FunctionTraits { typedef R ReturnType; typedef A1 A1Type; @@ -731,8 +774,14 @@ struct FunctionTraits { typedef A6 A6Type; }; -template +template struct FunctionTraits { typedef R ReturnType; typedef A1 A1Type; @@ -744,7 +793,6 @@ struct FunctionTraits { typedef A7 A7Type; }; - // ForceVoidReturn<> // // Set of templates that support forcing the function return type to void. @@ -776,25 +824,39 @@ struct ForceVoidReturn { typedef void(RunType)(A1, A2, A3, A4); }; -template +template struct ForceVoidReturn { typedef void(RunType)(A1, A2, A3, A4, A5); }; -template +template struct ForceVoidReturn { typedef void(RunType)(A1, A2, A3, A4, A5, A6); }; -template +template struct ForceVoidReturn { typedef void(RunType)(A1, A2, A3, A4, A5, A6, A7); }; - // FunctorTraits<> // // See description at top of file. @@ -805,19 +867,18 @@ struct FunctorTraits { }; template -struct FunctorTraits > { +struct FunctorTraits> { typedef typename FunctorTraits::RunnableType RunnableType; - typedef typename ForceVoidReturn< - typename RunnableType::RunType>::RunType RunType; + typedef + typename ForceVoidReturn::RunType RunType; }; template -struct FunctorTraits > { +struct FunctorTraits> { typedef Callback RunnableType; typedef typename Callback::RunType RunType; }; - // MakeRunnable<> // // Converts a passed in functor to a RunnableType using type inference. @@ -828,19 +889,18 @@ typename FunctorTraits::RunnableType MakeRunnable(const T& t) { } template -typename FunctorTraits::RunnableType -MakeRunnable(const IgnoreResultHelper& t) { +typename FunctorTraits::RunnableType MakeRunnable( + const IgnoreResultHelper& t) { return MakeRunnable(t.functor_); } template -const typename FunctorTraits >::RunnableType& -MakeRunnable(const Callback& t) { +const typename FunctorTraits>::RunnableType& MakeRunnable( + const Callback& t) { DCHECK(!t.is_null()); return t; } - // InvokeHelper<> // // There are 3 logical InvokeHelper<> specializations: normal, void-return, @@ -858,45 +918,38 @@ MakeRunnable(const Callback& t) { // // WeakCalls similarly need special syntax that is applied to the first // argument to check if they should no-op themselves. -template struct InvokeHelper; template -struct InvokeHelper { - static ReturnType MakeItSo(Runnable runnable) { - return runnable.Run(); - } +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable) { return runnable.Run(); } }; template -struct InvokeHelper { - static void MakeItSo(Runnable runnable) { - runnable.Run(); - } +struct InvokeHelper { + static void MakeItSo(Runnable runnable) { runnable.Run(); } }; -template -struct InvokeHelper { +template +struct InvokeHelper { static ReturnType MakeItSo(Runnable runnable, A1 a1) { return runnable.Run(CallbackForward(a1)); } }; -template -struct InvokeHelper { +template +struct InvokeHelper { static void MakeItSo(Runnable runnable, A1 a1) { runnable.Run(CallbackForward(a1)); } }; template -struct InvokeHelper { +struct InvokeHelper { static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr) { if (!weak_ptr.get()) { return; @@ -905,25 +958,22 @@ struct InvokeHelper -struct InvokeHelper { +template +struct InvokeHelper { static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2) { return runnable.Run(CallbackForward(a1), CallbackForward(a2)); } }; -template -struct InvokeHelper { +template +struct InvokeHelper { static void MakeItSo(Runnable runnable, A1 a1, A2 a2) { runnable.Run(CallbackForward(a1), CallbackForward(a2)); } }; template -struct InvokeHelper { +struct InvokeHelper { static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2) { if (!weak_ptr.get()) { return; @@ -932,27 +982,27 @@ struct InvokeHelper -struct InvokeHelper { +template +struct InvokeHelper { static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3) { return runnable.Run(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3)); + CallbackForward(a3)); } }; -template -struct InvokeHelper { +template +struct InvokeHelper { static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3) { runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3)); } }; template -struct InvokeHelper { +struct InvokeHelper { static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3) { if (!weak_ptr.get()) { return; @@ -961,147 +1011,223 @@ struct InvokeHelper -struct InvokeHelper { +template +struct InvokeHelper { static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4) { return runnable.Run(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4)); + CallbackForward(a3), CallbackForward(a4)); } }; -template -struct InvokeHelper { +template +struct InvokeHelper { static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4) { runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4)); + CallbackForward(a4)); } }; -template -struct InvokeHelper { - static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, - A4 a4) { +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, + BoundWeakPtr weak_ptr, + A2 a2, + A3 a3, + A4 a4) { if (!weak_ptr.get()) { return; } runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4)); - } -}; - -template -struct InvokeHelper { - static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, - A5 a5) { + CallbackForward(a4)); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, + A1 a1, + A2 a2, + A3 a3, + A4 a4, + A5 a5) { return runnable.Run(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5)); } }; -template -struct InvokeHelper { +template +struct InvokeHelper { static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4), CallbackForward(a5)); - } -}; - -template -struct InvokeHelper { - static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, - A4 a4, A5 a5) { + CallbackForward(a4), CallbackForward(a5)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, + BoundWeakPtr weak_ptr, + A2 a2, + A3 a3, + A4 a4, + A5 a5) { if (!weak_ptr.get()) { return; } runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4), CallbackForward(a5)); + CallbackForward(a4), CallbackForward(a5)); } }; -template -struct InvokeHelper { - static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, - A5 a5, A6 a6) { +template +struct InvokeHelper { + static ReturnType + MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { return runnable.Run(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6)); + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6)); } }; -template -struct InvokeHelper { - static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, - A6 a6) { +template +struct InvokeHelper { + static void + MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4), CallbackForward(a5), CallbackForward(a6)); - } -}; - -template -struct InvokeHelper { - static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, - A4 a4, A5 a5, A6 a6) { + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, + BoundWeakPtr weak_ptr, + A2 a2, + A3 a3, + A4 a4, + A5 a5, + A6 a6) { if (!weak_ptr.get()) { return; } runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4), CallbackForward(a5), CallbackForward(a6)); - } -}; - -template -struct InvokeHelper { - static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, - A5 a5, A6 a6, A7 a7) { + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6)); + } +}; + +template +struct InvokeHelper { + static ReturnType + MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { return runnable.Run(CallbackForward(a1), CallbackForward(a2), - CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), - CallbackForward(a6), CallbackForward(a7)); - } -}; - -template -struct InvokeHelper { - static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, - A6 a6, A7 a7) { + CallbackForward(a3), CallbackForward(a4), + CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); + } +}; + +template +struct InvokeHelper { + static void + MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4), CallbackForward(a5), CallbackForward(a6), - CallbackForward(a7)); - } -}; - -template -struct InvokeHelper { - static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, - A4 a4, A5 a5, A6 a6, A7 a7) { + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, + BoundWeakPtr weak_ptr, + A2 a2, + A3 a3, + A4 a4, + A5 a5, + A6 a6, + A7 a7) { if (!weak_ptr.get()) { return; } runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), - CallbackForward(a4), CallbackForward(a5), CallbackForward(a6), - CallbackForward(a7)); + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); } }; @@ -1139,22 +1265,21 @@ struct Invoker<0, StorageType, R()> { // InvokeHelper<>::MakeItSo() call below. return InvokeHelper - ::MakeItSo(storage->runnable_); + typename StorageType::RunnableType, + void()>::MakeItSo(storage->runnable_); } }; // Arity 1 -> 1. -template +template struct Invoker<0, StorageType, R(X1)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X1); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x1) { + typename CallbackParamTraits::ForwardType x1) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1162,14 +1287,15 @@ struct Invoker<0, StorageType, R(X1)> { // InvokeHelper<>::MakeItSo() call below. return InvokeHelper::ForwardType x1)> - ::MakeItSo(storage->runnable_, CallbackForward(x1)); + typename StorageType::RunnableType, + void(typename CallbackParamTraits::ForwardType + x1)>::MakeItSo(storage->runnable_, + CallbackForward(x1)); } }; // Arity 1 -> 0. -template +template struct Invoker<1, StorageType, R(X1)> { typedef R(RunType)(BindStateBase*); @@ -1186,24 +1312,24 @@ struct Invoker<1, StorageType, R(X1)> { typename Bound1UnwrapTraits::ForwardType x1 = Bound1UnwrapTraits::Unwrap(storage->p1_); return InvokeHelper - ::MakeItSo(storage->runnable_, CallbackForward(x1)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType)>:: + MakeItSo(storage->runnable_, CallbackForward(x1)); } }; // Arity 2 -> 2. -template +template struct Invoker<0, StorageType, R(X1, X2)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X1, X2); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x1, - typename CallbackParamTraits::ForwardType x2) { + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1211,24 +1337,25 @@ struct Invoker<0, StorageType, R(X1, X2)> { // InvokeHelper<>::MakeItSo() call below. return InvokeHelper::ForwardType x1, - typename CallbackParamTraits::ForwardType x2)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2)); + typename StorageType::RunnableType, + void(typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType + x2)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2)); } }; // Arity 2 -> 1. -template +template struct Invoker<1, StorageType, R(X1, X2)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X2); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x2) { + typename CallbackParamTraits::ForwardType x2) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1239,16 +1366,17 @@ struct Invoker<1, StorageType, R(X1, X2)> { typename Bound1UnwrapTraits::ForwardType x1 = Bound1UnwrapTraits::Unwrap(storage->p1_); return InvokeHelper::ForwardType x2)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType + x2)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2)); } }; // Arity 2 -> 0. -template +template struct Invoker<2, StorageType, R(X1, X2)> { typedef R(RunType)(BindStateBase*); @@ -1268,29 +1396,31 @@ struct Invoker<2, StorageType, R(X1, X2)> { typename Bound2UnwrapTraits::ForwardType x2 = Bound2UnwrapTraits::Unwrap(storage->p2_); return InvokeHelper - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType)>:: + MakeItSo(storage->runnable_, CallbackForward(x1), CallbackForward(x2)); } }; // Arity 3 -> 3. -template +template struct Invoker<0, StorageType, R(X1, X2, X3)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X1, X2, X3); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3) { + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1298,28 +1428,33 @@ struct Invoker<0, StorageType, R(X1, X2, X3)> { // InvokeHelper<>::MakeItSo() call below. return InvokeHelper::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3)); + typename StorageType::RunnableType, + void(typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType + x3)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2), + CallbackForward(x3)); } }; // Arity 3 -> 2. -template +template struct Invoker<1, StorageType, R(X1, X2, X3)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X2, X3); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3) { + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1330,26 +1465,31 @@ struct Invoker<1, StorageType, R(X1, X2, X3)> { typename Bound1UnwrapTraits::ForwardType x1 = Bound1UnwrapTraits::Unwrap(storage->p1_); return InvokeHelper::ForwardType x2, - typename CallbackParamTraits::ForwardType x3)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType + x3)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2), + CallbackForward(x3)); } }; // Arity 3 -> 1. -template +template struct Invoker<2, StorageType, R(X1, X2, X3)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X3); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x3) { + typename CallbackParamTraits::ForwardType x3) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1363,18 +1503,23 @@ struct Invoker<2, StorageType, R(X1, X2, X3)> { typename Bound2UnwrapTraits::ForwardType x2 = Bound2UnwrapTraits::Unwrap(storage->p2_); return InvokeHelper::ForwardType x3)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType + x3)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2), + CallbackForward(x3)); } }; // Arity 3 -> 0. -template +template struct Invoker<3, StorageType, R(X1, X2, X3)> { typedef R(RunType)(BindStateBase*); @@ -1397,32 +1542,36 @@ struct Invoker<3, StorageType, R(X1, X2, X3)> { typename Bound3UnwrapTraits::ForwardType x3 = Bound3UnwrapTraits::Unwrap(storage->p3_); return InvokeHelper - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType)>:: + MakeItSo(storage->runnable_, CallbackForward(x1), CallbackForward(x2), + CallbackForward(x3)); } }; // Arity 4 -> 4. -template +template struct Invoker<0, StorageType, R(X1, X2, X3, X4)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X1, X2, X3, X4); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4) { + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1430,32 +1579,38 @@ struct Invoker<0, StorageType, R(X1, X2, X3, X4)> { // InvokeHelper<>::MakeItSo() call below. return InvokeHelper::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4)); + typename StorageType::RunnableType, + void(typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType + x4)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2), + CallbackForward(x3), + CallbackForward(x4)); } }; // Arity 4 -> 3. -template +template struct Invoker<1, StorageType, R(X1, X2, X3, X4)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X2, X3, X4); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4) { + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1466,30 +1621,36 @@ struct Invoker<1, StorageType, R(X1, X2, X3, X4)> { typename Bound1UnwrapTraits::ForwardType x1 = Bound1UnwrapTraits::Unwrap(storage->p1_); return InvokeHelper::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType + x4)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2), + CallbackForward(x3), + CallbackForward(x4)); } }; // Arity 4 -> 2. -template +template struct Invoker<2, StorageType, R(X1, X2, X3, X4)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X3, X4); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4) { + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1503,28 +1664,34 @@ struct Invoker<2, StorageType, R(X1, X2, X3, X4)> { typename Bound2UnwrapTraits::ForwardType x2 = Bound2UnwrapTraits::Unwrap(storage->p2_); return InvokeHelper::ForwardType x3, - typename CallbackParamTraits::ForwardType x4)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType + x4)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2), + CallbackForward(x3), + CallbackForward(x4)); } }; // Arity 4 -> 1. -template +template struct Invoker<3, StorageType, R(X1, X2, X3, X4)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X4); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x4) { + typename CallbackParamTraits::ForwardType x4) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1541,20 +1708,26 @@ struct Invoker<3, StorageType, R(X1, X2, X3, X4)> { typename Bound3UnwrapTraits::ForwardType x3 = Bound3UnwrapTraits::Unwrap(storage->p3_); return InvokeHelper::ForwardType x4)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType + x4)>::MakeItSo(storage->runnable_, + CallbackForward(x1), + CallbackForward(x2), + CallbackForward(x3), + CallbackForward(x4)); } }; // Arity 4 -> 0. -template +template struct Invoker<4, StorageType, R(X1, X2, X3, X4)> { typedef R(RunType)(BindStateBase*); @@ -1580,72 +1753,81 @@ struct Invoker<4, StorageType, R(X1, X2, X3, X4)> { typename Bound4UnwrapTraits::ForwardType x4 = Bound4UnwrapTraits::Unwrap(storage->p4_); return InvokeHelper - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType)>:: + MakeItSo(storage->runnable_, CallbackForward(x1), CallbackForward(x2), + CallbackForward(x3), CallbackForward(x4)); } }; // Arity 5 -> 5. -template +template struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X1, X2, X3, X4, X5); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5) { + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, // you really want to warp ahead and step through the // InvokeHelper<>::MakeItSo() call below. - return InvokeHelper::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType + x5)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); } }; // Arity 5 -> 4. -template +template struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X2, X3, X4, X5); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5) { + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1655,34 +1837,39 @@ struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5)> { typename Bound1UnwrapTraits::ForwardType x1 = Bound1UnwrapTraits::Unwrap(storage->p1_); - return InvokeHelper::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType + x5)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); } }; // Arity 5 -> 3. -template +template struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X3, X4, X5); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5) { + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1695,32 +1882,37 @@ struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5)> { Bound1UnwrapTraits::Unwrap(storage->p1_); typename Bound2UnwrapTraits::ForwardType x2 = Bound2UnwrapTraits::Unwrap(storage->p2_); - return InvokeHelper::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType + x5)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); } }; // Arity 5 -> 2. -template +template struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X4, X5); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5) { + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1736,30 +1928,35 @@ struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5)> { Bound2UnwrapTraits::Unwrap(storage->p2_); typename Bound3UnwrapTraits::ForwardType x3 = Bound3UnwrapTraits::Unwrap(storage->p3_); - return InvokeHelper::ForwardType x4, - typename CallbackParamTraits::ForwardType x5)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType + x5)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); } }; // Arity 5 -> 1. -template +template struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X5); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x5) { + typename CallbackParamTraits::ForwardType x5) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1778,22 +1975,27 @@ struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5)> { Bound3UnwrapTraits::Unwrap(storage->p3_); typename Bound4UnwrapTraits::ForwardType x4 = Bound4UnwrapTraits::Unwrap(storage->p4_); - return InvokeHelper::ForwardType x5)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType + x5)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); } }; // Arity 5 -> 0. -template +template struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5)> { typedef R(RunType)(BindStateBase*); @@ -1822,79 +2024,90 @@ struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5)> { typename Bound5UnwrapTraits::ForwardType x5 = Bound5UnwrapTraits::Unwrap(storage->p5_); return InvokeHelper - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename Bound5UnwrapTraits::ForwardType)>:: + MakeItSo(storage->runnable_, CallbackForward(x1), CallbackForward(x2), + CallbackForward(x3), CallbackForward(x4), CallbackForward(x5)); } }; // Arity 6 -> 6. -template +template struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5, X6)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X1, X2, X3, X4, X5, X6); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6) { + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, // you really want to warp ahead and step through the // InvokeHelper<>::MakeItSo() call below. - return InvokeHelper::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType + x6)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); } }; // Arity 6 -> 5. -template +template struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X2, X3, X4, X5, X6); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6) { + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1904,38 +2117,44 @@ struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6)> { typename Bound1UnwrapTraits::ForwardType x1 = Bound1UnwrapTraits::Unwrap(storage->p1_); - return InvokeHelper::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType + x6)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); } }; // Arity 6 -> 4. -template +template struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X3, X4, X5, X6); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6) { + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1948,36 +2167,42 @@ struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6)> { Bound1UnwrapTraits::Unwrap(storage->p1_); typename Bound2UnwrapTraits::ForwardType x2 = Bound2UnwrapTraits::Unwrap(storage->p2_); - return InvokeHelper::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType + x6)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); } }; // Arity 6 -> 3. -template +template struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X4, X5, X6); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6) { + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -1993,34 +2218,40 @@ struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6)> { Bound2UnwrapTraits::Unwrap(storage->p2_); typename Bound3UnwrapTraits::ForwardType x3 = Bound3UnwrapTraits::Unwrap(storage->p3_); - return InvokeHelper::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType + x6)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); } }; // Arity 6 -> 2. -template +template struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X5, X6); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6) { + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2039,32 +2270,38 @@ struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6)> { Bound3UnwrapTraits::Unwrap(storage->p3_); typename Bound4UnwrapTraits::ForwardType x4 = Bound4UnwrapTraits::Unwrap(storage->p4_); - return InvokeHelper::ForwardType x5, - typename CallbackParamTraits::ForwardType x6)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType + x6)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); } }; // Arity 6 -> 1. -template +template struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X6); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x6) { + typename CallbackParamTraits::ForwardType x6) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2086,24 +2323,30 @@ struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6)> { Bound4UnwrapTraits::Unwrap(storage->p4_); typename Bound5UnwrapTraits::ForwardType x5 = Bound5UnwrapTraits::Unwrap(storage->p5_); - return InvokeHelper::ForwardType x6)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename Bound5UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType + x6)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); } }; // Arity 6 -> 0. -template +template struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6)> { typedef R(RunType)(BindStateBase*); @@ -2135,86 +2378,99 @@ struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6)> { typename Bound6UnwrapTraits::ForwardType x6 = Bound6UnwrapTraits::Unwrap(storage->p6_); return InvokeHelper - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename Bound5UnwrapTraits::ForwardType, + typename Bound6UnwrapTraits::ForwardType)>:: + MakeItSo(storage->runnable_, CallbackForward(x1), CallbackForward(x2), + CallbackForward(x3), CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); } }; // Arity 7 -> 7. -template +template struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X1, X2, X3, X4, X5, X6, X7); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7) { + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, // you really want to warp ahead and step through the // InvokeHelper<>::MakeItSo() call below. - return InvokeHelper::ForwardType x1, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType + x7)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; // Arity 7 -> 6. -template +template struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X2, X3, X4, X5, X6, X7); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7) { + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2224,41 +2480,48 @@ struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typename Bound1UnwrapTraits::ForwardType x1 = Bound1UnwrapTraits::Unwrap(storage->p1_); - return InvokeHelper::ForwardType x2, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType + x7)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; // Arity 7 -> 5. -template +template struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X3, X4, X5, X6, X7); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7) { + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2271,39 +2534,46 @@ struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { Bound1UnwrapTraits::Unwrap(storage->p1_); typename Bound2UnwrapTraits::ForwardType x2 = Bound2UnwrapTraits::Unwrap(storage->p2_); - return InvokeHelper::ForwardType x3, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType + x7)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; // Arity 7 -> 4. -template +template struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X4, X5, X6, X7); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7) { + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2319,37 +2589,44 @@ struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { Bound2UnwrapTraits::Unwrap(storage->p2_); typename Bound3UnwrapTraits::ForwardType x3 = Bound3UnwrapTraits::Unwrap(storage->p3_); - return InvokeHelper::ForwardType x4, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType + x7)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; // Arity 7 -> 3. -template +template struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X5, X6, X7); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7) { + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2368,35 +2645,42 @@ struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { Bound3UnwrapTraits::Unwrap(storage->p3_); typename Bound4UnwrapTraits::ForwardType x4 = Bound4UnwrapTraits::Unwrap(storage->p4_); - return InvokeHelper::ForwardType x5, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType + x7)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; // Arity 7 -> 2. -template +template struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X6, X7); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x6, - typename CallbackParamTraits::ForwardType x7) { + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2418,33 +2702,40 @@ struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { Bound4UnwrapTraits::Unwrap(storage->p4_); typename Bound5UnwrapTraits::ForwardType x5 = Bound5UnwrapTraits::Unwrap(storage->p5_); - return InvokeHelper::ForwardType x6, - typename CallbackParamTraits::ForwardType x7)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename Bound5UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType + x7)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; // Arity 7 -> 1. -template +template struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*, - typename CallbackParamTraits::ForwardType); + typename CallbackParamTraits::ForwardType); typedef R(UnboundRunType)(X7); static R Run(BindStateBase* base, - typename CallbackParamTraits::ForwardType x7) { + typename CallbackParamTraits::ForwardType x7) { StorageType* storage = static_cast(base); // Local references to make debugger stepping easier. If in a debugger, @@ -2469,25 +2760,32 @@ struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { Bound5UnwrapTraits::Unwrap(storage->p5_); typename Bound6UnwrapTraits::ForwardType x6 = Bound6UnwrapTraits::Unwrap(storage->p6_); - return InvokeHelper::ForwardType x7)> - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + return InvokeHelper< + StorageType::IsWeakCall::value, R, typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename Bound5UnwrapTraits::ForwardType, + typename Bound6UnwrapTraits::ForwardType, + typename CallbackParamTraits::ForwardType + x7)>::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; // Arity 7 -> 0. -template +template struct Invoker<7, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typedef R(RunType)(BindStateBase*); @@ -2522,22 +2820,20 @@ struct Invoker<7, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { typename Bound7UnwrapTraits::ForwardType x7 = Bound7UnwrapTraits::Unwrap(storage->p7_); return InvokeHelper - ::MakeItSo(storage->runnable_, CallbackForward(x1), - CallbackForward(x2), CallbackForward(x3), - CallbackForward(x4), CallbackForward(x5), - CallbackForward(x6), CallbackForward(x7)); + typename StorageType::RunnableType, + void(typename Bound1UnwrapTraits::ForwardType, + typename Bound2UnwrapTraits::ForwardType, + typename Bound3UnwrapTraits::ForwardType, + typename Bound4UnwrapTraits::ForwardType, + typename Bound5UnwrapTraits::ForwardType, + typename Bound6UnwrapTraits::ForwardType, + typename Bound7UnwrapTraits::ForwardType)>:: + MakeItSo(storage->runnable_, CallbackForward(x1), CallbackForward(x2), + CallbackForward(x3), CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); } }; - // BindState<> // // This stores all the state passed into Bind() and is also where most @@ -2560,11 +2856,9 @@ struct BindState : public BindStateBase { typedef Invoker<0, BindState, RunType> InvokerType; typedef typename InvokerType::UnboundRunType UnboundRunType; explicit BindState(const Runnable& runnable) - : BindStateBase(&Destroy), - runnable_(runnable) { - } + : BindStateBase(&Destroy), runnable_(runnable) {} - ~BindState() { } + ~BindState() {} static void Destroy(BindStateBase* self) { delete static_cast(self); @@ -2584,14 +2878,13 @@ struct BindState : public BindStateBase { typedef UnwrapTraits Bound1UnwrapTraits; BindState(const Runnable& runnable, const P1& p1) - : BindStateBase(&Destroy), - runnable_(runnable), - p1_(p1) { + : BindStateBase(&Destroy), runnable_(runnable), p1_(p1) { MaybeRefcount::value, P1>::AddRef(p1_); } - ~BindState() { MaybeRefcount::value, - P1>::Release(p1_); } + ~BindState() { + MaybeRefcount::value, P1>::Release(p1_); + } static void Destroy(BindStateBase* self) { delete static_cast(self); @@ -2613,15 +2906,13 @@ struct BindState : public BindStateBase { typedef UnwrapTraits Bound2UnwrapTraits; BindState(const Runnable& runnable, const P1& p1, const P2& p2) - : BindStateBase(&Destroy), - runnable_(runnable), - p1_(p1), - p2_(p2) { + : BindStateBase(&Destroy), runnable_(runnable), p1_(p1), p2_(p2) { MaybeRefcount::value, P1>::AddRef(p1_); } - ~BindState() { MaybeRefcount::value, - P1>::Release(p1_); } + ~BindState() { + MaybeRefcount::value, P1>::Release(p1_); + } static void Destroy(BindStateBase* self) { delete static_cast(self); @@ -2632,10 +2923,12 @@ struct BindState : public BindStateBase { P2 p2_; }; -template -struct BindState - : public BindStateBase { +template +struct BindState : public BindStateBase { typedef Runnable RunnableType; typedef IsWeakMethod::value, P1> IsWeakCall; typedef Invoker<3, BindState, RunType> InvokerType; @@ -2655,8 +2948,9 @@ struct BindState MaybeRefcount::value, P1>::AddRef(p1_); } - ~BindState() { MaybeRefcount::value, - P1>::Release(p1_); } + ~BindState() { + MaybeRefcount::value, P1>::Release(p1_); + } static void Destroy(BindStateBase* self) { delete static_cast(self); @@ -2668,8 +2962,12 @@ struct BindState P3 p3_; }; -template +template struct BindState : public BindStateBase { typedef Runnable RunnableType; @@ -2683,8 +2981,11 @@ struct BindState typedef UnwrapTraits Bound3UnwrapTraits; typedef UnwrapTraits Bound4UnwrapTraits; - BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, - const P4& p4) + BindState(const Runnable& runnable, + const P1& p1, + const P2& p2, + const P3& p3, + const P4& p4) : BindStateBase(&Destroy), runnable_(runnable), p1_(p1), @@ -2694,8 +2995,9 @@ struct BindState MaybeRefcount::value, P1>::AddRef(p1_); } - ~BindState() { MaybeRefcount::value, - P1>::Release(p1_); } + ~BindState() { + MaybeRefcount::value, P1>::Release(p1_); + } static void Destroy(BindStateBase* self) { delete static_cast(self); @@ -2708,8 +3010,13 @@ struct BindState P4 p4_; }; -template +template struct BindState : public BindStateBase { typedef Runnable RunnableType; @@ -2724,8 +3031,12 @@ struct BindState typedef UnwrapTraits Bound4UnwrapTraits; typedef UnwrapTraits Bound5UnwrapTraits; - BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, - const P4& p4, const P5& p5) + BindState(const Runnable& runnable, + const P1& p1, + const P2& p2, + const P3& p3, + const P4& p4, + const P5& p5) : BindStateBase(&Destroy), runnable_(runnable), p1_(p1), @@ -2736,8 +3047,9 @@ struct BindState MaybeRefcount::value, P1>::AddRef(p1_); } - ~BindState() { MaybeRefcount::value, - P1>::Release(p1_); } + ~BindState() { + MaybeRefcount::value, P1>::Release(p1_); + } static void Destroy(BindStateBase* self) { delete static_cast(self); @@ -2751,8 +3063,14 @@ struct BindState P5 p5_; }; -template +template struct BindState : public BindStateBase { typedef Runnable RunnableType; @@ -2768,8 +3086,13 @@ struct BindState typedef UnwrapTraits Bound5UnwrapTraits; typedef UnwrapTraits Bound6UnwrapTraits; - BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, - const P4& p4, const P5& p5, const P6& p6) + BindState(const Runnable& runnable, + const P1& p1, + const P2& p2, + const P3& p3, + const P4& p4, + const P5& p5, + const P6& p6) : BindStateBase(&Destroy), runnable_(runnable), p1_(p1), @@ -2781,8 +3104,9 @@ struct BindState MaybeRefcount::value, P1>::AddRef(p1_); } - ~BindState() { MaybeRefcount::value, - P1>::Release(p1_); } + ~BindState() { + MaybeRefcount::value, P1>::Release(p1_); + } static void Destroy(BindStateBase* self) { delete static_cast(self); @@ -2797,8 +3121,15 @@ struct BindState P6 p6_; }; -template +template struct BindState : public BindStateBase { typedef Runnable RunnableType; @@ -2815,8 +3146,14 @@ struct BindState typedef UnwrapTraits Bound6UnwrapTraits; typedef UnwrapTraits Bound7UnwrapTraits; - BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, - const P4& p4, const P5& p5, const P6& p6, const P7& p7) + BindState(const Runnable& runnable, + const P1& p1, + const P2& p2, + const P3& p3, + const P4& p4, + const P5& p5, + const P6& p6, + const P7& p7) : BindStateBase(&Destroy), runnable_(runnable), p1_(p1), @@ -2829,8 +3166,9 @@ struct BindState MaybeRefcount::value, P1>::AddRef(p1_); } - ~BindState() { MaybeRefcount::value, - P1>::Release(p1_); } + ~BindState() { + MaybeRefcount::value, P1>::Release(p1_); + } static void Destroy(BindStateBase* self) { delete static_cast(self); diff --git a/src/include/base/internal/cef_bind_internal_win.h b/src/include/base/internal/cef_bind_internal_win.h index 1b061ccd0..4a363def8 100644 --- a/src/include/base/internal/cef_bind_internal_win.h +++ b/src/include/base/internal/cef_bind_internal_win.h @@ -48,338 +48,344 @@ class RunnableAdapter; // __stdcall Function: Arity 0. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(); + typedef R(RunType)(); - explicit RunnableAdapter(R(__stdcall *function)()) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)()) : function_(function) {} - R Run() { - return function_(); - } + R Run() { return function_(); } private: - R (__stdcall *function_)(); + R(__stdcall* function_)(); }; // __fastcall Function: Arity 0. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(); + typedef R(RunType)(); - explicit RunnableAdapter(R(__fastcall *function)()) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)()) : function_(function) {} - R Run() { - return function_(); - } + R Run() { return function_(); } private: - R (__fastcall *function_)(); + R(__fastcall* function_)(); }; // __stdcall Function: Arity 1. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1); + typedef R(RunType)(A1); - explicit RunnableAdapter(R(__stdcall *function)(A1)) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)(A1)) : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1) { return function_(a1); } private: - R (__stdcall *function_)(A1); + R(__stdcall* function_)(A1); }; // __fastcall Function: Arity 1. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1); + typedef R(RunType)(A1); - explicit RunnableAdapter(R(__fastcall *function)(A1)) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)(A1)) : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1) { return function_(a1); } private: - R (__fastcall *function_)(A1); + R(__fastcall* function_)(A1); }; // __stdcall Function: Arity 2. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2); + typedef R(RunType)(A1, A2); - explicit RunnableAdapter(R(__stdcall *function)(A1, A2)) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)(A1, A2)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2) { + typename CallbackParamTraits::ForwardType a2) { return function_(a1, a2); } private: - R (__stdcall *function_)(A1, A2); + R(__stdcall* function_)(A1, A2); }; // __fastcall Function: Arity 2. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2); + typedef R(RunType)(A1, A2); - explicit RunnableAdapter(R(__fastcall *function)(A1, A2)) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)(A1, A2)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2) { + typename CallbackParamTraits::ForwardType a2) { return function_(a1, a2); } private: - R (__fastcall *function_)(A1, A2); + R(__fastcall* function_)(A1, A2); }; // __stdcall Function: Arity 3. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3); + typedef R(RunType)(A1, A2, A3); - explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3)) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)(A1, A2, A3)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { return function_(a1, a2, a3); } private: - R (__stdcall *function_)(A1, A2, A3); + R(__stdcall* function_)(A1, A2, A3); }; // __fastcall Function: Arity 3. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3); + typedef R(RunType)(A1, A2, A3); - explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3)) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)(A1, A2, A3)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { return function_(a1, a2, a3); } private: - R (__fastcall *function_)(A1, A2, A3); + R(__fastcall* function_)(A1, A2, A3); }; // __stdcall Function: Arity 4. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4); + typedef R(RunType)(A1, A2, A3, A4); - explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4)) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)(A1, A2, A3, A4)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { return function_(a1, a2, a3, a4); } private: - R (__stdcall *function_)(A1, A2, A3, A4); + R(__stdcall* function_)(A1, A2, A3, A4); }; // __fastcall Function: Arity 4. template -class RunnableAdapter { +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4); + typedef R(RunType)(A1, A2, A3, A4); - explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4)) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)(A1, A2, A3, A4)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { return function_(a1, a2, a3, a4); } private: - R (__fastcall *function_)(A1, A2, A3, A4); + R(__fastcall* function_)(A1, A2, A3, A4); }; // __stdcall Function: Arity 5. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5); + typedef R(RunType)(A1, A2, A3, A4, A5); - explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4, A5)) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)(A1, A2, A3, A4, A5)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { return function_(a1, a2, a3, a4, a5); } private: - R (__stdcall *function_)(A1, A2, A3, A4, A5); + R(__stdcall* function_)(A1, A2, A3, A4, A5); }; // __fastcall Function: Arity 5. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5); + typedef R(RunType)(A1, A2, A3, A4, A5); - explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4, A5)) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)(A1, A2, A3, A4, A5)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { return function_(a1, a2, a3, a4, a5); } private: - R (__fastcall *function_)(A1, A2, A3, A4, A5); + R(__fastcall* function_)(A1, A2, A3, A4, A5); }; // __stdcall Function: Arity 6. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5, A6); + typedef R(RunType)(A1, A2, A3, A4, A5, A6); - explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4, A5, A6)) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)(A1, A2, A3, A4, A5, A6)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { return function_(a1, a2, a3, a4, a5, a6); } private: - R (__stdcall *function_)(A1, A2, A3, A4, A5, A6); + R(__stdcall* function_)(A1, A2, A3, A4, A5, A6); }; // __fastcall Function: Arity 6. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5, A6); + typedef R(RunType)(A1, A2, A3, A4, A5, A6); - explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4, A5, A6)) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)(A1, A2, A3, A4, A5, A6)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { return function_(a1, a2, a3, a4, a5, a6); } private: - R (__fastcall *function_)(A1, A2, A3, A4, A5, A6); + R(__fastcall* function_)(A1, A2, A3, A4, A5, A6); }; // __stdcall Function: Arity 7. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5, A6, A7); + typedef R(RunType)(A1, A2, A3, A4, A5, A6, A7); - explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4, A5, A6, A7)) - : function_(function) { - } + explicit RunnableAdapter(R(__stdcall* function)(A1, A2, A3, A4, A5, A6, A7)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6, - typename CallbackParamTraits::ForwardType a7) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { return function_(a1, a2, a3, a4, a5, a6, a7); } private: - R (__stdcall *function_)(A1, A2, A3, A4, A5, A6, A7); + R(__stdcall* function_)(A1, A2, A3, A4, A5, A6, A7); }; // __fastcall Function: Arity 7. -template -class RunnableAdapter { +template +class RunnableAdapter { public: - typedef R (RunType)(A1, A2, A3, A4, A5, A6, A7); + typedef R(RunType)(A1, A2, A3, A4, A5, A6, A7); - explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4, A5, A6, A7)) - : function_(function) { - } + explicit RunnableAdapter(R(__fastcall* function)(A1, A2, A3, A4, A5, A6, A7)) + : function_(function) {} R Run(typename CallbackParamTraits::ForwardType a1, - typename CallbackParamTraits::ForwardType a2, - typename CallbackParamTraits::ForwardType a3, - typename CallbackParamTraits::ForwardType a4, - typename CallbackParamTraits::ForwardType a5, - typename CallbackParamTraits::ForwardType a6, - typename CallbackParamTraits::ForwardType a7) { + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { return function_(a1, a2, a3, a4, a5, a6, a7); } private: - R (__fastcall *function_)(A1, A2, A3, A4, A5, A6, A7); + R(__fastcall* function_)(A1, A2, A3, A4, A5, A6, A7); }; } // namespace cef_internal diff --git a/src/include/base/internal/cef_callback_internal.h b/src/include/base/internal/cef_callback_internal.h index 542e84389..1f2e16c97 100644 --- a/src/include/base/internal/cef_callback_internal.h +++ b/src/include/base/internal/cef_callback_internal.h @@ -92,7 +92,7 @@ class CallbackBase { // another type. It is not okay to use void*. We create a InvokeFuncStorage // that that can store our function pointer, and then cast it back to // the original type on usage. - typedef void(*InvokeFuncStorage)(void); + typedef void (*InvokeFuncStorage)(void); // Returns true if this callback equals |other|. |other| may be null. bool Equals(const CallbackBase& other) const; @@ -115,15 +115,16 @@ class CallbackBase { // A helper template to determine if given type is non-const move-only-type, // i.e. if a value of the given type should be passed via .Pass() in a // destructive way. -template struct IsMoveOnlyType { +template +struct IsMoveOnlyType { template static YesType Test(const typename U::MoveOnlyTypeForCPP03*); template static NoType Test(...); - static const bool value = sizeof(Test(0)) == sizeof(YesType) && - !is_const::value; + static const bool value = + sizeof(Test(0)) == sizeof(YesType) && !is_const::value; }; // This is a typetraits object that's used to take an argument type, and diff --git a/src/include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h b/src/include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h index 8584fcd70..9f2f932fe 100644 --- a/src/include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h +++ b/src/include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h @@ -51,9 +51,7 @@ namespace cef_internal { template struct NeedsScopedRefptrButGetsRawPtr { #if defined(OS_WIN) - enum { - value = base::false_type::value - }; + enum { value = base::false_type::value }; #else enum { // Human readable translation: you needed to be a scoped_refptr if you are a @@ -77,74 +75,103 @@ struct ParamsUseScopedRefptrCorrectly { }; template -struct ParamsUseScopedRefptrCorrectly > { +struct ParamsUseScopedRefptrCorrectly> { enum { value = !NeedsScopedRefptrButGetsRawPtr::value }; }; template -struct ParamsUseScopedRefptrCorrectly > { - enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value) }; +struct ParamsUseScopedRefptrCorrectly> { + enum { + value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) + }; }; template -struct ParamsUseScopedRefptrCorrectly > { - enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value) }; +struct ParamsUseScopedRefptrCorrectly> { + enum { + value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) + }; }; template -struct ParamsUseScopedRefptrCorrectly > { - enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value) }; +struct ParamsUseScopedRefptrCorrectly> { + enum { + value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) + }; }; template -struct ParamsUseScopedRefptrCorrectly > { - enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value) }; +struct ParamsUseScopedRefptrCorrectly> { + enum { + value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) + }; }; -template -struct ParamsUseScopedRefptrCorrectly > { - enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value) }; +struct ParamsUseScopedRefptrCorrectly> { + enum { + value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) + }; }; -template -struct ParamsUseScopedRefptrCorrectly > { - enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value) }; +template +struct ParamsUseScopedRefptrCorrectly> { + enum { + value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) + }; }; -template -struct ParamsUseScopedRefptrCorrectly > { - enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value || - NeedsScopedRefptrButGetsRawPtr::value) }; +template +struct ParamsUseScopedRefptrCorrectly> { + enum { + value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) + }; }; } // namespace cef_internal diff --git a/src/include/cef_geolocation.h b/src/include/cef_accessibility_handler.h similarity index 68% rename from src/include/cef_geolocation.h rename to src/include/cef_accessibility_handler.h index 32005a430..c34e0c577 100644 --- a/src/include/cef_geolocation.h +++ b/src/include/cef_accessibility_handler.h @@ -1,4 +1,4 @@ -// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// Copyright (c) 2017 Marshall A. Greenblatt. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are @@ -34,33 +34,33 @@ // tools directory for more information. // -#ifndef CEF_INCLUDE_CEF_GEOLOCATION_H_ -#define CEF_INCLUDE_CEF_GEOLOCATION_H_ +#ifndef CEF_INCLUDE_CEF_ACCESSIBILITY_HANDLER_H_ +#define CEF_INCLUDE_CEF_ACCESSIBILITY_HANDLER_H_ #pragma once -#include "include/cef_base.h" +#include "include/cef_values.h" /// -// Implement this interface to receive geolocation updates. The methods of this -// class will be called on the browser process UI thread. +// Implement this interface to receive accessibility notification when +// accessibility events have been registered. The methods of this class will +// be called on the UI thread. /// /*--cef(source=client)--*/ -class CefGetGeolocationCallback : public virtual CefBaseRefCounted { +class CefAccessibilityHandler : public virtual CefBaseRefCounted { public: /// - // Called with the 'best available' location information or, if the location - // update failed, with error information. + // Called after renderer process sends accessibility tree changes to the + // browser process. /// /*--cef()--*/ - virtual void OnLocationUpdate(const CefGeoposition& position) =0; -}; + virtual void OnAccessibilityTreeChange(CefRefPtr value) = 0; -/// -// Request a one-time geolocation update. This function bypasses any user -// permission checks so should only be used by code that is allowed to access -// location information. -/// -/*--cef()--*/ -bool CefGetGeolocation(CefRefPtr callback); + /// + // Called after renderer process sends accessibility location changes to the + // browser process. + /// + /*--cef()--*/ + virtual void OnAccessibilityLocationChange(CefRefPtr value) = 0; +}; -#endif // CEF_INCLUDE_CEF_GEOLOCATION_H_ +#endif // CEF_INCLUDE_CEF_ACCESSIBILITY_HANDLER_H_ diff --git a/src/include/cef_app.h b/src/include/cef_app.h index 5aca29b30..3962a09c0 100644 --- a/src/include/cef_app.h +++ b/src/include/cef_app.h @@ -34,7 +34,6 @@ // tools directory for more information. // - #ifndef CEF_INCLUDE_CEF_APP_H_ #define CEF_INCLUDE_CEF_APP_H_ #pragma once @@ -159,8 +158,7 @@ class CefApp : public virtual CefBaseRefCounted { /*--cef(optional_param=process_type)--*/ virtual void OnBeforeCommandLineProcessing( const CefString& process_type, - CefRefPtr command_line) { - } + CefRefPtr command_line) {} /// // Provides an opportunity to register custom schemes. Do not keep a reference @@ -170,8 +168,7 @@ class CefApp : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void OnRegisterCustomSchemes( - CefRawPtr registrar) { - } + CefRawPtr registrar) {} /// // Return the handler for resource bundle events. If diff --git a/src/include/cef_application_mac.h b/src/include/cef_application_mac.h index 473e99727..e2858c48e 100644 --- a/src/include/cef_application_mac.h +++ b/src/include/cef_application_mac.h @@ -31,7 +31,9 @@ #define CEF_INCLUDE_CEF_APPLICATION_MAC_H_ #pragma once +#ifdef __cplusplus #include "include/cef_base.h" +#endif // __cplusplus #if defined(OS_MACOSX) && defined(__OBJC__) @@ -82,25 +84,27 @@ @protocol CefAppProtocol @end +#ifdef __cplusplus + // Controls the state of |isHandlingSendEvent| in the event loop so that it is // reset properly. class CefScopedSendingEvent { public: CefScopedSendingEvent() - : app_(static_cast*>( - [NSApplication sharedApplication])), - handling_([app_ isHandlingSendEvent]) { + : app_(static_cast*>( + [NSApplication sharedApplication])), + handling_([app_ isHandlingSendEvent]) { [app_ setHandlingSendEvent:YES]; } - ~CefScopedSendingEvent() { - [app_ setHandlingSendEvent:handling_]; - } + ~CefScopedSendingEvent() { [app_ setHandlingSendEvent:handling_]; } private: NSApplication* app_; BOOL handling_; }; +#endif // __cplusplus + #endif // defined(OS_MACOSX) && defined(__OBJC__) #endif // CEF_INCLUDE_CEF_APPLICATION_MAC_H_ diff --git a/src/include/cef_auth_callback.h b/src/include/cef_auth_callback.h index ca511fdc4..fc8a10a9e 100644 --- a/src/include/cef_auth_callback.h +++ b/src/include/cef_auth_callback.h @@ -50,15 +50,15 @@ class CefAuthCallback : public virtual CefBaseRefCounted { /// // Continue the authentication request. /// - /*--cef(capi_name=cont)--*/ + /*--cef(capi_name=cont,optional_param=username,optional_param=password)--*/ virtual void Continue(const CefString& username, - const CefString& password) =0; + const CefString& password) = 0; /// // Cancel the authentication request. /// /*--cef()--*/ - virtual void Cancel() =0; + virtual void Cancel() = 0; }; #endif // CEF_INCLUDE_CEF_AUTH_CALLBACK_H_ diff --git a/src/include/cef_base.h b/src/include/cef_base.h index c152cf06d..816108e2a 100644 --- a/src/include/cef_base.h +++ b/src/include/cef_base.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #ifndef CEF_INCLUDE_CEF_BASE_H_ #define CEF_INCLUDE_CEF_BASE_H_ #pragma once @@ -56,18 +55,18 @@ class CefBaseRefCounted { // Called to increment the reference count for the object. Should be called // for every new copy of a pointer to a given object. /// - virtual void AddRef() const =0; + virtual void AddRef() const = 0; /// // Called to decrement the reference count for the object. Returns true if // the reference count is 0, in which case the object should self-delete. /// - virtual bool Release() const =0; + virtual bool Release() const = 0; /// // Returns true if the reference count is 1. /// - virtual bool HasOneRef() const =0; + virtual bool HasOneRef() const = 0; protected: virtual ~CefBaseRefCounted() {} @@ -91,23 +90,17 @@ class CefRefCount { /// // Increment the reference count. /// - void AddRef() const { - base::AtomicRefCountInc(&ref_count_); - } + void AddRef() const { base::AtomicRefCountInc(&ref_count_); } /// // Decrement the reference count. Returns true if the reference count is 0. /// - bool Release() const { - return !base::AtomicRefCountDec(&ref_count_); - } + bool Release() const { return !base::AtomicRefCountDec(&ref_count_); } /// // Returns true if the reference count is 1. /// - bool HasOneRef() const { - return base::AtomicRefCountIsOne(&ref_count_); - } + bool HasOneRef() const { return base::AtomicRefCountIsOne(&ref_count_); } private: mutable base::AtomicRefCount ref_count_; @@ -118,23 +111,20 @@ class CefRefCount { // Macro that provides a reference counting implementation for classes extending // CefBase. /// -#define IMPLEMENT_REFCOUNTING(ClassName) \ - public: \ - void AddRef() const OVERRIDE { \ - ref_count_.AddRef(); \ - } \ - bool Release() const OVERRIDE { \ - if (ref_count_.Release()) { \ - delete static_cast(this); \ - return true; \ - } \ - return false; \ - } \ - bool HasOneRef() const OVERRIDE { \ - return ref_count_.HasOneRef(); \ - } \ - private: \ - CefRefCount ref_count_; +#define IMPLEMENT_REFCOUNTING(ClassName) \ + public: \ + void AddRef() const OVERRIDE { ref_count_.AddRef(); } \ + bool Release() const OVERRIDE { \ + if (ref_count_.Release()) { \ + delete static_cast(this); \ + return true; \ + } \ + return false; \ + } \ + bool HasOneRef() const OVERRIDE { return ref_count_.HasOneRef(); } \ + \ + private: \ + CefRefCount ref_count_; /// // Macro that provides a locking implementation. Use the Lock() and Unlock() @@ -169,19 +159,21 @@ class CefRefCount { // value_++; // } /// -#define IMPLEMENT_LOCKING(ClassName) \ - public: \ - class AutoLock { \ - public: \ - explicit AutoLock(ClassName* base) : base_(base) { base_->Lock(); } \ - ~AutoLock() { base_->Unlock(); } \ - private: \ - ClassName* base_; \ - DISALLOW_COPY_AND_ASSIGN(AutoLock); \ - }; \ - void Lock() { lock_.Acquire(); } \ - void Unlock() { lock_.Release(); } \ - private: \ - base::Lock lock_; +#define IMPLEMENT_LOCKING(ClassName) \ + public: \ + class AutoLock { \ + public: \ + explicit AutoLock(ClassName* base) : base_(base) { base_->Lock(); } \ + ~AutoLock() { base_->Unlock(); } \ + \ + private: \ + ClassName* base_; \ + DISALLOW_COPY_AND_ASSIGN(AutoLock); \ + }; \ + void Lock() { lock_.Acquire(); } \ + void Unlock() { lock_.Release(); } \ + \ + private: \ + base::Lock lock_; #endif // CEF_INCLUDE_CEF_BASE_H_ diff --git a/src/include/cef_browser.h b/src/include/cef_browser.h index 3b4ed1617..72d9b3bae 100644 --- a/src/include/cef_browser.h +++ b/src/include/cef_browser.h @@ -38,6 +38,7 @@ #define CEF_INCLUDE_CEF_BROWSER_H_ #pragma once +#include #include "include/cef_base.h" #include "include/cef_drag_data.h" #include "include/cef_frame.h" @@ -45,12 +46,10 @@ #include "include/cef_navigation_entry.h" #include "include/cef_process_message.h" #include "include/cef_request_context.h" -#include class CefBrowserHost; class CefClient; - /// // Class used to represent a browser window. When used in the browser process // the methods of this class may be called on any thread unless otherwise @@ -65,122 +64,123 @@ class CefBrowser : public virtual CefBaseRefCounted { // browser process. /// /*--cef()--*/ - virtual CefRefPtr GetHost() =0; + virtual CefRefPtr GetHost() = 0; /// // Returns true if the browser can navigate backwards. /// /*--cef()--*/ - virtual bool CanGoBack() =0; + virtual bool CanGoBack() = 0; /// // Navigate backwards. /// /*--cef()--*/ - virtual void GoBack() =0; + virtual void GoBack() = 0; /// // Returns true if the browser can navigate forwards. /// /*--cef()--*/ - virtual bool CanGoForward() =0; + virtual bool CanGoForward() = 0; /// // Navigate forwards. /// /*--cef()--*/ - virtual void GoForward() =0; + virtual void GoForward() = 0; /// // Returns true if the browser is currently loading. /// /*--cef()--*/ - virtual bool IsLoading() =0; + virtual bool IsLoading() = 0; /// // Reload the current page. /// /*--cef()--*/ - virtual void Reload() =0; + virtual void Reload() = 0; /// // Reload the current page ignoring any cached data. /// /*--cef()--*/ - virtual void ReloadIgnoreCache() =0; + virtual void ReloadIgnoreCache() = 0; /// // Stop loading the page. /// /*--cef()--*/ - virtual void StopLoad() =0; + virtual void StopLoad() = 0; /// - // Returns the globally unique identifier for this browser. + // Returns the globally unique identifier for this browser. This value is also + // used as the tabId for extension APIs. /// /*--cef()--*/ - virtual int GetIdentifier() =0; + virtual int GetIdentifier() = 0; /// // Returns true if this object is pointing to the same handle as |that| // object. /// /*--cef()--*/ - virtual bool IsSame(CefRefPtr that) =0; + virtual bool IsSame(CefRefPtr that) = 0; /// // Returns true if the window is a popup window. /// /*--cef()--*/ - virtual bool IsPopup() =0; + virtual bool IsPopup() = 0; /// // Returns true if a document has been loaded in the browser. /// /*--cef()--*/ - virtual bool HasDocument() =0; + virtual bool HasDocument() = 0; /// // Returns the main (top-level) frame for the browser window. /// /*--cef()--*/ - virtual CefRefPtr GetMainFrame() =0; + virtual CefRefPtr GetMainFrame() = 0; /// // Returns the focused frame for the browser window. /// /*--cef()--*/ - virtual CefRefPtr GetFocusedFrame() =0; + virtual CefRefPtr GetFocusedFrame() = 0; /// // Returns the frame with the specified identifier, or NULL if not found. /// /*--cef(capi_name=get_frame_byident)--*/ - virtual CefRefPtr GetFrame(int64 identifier) =0; + virtual CefRefPtr GetFrame(int64 identifier) = 0; /// // Returns the frame with the specified name, or NULL if not found. /// /*--cef(optional_param=name)--*/ - virtual CefRefPtr GetFrame(const CefString& name) =0; + virtual CefRefPtr GetFrame(const CefString& name) = 0; /// // Returns the number of frames that currently exist. /// /*--cef()--*/ - virtual size_t GetFrameCount() =0; + virtual size_t GetFrameCount() = 0; /// // Returns the identifiers of all existing frames. /// /*--cef(count_func=identifiers:GetFrameCount)--*/ - virtual void GetFrameIdentifiers(std::vector& identifiers) =0; + virtual void GetFrameIdentifiers(std::vector& identifiers) = 0; /// // Returns the names of all existing frames. /// /*--cef()--*/ - virtual void GetFrameNames(std::vector& names) =0; + virtual void GetFrameNames(std::vector& names) = 0; /// // Send a message to the specified |target_process|. Returns true if the @@ -188,10 +188,9 @@ class CefBrowser : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual bool SendProcessMessage(CefProcessId target_process, - CefRefPtr message) =0; + CefRefPtr message) = 0; }; - /// // Callback interface for CefBrowserHost::RunFileDialog. The methods of this // class will be called on the browser process UI thread. @@ -209,10 +208,9 @@ class CefRunFileDialogCallback : public virtual CefBaseRefCounted { /*--cef(index_param=selected_accept_filter,optional_param=file_paths)--*/ virtual void OnFileDialogDismissed( int selected_accept_filter, - const std::vector& file_paths) =0; + const std::vector& file_paths) = 0; }; - /// // Callback interface for CefBrowserHost::GetNavigationEntries. The methods of // this class will be called on the browser process UI thread. @@ -231,10 +229,9 @@ class CefNavigationEntryVisitor : public virtual CefBaseRefCounted { virtual bool Visit(CefRefPtr entry, bool current, int index, - int total) =0; + int total) = 0; }; - /// // Callback interface for CefBrowserHost::PrintToPDF. The methods of this class // will be called on the browser process UI thread. @@ -248,10 +245,9 @@ class CefPdfPrintCallback : public virtual CefBaseRefCounted { // successfully or false otherwise. /// /*--cef()--*/ - virtual void OnPdfPrintFinished(const CefString& path, bool ok) =0; + virtual void OnPdfPrintFinished(const CefString& path, bool ok) = 0; }; - /// // Callback interface for CefBrowserHost::DownloadImage. The methods of this // class will be called on the browser process UI thread. @@ -266,13 +262,11 @@ class CefDownloadImageCallback : public virtual CefBaseRefCounted { // multiple scale factors, or empty if the download failed. /// /*--cef(optional_param=image)--*/ - virtual void OnDownloadImageFinished( - const CefString& image_url, - int http_status_code, - CefRefPtr image) =0; + virtual void OnDownloadImageFinished(const CefString& image_url, + int http_status_code, + CefRefPtr image) = 0; }; - /// // Class used to represent the browser process aspects of a browser window. The // methods of this class can only be called in the browser process. They may be @@ -321,7 +315,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // Returns the hosted browser object. /// /*--cef()--*/ - virtual CefRefPtr GetBrowser() =0; + virtual CefRefPtr GetBrowser() = 0; /// // Request that the browser close. The JavaScript 'onbeforeunload' event will @@ -334,7 +328,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // information. /// /*--cef()--*/ - virtual void CloseBrowser(bool force_close) =0; + virtual void CloseBrowser(bool force_close) = 0; /// // Helper for closing a browser. Call this method from the top-level window @@ -345,13 +339,13 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // information. This method must be called on the browser process UI thread. /// /*--cef()--*/ - virtual bool TryCloseBrowser() =0; + virtual bool TryCloseBrowser() = 0; /// // Set whether the browser is focused. /// /*--cef()--*/ - virtual void SetFocus(bool focus) =0; + virtual void SetFocus(bool focus) = 0; /// // Retrieve the window handle for this browser. If this browser is wrapped in @@ -359,41 +353,41 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // thread and it will return the handle for the top-level native window. /// /*--cef()--*/ - virtual CefWindowHandle GetWindowHandle() =0; + virtual CefWindowHandle GetWindowHandle() = 0; /// // Retrieve the window handle of the browser that opened this browser. Will // return NULL for non-popup windows or if this browser is wrapped in a // CefBrowserView. This method can be used in combination with custom handling - // of modal windows. + // of modal windows. /// /*--cef()--*/ - virtual CefWindowHandle GetOpenerWindowHandle() =0; + virtual CefWindowHandle GetOpenerWindowHandle() = 0; /// // Returns true if this browser is wrapped in a CefBrowserView. /// /*--cef()--*/ - virtual bool HasView() =0; + virtual bool HasView() = 0; /// // Returns the client for this browser. /// /*--cef()--*/ - virtual CefRefPtr GetClient() =0; + virtual CefRefPtr GetClient() = 0; /// // Returns the request context for this browser. /// /*--cef()--*/ - virtual CefRefPtr GetRequestContext() =0; + virtual CefRefPtr GetRequestContext() = 0; /// // Get the current zoom level. The default zoom level is 0.0. This method can // only be called on the UI thread. /// /*--cef()--*/ - virtual double GetZoomLevel() =0; + virtual double GetZoomLevel() = 0; /// // Change the zoom level to the specified value. Specify 0.0 to reset the @@ -402,7 +396,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // UI thread. /// /*--cef()--*/ - virtual void SetZoomLevel(double zoomLevel) =0; + virtual void SetZoomLevel(double zoomLevel) = 0; /// // Call to run a file chooser dialog. Only a single file chooser dialog may be @@ -427,13 +421,13 @@ class CefBrowserHost : public virtual CefBaseRefCounted { const CefString& default_file_path, const std::vector& accept_filters, int selected_accept_filter, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// // Download the file at |url| using CefDownloadHandler. /// /*--cef()--*/ - virtual void StartDownload(const CefString& url) =0; + virtual void StartDownload(const CefString& url) = 0; /// // Download |image_url| and execute |callback| on completion with the images @@ -452,13 +446,13 @@ class CefBrowserHost : public virtual CefBaseRefCounted { bool is_favicon, uint32 max_image_size, bool bypass_cache, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// // Print the current browser contents. /// /*--cef()--*/ - virtual void Print() =0; + virtual void Print() = 0; /// // Print the current browser contents to the PDF file specified by |path| and @@ -469,25 +463,31 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /*--cef(optional_param=callback)--*/ virtual void PrintToPDF(const CefString& path, const CefPdfPrintSettings& settings, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// - // Search for |searchText|. |identifier| can be used to have multiple searches - // running simultaniously. |forward| indicates whether to search forward or - // backward within the page. |matchCase| indicates whether the search should - // be case-sensitive. |findNext| indicates whether this is the first request - // or a follow-up. The CefFindHandler instance, if any, returned via - // CefClient::GetFindHandler will be called to report find results. + // Search for |searchText|. |identifier| must be a unique ID and these IDs + // must strictly increase so that newer requests always have greater IDs than + // older requests. If |identifier| is zero or less than the previous ID value + // then it will be automatically assigned a new valid ID. |forward| indicates + // whether to search forward or backward within the page. |matchCase| + // indicates whether the search should be case-sensitive. |findNext| indicates + // whether this is the first request or a follow-up. The CefFindHandler + // instance, if any, returned via CefClient::GetFindHandler will be called to + // report find results. /// /*--cef()--*/ - virtual void Find(int identifier, const CefString& searchText, - bool forward, bool matchCase, bool findNext) =0; + virtual void Find(int identifier, + const CefString& searchText, + bool forward, + bool matchCase, + bool findNext) = 0; /// // Cancel all searches that are currently going on. /// /*--cef()--*/ - virtual void StopFinding(bool clearSelection) =0; + virtual void StopFinding(bool clearSelection) = 0; /// // Open developer tools (DevTools) in its own browser. The DevTools browser @@ -503,20 +503,20 @@ class CefBrowserHost : public virtual CefBaseRefCounted { virtual void ShowDevTools(const CefWindowInfo& windowInfo, CefRefPtr client, const CefBrowserSettings& settings, - const CefPoint& inspect_element_at) =0; + const CefPoint& inspect_element_at) = 0; /// // Explicitly close the associated DevTools browser, if any. /// /*--cef()--*/ - virtual void CloseDevTools() =0; + virtual void CloseDevTools() = 0; /// // Returns true if this browser currently has an associated DevTools browser. // Must be called on the browser process UI thread. /// /*--cef()--*/ - virtual bool HasDevTools() =0; + virtual bool HasDevTools() = 0; /// // Retrieve a snapshot of current navigation entries as values sent to the @@ -526,38 +526,38 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void GetNavigationEntries( CefRefPtr visitor, - bool current_only) =0; + bool current_only) = 0; /// // Set whether mouse cursor change is disabled. /// /*--cef()--*/ - virtual void SetMouseCursorChangeDisabled(bool disabled) =0; + virtual void SetMouseCursorChangeDisabled(bool disabled) = 0; /// // Returns true if mouse cursor change is disabled. /// /*--cef()--*/ - virtual bool IsMouseCursorChangeDisabled() =0; + virtual bool IsMouseCursorChangeDisabled() = 0; /// // If a misspelled word is currently selected in an editable node calling // this method will replace it with the specified |word|. /// /*--cef()--*/ - virtual void ReplaceMisspelling(const CefString& word) =0; + virtual void ReplaceMisspelling(const CefString& word) = 0; /// // Add the specified |word| to the spelling dictionary. /// /*--cef()--*/ - virtual void AddWordToDictionary(const CefString& word) =0; + virtual void AddWordToDictionary(const CefString& word) = 0; /// // Returns true if window rendering is disabled. /// /*--cef()--*/ - virtual bool IsWindowRenderingDisabled() =0; + virtual bool IsWindowRenderingDisabled() = 0; /// // Notify the browser that the widget has been resized. The browser will first @@ -566,7 +566,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void WasResized() =0; + virtual void WasResized() = 0; /// // Notify the browser that it has been hidden or shown. Layouting and @@ -574,7 +574,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // hidden. This method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void WasHidden(bool hidden) =0; + virtual void WasHidden(bool hidden) = 0; /// // Send a notification to the browser that the screen info has changed. The @@ -585,7 +585,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // disabled. /// /*--cef()--*/ - virtual void NotifyScreenInfoChanged() =0; + virtual void NotifyScreenInfoChanged() = 0; /// // Invalidate the view. The browser will call CefRenderHandler::OnPaint @@ -593,13 +593,13 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // disabled. /// /*--cef()--*/ - virtual void Invalidate(PaintElementType type) =0; + virtual void Invalidate(PaintElementType type) = 0; /// // Send a key event to the browser. /// /*--cef()--*/ - virtual void SendKeyEvent(const CefKeyEvent& event) =0; + virtual void SendKeyEvent(const CefKeyEvent& event) = 0; /// // Send a mouse click event to the browser. The |x| and |y| coordinates are @@ -608,7 +608,8 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void SendMouseClickEvent(const CefMouseEvent& event, MouseButtonType type, - bool mouseUp, int clickCount) =0; + bool mouseUp, + int clickCount) = 0; /// // Send a mouse move event to the browser. The |x| and |y| coordinates are @@ -616,7 +617,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void SendMouseMoveEvent(const CefMouseEvent& event, - bool mouseLeave) =0; + bool mouseLeave) = 0; /// // Send a mouse wheel event to the browser. The |x| and |y| coordinates are @@ -627,26 +628,27 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void SendMouseWheelEvent(const CefMouseEvent& event, - int deltaX, int deltaY) =0; + int deltaX, + int deltaY) = 0; /// // Send a focus event to the browser. /// /*--cef()--*/ - virtual void SendFocusEvent(bool setFocus) =0; + virtual void SendFocusEvent(bool setFocus) = 0; /// // Send a capture lost event to the browser. /// /*--cef()--*/ - virtual void SendCaptureLostEvent() =0; + virtual void SendCaptureLostEvent() = 0; /// // Notify the browser that the window hosting it is about to be moved or // resized. This method is only used on Windows and Linux. /// /*--cef()--*/ - virtual void NotifyMoveOrResizeStarted() =0; + virtual void NotifyMoveOrResizeStarted() = 0; /// // Returns the maximum rate in frames per second (fps) that CefRenderHandler:: @@ -656,7 +658,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // can only be called on the UI thread. /// /*--cef()--*/ - virtual int GetWindowlessFrameRate() =0; + virtual int GetWindowlessFrameRate() = 0; /// // Set the maximum rate in frames per second (fps) that CefRenderHandler:: @@ -666,7 +668,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // set at browser creation via CefBrowserSettings.windowless_frame_rate. /// /*--cef()--*/ - virtual void SetWindowlessFrameRate(int frame_rate) =0; + virtual void SetWindowlessFrameRate(int frame_rate) = 0; /// // Begins a new composition or updates the existing composition. Blink has a @@ -696,7 +698,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { const CefString& text, const std::vector& underlines, const CefRange& replacement_range, - const CefRange& selection_range) =0; + const CefRange& selection_range) = 0; /// // Completes the existing composition by optionally inserting the specified @@ -710,7 +712,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /*--cef(optional_param=text)--*/ virtual void ImeCommitText(const CefString& text, const CefRange& replacement_range, - int relative_cursor_pos) =0; + int relative_cursor_pos) = 0; /// // Completes the existing composition by applying the current composition node @@ -719,7 +721,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // This method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void ImeFinishComposingText(bool keep_selection) =0; + virtual void ImeFinishComposingText(bool keep_selection) = 0; /// // Cancels the existing composition and discards the composition node @@ -728,7 +730,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // This method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void ImeCancelComposition() =0; + virtual void ImeCancelComposition() = 0; /// // Call this method when the user drags the mouse into the web view (before @@ -741,8 +743,8 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void DragTargetDragEnter(CefRefPtr drag_data, - const CefMouseEvent& event, - DragOperationsMask allowed_ops) =0; + const CefMouseEvent& event, + DragOperationsMask allowed_ops) = 0; /// // Call this method each time the mouse is moved across the web view during @@ -752,7 +754,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void DragTargetDragOver(const CefMouseEvent& event, - DragOperationsMask allowed_ops) =0; + DragOperationsMask allowed_ops) = 0; /// // Call this method when the user drags the mouse out of the web view (after @@ -760,7 +762,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // This method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void DragTargetDragLeave() =0; + virtual void DragTargetDragLeave() = 0; /// // Call this method when the user completes the drag operation by dropping @@ -770,7 +772,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // This method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void DragTargetDrop(const CefMouseEvent& event) =0; + virtual void DragTargetDrop(const CefMouseEvent& event) = 0; /// // Call this method when the drag operation started by a @@ -782,7 +784,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // This method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void DragSourceEndedAt(int x, int y, DragOperationsMask op) =0; + virtual void DragSourceEndedAt(int x, int y, DragOperationsMask op) = 0; /// // Call this method when the drag operation started by a @@ -794,14 +796,68 @@ class CefBrowserHost : public virtual CefBaseRefCounted { // This method is only used when window rendering is disabled. /// /*--cef()--*/ - virtual void DragSourceSystemDragEnded() =0; + virtual void DragSourceSystemDragEnded() = 0; /// // Returns the current visible navigation entry for this browser. This method // can only be called on the UI thread. /// /*--cef()--*/ - virtual CefRefPtr GetVisibleNavigationEntry() =0; + virtual CefRefPtr GetVisibleNavigationEntry() = 0; + + /// + // Set accessibility state for all frames. |accessibility_state| may be + // default, enabled or disabled. If |accessibility_state| is STATE_DEFAULT + // then accessibility will be disabled by default and the state may be further + // controlled with the "force-renderer-accessibility" and + // "disable-renderer-accessibility" command-line switches. If + // |accessibility_state| is STATE_ENABLED then accessibility will be enabled. + // If |accessibility_state| is STATE_DISABLED then accessibility will be + // completely disabled. + // + // For windowed browsers accessibility will be enabled in Complete mode (which + // corresponds to kAccessibilityModeComplete in Chromium). In this mode all + // platform accessibility objects will be created and managed by Chromium's + // internal implementation. The client needs only to detect the screen reader + // and call this method appropriately. For example, on macOS the client can + // handle the @"AXEnhancedUserInterface" accessibility attribute to detect + // VoiceOver state changes and on Windows the client can handle WM_GETOBJECT + // with OBJID_CLIENT to detect accessibility readers. + // + // For windowless browsers accessibility will be enabled in TreeOnly mode + // (which corresponds to kAccessibilityModeWebContentsOnly in Chromium). In + // this mode renderer accessibility is enabled, the full tree is computed, and + // events are passed to CefAccessibiltyHandler, but platform accessibility + // objects are not created. The client may implement platform accessibility + // objects using CefAccessibiltyHandler callbacks if desired. + /// + /*--cef()--*/ + virtual void SetAccessibilityState(cef_state_t accessibility_state) = 0; + + /// + // Enable notifications of auto resize via CefDisplayHandler::OnAutoResize. + // Notifications are disabled by default. |min_size| and |max_size| define the + // range of allowed sizes. + /// + /*--cef()--*/ + virtual void SetAutoResizeEnabled(bool enabled, + const CefSize& min_size, + const CefSize& max_size) = 0; + + /// + // Returns the extension hosted in this browser or NULL if no extension is + // hosted. See CefRequestContext::LoadExtension for details. + /// + /*--cef()--*/ + virtual CefRefPtr GetExtension() = 0; + + /// + // Returns true if this browser is hosting an extension background script. + // Background hosts do not have a window and are not displayable. See + // CefRequestContext::LoadExtension for details. + /// + /*--cef()--*/ + virtual bool IsBackgroundHost() = 0; }; #endif // CEF_INCLUDE_CEF_BROWSER_H_ diff --git a/src/include/cef_browser_process_handler.h b/src/include/cef_browser_process_handler.h index e65503fbd..fb770997b 100644 --- a/src/include/cef_browser_process_handler.h +++ b/src/include/cef_browser_process_handler.h @@ -84,9 +84,7 @@ class CefBrowserProcessHandler : public virtual CefBaseRefCounted { // provided then printing will not be supported on the Linux platform. /// /*--cef()--*/ - virtual CefRefPtr GetPrintHandler() { - return NULL; - } + virtual CefRefPtr GetPrintHandler() { return NULL; } /// // Called from any thread when work has been scheduled for the browser process diff --git a/src/include/cef_callback.h b/src/include/cef_callback.h index 5be51e941..e206cb976 100644 --- a/src/include/cef_callback.h +++ b/src/include/cef_callback.h @@ -50,13 +50,13 @@ class CefCallback : public virtual CefBaseRefCounted { // Continue processing. /// /*--cef(capi_name=cont)--*/ - virtual void Continue() =0; + virtual void Continue() = 0; /// // Cancel processing. /// /*--cef()--*/ - virtual void Cancel() =0; + virtual void Cancel() = 0; }; /// @@ -69,7 +69,7 @@ class CefCompletionCallback : public virtual CefBaseRefCounted { // Method that will be called once the task is complete. /// /*--cef()--*/ - virtual void OnComplete() =0; + virtual void OnComplete() = 0; }; #endif // CEF_INCLUDE_CEF_CALLBACK_H_ diff --git a/src/include/cef_client.h b/src/include/cef_client.h index 9421c7c08..59173c778 100644 --- a/src/include/cef_client.h +++ b/src/include/cef_client.h @@ -46,7 +46,6 @@ #include "include/cef_drag_handler.h" #include "include/cef_find_handler.h" #include "include/cef_focus_handler.h" -#include "include/cef_geolocation_handler.h" #include "include/cef_jsdialog_handler.h" #include "include/cef_keyboard_handler.h" #include "include/cef_life_span_handler.h" @@ -75,108 +74,75 @@ class CefClient : public virtual CefBaseRefCounted { // implementation will be used. /// /*--cef()--*/ - virtual CefRefPtr GetDialogHandler() { - return NULL; - } + virtual CefRefPtr GetDialogHandler() { return NULL; } /// // Return the handler for browser display state events. /// /*--cef()--*/ - virtual CefRefPtr GetDisplayHandler() { - return NULL; - } + virtual CefRefPtr GetDisplayHandler() { return NULL; } /// // Return the handler for download events. If no handler is returned downloads // will not be allowed. /// /*--cef()--*/ - virtual CefRefPtr GetDownloadHandler() { - return NULL; - } + virtual CefRefPtr GetDownloadHandler() { return NULL; } /// // Return the handler for drag events. /// /*--cef()--*/ - virtual CefRefPtr GetDragHandler() { - return NULL; - } + virtual CefRefPtr GetDragHandler() { return NULL; } /// // Return the handler for find result events. /// /*--cef()--*/ - virtual CefRefPtr GetFindHandler() { - return NULL; - } + virtual CefRefPtr GetFindHandler() { return NULL; } /// // Return the handler for focus events. /// /*--cef()--*/ - virtual CefRefPtr GetFocusHandler() { - return NULL; - } - - /// - // Return the handler for geolocation permissions requests. If no handler is - // provided geolocation access will be denied by default. - /// - /*--cef()--*/ - virtual CefRefPtr GetGeolocationHandler() { - return NULL; - } + virtual CefRefPtr GetFocusHandler() { return NULL; } /// // Return the handler for JavaScript dialogs. If no handler is provided the // default implementation will be used. /// /*--cef()--*/ - virtual CefRefPtr GetJSDialogHandler() { - return NULL; - } + virtual CefRefPtr GetJSDialogHandler() { return NULL; } /// // Return the handler for keyboard events. /// /*--cef()--*/ - virtual CefRefPtr GetKeyboardHandler() { - return NULL; - } + virtual CefRefPtr GetKeyboardHandler() { return NULL; } /// // Return the handler for browser life span events. /// /*--cef()--*/ - virtual CefRefPtr GetLifeSpanHandler() { - return NULL; - } + virtual CefRefPtr GetLifeSpanHandler() { return NULL; } /// // Return the handler for browser load status events. /// /*--cef()--*/ - virtual CefRefPtr GetLoadHandler() { - return NULL; - } + virtual CefRefPtr GetLoadHandler() { return NULL; } /// // Return the handler for off-screen rendering events. /// /*--cef()--*/ - virtual CefRefPtr GetRenderHandler() { - return NULL; - } + virtual CefRefPtr GetRenderHandler() { return NULL; } /// // Return the handler for browser request events. /// /*--cef()--*/ - virtual CefRefPtr GetRequestHandler() { - return NULL; - } + virtual CefRefPtr GetRequestHandler() { return NULL; } /// // Called when a new message is received from a different process. Return true diff --git a/src/include/cef_command_line.h b/src/include/cef_command_line.h index 5e581b6e0..dd5491cd2 100644 --- a/src/include/cef_command_line.h +++ b/src/include/cef_command_line.h @@ -38,9 +38,9 @@ #define CEF_INCLUDE_CEF_COMMAND_LINE_H_ #pragma once -#include "include/cef_base.h" #include #include +#include "include/cef_base.h" /// // Class used to create and/or parse command line arguments. Arguments with @@ -76,20 +76,20 @@ class CefCommandLine : public virtual CefBaseRefCounted { // function returns false. /// /*--cef()--*/ - virtual bool IsValid() =0; + virtual bool IsValid() = 0; /// // Returns true if the values of this object are read-only. Some APIs may // expose read-only objects. /// /*--cef()--*/ - virtual bool IsReadOnly() =0; + virtual bool IsReadOnly() = 0; /// // Returns a writable copy of this object. /// /*--cef()--*/ - virtual CefRefPtr Copy() =0; + virtual CefRefPtr Copy() = 0; /// // Initialize the command line with the specified |argc| and |argv| values. @@ -97,112 +97,112 @@ class CefCommandLine : public virtual CefBaseRefCounted { // supported on non-Windows platforms. /// /*--cef()--*/ - virtual void InitFromArgv(int argc, const char* const* argv) =0; + virtual void InitFromArgv(int argc, const char* const* argv) = 0; /// // Initialize the command line with the string returned by calling // GetCommandLineW(). This method is only supported on Windows. /// /*--cef()--*/ - virtual void InitFromString(const CefString& command_line) =0; + virtual void InitFromString(const CefString& command_line) = 0; /// // Reset the command-line switches and arguments but leave the program // component unchanged. /// /*--cef()--*/ - virtual void Reset() =0; + virtual void Reset() = 0; /// // Retrieve the original command line string as a vector of strings. // The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* } /// /*--cef()--*/ - virtual void GetArgv(std::vector& argv) =0; + virtual void GetArgv(std::vector& argv) = 0; /// // Constructs and returns the represented command line string. Use this method // cautiously because quoting behavior is unclear. /// /*--cef()--*/ - virtual CefString GetCommandLineString() =0; + virtual CefString GetCommandLineString() = 0; /// // Get the program part of the command line string (the first item). /// /*--cef()--*/ - virtual CefString GetProgram() =0; + virtual CefString GetProgram() = 0; /// // Set the program part of the command line string (the first item). /// /*--cef()--*/ - virtual void SetProgram(const CefString& program) =0; + virtual void SetProgram(const CefString& program) = 0; /// // Returns true if the command line has switches. /// /*--cef()--*/ - virtual bool HasSwitches() =0; + virtual bool HasSwitches() = 0; /// // Returns true if the command line contains the given switch. /// /*--cef()--*/ - virtual bool HasSwitch(const CefString& name) =0; + virtual bool HasSwitch(const CefString& name) = 0; /// // Returns the value associated with the given switch. If the switch has no // value or isn't present this method returns the empty string. /// /*--cef()--*/ - virtual CefString GetSwitchValue(const CefString& name) =0; + virtual CefString GetSwitchValue(const CefString& name) = 0; /// // Returns the map of switch names and values. If a switch has no value an // empty string is returned. /// /*--cef()--*/ - virtual void GetSwitches(SwitchMap& switches) =0; + virtual void GetSwitches(SwitchMap& switches) = 0; /// // Add a switch to the end of the command line. If the switch has no value // pass an empty value string. /// /*--cef()--*/ - virtual void AppendSwitch(const CefString& name) =0; + virtual void AppendSwitch(const CefString& name) = 0; /// // Add a switch with the specified value to the end of the command line. /// /*--cef()--*/ virtual void AppendSwitchWithValue(const CefString& name, - const CefString& value) =0; + const CefString& value) = 0; /// // True if there are remaining command line arguments. /// /*--cef()--*/ - virtual bool HasArguments() =0; + virtual bool HasArguments() = 0; /// // Get the remaining command line arguments. /// /*--cef()--*/ - virtual void GetArguments(ArgumentList& arguments) =0; + virtual void GetArguments(ArgumentList& arguments) = 0; /// // Add an argument to the end of the command line. /// /*--cef()--*/ - virtual void AppendArgument(const CefString& argument) =0; + virtual void AppendArgument(const CefString& argument) = 0; /// // Insert a command before the current command. // Common for debuggers, like "valgrind" or "gdb --args". /// /*--cef()--*/ - virtual void PrependWrapper(const CefString& wrapper) =0; + virtual void PrependWrapper(const CefString& wrapper) = 0; }; #endif // CEF_INCLUDE_CEF_COMMAND_LINE_H_ diff --git a/src/include/cef_context_menu_handler.h b/src/include/cef_context_menu_handler.h index 7619b8ed0..2a2a73e61 100644 --- a/src/include/cef_context_menu_handler.h +++ b/src/include/cef_context_menu_handler.h @@ -45,7 +45,6 @@ class CefContextMenuParams; - /// // Callback interface used for continuation of custom context menu display. /// @@ -59,16 +58,15 @@ class CefRunContextMenuCallback : public virtual CefBaseRefCounted { // |event_flags|. /// /*--cef(capi_name=cont)--*/ - virtual void Continue(int command_id, EventFlags event_flags) =0; + virtual void Continue(int command_id, EventFlags event_flags) = 0; /// // Cancel context menu display. /// /*--cef()--*/ - virtual void Cancel() =0; + virtual void Cancel() = 0; }; - /// // Implement this interface to handle context menu events. The methods of this // class will be called on the UI thread. @@ -122,7 +120,9 @@ class CefContextMenuHandler : public virtual CefBaseRefCounted { CefRefPtr frame, CefRefPtr params, int command_id, - EventFlags event_flags) { return false; } + EventFlags event_flags) { + return false; + } /// // Called when the context menu is dismissed irregardless of whether the menu @@ -133,7 +133,6 @@ class CefContextMenuHandler : public virtual CefBaseRefCounted { CefRefPtr frame) {} }; - /// // Provides information about the context menu state. The ethods of this class // can only be accessed on browser process the UI thread. @@ -151,49 +150,49 @@ class CefContextMenuParams : public virtual CefBaseRefCounted { // Coords are relative to the associated RenderView's origin. /// /*--cef()--*/ - virtual int GetXCoord() =0; + virtual int GetXCoord() = 0; /// // Returns the Y coordinate of the mouse where the context menu was invoked. // Coords are relative to the associated RenderView's origin. /// /*--cef()--*/ - virtual int GetYCoord() =0; + virtual int GetYCoord() = 0; /// // Returns flags representing the type of node that the context menu was // invoked on. /// /*--cef(default_retval=CM_TYPEFLAG_NONE)--*/ - virtual TypeFlags GetTypeFlags() =0; + virtual TypeFlags GetTypeFlags() = 0; /// // Returns the URL of the link, if any, that encloses the node that the // context menu was invoked on. /// /*--cef()--*/ - virtual CefString GetLinkUrl() =0; + virtual CefString GetLinkUrl() = 0; /// // Returns the link URL, if any, to be used ONLY for "copy link address". We // don't validate this field in the frontend process. /// /*--cef()--*/ - virtual CefString GetUnfilteredLinkUrl() =0; + virtual CefString GetUnfilteredLinkUrl() = 0; /// // Returns the source URL, if any, for the element that the context menu was // invoked on. Example of elements with source URLs are img, audio, and video. /// /*--cef()--*/ - virtual CefString GetSourceUrl() =0; + virtual CefString GetSourceUrl() = 0; /// // Returns true if the context menu was invoked on an image which has // non-empty contents. /// /*--cef()--*/ - virtual bool HasImageContents() =0; + virtual bool HasImageContents() = 0; /// // Returns the title text or the alt text if the context menu was invoked on @@ -206,87 +205,88 @@ class CefContextMenuParams : public virtual CefBaseRefCounted { // Returns the URL of the top level page that the context menu was invoked on. /// /*--cef()--*/ - virtual CefString GetPageUrl() =0; + virtual CefString GetPageUrl() = 0; /// // Returns the URL of the subframe that the context menu was invoked on. /// /*--cef()--*/ - virtual CefString GetFrameUrl() =0; + virtual CefString GetFrameUrl() = 0; /// // Returns the character encoding of the subframe that the context menu was // invoked on. /// /*--cef()--*/ - virtual CefString GetFrameCharset() =0; + virtual CefString GetFrameCharset() = 0; /// // Returns the type of context node that the context menu was invoked on. /// /*--cef(default_retval=CM_MEDIATYPE_NONE)--*/ - virtual MediaType GetMediaType() =0; + virtual MediaType GetMediaType() = 0; /// // Returns flags representing the actions supported by the media element, if // any, that the context menu was invoked on. /// /*--cef(default_retval=CM_MEDIAFLAG_NONE)--*/ - virtual MediaStateFlags GetMediaStateFlags() =0; + virtual MediaStateFlags GetMediaStateFlags() = 0; /// // Returns the text of the selection, if any, that the context menu was // invoked on. /// /*--cef()--*/ - virtual CefString GetSelectionText() =0; + virtual CefString GetSelectionText() = 0; /// // Returns the text of the misspelled word, if any, that the context menu was // invoked on. /// /*--cef()--*/ - virtual CefString GetMisspelledWord() =0; + virtual CefString GetMisspelledWord() = 0; /// // Returns true if suggestions exist, false otherwise. Fills in |suggestions| // from the spell check service for the misspelled word if there is one. /// /*--cef()--*/ - virtual bool GetDictionarySuggestions(std::vector& suggestions) =0; + virtual bool GetDictionarySuggestions( + std::vector& suggestions) = 0; /// // Returns true if the context menu was invoked on an editable node. /// /*--cef()--*/ - virtual bool IsEditable() =0; + virtual bool IsEditable() = 0; /// // Returns true if the context menu was invoked on an editable node where // spell-check is enabled. /// /*--cef()--*/ - virtual bool IsSpellCheckEnabled() =0; + virtual bool IsSpellCheckEnabled() = 0; /// // Returns flags representing the actions supported by the editable node, if // any, that the context menu was invoked on. /// /*--cef(default_retval=CM_EDITFLAG_NONE)--*/ - virtual EditStateFlags GetEditStateFlags() =0; + virtual EditStateFlags GetEditStateFlags() = 0; /// // Returns true if the context menu contains items specified by the renderer // process (for example, plugin placeholder or pepper plugin menu items). /// /*--cef()--*/ - virtual bool IsCustomMenu() =0; + virtual bool IsCustomMenu() = 0; /// // Returns true if the context menu was invoked from a pepper plugin. /// /*--cef()--*/ - virtual bool IsPepperMenu() =0; + virtual bool IsPepperMenu() = 0; }; #endif // CEF_INCLUDE_CEF_CONTEXT_MENU_HANDLER_H_ diff --git a/src/include/cef_cookie.h b/src/include/cef_cookie.h index 28f056d8a..eb57630ab 100644 --- a/src/include/cef_cookie.h +++ b/src/include/cef_cookie.h @@ -38,9 +38,9 @@ #define CEF_INCLUDE_CEF_COOKIE_H_ #pragma once +#include #include "include/cef_base.h" #include "include/cef_callback.h" -#include class CefCookieVisitor; class CefSetCookieCallback; @@ -64,6 +64,17 @@ class CefCookieManager : public virtual CefBaseRefCounted { static CefRefPtr GetGlobalManager( CefRefPtr callback); + /// + // Returns a cookie manager that neither stores nor retrieves cookies. All + // usage of cookies will be blocked including cookies accessed via the network + // (request/response headers), via JavaScript (document.cookie), and via + // CefCookieManager methods. No cookies will be displayed in DevTools. If you + // wish to only block cookies sent via the network use the CefRequestHandler + // CanGetCookies and CanSetCookie methods instead. + /// + /*--cef()--*/ + static CefRefPtr GetBlockingManager(); + /// // Creates a new cookie manager. If |path| is empty data will be stored in // memory only. Otherwise, data will be stored at the specified |path|. To @@ -88,7 +99,7 @@ class CefCookieManager : public virtual CefBaseRefCounted { /*--cef(optional_param=callback)--*/ virtual void SetSupportedSchemes( const std::vector& schemes, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// // Visit all cookies on the IO thread. The returned cookies are ordered by @@ -96,7 +107,7 @@ class CefCookieManager : public virtual CefBaseRefCounted { // cannot be accessed. /// /*--cef()--*/ - virtual bool VisitAllCookies(CefRefPtr visitor) =0; + virtual bool VisitAllCookies(CefRefPtr visitor) = 0; /// // Visit a subset of cookies on the IO thread. The results are filtered by the @@ -108,7 +119,7 @@ class CefCookieManager : public virtual CefBaseRefCounted { /*--cef()--*/ virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, - CefRefPtr visitor) =0; + CefRefPtr visitor) = 0; /// // Sets a cookie given a valid URL and explicit user-provided cookie @@ -122,7 +133,7 @@ class CefCookieManager : public virtual CefBaseRefCounted { /*--cef(optional_param=callback)--*/ virtual bool SetCookie(const CefString& url, const CefCookie& cookie, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// // Delete all cookies that match the specified parameters. If both |url| and @@ -139,7 +150,7 @@ class CefCookieManager : public virtual CefBaseRefCounted { optional_param=callback)--*/ virtual bool DeleteCookies(const CefString& url, const CefString& cookie_name, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// // Sets the directory path that will be used for storing cookie data. If @@ -154,7 +165,7 @@ class CefCookieManager : public virtual CefBaseRefCounted { /*--cef(optional_param=path,optional_param=callback)--*/ virtual bool SetStoragePath(const CefString& path, bool persist_session_cookies, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// // Flush the backing store (if any) to disk. If |callback| is non-NULL it will @@ -162,10 +173,9 @@ class CefCookieManager : public virtual CefBaseRefCounted { // Returns false if cookies cannot be accessed. /// /*--cef(optional_param=callback)--*/ - virtual bool FlushStore(CefRefPtr callback) =0; + virtual bool FlushStore(CefRefPtr callback) = 0; }; - /// // Interface to implement for visiting cookie values. The methods of this class // will always be called on the IO thread. @@ -181,11 +191,12 @@ class CefCookieVisitor : public virtual CefBaseRefCounted { // no cookies are found. /// /*--cef()--*/ - virtual bool Visit(const CefCookie& cookie, int count, int total, - bool& deleteCookie) =0; + virtual bool Visit(const CefCookie& cookie, + int count, + int total, + bool& deleteCookie) = 0; }; - /// // Interface to implement to be notified of asynchronous completion via // CefCookieManager::SetCookie(). @@ -198,10 +209,9 @@ class CefSetCookieCallback : public virtual CefBaseRefCounted { // cookie was set successfully. /// /*--cef()--*/ - virtual void OnComplete(bool success) =0; + virtual void OnComplete(bool success) = 0; }; - /// // Interface to implement to be notified of asynchronous completion via // CefCookieManager::DeleteCookies(). @@ -214,7 +224,7 @@ class CefDeleteCookiesCallback : public virtual CefBaseRefCounted { // number of cookies that were deleted or -1 if unknown. /// /*--cef()--*/ - virtual void OnComplete(int num_deleted) =0; + virtual void OnComplete(int num_deleted) = 0; }; #endif // CEF_INCLUDE_CEF_COOKIE_H_ diff --git a/src/include/cef_crash_util.h b/src/include/cef_crash_util.h index d9ecfe351..e569df74a 100644 --- a/src/include/cef_crash_util.h +++ b/src/include/cef_crash_util.h @@ -121,14 +121,12 @@ // // CrashKeys section: // -// Any number of crash keys can be specified for use by the application. Crash -// key values will be truncated based on the specified size (small = 63 bytes, -// medium = 252 bytes, large = 1008 bytes). The value of crash keys can be set -// from any thread or process using the CefSetCrashKeyValue function. These -// key/value pairs will be sent to the crash server along with the crash dump -// file. Medium and large values will be chunked for submission. For example, -// if your key is named "mykey" then the value will be broken into ordered -// chunks and submitted using keys named "mykey-1", "mykey-2", etc. +// A maximum of 26 crash keys of each size can be specified for use by the +// application. Crash key values will be truncated based on the specified size +// (small = 64 bytes, medium = 256 bytes, large = 1024 bytes). The value of +// crash keys can be set from any thread or process using the +// CefSetCrashKeyValue function. These key/value pairs will be sent to the crash +// server along with the crash dump file. /// /*--cef()--*/ bool CefCrashReportingEnabled(); diff --git a/src/include/cef_dialog_handler.h b/src/include/cef_dialog_handler.h index 3ca98fb51..3ce02e6c1 100644 --- a/src/include/cef_dialog_handler.h +++ b/src/include/cef_dialog_handler.h @@ -57,16 +57,15 @@ class CefFileDialogCallback : public virtual CefBaseRefCounted { /*--cef(capi_name=cont,index_param=selected_accept_filter, optional_param=file_paths)--*/ virtual void Continue(int selected_accept_filter, - const std::vector& file_paths) =0; + const std::vector& file_paths) = 0; /// // Cancel the file selection. /// /*--cef()--*/ - virtual void Cancel() =0; + virtual void Cancel() = 0; }; - /// // Implement this interface to handle dialog events. The methods of this class // will be called on the browser process UI thread. diff --git a/src/include/cef_display_handler.h b/src/include/cef_display_handler.h index 6147cc799..4fdc3c312 100644 --- a/src/include/cef_display_handler.h +++ b/src/include/cef_display_handler.h @@ -91,8 +91,9 @@ class CefDisplayHandler : public virtual CefBaseRefCounted { // drawing tooltips and the return value is ignored. /// /*--cef(optional_param=text)--*/ - virtual bool OnTooltip(CefRefPtr browser, - CefString& text) { return false; } + virtual bool OnTooltip(CefRefPtr browser, CefString& text) { + return false; + } /// // Called when the browser receives a status message. |value| contains the @@ -108,9 +109,32 @@ class CefDisplayHandler : public virtual CefBaseRefCounted { /// /*--cef(optional_param=message,optional_param=source)--*/ virtual bool OnConsoleMessage(CefRefPtr browser, + cef_log_severity_t level, const CefString& message, const CefString& source, - int line) { return false; } + int line) { + return false; + } + + /// + // Called when auto-resize is enabled via CefBrowserHost::SetAutoResizeEnabled + // and the contents have auto-resized. |new_size| will be the desired size in + // view coordinates. Return true if the resize was handled or false for + // default handling. + /// + /*--cef()--*/ + virtual bool OnAutoResize(CefRefPtr browser, + const CefSize& new_size) { + return false; + } + + /// + // Called when the overall page loading progress has changed. |progress| + // ranges from 0.0 to 1.0. + /// + /*--cef()--*/ + virtual void OnLoadingProgressChange(CefRefPtr browser, + double progress) {} }; #endif // CEF_INCLUDE_CEF_DISPLAY_HANDLER_H_ diff --git a/src/include/cef_dom.h b/src/include/cef_dom.h index f653a074f..382b19305 100644 --- a/src/include/cef_dom.h +++ b/src/include/cef_dom.h @@ -38,8 +38,8 @@ #define CEF_INCLUDE_CEF_DOM_H_ #pragma once -#include "include/cef_base.h" #include +#include "include/cef_base.h" class CefDOMDocument; class CefDOMNode; @@ -59,10 +59,9 @@ class CefDOMVisitor : public virtual CefBaseRefCounted { // of this method. /// /*--cef()--*/ - virtual void Visit(CefRefPtr document) =0; + virtual void Visit(CefRefPtr document) = 0; }; - /// // Class used to represent a DOM document. The methods of this class should only // be called on the render process main thread thread. @@ -76,89 +75,88 @@ class CefDOMDocument : public virtual CefBaseRefCounted { // Returns the document type. /// /*--cef(default_retval=DOM_DOCUMENT_TYPE_UNKNOWN)--*/ - virtual Type GetType() =0; + virtual Type GetType() = 0; /// // Returns the root document node. /// /*--cef()--*/ - virtual CefRefPtr GetDocument() =0; + virtual CefRefPtr GetDocument() = 0; /// // Returns the BODY node of an HTML document. /// /*--cef()--*/ - virtual CefRefPtr GetBody() =0; + virtual CefRefPtr GetBody() = 0; /// // Returns the HEAD node of an HTML document. /// /*--cef()--*/ - virtual CefRefPtr GetHead() =0; + virtual CefRefPtr GetHead() = 0; /// // Returns the title of an HTML document. /// /*--cef()--*/ - virtual CefString GetTitle() =0; + virtual CefString GetTitle() = 0; /// // Returns the document element with the specified ID value. /// /*--cef()--*/ - virtual CefRefPtr GetElementById(const CefString& id) =0; + virtual CefRefPtr GetElementById(const CefString& id) = 0; /// // Returns the node that currently has keyboard focus. /// /*--cef()--*/ - virtual CefRefPtr GetFocusedNode() =0; + virtual CefRefPtr GetFocusedNode() = 0; /// // Returns true if a portion of the document is selected. /// /*--cef()--*/ - virtual bool HasSelection() =0; + virtual bool HasSelection() = 0; /// // Returns the selection offset within the start node. /// /*--cef()--*/ - virtual int GetSelectionStartOffset() =0; + virtual int GetSelectionStartOffset() = 0; /// // Returns the selection offset within the end node. /// /*--cef()--*/ - virtual int GetSelectionEndOffset() =0; + virtual int GetSelectionEndOffset() = 0; /// // Returns the contents of this selection as markup. /// /*--cef()--*/ - virtual CefString GetSelectionAsMarkup() =0; + virtual CefString GetSelectionAsMarkup() = 0; /// // Returns the contents of this selection as text. /// /*--cef()--*/ - virtual CefString GetSelectionAsText() =0; + virtual CefString GetSelectionAsText() = 0; /// // Returns the base URL for the document. /// /*--cef()--*/ - virtual CefString GetBaseURL() =0; + virtual CefString GetBaseURL() = 0; /// // Returns a complete URL based on the document base URL and the specified // partial URL. /// /*--cef()--*/ - virtual CefString GetCompleteURL(const CefString& partialURL) =0; + virtual CefString GetCompleteURL(const CefString& partialURL) = 0; }; - /// // Class used to represent a DOM node. The methods of this class should only be // called on the render process main thread. @@ -173,110 +171,110 @@ class CefDOMNode : public virtual CefBaseRefCounted { // Returns the type for this node. /// /*--cef(default_retval=DOM_NODE_TYPE_UNSUPPORTED)--*/ - virtual Type GetType() =0; + virtual Type GetType() = 0; /// // Returns true if this is a text node. /// /*--cef()--*/ - virtual bool IsText() =0; + virtual bool IsText() = 0; /// // Returns true if this is an element node. /// /*--cef()--*/ - virtual bool IsElement() =0; + virtual bool IsElement() = 0; /// // Returns true if this is an editable node. /// /*--cef()--*/ - virtual bool IsEditable() =0; + virtual bool IsEditable() = 0; /// // Returns true if this is a form control element node. /// /*--cef()--*/ - virtual bool IsFormControlElement() =0; + virtual bool IsFormControlElement() = 0; /// // Returns the type of this form control element node. /// /*--cef()--*/ - virtual CefString GetFormControlElementType() =0; + virtual CefString GetFormControlElementType() = 0; /// // Returns true if this object is pointing to the same handle as |that| // object. /// /*--cef()--*/ - virtual bool IsSame(CefRefPtr that) =0; + virtual bool IsSame(CefRefPtr that) = 0; /// // Returns the name of this node. /// /*--cef()--*/ - virtual CefString GetName() =0; + virtual CefString GetName() = 0; /// // Returns the value of this node. /// /*--cef()--*/ - virtual CefString GetValue() =0; + virtual CefString GetValue() = 0; /// // Set the value of this node. Returns true on success. /// /*--cef()--*/ - virtual bool SetValue(const CefString& value) =0; + virtual bool SetValue(const CefString& value) = 0; /// // Returns the contents of this node as markup. /// /*--cef()--*/ - virtual CefString GetAsMarkup() =0; + virtual CefString GetAsMarkup() = 0; /// // Returns the document associated with this node. /// /*--cef()--*/ - virtual CefRefPtr GetDocument() =0; + virtual CefRefPtr GetDocument() = 0; /// // Returns the parent node. /// /*--cef()--*/ - virtual CefRefPtr GetParent() =0; + virtual CefRefPtr GetParent() = 0; /// // Returns the previous sibling node. /// /*--cef()--*/ - virtual CefRefPtr GetPreviousSibling() =0; + virtual CefRefPtr GetPreviousSibling() = 0; /// // Returns the next sibling node. /// /*--cef()--*/ - virtual CefRefPtr GetNextSibling() =0; + virtual CefRefPtr GetNextSibling() = 0; /// // Returns true if this node has child nodes. /// /*--cef()--*/ - virtual bool HasChildren() =0; + virtual bool HasChildren() = 0; /// // Return the first child node. /// /*--cef()--*/ - virtual CefRefPtr GetFirstChild() =0; + virtual CefRefPtr GetFirstChild() = 0; /// // Returns the last child node. /// /*--cef()--*/ - virtual CefRefPtr GetLastChild() =0; + virtual CefRefPtr GetLastChild() = 0; // The following methods are valid only for element nodes. @@ -284,31 +282,31 @@ class CefDOMNode : public virtual CefBaseRefCounted { // Returns the tag name of this element. /// /*--cef()--*/ - virtual CefString GetElementTagName() =0; + virtual CefString GetElementTagName() = 0; /// // Returns true if this element has attributes. /// /*--cef()--*/ - virtual bool HasElementAttributes() =0; + virtual bool HasElementAttributes() = 0; /// // Returns true if this element has an attribute named |attrName|. /// /*--cef()--*/ - virtual bool HasElementAttribute(const CefString& attrName) =0; + virtual bool HasElementAttribute(const CefString& attrName) = 0; /// // Returns the element attribute named |attrName|. /// /*--cef()--*/ - virtual CefString GetElementAttribute(const CefString& attrName) =0; + virtual CefString GetElementAttribute(const CefString& attrName) = 0; /// // Returns a map of all element attributes. /// /*--cef()--*/ - virtual void GetElementAttributes(AttributeMap& attrMap) =0; + virtual void GetElementAttributes(AttributeMap& attrMap) = 0; /// // Set the value for the element attribute named |attrName|. Returns true on @@ -316,19 +314,19 @@ class CefDOMNode : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual bool SetElementAttribute(const CefString& attrName, - const CefString& value) =0; + const CefString& value) = 0; /// // Returns the inner text of the element. /// /*--cef()--*/ - virtual CefString GetElementInnerText() =0; + virtual CefString GetElementInnerText() = 0; /// // Returns the bounds of the element. /// /*--cef()--*/ - virtual CefRect GetElementBounds() =0; + virtual CefRect GetElementBounds() = 0; }; #endif // CEF_INCLUDE_CEF_DOM_H_ diff --git a/src/include/cef_download_handler.h b/src/include/cef_download_handler.h index b32c248e5..dfaeba500 100644 --- a/src/include/cef_download_handler.h +++ b/src/include/cef_download_handler.h @@ -42,7 +42,6 @@ #include "include/cef_browser.h" #include "include/cef_download_item.h" - /// // Callback interface used to asynchronously continue a download. /// @@ -56,10 +55,9 @@ class CefBeforeDownloadCallback : public virtual CefBaseRefCounted { // if you do wish to show the default "Save As" dialog. /// /*--cef(capi_name=cont,optional_param=download_path)--*/ - virtual void Continue(const CefString& download_path, bool show_dialog) =0; + virtual void Continue(const CefString& download_path, bool show_dialog) = 0; }; - /// // Callback interface used to asynchronously cancel a download. /// @@ -70,22 +68,21 @@ class CefDownloadItemCallback : public virtual CefBaseRefCounted { // Call to cancel the download. /// /*--cef()--*/ - virtual void Cancel() =0; + virtual void Cancel() = 0; /// // Call to pause the download. /// /*--cef()--*/ - virtual void Pause() =0; + virtual void Pause() = 0; /// // Call to resume the download. /// /*--cef()--*/ - virtual void Resume() =0; + virtual void Resume() = 0; }; - /// // Class used to handle file downloads. The methods of this class will called // on the browser process UI thread. @@ -105,7 +102,7 @@ class CefDownloadHandler : public virtual CefBaseRefCounted { CefRefPtr browser, CefRefPtr download_item, const CefString& suggested_name, - CefRefPtr callback) =0; + CefRefPtr callback) = 0; /// // Called when a download's status or progress information has been updated. @@ -115,10 +112,9 @@ class CefDownloadHandler : public virtual CefBaseRefCounted { // this method. /// /*--cef()--*/ - virtual void OnDownloadUpdated( - CefRefPtr browser, - CefRefPtr download_item, - CefRefPtr callback) {} + virtual void OnDownloadUpdated(CefRefPtr browser, + CefRefPtr download_item, + CefRefPtr callback) {} }; #endif // CEF_INCLUDE_CEF_DOWNLOAD_HANDLER_H_ diff --git a/src/include/cef_download_item.h b/src/include/cef_download_item.h index b0ea797ff..930f53bb4 100644 --- a/src/include/cef_download_item.h +++ b/src/include/cef_download_item.h @@ -51,104 +51,104 @@ class CefDownloadItem : public virtual CefBaseRefCounted { // function returns false. /// /*--cef()--*/ - virtual bool IsValid() =0; + virtual bool IsValid() = 0; /// // Returns true if the download is in progress. /// /*--cef()--*/ - virtual bool IsInProgress() =0; + virtual bool IsInProgress() = 0; /// // Returns true if the download is complete. /// /*--cef()--*/ - virtual bool IsComplete() =0; + virtual bool IsComplete() = 0; /// // Returns true if the download has been canceled or interrupted. /// /*--cef()--*/ - virtual bool IsCanceled() =0; + virtual bool IsCanceled() = 0; /// // Returns a simple speed estimate in bytes/s. /// /*--cef()--*/ - virtual int64 GetCurrentSpeed() =0; + virtual int64 GetCurrentSpeed() = 0; /// // Returns the rough percent complete or -1 if the receive total size is // unknown. /// /*--cef()--*/ - virtual int GetPercentComplete() =0; + virtual int GetPercentComplete() = 0; /// // Returns the total number of bytes. /// /*--cef()--*/ - virtual int64 GetTotalBytes() =0; + virtual int64 GetTotalBytes() = 0; /// // Returns the number of received bytes. /// /*--cef()--*/ - virtual int64 GetReceivedBytes() =0; + virtual int64 GetReceivedBytes() = 0; /// // Returns the time that the download started. /// /*--cef()--*/ - virtual CefTime GetStartTime() =0; + virtual CefTime GetStartTime() = 0; /// // Returns the time that the download ended. /// /*--cef()--*/ - virtual CefTime GetEndTime() =0; + virtual CefTime GetEndTime() = 0; /// // Returns the full path to the downloaded or downloading file. /// /*--cef()--*/ - virtual CefString GetFullPath() =0; + virtual CefString GetFullPath() = 0; /// // Returns the unique identifier for this download. /// /*--cef()--*/ - virtual uint32 GetId() =0; + virtual uint32 GetId() = 0; /// // Returns the URL. /// /*--cef()--*/ - virtual CefString GetURL() =0; + virtual CefString GetURL() = 0; /// // Returns the original URL before any redirections. /// /*--cef()--*/ - virtual CefString GetOriginalUrl() =0; + virtual CefString GetOriginalUrl() = 0; /// // Returns the suggested file name. /// /*--cef()--*/ - virtual CefString GetSuggestedFileName() =0; + virtual CefString GetSuggestedFileName() = 0; /// // Returns the content disposition. /// /*--cef()--*/ - virtual CefString GetContentDisposition() =0; + virtual CefString GetContentDisposition() = 0; /// // Returns the mime type. /// /*--cef()--*/ - virtual CefString GetMimeType() =0; + virtual CefString GetMimeType() = 0; }; #endif // CEF_INCLUDE_CEF_DOWNLOAD_ITEM_H_ diff --git a/src/include/cef_drag_data.h b/src/include/cef_drag_data.h index de37ecc46..35661f870 100644 --- a/src/include/cef_drag_data.h +++ b/src/include/cef_drag_data.h @@ -38,10 +38,10 @@ #define CEF_INCLUDE_CEF_DRAG_DATA_H_ #pragma once +#include #include "include/cef_base.h" #include "include/cef_image.h" #include "include/cef_stream.h" -#include /// // Class used to represent drag data. The methods of this class may be called @@ -60,74 +60,74 @@ class CefDragData : public virtual CefBaseRefCounted { // Returns a copy of the current object. /// /*--cef()--*/ - virtual CefRefPtr Clone() =0; + virtual CefRefPtr Clone() = 0; /// // Returns true if this object is read-only. /// /*--cef()--*/ - virtual bool IsReadOnly() =0; + virtual bool IsReadOnly() = 0; /// // Returns true if the drag data is a link. /// /*--cef()--*/ - virtual bool IsLink() =0; + virtual bool IsLink() = 0; /// // Returns true if the drag data is a text or html fragment. /// /*--cef()--*/ - virtual bool IsFragment() =0; + virtual bool IsFragment() = 0; /// // Returns true if the drag data is a file. /// /*--cef()--*/ - virtual bool IsFile() =0; + virtual bool IsFile() = 0; /// // Return the link URL that is being dragged. /// /*--cef()--*/ - virtual CefString GetLinkURL() =0; + virtual CefString GetLinkURL() = 0; /// // Return the title associated with the link being dragged. /// /*--cef()--*/ - virtual CefString GetLinkTitle() =0; + virtual CefString GetLinkTitle() = 0; /// // Return the metadata, if any, associated with the link being dragged. /// /*--cef()--*/ - virtual CefString GetLinkMetadata() =0; + virtual CefString GetLinkMetadata() = 0; /// // Return the plain text fragment that is being dragged. /// /*--cef()--*/ - virtual CefString GetFragmentText() =0; + virtual CefString GetFragmentText() = 0; /// // Return the text/html fragment that is being dragged. /// /*--cef()--*/ - virtual CefString GetFragmentHtml() =0; + virtual CefString GetFragmentHtml() = 0; /// // Return the base URL that the fragment came from. This value is used for // resolving relative URLs and may be empty. /// /*--cef()--*/ - virtual CefString GetFragmentBaseURL() =0; + virtual CefString GetFragmentBaseURL() = 0; /// // Return the name of the file being dragged out of the browser window. /// /*--cef()--*/ - virtual CefString GetFileName() =0; + virtual CefString GetFileName() = 0; /// // Write the contents of the file being dragged out of the web view into @@ -136,50 +136,50 @@ class CefDragData : public virtual CefBaseRefCounted { // Call GetFileName() to get a suggested name for the file. /// /*--cef(optional_param=writer)--*/ - virtual size_t GetFileContents(CefRefPtr writer) =0; + virtual size_t GetFileContents(CefRefPtr writer) = 0; /// // Retrieve the list of file names that are being dragged into the browser // window. /// /*--cef()--*/ - virtual bool GetFileNames(std::vector& names) =0; + virtual bool GetFileNames(std::vector& names) = 0; /// // Set the link URL that is being dragged. /// /*--cef(optional_param=url)--*/ - virtual void SetLinkURL(const CefString& url) =0; + virtual void SetLinkURL(const CefString& url) = 0; /// // Set the title associated with the link being dragged. /// /*--cef(optional_param=title)--*/ - virtual void SetLinkTitle(const CefString& title) =0; + virtual void SetLinkTitle(const CefString& title) = 0; /// // Set the metadata associated with the link being dragged. /// /*--cef(optional_param=data)--*/ - virtual void SetLinkMetadata(const CefString& data) =0; + virtual void SetLinkMetadata(const CefString& data) = 0; /// // Set the plain text fragment that is being dragged. /// /*--cef(optional_param=text)--*/ - virtual void SetFragmentText(const CefString& text) =0; + virtual void SetFragmentText(const CefString& text) = 0; /// // Set the text/html fragment that is being dragged. /// /*--cef(optional_param=html)--*/ - virtual void SetFragmentHtml(const CefString& html) =0; + virtual void SetFragmentHtml(const CefString& html) = 0; /// // Set the base URL that the fragment came from. /// /*--cef(optional_param=base_url)--*/ - virtual void SetFragmentBaseURL(const CefString& base_url) =0; + virtual void SetFragmentBaseURL(const CefString& base_url) = 0; /// // Reset the file contents. You should do this before calling @@ -187,31 +187,33 @@ class CefDragData : public virtual CefBaseRefCounted { // drag in this kind of data. /// /*--cef()--*/ - virtual void ResetFileContents() =0; + virtual void ResetFileContents() = 0; /// // Add a file that is being dragged into the webview. /// /*--cef(optional_param=display_name)--*/ - virtual void AddFile(const CefString& path, const CefString& display_name) =0; + virtual void AddFile(const CefString& path, + const CefString& display_name) = 0; /// - // Get image representation of drag data (may be NULL). + // Get the image representation of drag data. May return NULL if no image + // representation is available. /// /*--cef()--*/ - virtual CefRefPtr GetImage() =0; + virtual CefRefPtr GetImage() = 0; /// - // Get image hotspot (drag start location relative to image dimensions). + // Get the image hotspot (drag start location relative to image dimensions). /// /*--cef()--*/ - virtual CefPoint GetImageHotspot() =0; + virtual CefPoint GetImageHotspot() = 0; /// - // Whether image representation of drag data is available. + // Returns true if an image representation of drag data is available. /// /*--cef()--*/ - virtual bool HasImage() =0; + virtual bool HasImage() = 0; }; #endif // CEF_INCLUDE_CEF_DRAG_DATA_H_ diff --git a/src/include/cef_drag_handler.h b/src/include/cef_drag_handler.h index aee013668..0410c0d8d 100644 --- a/src/include/cef_drag_handler.h +++ b/src/include/cef_drag_handler.h @@ -39,8 +39,8 @@ #pragma once #include "include/cef_base.h" -#include "include/cef_drag_data.h" #include "include/cef_browser.h" +#include "include/cef_drag_data.h" /// // Implement this interface to handle events related to dragging. The methods of @@ -60,7 +60,9 @@ class CefDragHandler : public virtual CefBaseRefCounted { /*--cef()--*/ virtual bool OnDragEnter(CefRefPtr browser, CefRefPtr dragData, - DragOperationsMask mask) { return false; } + DragOperationsMask mask) { + return false; + } /// // Called whenever draggable regions for the browser window change. These can diff --git a/src/include/cef_extension.h b/src/include/cef_extension.h new file mode 100644 index 000000000..c34d01326 --- /dev/null +++ b/src/include/cef_extension.h @@ -0,0 +1,117 @@ +// Copyright (c) 2017 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_EXTENSION_H_ +#define CEF_INCLUDE_CEF_EXTENSION_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_values.h" + +class CefExtensionHandler; +class CefRequestContext; + +/// +// Object representing an extension. Methods may be called on any thread unless +// otherwise indicated. +/// +/*--cef(source=library)--*/ +class CefExtension : public CefBaseRefCounted { + public: + /// + // Returns the unique extension identifier. This is calculated based on the + // extension public key, if available, or on the extension path. See + // https://developer.chrome.com/extensions/manifest/key for details. + /// + /*--cef()--*/ + virtual CefString GetIdentifier() = 0; + + /// + // Returns the absolute path to the extension directory on disk. This value + // will be prefixed with PK_DIR_RESOURCES if a relative path was passed to + // CefRequestContext::LoadExtension. + /// + /*--cef()--*/ + virtual CefString GetPath() = 0; + + /// + // Returns the extension manifest contents as a CefDictionaryValue object. See + // https://developer.chrome.com/extensions/manifest for details. + /// + /*--cef()--*/ + virtual CefRefPtr GetManifest() = 0; + + /// + // Returns true if this object is the same extension as |that| object. + // Extensions are considered the same if identifier, path and loader context + // match. + /// + /*--cef()--*/ + virtual bool IsSame(CefRefPtr that) = 0; + + /// + // Returns the handler for this extension. Will return NULL for internal + // extensions or if no handler was passed to CefRequestContext::LoadExtension. + /// + /*--cef()--*/ + virtual CefRefPtr GetHandler() = 0; + + /// + // Returns the request context that loaded this extension. Will return NULL + // for internal extensions or if the extension has been unloaded. See the + // CefRequestContext::LoadExtension documentation for more information about + // loader contexts. Must be called on the browser process UI thread. + /// + /*--cef()--*/ + virtual CefRefPtr GetLoaderContext() = 0; + + /// + // Returns true if this extension is currently loaded. Must be called on the + // browser process UI thread. + /// + /*--cef()--*/ + virtual bool IsLoaded() = 0; + + /// + // Unload this extension if it is not an internal extension and is currently + // loaded. Will result in a call to CefExtensionHandler::OnExtensionUnloaded + // on success. + /// + /*--cef()--*/ + virtual void Unload() = 0; +}; + +#endif // CEF_INCLUDE_CEF_EXTENSION_H_ diff --git a/src/include/cef_extension_handler.h b/src/include/cef_extension_handler.h new file mode 100644 index 000000000..7b0b86a36 --- /dev/null +++ b/src/include/cef_extension_handler.h @@ -0,0 +1,199 @@ +// Copyright (c) 2017 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_EXTENSION_HANDLER_H_ +#define CEF_INCLUDE_CEF_EXTENSION_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_extension.h" +#include "include/cef_stream.h" + +class CefClient; + +/// +// Callback interface used for asynchronous continuation of +// CefExtensionHandler::GetExtensionResource. +/// +/*--cef(source=library)--*/ +class CefGetExtensionResourceCallback : public CefBaseRefCounted { + public: + /// + // Continue the request. Read the resource contents from |stream|. + /// + /*--cef(capi_name=cont,optional_param=stream)--*/ + virtual void Continue(CefRefPtr stream) = 0; + + /// + // Cancel the request. + /// + /*--cef()--*/ + virtual void Cancel() = 0; +}; + +/// +// Implement this interface to handle events related to browser extensions. +// The methods of this class will be called on the UI thread. See +// CefRequestContext::LoadExtension for information about extension loading. +/// +/*--cef(source=client)--*/ +class CefExtensionHandler : public virtual CefBaseRefCounted { + public: + /// + // Called if the CefRequestContext::LoadExtension request fails. |result| will + // be the error code. + /// + /*--cef()--*/ + virtual void OnExtensionLoadFailed(cef_errorcode_t result) {} + + /// + // Called if the CefRequestContext::LoadExtension request succeeds. + // |extension| is the loaded extension. + /// + /*--cef()--*/ + virtual void OnExtensionLoaded(CefRefPtr extension) {} + + /// + // Called after the CefExtension::Unload request has completed. + /// + /*--cef()--*/ + virtual void OnExtensionUnloaded(CefRefPtr extension) {} + + /// + // Called when an extension needs a browser to host a background script + // specified via the "background" manifest key. The browser will have no + // visible window and cannot be displayed. |extension| is the extension that + // is loading the background script. |url| is an internally generated + // reference to an HTML page that will be used to load the background script + // via a + + +""" + + +class RequestHandler: + def GetResourceHandler(self, browser, frame, request): + print(request.GetPostData()) + return None + +def main(): + sys.excepthook = cef.ExceptHook + cef.Initialize() + browser = cef.CreateBrowserSync(url=cef.GetDataUrl(html)) + browser.SetClientHandler(RequestHandler()) + cef.MessageLoop() + del browser + cef.Shutdown() + + +if __name__ == '__main__': + main() diff --git a/unittests/main_test.py b/unittests/main_test.py index d7a2fbf95..ce71af20f 100644 --- a/unittests/main_test.py +++ b/unittests/main_test.py @@ -7,14 +7,14 @@ import unittest # noinspection PyUnresolvedReferences import _test_runner -from os.path import basename +from _common import * + from cefpython3 import cefpython as cef -import time -import base64 + +import glob +import os import sys -# To show the window for an extended period of time increase this number. -MESSAGE_LOOP_RANGE = 200 # each iteration is 0.01 sec g_datauri_data = """ @@ -25,6 +25,10 @@ font-family: Arial; font-size: 11pt; } + body { + width: 810px; + heiht: 610px; + } @@ -86,25 +113,14 @@ """ -g_datauri = "data:text/html;base64,"+base64.b64encode(g_datauri_data.encode( - "utf-8", "replace")).decode("utf-8", "replace") - -g_subtests_ran = 0 - - -def subtest_message(message): - global g_subtests_ran - g_subtests_ran += 1 - print(str(g_subtests_ran) + ". " + message) - sys.stdout.flush() +g_datauri = cef.GetDataUrl(g_datauri_data) class MainTest_IsolatedTest(unittest.TestCase): - def test_main(self): - """Main entry point.""" - # All this code must run inside one single test, otherwise strange - # things happen. + """Main entry point. All the code must run inside one + single test, otherwise strange things happen.""" + print("") print("CEF Python {ver}".format(ver=cef.__version__)) print("Python {ver}".format(ver=sys.version[:6])) @@ -115,186 +131,250 @@ def test_main(self): "log_severity": cef.LOGSEVERITY_ERROR, "log_file": "", } + if not LINUX: + # On Linux you get a lot of "X error received" messages + # from Chromium's "x11_util.cc", so do not show them. + settings["log_severity"] = cef.LOGSEVERITY_WARNING if "--debug" in sys.argv: settings["debug"] = True settings["log_severity"] = cef.LOGSEVERITY_INFO + if "--debug-warning" in sys.argv: + settings["debug"] = True + settings["log_severity"] = cef.LOGSEVERITY_WARNING cef.Initialize(settings) subtest_message("cef.Initialize() ok") - # Test global handler + # CRL set file + certrevoc_dir = "" + if WINDOWS: + certrevoc_dir = r"C:\localappdata\Google\Chrome\User Data" \ + r"\CertificateRevocation" + elif LINUX: + certrevoc_dir = r"/home/*/.config/google-chrome" \ + r"/CertificateRevocation" + elif MAC: + certrevoc_dir = r"/Users/*/Library/Application Support/Google" \ + r"/Chrome/CertificateRevocation" + crlset_files = glob.iglob(os.path.join(certrevoc_dir, "*", + "crl-set")) + crlset = "" + for crlset in crlset_files: + pass + if os.path.exists(crlset): + cef.LoadCrlSetsFile(crlset) + subtest_message("cef.LoadCrlSetsFile ok") + + # High DPI on Windows. + # Setting DPI awareness from Python is usually too late and should be done + # via manifest file. Alternatively change python.exe properties > Compatibility + # > High DPI scaling override > Application. + # Using cef.DpiAware.EnableHighDpiSupport is problematic, it can cause + # display glitches. + if WINDOWS: + self.assertIsInstance(cef.DpiAware.GetSystemDpi(), tuple) + window_size = cef.DpiAware.CalculateWindowSize(800, 600) + self.assertIsInstance(window_size, tuple) + self.assertGreater(window_size[0], 0) + self.assertGreater(cef.DpiAware.Scale((800, 600))[0], 0) + + # OFF - see comments above. + # cef.DpiAware.EnableHighDpiSupport() + # self.assertTrue(cef.DpiAware.IsProcessDpiAware()) + + # Make some calls again after DPI Aware was set + self.assertIsInstance(cef.DpiAware.GetSystemDpi(), tuple) + self.assertGreater(cef.DpiAware.Scale([800, 600])[0], 0) + self.assertIsInstance(cef.DpiAware.Scale(800), int) + self.assertGreater(cef.DpiAware.Scale(800), 0) + subtest_message("cef.DpiAware ok") + + # Global handler global_handler = GlobalHandler(self) cef.SetGlobalClientCallback("OnAfterCreated", global_handler._OnAfterCreated) subtest_message("cef.SetGlobalClientCallback() ok") - # Test creation of browser - browser = cef.CreateBrowserSync(url=g_datauri) + # Create browser + browser_settings = { + "inherit_client_handlers_for_popups": False, + } + browser = cef.CreateBrowserSync(url=g_datauri, + settings=browser_settings) self.assertIsNotNone(browser, "Browser object") + browser.SetFocus(True) subtest_message("cef.CreateBrowserSync() ok") - # Test other handlers: LoadHandler, DisplayHandler etc. - client_handlers = [LoadHandler(self), DisplayHandler(self)] + # Client handlers + display_handler2 = DisplayHandler2(self) + v8context_handler = V8ContextHandler(self) + client_handlers = [LoadHandler(self, g_datauri), + DisplayHandler(self), + display_handler2, + v8context_handler] for handler in client_handlers: browser.SetClientHandler(handler) subtest_message("browser.SetClientHandler() ok") - # Test javascript bindings + # Javascript bindings external = External(self) bindings = cef.JavascriptBindings( bindToFrames=False, bindToPopups=False) + bindings.SetFunction("js_code_completed", js_code_completed) bindings.SetFunction("test_function", external.test_function) bindings.SetProperty("test_property1", external.test_property1) bindings.SetProperty("test_property2", external.test_property2) + # Property with a function value can also be bound. CEF Python + # supports passing functions as callbacks when called from + # javascript, and as a side effect any value and in this case + # a property can also be a function. + bindings.SetProperty("test_property3_function", + external.test_property3_function) bindings.SetProperty("cefpython_version", cef.GetVersion()) bindings.SetObject("external", external) browser.SetJavascriptBindings(bindings) subtest_message("browser.SetJavascriptBindings() ok") - # Run message loop for some time. - # noinspection PyTypeChecker - for i in range(MESSAGE_LOOP_RANGE): - cef.MessageLoopWork() - time.sleep(0.01) - subtest_message("cef.MessageLoopWork() ok") - - # Test browser closing. Remember to clean reference. + # Set auto resize. Call it after js bindings were set. + browser.SetAutoResizeEnabled(enabled=True, + min_size=[800, 600], + max_size=[1024, 768]) + subtest_message("browser.SetAutoResizeEnabled() ok") + + # Test Request.SetPostData(list) + # noinspection PyArgumentList + req = cef.Request.CreateRequest() + req_file = os.path.dirname(os.path.abspath(__file__)) + req_file = os.path.join(req_file, "main_test.py") + if sys.version_info.major > 2: + req_file = req_file.encode("utf-8") + req_data = [b"--key=value", b"@"+req_file] + req.SetMethod("POST") + req.SetPostData(req_data) + self.assertEqual(req_data, req.GetPostData()) + subtest_message("cef.Request.SetPostData(list) ok") + + # Test Request.SetPostData(dict) + # noinspection PyArgumentList + req = cef.Request.CreateRequest() + req_data = {b"key": b"value"} + req.SetMethod("POST") + req.SetPostData(req_data) + self.assertEqual(req_data, req.GetPostData()) + subtest_message("cef.Request.SetPostData(dict) ok") + + # Cookie manager + self.assertIsInstance(cef.CookieManager.CreateManager(path=""), + cef.PyCookieManager) + self.assertIsInstance(cef.CookieManager.GetGlobalManager(), + cef.PyCookieManager) + self.assertIsInstance(cef.CookieManager.GetBlockingManager(), + cef.PyCookieManager) + subtest_message("cef.CookieManager ok") + + # Window Utils + if WINDOWS: + hwnd = 1 # When using 0 getting issues with OnautoResize + self.assertFalse(cef.WindowUtils.IsWindowHandle(hwnd)) + cef.WindowUtils.OnSetFocus(hwnd, 0, 0, 0) + cef.WindowUtils.OnSize(hwnd, 0, 0, 0) + cef.WindowUtils.OnEraseBackground(hwnd, 0, 0, 0) + cef.WindowUtils.GetParentHandle(hwnd) + cef.WindowUtils.SetTitle(browser, "Main test") + subtest_message("cef.WindowUtils ok") + elif LINUX: + cef.WindowUtils.InstallX11ErrorHandlers() + subtest_message("cef.WindowUtils ok") + elif MAC: + hwnd = 0 + cef.WindowUtils.GetParentHandle(hwnd) + cef.WindowUtils.IsWindowHandle(hwnd) + subtest_message("cef.WindowUtils ok") + + # Run message loop + run_message_loop() + + # Make sure popup browser was destroyed + self.assertIsInstance(cef.GetBrowserByIdentifier(MAIN_BROWSER_ID), + cef.PyBrowser) + self.assertIsNone(cef.GetBrowserByIdentifier(POPUP_BROWSER_ID)) + subtest_message("cef.GetBrowserByIdentifier() ok") + + # Close browser and clean reference browser.CloseBrowser(True) del browser subtest_message("browser.CloseBrowser() ok") - # Give it some time to close before calling shutdown. + # Give it some time to close before checking asserts + # and calling shutdown. + do_message_loop_work(25) + + # Asserts before shutdown + self.assertEqual(display_handler2.OnLoadingProgressChange_Progress, + 1.0) # noinspection PyTypeChecker - for i in range(25): - cef.MessageLoopWork() - time.sleep(0.01) - - # Automatic check of asserts in handlers and in external - for obj in [] + client_handlers + [global_handler, external]: - test_for_True = False # Test whether asserts are working correctly - for key, value in obj.__dict__.items(): - if key == "test_for_True": - test_for_True = True - continue - if "_True" in key: - self.assertTrue(value, "Check assert: " + - obj.__class__.__name__ + "." + key) - subtest_message(obj.__class__.__name__ + "." + - key.replace("_True", "") + - " ok") - elif "_False" in key: - self.assertFalse(value, "Check assert: " + - obj.__class__.__name__ + "." + key) - subtest_message(obj.__class__.__name__ + "." + - key.replace("_False", "") + - " ok") - self.assertTrue(test_for_True) + check_auto_asserts(self, [] + client_handlers + + [global_handler, + external]) # Test shutdown of CEF cef.Shutdown() subtest_message("cef.Shutdown() ok") - # Display real number of tests there were run - print("\nRan " + str(g_subtests_ran) + " sub-tests in test_main") + # Display summary + show_test_summary(__file__) sys.stdout.flush() -class GlobalHandler(object): - def __init__(self, test_case): - self.test_case = test_case - - # Asserts for True/False will be checked just before shutdown - self.test_for_True = True # Test whether asserts are working correctly - self.OnAfterCreated_True = False - - def _OnAfterCreated(self, browser, **_): - # For asserts that are checked automatically before shutdown its - # values should be set first, so that when other asserts fail - # (the ones called through the test_case member) they are reported - # correctly. - self.test_case.assertFalse(self.OnAfterCreated_True) - self.OnAfterCreated_True = True - self.test_case.assertEqual(browser.GetIdentifier(), 1) - - -class LoadHandler(object): +class DisplayHandler2(object): def __init__(self, test_case): self.test_case = test_case - self.frame_source_visitor = None - - # Asserts for True/False will be checked just before shutdown - self.test_for_True = True # Test whether asserts are working correctly - self.OnLoadStart_True = False - self.OnLoadEnd_True = False - self.FrameSourceVisitor_True = False - # self.OnLoadingStateChange_Start_True = False # FAILS - self.OnLoadingStateChange_End_True = False - - def OnLoadStart(self, browser, frame, **_): - self.test_case.assertFalse(self.OnLoadStart_True) - self.OnLoadStart_True = True - self.test_case.assertEqual(browser.GetUrl(), frame.GetUrl()) - self.test_case.assertEqual(browser.GetUrl(), g_datauri) - - def OnLoadEnd(self, browser, frame, http_code, **_): - # OnLoadEnd should be called only once - self.test_case.assertFalse(self.OnLoadEnd_True) - self.OnLoadEnd_True = True - self.test_case.assertEqual(http_code, 200) - self.frame_source_visitor = FrameSourceVisitor(self, self.test_case) - frame.GetSource(self.frame_source_visitor) - browser.ExecuteJavascript("print('LoadHandler.OnLoadEnd() ok')") - - def OnLoadingStateChange(self, browser, is_loading, can_go_back, - can_go_forward, **_): - if is_loading: - # TODO: this test fails, looks like OnLoadingStaetChange with - # is_loading=False is being called very fast, before - # OnLoadStart and before client handler is set by calling - # browser.SetClientHandler(). - # SOLUTION: allow to set OnLoadingStateChange through - # SetGlobalClientCallback similarly to _OnAfterCreated(). - # self.test_case.assertFalse(self.OnLoadingStateChange_Start_True) - # self.OnLoadingStateChange_Start_True = True - pass - else: - self.test_case.assertFalse(self.OnLoadingStateChange_End_True) - self.OnLoadingStateChange_End_True = True - self.test_case.assertEqual(browser.CanGoBack(), can_go_back) - self.test_case.assertEqual(browser.CanGoForward(), can_go_forward) - - -class DisplayHandler(object): + # Asserts for True/False will be checked just before shutdown. + # Test whether asserts are working correctly. + self.test_for_True = True + self.OnAutoResize_True = False + self.OnLoadingProgressChange_True = False + self.OnLoadingProgressChange_Progress = 0.0 + + def OnAutoResize(self, new_size, **_): + self.OnAutoResize_True = True + self.test_case.assertGreaterEqual(new_size[0], 800) + self.test_case.assertLessEqual(new_size[0], 1024) + self.test_case.assertGreaterEqual(new_size[1], 600) + self.test_case.assertLessEqual(new_size[1], 768) + + def OnLoadingProgressChange(self, progress, **_): + self.OnLoadingProgressChange_True = True + self.OnLoadingProgressChange_Progress = progress + + +class V8ContextHandler(object): def __init__(self, test_case): self.test_case = test_case - - # Asserts for True/False will be checked just before shutdown - self.test_for_True = True # Test whether asserts are working correctly - self.javascript_errors_False = False - self.OnConsoleMessage_True = False - - def OnConsoleMessage(self, message, **_): - if "error" in message.lower() or "uncaught" in message.lower(): - self.javascript_errors_False = True - raise Exception(message) + self.OnContextCreatedFirstCall_True = False + self.OnContextCreatedSecondCall_True = False + self.OnContextReleased_True = False + + def OnContextCreated(self, browser, frame): + """CEF creates one context when creating browser and this one is + released immediately. Then when it loads url another context is + created.""" + if not self.OnContextCreatedFirstCall_True: + self.OnContextCreatedFirstCall_True = True else: - # Check whether messages from javascript are coming - self.OnConsoleMessage_True = True - subtest_message(message) - - -class FrameSourceVisitor(object): - """Visitor for Frame.GetSource().""" - - def __init__(self, load_handler, test_case): - self.load_handler = load_handler - self.test_case = test_case - - def Visit(self, **_): - self.test_case.assertFalse(self.load_handler.FrameSourceVisitor_True) - self.load_handler.FrameSourceVisitor_True = True - self.test_case.assertIn("747ef3e6011b6a61e6b3c6e54bdd2dee", - g_datauri_data) - + self.test_case.assertFalse(self.OnContextCreatedSecondCall_True) + self.OnContextCreatedSecondCall_True = True + self.test_case.assertEqual(browser.GetIdentifier(), MAIN_BROWSER_ID) + self.test_case.assertEqual(frame.GetIdentifier(), 2) + + def OnContextReleased(self, browser, frame): + """This gets called only for the initial empty context, see comment + in OnContextCreated. This should never get called for the main frame + of the main browser, because it happens during app exit and there + isn't enough time for the IPC messages to go through.""" + self.test_case.assertFalse(self.OnContextReleased_True) + self.OnContextReleased_True = True + self.test_case.assertEqual(browser.GetIdentifier(), MAIN_BROWSER_ID) + self.test_case.assertEqual(frame.GetIdentifier(), 2) class External(object): """Javascript 'window.external' object.""" @@ -303,13 +383,15 @@ def __init__(self, test_case): self.test_case = test_case # Test binding properties to the 'window' object. + # 2147483648 is out of INT_MAX limit and will be sent to JS as string value. self.test_property1 = "Test binding property to the 'window' object" self.test_property2 = {"key1": self.test_property1, - "key2": ["Inside list", 1, 2]} + "key2": ["Inside list", 2147483647, 2147483648]} # Asserts for True/False will be checked just before shutdown self.test_for_True = True # Test whether asserts are working correctly self.test_function_True = False + self.test_property3_function_True = False self.test_callbacks_True = False self.py_callback_True = False @@ -317,6 +399,10 @@ def test_function(self): """Test binding function to the 'window' object.""" self.test_function_True = True + def test_property3_function(self): + """Test binding function to the 'window' object.""" + self.test_property3_function_True = True + def test_callbacks(self, js_callback): """Test both javascript and python callbacks.""" def py_callback(msg_from_js): @@ -328,4 +414,4 @@ def py_callback(msg_from_js): if __name__ == "__main__": - _test_runner.main(basename(__file__)) + _test_runner.main(os.path.basename(__file__)) diff --git a/unittests/osr_test.py b/unittests/osr_test.py new file mode 100644 index 000000000..672e98fe5 --- /dev/null +++ b/unittests/osr_test.py @@ -0,0 +1,275 @@ +# Copyright (c) 2018 CEF Python, see the Authors file. +# All rights reserved. Licensed under BSD 3-clause license. +# Project website: https://github.com/cztomczak/cefpython + +"""Off-screen rendering tests.""" + +import unittest +# noinspection PyUnresolvedReferences +import _test_runner +from _common import * + +from cefpython3 import cefpython as cef + +import sys + +g_datauri_data = """ + + + + + + + + + +

Off-screen rendering test

+
+
Test selection.
+ + +""" +g_datauri = cef.GetDataUrl(g_datauri_data) + + +class OsrTest_IsolatedTest(unittest.TestCase): + def test_osr(self): + """Main entry point. All the code must run inside one + single test, otherwise strange things happen.""" + + print("") + print("CEF Python {ver}".format(ver=cef.__version__)) + print("Python {ver}".format(ver=sys.version[:6])) + + # Application settings + settings = { + "debug": False, + "log_severity": cef.LOGSEVERITY_ERROR, + "log_file": "", + "windowless_rendering_enabled": True + } + if not LINUX: + # On Linux you get a lot of "X error received" messages + # from Chromium's "x11_util.cc", so do not show them. + settings["log_severity"] = cef.LOGSEVERITY_WARNING + if "--debug" in sys.argv: + settings["debug"] = True + settings["log_severity"] = cef.LOGSEVERITY_INFO + if "--debug-warning" in sys.argv: + settings["debug"] = True + settings["log_severity"] = cef.LOGSEVERITY_WARNING + + switches = { + # GPU acceleration is not supported in OSR mode, so must disable + # it using these Chromium switches (Issue #240 and #463) + "disable-gpu": "", + "disable-gpu-compositing": "", + # Tweaking OSR performance by setting the same Chromium flags + # as in upstream cefclient (Issue #240). + "enable-begin-frame-scheduling": "", + "disable-surfaces": "", # This is required for PDF ext to work + } + browser_settings = { + # Tweaking OSR performance (Issue #240) + "windowless_frame_rate": 30, # Default frame rate in CEF is 30 + } + + # Initialize + cef.Initialize(settings=settings, switches=switches) + subtest_message("cef.Initialize() ok") + + # Accessibility handler + accessibility_handler = AccessibilityHandler(self) + cef.SetGlobalClientHandler(accessibility_handler) + subtest_message("cef.SetGlobalClientHandler() ok") + + # Global handler + global_handler = GlobalHandler(self) + cef.SetGlobalClientCallback("OnAfterCreated", + global_handler._OnAfterCreated) + subtest_message("cef.SetGlobalClientCallback() ok") + + # Create browser + window_info = cef.WindowInfo() + window_info.SetAsOffscreen(0) + browser = cef.CreateBrowserSync(window_info=window_info, + settings=browser_settings, + url=g_datauri) + + # Javascript bindings + bindings = cef.JavascriptBindings( + bindToFrames=False, bindToPopups=False) + bindings.SetFunction("js_code_completed", js_code_completed) + bindings.SetProperty("cefpython_version", cef.GetVersion()) + browser.SetJavascriptBindings(bindings) + subtest_message("browser.SetJavascriptBindings() ok") + + # Enable accessibility + browser.SetAccessibilityState(cef.STATE_ENABLED) + subtest_message("cef.SetAccessibilityState(STATE_ENABLED) ok") + + # Client handlers + client_handlers = [LoadHandler(self, g_datauri), + DisplayHandler(self), + RenderHandler(self)] + for handler in client_handlers: + browser.SetClientHandler(handler) + + # Initiate OSR rendering + browser.SendFocusEvent(True) + browser.WasResized() + + # Test selection + on_load_end(select_h1_text, browser) + + # Message loop + run_message_loop() + + # Close browser and clean reference + browser.CloseBrowser(True) + del browser + subtest_message("browser.CloseBrowser() ok") + + # Give it some time to close before checking asserts + # and calling shutdown. + do_message_loop_work(25) + + # Asserts before shutdown + # noinspection PyTypeChecker + check_auto_asserts(self, [] + client_handlers + + [global_handler, + accessibility_handler]) + + # Test shutdown of CEF + cef.Shutdown() + subtest_message("cef.Shutdown() ok") + + # Display summary + show_test_summary(__file__) + sys.stdout.flush() + + +class AccessibilityHandler(object): + def __init__(self, test_case): + self.test_case = test_case + + # Asserts for True/False will be checked just before shutdown. + # Test whether asserts are working correctly. + self.test_for_True = True + + self.javascript_errors_False = False + self._OnAccessibilityTreeChange_True = False + self._OnAccessibilityLocationChange_True = False + self.loadComplete_True = False + self.layoutComplete_True = False + + def _OnAccessibilityTreeChange(self, value): + self._OnAccessibilityTreeChange_True = True + for event in value: + if "event_type" in event: + if event["event_type"] == "loadComplete": + # LoadHandler.OnLoadEnd is called after this event + self.test_case.assertFalse(self.loadComplete_True) + self.loadComplete_True = True + elif event["event_type"] == "layoutComplete": + # layoutComplete event occurs twice, one when a blank + # page is loaded and second time when loading datauri. + if self.loadComplete_True: + self.test_case.assertFalse(self.layoutComplete_True) + self.layoutComplete_True = True + + def _OnAccessibilityLocationChange(self, **_): + self._OnAccessibilityLocationChange_True = True + + +def select_h1_text(browser): + browser.SendMouseClickEvent(0, 0, cef.MOUSEBUTTON_LEFT, + mouseUp=False, clickCount=1) + browser.SendMouseMoveEvent(400, 20, mouseLeave=False, + modifiers=cef.EVENTFLAG_LEFT_MOUSE_BUTTON) + browser.SendMouseClickEvent(400, 20, cef.MOUSEBUTTON_LEFT, + mouseUp=True, clickCount=1) + browser.Invalidate(cef.PET_VIEW) + subtest_message("select_h1_text() ok") + + +class RenderHandler(object): + def __init__(self, test_case): + self.test_case = test_case + + # Asserts for True/False will be checked just before shutdown. + # Test whether asserts are working correctly. + self.test_for_True = True + + self.GetViewRect_True = False + self.OnPaint_True = False + self.OnTextSelectionChanged_True = False + + def GetViewRect(self, rect_out, **_): + """Called to retrieve the view rectangle which is relative + to screen coordinates. Return True if the rectangle was + provided.""" + # rect_out --> [x, y, width, height] + self.GetViewRect_True = True + rect_out.extend([0, 0, 800, 600]) + return True + + def OnPaint(self, element_type, paint_buffer, **_): + """Called when an element should be painted.""" + if element_type == cef.PET_VIEW: + self.test_case.assertEqual(paint_buffer.width, 800) + self.test_case.assertEqual(paint_buffer.height, 600) + if not self.OnPaint_True: + self.OnPaint_True = True + subtest_message("RenderHandler.OnPaint: viewport ok") + else: + raise Exception("Unsupported element_type in OnPaint") + + def OnTextSelectionChanged(self, selected_text, selected_range, **_): + if not self.OnTextSelectionChanged_True: + self.OnTextSelectionChanged_True = True + # First call + self.test_case.assertEqual(selected_text, "") + self.test_case.assertEqual(selected_range, [0, 0]) + else: + # Second call. + #

tag should be selected. + self.test_case.assertEqual(selected_text, + "Off-screen rendering test") + + +if __name__ == "__main__": + _test_runner.main(os.path.basename(__file__))