int BrowserManager::Impl::CreateBrowser(
		const BrowserSettings &browserSettings,
		const std::shared_ptr<BrowserListener> &browserListener)
{
	int browserIdentifier = 0;
	os_event_t *createdEvent;
	os_event_init(&createdEvent, OS_EVENT_TYPE_AUTO);

	CefPostTask(TID_UI, BrowserTask::newTask(
			[&] 
	{

		CefRefPtr<BrowserRenderHandler> renderHandler(
				new BrowserRenderHandler(browserSettings.width, 
				browserSettings.height, browserListener));

		CefRefPtr<BrowserLoadHandler> loadHandler(
				new BrowserLoadHandler(browserSettings.css));

		CefRefPtr<BrowserClient> browserClient(
				new BrowserClient(renderHandler,loadHandler)); 

		CefWindowInfo windowInfo;
		windowInfo.transparent_painting_enabled = true;
		windowInfo.width = browserSettings.width;
		windowInfo.height = browserSettings.height;
		windowInfo.windowless_rendering_enabled = true;

		CefBrowserSettings cefBrowserSettings;
		cefBrowserSettings.windowless_frame_rate = browserSettings.fps;

		CefRefPtr<CefBrowser> browser =
				CefBrowserHost::CreateBrowserSync(windowInfo, 
				browserClient, browserSettings.url, 
				cefBrowserSettings, nullptr);

		if (browser != nullptr) {
			browserIdentifier = browser->GetIdentifier();
			browserMap[browserIdentifier] = browser;
		}
		os_event_signal(createdEvent);
	}));

	os_event_wait(createdEvent);
	os_event_destroy(createdEvent);
	return browserIdentifier;
}
示例#2
0
文件: MainFrm.cpp 项目: Omgan/cef-mfc
void CMainFrame::OnCefCallJavaScriptFunction()
{
  CCEFView *pView = CCEFView::GetView();
  CefRefPtr<CefBrowser> browser = pView->m_clientHandler->GetBrowser();
  CefRefPtr<CefFrame> frame = browser->GetMainFrame();
  CefPostTask(TID_UI, NewCefRunnableMethod(pView->m_clientHandler.get(), &ClientHandler::GetURL));
  frame->ExecuteJavaScript("foo();", "", 0);
  CefPostTask(TID_UI, NewCefRunnableMethod(pView->m_clientHandler.get(), &ClientHandler::JavaScriptTest));
}
void ClientHandler::CloseAllBrowsers(bool force_close) {
    
  std::cout << "Executing CloseAllBrowsers";
  
  if (!CefCurrentlyOn(TID_UI)) {
    // Execute on the UI thread.
    CefPostTask(TID_UI,
        base::Bind(&ClientHandler::CloseAllBrowsers, this, force_close));
    return;
    
  }

  if (!popup_browsers_.empty()) {
    // Request that any popup browsers close.
    BrowserList::const_iterator it = popup_browsers_.begin();
    for (; it != popup_browsers_.end(); ++it)
      (*it)->GetHost()->CloseBrowser(force_close);
  }

  if (browser_.get()) {
    // Request that the main browser close.
    developerStudioProcess->StopProcess();
    browser_->GetHost()->CloseBrowser(force_close);
  }
}
示例#4
0
  // The download is complete.
  virtual void Complete() {
    REQUIRE_UI_THREAD();

    // Flush and close the file on the FILE thread.
    CefPostTask(TID_FILE,
        NewCefRunnableMethod(this, &ClientDownloadHandler::OnComplete));
  }
示例#5
0
  // A portion of the file contents have been received. This method will be
  // called multiple times until the download is complete. Return |true| to
  // continue receiving data and |false| to cancel.
  virtual bool ReceivedData(void* data, int data_size) {
    REQUIRE_UI_THREAD();

    if (data_size == 0)
      return true;
    received_size += data_size;
    buffer_size += data_size;

    // Create a new vector for the data.
    std::vector<char>* buffer = new std::vector<char>(data_size);
    memcpy(&(*buffer)[0], data, data_size);

    // Add the new data vector to the pending data queue.
    {
      AutoLock lock_scope(this);
      pending_data_.push_back(buffer);
    }

    // Write data to file on the FILE thread.
    if (buffer_size > flush_size) {
      buffer_size = 0;
      CefPostTask(TID_FILE,
          NewCefRunnableMethod(this, &ClientDownloadHandler::OnReceivedData));
    }
    return bcontinue;
  }
// Cef的初始化接口,同时备注了使用各个版本的Cef时遇到的各种坑
// Cef1916版本较稳定,各个功能使用正常,但是某些在debug模式网页打开时会出中断警告(但并不是错误),可能是因为对新html标准支持不够,但是在release模式下正常使用
// Cef2357版本无法使用,当程序处理重定向信息并且重新加载页面后,渲染进程会崩掉
// Cef2526、2623版本对各种新页面都支持,唯一的坑就是debug模式在多线程消息循环开启下,程序退出时会中断,但是release模式正常。
//		(PS:如果开发者不使用负责Cef功能的开发,可以切换到release模式的cef dll文件,这样即使在deubg下也不会报错,修改AddCefDllToPath代码可以切换到release目录)
bool CefManager::Initialize(const std::wstring& app_data_dir, CefSettings &settings, bool is_enable_offset_render /*= true*/)
{
#if !defined(SUPPORT_CEF)
	return true;
#endif
	is_enable_offset_render_ = is_enable_offset_render;

	CefMainArgs main_args(GetModuleHandle(NULL));
	CefRefPtr<ClientApp> app(new ClientApp);
	
	// 如果是在子进程中调用,会堵塞直到子进程退出,并且exit_code返回大于等于0
	// 如果在Browser进程中调用,则立即返回-1
	int exit_code = CefExecuteProcess(main_args, app.get(), NULL);
	if (exit_code >= 0)
		return false;

	GetCefSetting(app_data_dir, settings);

	bool bRet = CefInitialize(main_args, settings, app.get(), NULL);
	
	if (is_enable_offset_render_)
	{
		HWND hwnd = CreateWindow(L"Static", L"", WS_POPUP, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
		CefPostTask(TID_UI, base::Bind(&FixContextMenuBug, hwnd));
	}

	return bRet;
}
示例#7
0
// Called due to cefQuery execution in binding.html.
bool QueryHandler::OnQuery(CefRefPtr<CefBrowser> browser,
                           CefRefPtr<CefFrame> frame,
                           int64 query_id,
                           const CefString& request,
                           bool persistent,
                           CefRefPtr<Callback> callback) {
  try {
    auto query = createQuery(browser, frame, request.ToString());

    if (!query)
      return false;

    CefPostTask(TID_FILE, base::Bind(&Query::execute, query, callback));
  } catch (std::exception& e) {
    auto logger = lootState_.getLogger();
    if (logger) {
      logger->error("Failed to parse CEF query request \"{}\": {}",
        request.ToString(),
        e.what());
    }
    callback->Failure(-1, e.what());
  }

  return true;
}
示例#8
0
void CefClientImpl::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
	if (!message_router_) {
		// Create the browser-side router for query handling.
		CefMessageRouterConfig config;
		message_router_ = CefMessageRouterBrowserSide::Create(config);
		// Register handlers with the router.
		message_router_->AddHandler(new Handler(), false);
	}

 
	if(!GetBrowser())
	{
		base::AutoLock lock_scope(lock_);
		browser_child = browser;
		browser_id_ = browser->GetIdentifier();
	}else if (browser->IsPopup()) {
		// Add to the list of popup browsers.
		popup_browsers_.push_back(browser);

		// Give focus to the popup browser. Perform asynchronously because the
		// parent window may attempt to keep focus after launching the popup.
		CefPostTask(TID_UI,
			base::Bind(&CefBrowserHost::SetFocus, browser->GetHost().get(), true));
	}

	browser_count_++;

	//std::stringstream ss;
	//ss << "<html><body bgcolor=\"white\"><h1>Chatting with xxx</h1>Text:<pre>" << "XXXYY" <<
	//    "</pre></body></html>";
	//browser->GetMainFrame()->LoadString(ss.str(), "http://tests/gettext");
}
void ClientHandler::SendNotification(NotificationType type) {
 	if (type == NOTIFY_DOWNLOAD_COMPLETE) {
        std::string downloadedFile(GetLastDownloadFile());
        GtkWidget* widget = NULL;
        CefPostTask(TID_UI, NewCefRunnableFunction(AppCreateWebinosBrowser,downloadedFile,false,true,widget,0,0));
    }
}
示例#10
0
 void Initialize() {
   received_size = 0;
   buffer_size = 0;
   bcontinue = true;
   // Open the file on the FILE thread.
   CefPostTask(TID_FILE,
       NewCefRunnableMethod(this, &ClientDownloadHandler::OnOpen));
 }
示例#11
0
// Change the zoom factor on the UI thread.
static void ModifyZoom(CefRefPtr<CefBrowser> browser, double delta) {
  if (CefCurrentlyOn(TID_UI)) {
    browser->GetHost()->SetZoomLevel(
        browser->GetHost()->GetZoomLevel() + delta);
  } else {
    CefPostTask(TID_UI, NewCefRunnableFunction(ModifyZoom, browser, delta));
  }
}
示例#12
0
bool Application::Execute(
    const CefString& name,
    CefRefPtr<CefV8Value> object,
    const CefV8ValueList& arguments,
    CefRefPtr<CefV8Value>& retval,
    CefString& exception
) {
    if (name == "exit") {
        printf("Exiting with value %d!\n", arguments[0]->GetIntValue());
        this->firstBrowser = NULL;
        // see http://www.magpcss.org/ceforum/viewtopic.php?f=6&t=891 for the 'right' way to do this
        CefRefPtr<CefProcessMessage> message = CefProcessMessage::Create("quit");
        message->GetArgumentList()->SetInt(0, arguments[0]->GetIntValue());
        message->GetArgumentList()->SetString(1, this->outBuffer);
        if(CefV8Context::GetEnteredContext()->GetBrowser()->SendProcessMessage(PID_BROWSER, message)) {
            printf("Got true from quit send process\n");
        } else { 
            printf("Got false from quit send process message\n");
        }
        return true;

    } else if (name == "open") {

    } else if (name == "openWindow") {
        CefPostTask(
            TID_UI,
            NewCefRunnableFunction(&noOpenWindow)
            );
        return true;

    } else if (name == "nop") {
        return true;

    } else if (name == "log") {
        /*if (object->IsSame(this->leprechaunObj)) {
            // Figure out if we need this some day...
            return false;
        }*/
        std::wstringstream ss;
        for (size_t i = 0; i < arguments.size(); ++i) {
            ss << arguments[i]->GetStringValue().ToWString();
        }
        printf("Got log: %S\n", ss.str().c_str());
        return true;
    } else if (name == "echo") {
        std::wstringstream ss;
        for (size_t i = 0; i < arguments.size(); ++i) {
            ss << arguments[i]->GetStringValue().ToWString();
        }
	this->outBuffer += ss.str().c_str();
	this->outBuffer += L"\n";
        return true;
    } else if (name == "onerror") {
        return true;
    }

    return false;
}
void ClientHandler::BeginTracing() {
  if (!CefCurrentlyOn(TID_UI)) {
    // Execute on the UI thread.
    CefPostTask(TID_UI, base::Bind(&ClientHandler::BeginTracing, this));
    return;
  }

  CefBeginTracing(CefString(), NULL);
}
示例#14
0
// Set focus to |browser| on the UI thread.
static void SetFocusBrowser(CefRefPtr<CefBrowser> browser) {
	if (!CefCurrentlyOn(TID_UI)) {
		// Execute on the UI thread.
		CefPostTask(TID_UI, base::Bind(&SetFocusBrowser, browser));
		return;
	}

	browser->GetHost()->SetFocus(true);
}
示例#15
0
void RunJavaScriptInvokeTest(CefRefPtr<CefBrowser> browser)
{
  if (CefCurrentlyOn(TID_UI)) {
    UIT_InvokeScript(browser);
  } else {
    // Execute on the UI thread.
    CefPostTask(TID_UI, NewCefRunnableFunction(&UIT_InvokeScript, browser));
  }
}
void ClientHandler::SetOSRHandler(CefRefPtr<RenderHandler> handler) {
  if (!CefCurrentlyOn(TID_UI)) {
    // Execute on the UI thread.
    CefPostTask(TID_UI,
        base::Bind(&ClientHandler::SetOSRHandler, this, handler));
    return;
  }

  osr_handler_ = handler;
}
void ClientHandler::SetEditWindowHandle(ClientWindowHandle handle) {
  if (!CefCurrentlyOn(TID_UI)) {
    // Execute on the UI thread.
    CefPostTask(TID_UI,
        base::Bind(&ClientHandler::SetEditWindowHandle, this, handle));
    return;
  }

  edit_handle_ = handle;
}
void BrowserManager::Impl::ExecuteOnBrowser(int browserIdentifier, 
		std::function<void(CefRefPtr<CefBrowser>)> f, 
		bool async)
{
	if (browserMap.count(browserIdentifier) > 0) {
		CefRefPtr<CefBrowser> browser = browserMap[browserIdentifier];
		if (async) {
			CefPostTask(TID_UI, BrowserTask::newTask([&] {
				f(browser);
			}));
		} else {
			os_event_t *finishedEvent;
			os_event_init(&finishedEvent, OS_EVENT_TYPE_AUTO);
			CefPostTask(TID_UI, BrowserTask::newTask([&] {
				f(browser);
				os_event_signal(finishedEvent);
			}));
			os_event_wait(finishedEvent);
			os_event_destroy(finishedEvent);
		}
	}
}
void FCEFWebBrowserWindow::CloseBrowser(bool bForce)
{
	if (IsValid())
	{
		// In case this is called from inside a CEF event handler, use CEF's task mechanism to
		// postpone the actual closing of the window until it is safe.
		CefRefPtr<CefBrowserHost> Host = InternalCefBrowser->GetHost();
		CefPostTask(TID_UI, new FCEFBrowserClosureTask(nullptr, [=]()
		{
			Host->CloseBrowser(bForce);
		}));
	}
}
示例#20
0
void HttpTrans::recvData(const int& code, FILE* fp, const int& id, const int& reDirectCount)
{
	//std::unique_lock<std::mutex> lock(lock_);
	std::wstring rsp;
	if ( fp )
	{
		fseek(fp, 0L, SEEK_END);
		long length = ftell(fp);
		fseek(fp, 0, SEEK_SET);
		if ( length > 0 )
		{
			char* szBuf = new char[length+1];
			memset(szBuf, 0, length + 1);
			if (fread_s(szBuf, length + 1, 1, length, fp) > 0){
				rsp = cyjh::UTF8ToUnicode(szBuf);
				delete[]szBuf;
			}
		}
	}
	std::shared_ptr<resp_context_> parm(new resp_context_);
	parm->id_ = id;
	parm->errcode_ = code;
	parm->head_ = " ";
	parm->body_ = " ";

	int i = 0;
	int pos = 0;
	while (i < reDirectCount)
	{
		pos = rsp.find(L"\r\n\r\n");
		if ( pos > 0 )
		{
			rsp.erase(0, pos + 4);
		}
		++i;
	}

	pos = rsp.find(L"\r\n\r\n");
	if ( pos > 0 )
	{
		std::wstring whead = rsp.substr(0, pos);
		int size = rsp.size() - pos - 4;
		if ( size > 0 )
		{
			std::wstring wbody = rsp.substr(pos + 4, size);
			parm->body_ = cyjh::UnicodeToUTF8(wbody);
		}
		parm->head_ = cyjh::UnicodeToUTF8(whead);
	}
	CefPostTask(TID_UI, base::Bind(&ackData, parm));
}
示例#21
0
    void LootHandler::CloseAllBrowsers(bool force_close) {
        if (!CefCurrentlyOn(TID_UI)) {
            // Execute on the UI thread.
            CefPostTask(TID_UI,
                        NewCefRunnableMethod(this, &LootHandler::CloseAllBrowsers, force_close));
            return;
        }

        if (browser_list_.empty())
            return;

        for (BrowserList::const_iterator it = browser_list_.begin(); it != browser_list_.end(); ++it) {
            (*it)->GetHost()->CloseBrowser(force_close);
        }
    }
void SimpleHandler::CloseAllBrowsers(bool force_close) {
	if (!CefCurrentlyOn(TID_UI)) {
		// Execute on the UI thread.
		CefPostTask(TID_UI,
			base::Bind(&SimpleHandler::CloseAllBrowsers, this, force_close));
		return;
	}

	if (browser_list_.empty())
		return;

	BrowserList::const_iterator it = browser_list_.begin();
	for (; it != browser_list_.end(); ++it)
		(*it)->GetHost()->CloseBrowser(force_close);
}
void ClientHandler::EndTracing() {
  if (!CefCurrentlyOn(TID_UI)) {
    // Execute on the UI thread.
    CefPostTask(TID_UI, base::Bind(&ClientHandler::EndTracing, this));
    return;
  }

  class Client : public CefEndTracingCallback,
                  public CefRunFileDialogCallback {
    public:
    explicit Client(CefRefPtr<ClientHandler> handler)
        : handler_(handler) {
      RunDialog();
    }

    void RunDialog() {
      static const char kDefaultFileName[] = "trace.txt";
      std::string path = handler_->GetDownloadPath(kDefaultFileName);
      if (path.empty())
        path = kDefaultFileName;

      // Results in a call to OnFileDialogDismissed.
      handler_->GetBrowser()->GetHost()->RunFileDialog(
          FILE_DIALOG_SAVE, CefString(), path, std::vector<CefString>(),
          this);
    }

    virtual void OnFileDialogDismissed(
        CefRefPtr<CefBrowserHost> browser_host,
        const std::vector<CefString>& file_paths) OVERRIDE {
      CEF_REQUIRE_UI_THREAD();
      if (!file_paths.empty()) {
        // File selected. Results in a call to OnEndTracingComplete.
        CefEndTracing(file_paths.front(), this);
      } else {
        // No file selected. Discard the trace data.
        CefEndTracing(CefString(), NULL);
      }
    }

    virtual void OnEndTracingComplete(
        const CefString& tracing_file) OVERRIDE {
      CEF_REQUIRE_UI_THREAD();
      handler_->SetLastDownloadFile(tracing_file.ToString());
      handler_->SendNotification(NOTIFY_DOWNLOAD_COMPLETE);
    }

    private:
示例#24
0
void WebViewFactory::ClearData(int compType)
{
	if (!CefCurrentlyOn(TID_UI)){
		CefPostTask(TID_UI, base::Bind(&WebViewFactory::ClearData, this, compType));
		return;
	}

	int len = m_viewList.size();
	if ( len > 0 )
	{
		WebViewList::iterator it = m_viewList.begin();
		//it->second->m_provider->GetBrowser()->GetHost()->CleaarData(compType);
		(*it)->clearData(compType);
	}

}
示例#25
0
  void OnComplete() {
    REQUIRE_FILE_THREAD();

    if (!file_)
      return;

    // Make sure any pending data is written.
    OnReceivedData();

    fclose(file_);
    file_ = NULL;

    // Notify the listener that the download completed.
    CefPostTask(TID_UI,
        NewCefRunnableMethod(this, &ClientDownloadHandler::SendComplete));
  }
示例#26
0
    void CloseBrowser(bool force_close)
    {
        if (!CefCurrentlyOn(TID_UI))
        {
            // Execute on the UI thread.
            CefPostTask(TID_UI,
                        base::Bind(&WebClientPrivate::CloseBrowser, this, force_close));

            return;
        }

        if (!browser_.get())
            return;

        browser_->GetHost()->CloseBrowser(force_close);
    }
示例#27
0
void WindowClient::CloseAllBrowsers() {
    if (!CefCurrentlyOn(TID_UI)) {
        // Execute on the UI thread.
        CefPostTask(TID_UI,
            base::Bind(&WindowClient::CloseAllBrowsers, this));
        return;
    }

    if (browsers_.empty()) {
        CefQuitMessageLoop();
    }

    for (BrowserList::const_iterator i = browsers_.begin(); i != browsers_.end(); ++i) {
        (*i)->GetHost()->CloseBrowser(true);
    }
}
void ClientHandler::SetButtonWindowHandles(ClientWindowHandle backHandle,
                                           ClientWindowHandle forwardHandle,
                                           ClientWindowHandle reloadHandle,
                                           ClientWindowHandle stopHandle) {
  if (!CefCurrentlyOn(TID_UI)) {
    // Execute on the UI thread.
    CefPostTask(TID_UI,
        base::Bind(&ClientHandler::SetButtonWindowHandles, this,
                   backHandle, forwardHandle, reloadHandle, stopHandle));
    return;
  }

  back_handle_ = backHandle;
  forward_handle_ = forwardHandle;
  reload_handle_ = reloadHandle;
  stop_handle_ = stopHandle;
}
void OSRWindow::Invalidate() {
  if (!CefCurrentlyOn(TID_UI)) {
    CefPostTask(TID_UI, base::Bind(&OSRWindow::Invalidate, this));
    return;
  }

  // Don't post another task if the previous task is still pending.
  if (render_task_pending_)
    return;

  render_task_pending_ = true;

  // Render at 30fps.
  static const int kRenderDelay = 1000 / 30;
  CefPostDelayedTask(TID_UI, base::Bind(&OSRWindow::Render, this),
                     kRenderDelay);
}
示例#30
0
JNIEXPORT void JNICALL Java_org_cef_browser_CefBrowser_1N_N_1UpdateUI
  (JNIEnv *env, jobject obj, jobject jcontentRect, jobject jbrowserRect) {
  CefRefPtr<CefBrowser> browser = JNI_GET_BROWSER_OR_RETURN(env, obj);
  CefRect contentRect = GetJNIRect(env, jcontentRect);
#if defined(OS_MACOSX)
  CefRect browserRect = GetJNIRect(env, jbrowserRect);
  util_mac::UpdateView(browser->GetHost()->GetWindowHandle(), contentRect,
      browserRect);
#elif defined(OS_WIN)
  HWND hwnd = browser->GetHost()->GetWindowHandle();
  if (CefCurrentlyOn(TID_UI))
    UpdateWindowRgn(hwnd, contentRect);
  else
    CefPostTask(TID_UI, NewCefRunnableFunction(&UpdateWindowRgn, hwnd,
        contentRect));
#endif
}