cefsimple 源码剖析

cefsimple源码分析

从前面文章我们已经知道怎么编译属于自己的CEF工程了,下面我们就拿最基础的工程cefsimple代码分析,做一个简短的Cef入门学习。
首先我们从函数入口开始跟踪学习Cef运行流程(至于Cef多进程调试我们放在后面文章研究),首先我们查看cefsimple_win.cc代码:

 UNREFERENCED_PARAMETER(hPrevInstance);
 UNREFERENCED_PARAMETER(lpCmdLine);
 
#宏展开和注释说明
// Use DBG_UNREFERENCED_PARAMETER() when a parameter is not yet
// referenced but will be once the module is completely developed

#define UNREFERENCED_PARAMETER(P)          \
    /*lint -save -e527 -e530 */ \
    { \
        (P) = (P); \
    } \

从上述我们可以看出,这个宏是为了消除编译警告(变量未被使用),防止产生错误(视警告为错误)。

紧接着调用 CefEnableHighDPISupport()

///
// Call during process startup to enable High-DPI support on Windows 7 or newer.
// Older versions of Windows should be left DPI-unaware because they do not
// support DirectWrite and GDI fonts are kerned very badly.
///
/*--cef(capi_name=cef_enable_highdpi_support)--*/
void CefEnableHighDPISupport();

这里主要是为了适应屏幕DPI(Dots Per Inch,每英寸点数,是一个量度单位,用于点阵数码影像,指每一英寸长度中,取样、可显示或输出点的数目)。所以说白了就是优化屏幕显示。

下面才是CEF的重点(CEF沙箱机制放在后面单独讲解,所以关于沙箱机制这一块先不管),CefExecuteProcess() 等价于下面这段代码

  //根据命令行的进程参数类型来创建对应的进程,当时Browser进程的时候返回-1
  // Parse command-line arguments.
  CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
  command_line->InitFromString(::GetCommandLineW());
 
  // Create a ClientApp of the correct type.
  CefRefPtr<CefApp> app;
  ClientApp::ProcessType process_type = ClientApp::GetProcessType(command_line);
  if (process_type == ClientApp::BrowserProcess)
    app = new ClientAppBrowser();
  else if (process_type == ClientApp::RendererProcess)
    app = new ClientAppRenderer();
  else if (process_type == ClientApp::OtherProcess)
    app = new ClientAppOther();
///
// This function should be called from the application entry point function to
// execute a secondary process. It can be used to run secondary processes from
// the browser client executable (default behavior) or from a separate
// executable specified by the CefSettings.browser_subprocess_path value. If
// called for the browser process (identified by no "type" command-line value)
// it will return immediately with a value of -1. If called for a recognized
// secondary process it will block until the process should exit and then return
// the process exit code. The |application| parameter may be empty. The
// |windows_sandbox_info| parameter is only used on Windows and may be NULL (see
// cef_sandbox_win.h for details).
///
/*--cef(api_hash_check,optional_param=application,
        optional_param=windows_sandbox_info)--*/
int CefExecuteProcess(const CefMainArgs& args,
                      CefRefPtr<CefApp> application,
                      void* windows_sandbox_info);

简单的就说如果是浏览器进程调用则立马返回-1,如果是辅助进程调用则阻塞然后返回进程的返回码。

所以这里我们需要判断如果返回码>=0 则不是浏览器进程,应该立马返回。

既然都跳转到了cef_app.h,我们索性看完cef_app.h这个文件的函数说明

// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// The contents of this file must follow a specific format in order to
// support the CEF translator tool. See the translator.README.txt file in the
// tools directory for more information.
//

#ifndef CEF_INCLUDE_CEF_APP_H_
#define CEF_INCLUDE_CEF_APP_H_
#pragma once

#include "include/cef_base.h"
#include "include/cef_browser_process_handler.h"
#include "include/cef_command_line.h"
#include "include/cef_render_process_handler.h"
#include "include/cef_resource_bundle_handler.h"
#include "include/cef_scheme.h"

class CefApp;

///
// This function should be called from the application entry point function to
// execute a secondary process. It can be used to run secondary processes from
// the browser client executable (default behavior) or from a separate
// executable specified by the CefSettings.browser_subprocess_path value. If
// called for the browser process (identified by no "type" command-line value)
// it will return immediately with a value of -1. If called for a recognized
// secondary process it will block until the process should exit and then return
// the process exit code. The |application| parameter may be empty. The
// |windows_sandbox_info| parameter is only used on Windows and may be NULL (see
// cef_sandbox_win.h for details).
///
/*--cef(api_hash_check,optional_param=application,
        optional_param=windows_sandbox_info)--*/ 
int CefExecuteProcess(const CefMainArgs& args,
                      CefRefPtr<CefApp> application,
                      void* windows_sandbox_info);

///
// This function should be called on the main application thread to initialize
// the CEF browser process. The |application| parameter may be empty. A return
// value of true indicates that it succeeded and false indicates that it failed.
// The |windows_sandbox_info| parameter is only used on Windows and may be NULL
// (see cef_sandbox_win.h for details).
///
/*--cef(api_hash_check,optional_param=application,
        optional_param=windows_sandbox_info)--*/
bool CefInitialize(const CefMainArgs& args,
                   const CefSettings& settings,
                   CefRefPtr<CefApp> application,
                   void* windows_sandbox_info);

///
// This function should be called on the main application thread to shut down
// the CEF browser process before the application exits.
///
/*--cef()--*/
void CefShutdown();

///
// Perform a single iteration of CEF message loop processing. This function is
// provided for cases where the CEF message loop must be integrated into an
// existing application message loop. Use of this function is not recommended
// for most users; use either the CefRunMessageLoop() function or
// CefSettings.multi_threaded_message_loop if possible. When using this function
// care must be taken to balance performance against excessive CPU usage. It is
// recommended to enable the CefSettings.external_message_pump option when using
// this function so that CefBrowserProcessHandler::OnScheduleMessagePumpWork()
// callbacks can facilitate the scheduling process. This function should only be
// called on the main application thread and only if CefInitialize() is called
// with a CefSettings.multi_threaded_message_loop value of false. This function
// will not block.
///
/*--cef()--*/
void CefDoMessageLoopWork();

///
// Run the CEF message loop. Use this function instead of an application-
// provided message loop to get the best balance between performance and CPU
// usage. This function should only be called on the main application thread and
// only if CefInitialize() is called with a
// CefSettings.multi_threaded_message_loop value of false. This function will
// block until a quit message is received by the system.
///
/*--cef()--*/
void CefRunMessageLoop();

///
// Quit the CEF message loop that was started by calling CefRunMessageLoop().
// This function should only be called on the main application thread and only
// if CefRunMessageLoop() was used.
///
/*--cef()--*/
void CefQuitMessageLoop();

///
// Set to true before calling Windows APIs like TrackPopupMenu that enter a
// modal message loop. Set to false after exiting the modal message loop.
///
/*--cef()--*/
void CefSetOSModalLoop(bool osModalLoop);

///
// Call during process startup to enable High-DPI support on Windows 7 or newer.
// Older versions of Windows should be left DPI-unaware because they do not
// support DirectWrite and GDI fonts are kerned very badly.
///
/*--cef(capi_name=cef_enable_highdpi_support)--*/
void CefEnableHighDPISupport();

///
// Implement this interface to provide handler implementations. Methods will be
// called by the process and/or thread indicated.
///
/*--cef(source=client,no_debugct_check)--*/
class CefApp : public virtual CefBaseRefCounted {
 public:
  ///
  // Provides an opportunity to view and/or modify command-line arguments before
  // processing by CEF and Chromium. The |process_type| value will be empty for
  // the browser process. Do not keep a reference to the CefCommandLine object
  // passed to this method. The CefSettings.command_line_args_disabled value
  // can be used to start with an empty command-line object. Any values
  // specified in CefSettings that equate to command-line arguments will be set
  // before this method is called. Be cautious when using this method to modify
  // command-line arguments for non-browser processes as this may result in
  // undefined behavior including crashes.
  ///
  /*--cef(optional_param=process_type)--*/
  virtual void OnBeforeCommandLineProcessing(
      const CefString& process_type,
      CefRefPtr<CefCommandLine> command_line) {}

  ///
  // Provides an opportunity to register custom schemes. Do not keep a reference
  // to the |registrar| object. This method is called on the main thread for
  // each process and the registered schemes should be the same across all
  // processes.
  ///
  /*--cef()--*/
  virtual void OnRegisterCustomSchemes(
      CefRawPtr<CefSchemeRegistrar> registrar) {}

  ///
  // Return the handler for resource bundle events. If
  // CefSettings.pack_loading_disabled is true a handler must be returned. If no
  // handler is returned resources will be loaded from pack files. This method
  // is called by the browser and render processes on multiple threads.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefResourceBundleHandler> GetResourceBundleHandler() {
    return NULL;
  }

  ///
  // Return the handler for functionality specific to the browser process. This
  // method is called on multiple threads in the browser process.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler() {
    return NULL;
  }

  ///
  // Return the handler for functionality specific to the render process. This
  // method is called on the render process main thread.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() {
    return NULL;
  }
};

#endif  // CEF_INCLUDE_CEF_APP_H_

全局函数提取

//用于检测是当前进程是否是浏览器进程(main入口函数调用)
int CefExecuteProcess(const CefMainArgs& args, CefRefPtr<CefApp> application, void* windows_sandbox_info);

//主线程里面初始化Cef 浏览器进程信息
bool CefInitialize(const CefMainArgs& args,const CefSettings& settings,CefRefPtr<CefApp> application, void* windows_sandbox_info);

//浏览器进程退出的时候调用
void CefShutdown();

//在CefInitialize之后调用,建议使用CefRunMessageLoop替代CefDoMessageLoopWork,
如果使用此函数那么将会回调CefBrowserProcessHandler::OnScheduleMessagePumpWork()
void CefDoMessageLoopWork();

//运行Cef 消息环,如果调用CefQuitMessageLoop则退出消息环
void CefRunMessageLoop();

//通知cef消息环退出
void CefQuitMessageLoop();

//调用windows Api进入模态消息环之前设置为true,退出模态消息环的时候设置为false,例如TrackPopupMenu
void CefSetOSModalLoop(bool osModalLoop);

//启用高DPI支持
void CefEnableHighDPISupport();

全局函数存在以上几个,并且根据cefsimple_win.cc总结基本调用就是:初始化=》run=》Shutdown,在程序退出的时候QuitMessge和windows消息机制类似。

class CefApp : public virtual CefBaseRefCounted {
 public:
 //提供修改命令行参数的机会
 virtual void OnBeforeCommandLineProcessing(const CefString& process_type,CefRefPtr<CefCommandLine> command_line);
 
 //提供修改注册用户主题的机会
 virtual void OnRegisterCustomSchemes( CefRawPtr<CefSchemeRegistrar> registrar);
 
  //资源包Handler
 virtual CefRefPtr<CefResourceBundleHandler> GetResourceBundleHandler();

//浏览器进程Handler
virtual CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler() ;

//渲染进程Handler
virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler();
 }

CefApp 类分析(重点注意GetxxxHandler,发现凡是我们需要处理对应的Handler,我们则需要继承当前Handler类,并且在该函数里面返回this,当然具体需要继承哪些Handler我们根据业务需求然后查看对应的Handler事件,实际处理。具体有哪些Handler可以被继承则查看GetxxxHandler返回值)

// Implement application-level callbacks for the browser process.
class SimpleApp : public CefApp, public CefBrowserProcessHandler {
 public:
 ...
 virtual CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler()
		  OVERRIDE {
		return this;
	}
  // CefBrowserProcessHandler methods:
  virtual void OnContextInitialized() OVERRIDE;
...
};

回头看看simple_app文件类SimpleApp的实现,是不是一下子清晰明了?俨然按照前面分析的一步步工作的,继承CefBrowserProcessHandler 则重写GetBrowserProcessHandler()返回this。然后在重写CefBrowserProcessHandler的事件OnContextInitialized这个函数做一些浏览器的创建工作。当我们调用CefInitialize初始化Cef浏览器进程信息的时候,该触发OnContextInitialized。

void SimpleApp::OnContextInitialized() {

  CEF_REQUIRE_UI_THREAD();
  ...
  CefRefPtr<CefCommandLine> command_line =CefCommandLine::GetGlobalCommandLine();
  ...
    CefWindowInfo window_info;
    window_info.SetAsPopup(NULL, "cefsimple");
    CefBrowserHost::CreateBrowser(window_info, handler, url, browser_settings,  NULL);
    ...
  }
}

OnContextInitialized则是根据命令行参数创建浏览器显示内容。此时一个简单的CefDemo基本完成。但是这个Demo并没有处理任何事件,只是简简单单的显示了一个网页而已。但是我们在操作的时候发现窗口的标题会随着我们访问的网页不同而变化,所以我们需要关注Cef事件通知,即CefClient。

class SimpleHandler : public CefClient,
                      public CefDisplayHandler,
                      public CefLifeSpanHandler,
                      public CefLoadHandler {
                      ...
                      }

但是who怎么知道需要继承哪些Handler呢?或者who怎么知道有哪些handler可以继承呢?还记得前面分析SimpleApp继承CefApp,CefxxxHandler么?所以我们大胆的猜测SimpleHandler继承CefClient和SimpleApp一样的原理,所以我们不妨看看CefClient头文件:

///
// Implement this interface to provide handler implementations.
///
/*--cef(source=client,no_debugct_check)--*/
class CefClient : public virtual CefBaseRefCounted {
 public:
  ///
  // Return the handler for context menus. If no handler is provided the default
  // implementation will be used.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefContextMenuHandler> GetContextMenuHandler() {
    return NULL;
  }

  ///
  // Return the handler for dialogs. If no handler is provided the default
  // implementation will be used.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefDialogHandler> GetDialogHandler() { return NULL; }

  ///
  // Return the handler for browser display state events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() { return NULL; }

  ///
  // Return the handler for download events. If no handler is returned downloads
  // will not be allowed.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefDownloadHandler> GetDownloadHandler() { return NULL; }

  ///
  // Return the handler for drag events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefDragHandler> GetDragHandler() { return NULL; }

  ///
  // Return the handler for find result events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefFindHandler> GetFindHandler() { return NULL; }

  ///
  // Return the handler for focus events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefFocusHandler> GetFocusHandler() { return NULL; }

  ///
  // Return the handler for JavaScript dialogs. If no handler is provided the
  // default implementation will be used.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefJSDialogHandler> GetJSDialogHandler() { return NULL; }

  ///
  // Return the handler for keyboard events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefKeyboardHandler> GetKeyboardHandler() { return NULL; }

  ///
  // Return the handler for browser life span events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() { return NULL; }

  ///
  // Return the handler for browser load status events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefLoadHandler> GetLoadHandler() { return NULL; }

  ///
  // Return the handler for off-screen rendering events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefRenderHandler> GetRenderHandler() { return NULL; }

  ///
  // Return the handler for browser request events.
  ///
  /*--cef()--*/
  virtual CefRefPtr<CefRequestHandler> GetRequestHandler() { return NULL; }

  ///
  // Called when a new message is received from a different process. Return true
  // if the message was handled or false otherwise. Do not keep a reference to
  // or attempt to access the message outside of this callback.
  ///
  /*--cef()--*/
  virtual bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser,
                                        CefProcessId source_process,
                                        CefRefPtr<CefProcessMessage> message) {
    return false;
  }
};

bingo,没错,原理是一样的,都是从CefClient::GetxxxHandler的返回对象继承,所以我们在实现SimpleHandler的时候只需要关注事件,然后从该对应的Handler继承,处理对应的回调即可。

class SimpleHandler : public CefClient,
	public CefDisplayHandler,
	public CefLifeSpanHandler,
	public CefLoadHandler {
 public:
 ...
  // CefClient 方法:
  virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE {return this;}
  virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE {return this;}
  virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE { return this; }

  // CefDisplayHandler 事件:处理浏览器标题发生变化事件
  virtual void OnTitleChange(CefRefPtr<CefBrowser> browser,const CefString& title) OVERRIDE;
  
  // CefLifeSpanHandler 事件
  virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
  virtual bool DoClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
  virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;

  // CefLoadHandler 事件:
  virtual void OnLoadError(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,ErrorCode errorCode,const CefString& errorText, const CefString& failedUrl) OVERRIDE;
...
}

例如Demo继承了CefDisplayHandler,CefLifeSpanHandler,CefLoadHandler 三个事件,并且处理了三个事件中的浏览器创建事件(CefLifeSpanHandler )、浏览器标题发生改变事件(CefDisplayHandler )、网页加载错误事件(CefLoadHandler )。例如标题发生改变的时候我们只需要在OnTitleChange里面SetWindowText就可以切换窗口标题了。此时一个简短的Demo分析完成。

Note:只有当所有的浏览器都关闭了才能CefQuitMessageLoop,所以我们需要标记浏览器创建对象数量。即:OnAfterCreated push ,OnBeforeClose pop 如果全部关闭则CefQuitMessageLoop。

拓展:在看cefsimple例子的时候我们发现在OnContextInitialized里面有一个use_views模式,那么请问一下我们怎么在命令行里面增加“use-views”呢?

so easy,结合CefBrowserProcessHandler::OnBeforeCommandLineProcessing事件,所以我们可以在SimpleApp里面重写该事件

void SimpleApp::OnBeforeCommandLineProcessing(
	const CefString& process_type,
	CefRefPtr<CefCommandLine> command_line)
{
	//测试use-views
	command_line->AppendSwitch("use-views");
	
}

总结:

Cef运行流程:CefExecuteProcess判断是否为浏览器进程=》init=》run=》shutdown(浏览器退出的时候CefQuitMessageLoop)。

Cef需要重写的对象:
CefApp:主要处理浏览器本身相关事件,具体事件参考头文件。
CefClient:主要处理了浏览器网页之间的事件,具体事件参考头文件。

猜你喜欢

转载自blog.csdn.net/CAir2/article/details/84969813