DevTools: devtools manager should know nothing about DevToolsWindow
[chromium-blink-merge.git] / chrome_frame / chrome_active_document.cc
blobf06a53a9d3da2d84feb01242618b1666295bd34b
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Implementation of ChromeActiveDocument
6 #include "chrome_frame/chrome_active_document.h"
8 #include <hlink.h>
9 #include <htiface.h>
10 #include <initguid.h>
11 #include <mshtmcid.h>
12 #include <shdeprecated.h>
13 #include <shlguid.h>
14 #include <shlobj.h>
15 #include <shobjidl.h>
16 #include <tlogstg.h>
17 #include <urlmon.h>
18 #include <wininet.h>
20 #include "base/command_line.h"
21 #include "base/debug/trace_event.h"
22 #include "base/file_util.h"
23 #include "base/logging.h"
24 #include "base/path_service.h"
25 #include "base/process_util.h"
26 #include "base/string_tokenizer.h"
27 #include "base/string_util.h"
28 #include "base/threading/thread.h"
29 #include "base/threading/thread_local.h"
30 #include "base/utf_string_conversions.h"
31 #include "base/win/scoped_variant.h"
32 #include "base/win/win_util.h"
33 #include "chrome/app/chrome_command_ids.h"
34 #include "chrome/app/chrome_dll_resource.h"
35 #include "chrome/common/automation_messages.h"
36 #include "chrome/common/chrome_constants.h"
37 #include "chrome/test/automation/browser_proxy.h"
38 #include "chrome/test/automation/tab_proxy.h"
39 #include "chrome_frame/bho.h"
40 #include "chrome_frame/bind_context_info.h"
41 #include "chrome_frame/buggy_bho_handling.h"
42 #include "chrome_frame/crash_reporting/crash_metrics.h"
43 #include "chrome_frame/utils.h"
44 #include "content/browser/tab_contents/tab_contents.h"
45 #include "content/common/navigation_types.h"
46 #include "content/common/page_zoom.h"
47 #include "grit/generated_resources.h"
49 DEFINE_GUID(CGID_DocHostCmdPriv, 0x000214D4L, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0,
50 0x46);
52 base::ThreadLocalPointer<ChromeActiveDocument> g_active_doc_cache;
54 bool g_first_launch_by_process_ = true;
56 const DWORD kIEEncodingIdArray[] = {
57 #define DEFINE_ENCODING_ID_ARRAY(encoding_name, id, chrome_name) encoding_name,
58 INTERNAL_IE_ENCODINGMENU_IDS(DEFINE_ENCODING_ID_ARRAY)
59 #undef DEFINE_ENCODING_ID_ARRAY
60 0 // The Last data must be 0 to indicate the end of the encoding id array.
63 ChromeActiveDocument::ChromeActiveDocument()
64 : navigation_info_(new NavigationInfo()),
65 first_navigation_(true),
66 is_automation_client_reused_(false),
67 popup_allowed_(false),
68 accelerator_table_(NULL) {
69 TRACE_EVENT_BEGIN_ETW("chromeframe.createactivedocument", this, "");
71 url_fetcher_->set_frame_busting(false);
72 memset(navigation_info_.get(), 0, sizeof(NavigationInfo));
75 HRESULT ChromeActiveDocument::FinalConstruct() {
76 // If we have a cached ChromeActiveDocument instance in TLS, then grab
77 // ownership of the cached document's automation client. This is an
78 // optimization to get Chrome active documents to load faster.
79 ChromeActiveDocument* cached_document = g_active_doc_cache.Get();
80 if (cached_document && cached_document->IsValid()) {
81 SetResourceModule();
82 DCHECK(automation_client_.get() == NULL);
83 automation_client_.swap(cached_document->automation_client_);
84 DVLOG(1) << "Reusing automation client instance from " << cached_document;
85 DCHECK(automation_client_.get() != NULL);
86 automation_client_->Reinitialize(this, url_fetcher_.get());
87 is_automation_client_reused_ = true;
88 OnAutomationServerReady();
89 } else {
90 // The FinalConstruct implementation in the ChromeFrameActivexBase class
91 // i.e. Base creates an instance of the ChromeFrameAutomationClient class
92 // and initializes it, which would spawn a new Chrome process, etc.
93 // We don't want to be doing this if we have a cached document, whose
94 // automation client instance can be reused.
95 HRESULT hr = BaseActiveX::FinalConstruct();
96 if (FAILED(hr))
97 return hr;
100 InitializeAutomationSettings();
102 find_dialog_.Init(automation_client_.get());
104 OLECMDF flags = static_cast<OLECMDF>(OLECMDF_ENABLED | OLECMDF_SUPPORTED);
106 null_group_commands_map_[OLECMDID_PRINT] = flags;
107 null_group_commands_map_[OLECMDID_FIND] = flags;
108 null_group_commands_map_[OLECMDID_CUT] = flags;
109 null_group_commands_map_[OLECMDID_COPY] = flags;
110 null_group_commands_map_[OLECMDID_PASTE] = flags;
111 null_group_commands_map_[OLECMDID_SELECTALL] = flags;
112 null_group_commands_map_[OLECMDID_SAVEAS] = flags;
114 mshtml_group_commands_map_[IDM_BASELINEFONT1] = flags;
115 mshtml_group_commands_map_[IDM_BASELINEFONT2] = flags;
116 mshtml_group_commands_map_[IDM_BASELINEFONT3] = flags;
117 mshtml_group_commands_map_[IDM_BASELINEFONT4] = flags;
118 mshtml_group_commands_map_[IDM_BASELINEFONT5] = flags;
119 mshtml_group_commands_map_[IDM_VIEWSOURCE] = flags;
121 HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase);
122 accelerator_table_ =
123 LoadAccelerators(this_module,
124 MAKEINTRESOURCE(IDR_CHROME_FRAME_IE_FULL_TAB));
125 DCHECK(accelerator_table_ != NULL);
126 return S_OK;
129 ChromeActiveDocument::~ChromeActiveDocument() {
130 DVLOG(1) << __FUNCTION__;
131 if (find_dialog_.IsWindow())
132 find_dialog_.DestroyWindow();
133 // ChromeFramePlugin
134 BaseActiveX::Uninitialize();
136 TRACE_EVENT_END_ETW("chromeframe.createactivedocument", this, "");
139 // Override DoVerb
140 STDMETHODIMP ChromeActiveDocument::DoVerb(LONG verb,
141 LPMSG msg,
142 IOleClientSite* active_site,
143 LONG index,
144 HWND parent_window,
145 LPCRECT pos) {
146 // IE will try and in-place activate us in some cases. This happens when
147 // the user opens a new IE window with a URL that has us as the DocObject.
148 // Here we refuse to be activated in-place and we will force IE to UIActivate
149 // us.
150 if (OLEIVERB_INPLACEACTIVATE == verb)
151 return OLEOBJ_E_INVALIDVERB;
152 // Check if we should activate as a docobject or not
153 // (client supports IOleDocumentSite)
154 if (doc_site_) {
155 switch (verb) {
156 case OLEIVERB_SHOW: {
157 base::win::ScopedComPtr<IDocHostUIHandler> doc_host_handler;
158 doc_host_handler.QueryFrom(doc_site_);
159 if (doc_host_handler.get())
160 doc_host_handler->ShowUI(DOCHOSTUITYPE_BROWSE, this, this, NULL, NULL);
162 case OLEIVERB_OPEN:
163 case OLEIVERB_UIACTIVATE:
164 if (!m_bUIActive)
165 return doc_site_->ActivateMe(NULL);
166 break;
169 return IOleObjectImpl<ChromeActiveDocument>::DoVerb(verb,
170 msg,
171 active_site,
172 index,
173 parent_window,
174 pos);
177 // Override IOleInPlaceActiveObjectImpl::OnDocWindowActivate
178 STDMETHODIMP ChromeActiveDocument::OnDocWindowActivate(BOOL activate) {
179 DVLOG(1) << __FUNCTION__;
180 return S_OK;
183 STDMETHODIMP ChromeActiveDocument::TranslateAccelerator(MSG* msg) {
184 DVLOG(1) << __FUNCTION__;
185 if (msg == NULL)
186 return E_POINTER;
188 if (msg->message == WM_KEYDOWN && msg->wParam == VK_TAB) {
189 HWND focus = ::GetFocus();
190 if (focus != m_hWnd && !::IsChild(m_hWnd, focus)) {
191 // The call to SetFocus triggers a WM_SETFOCUS that makes the base class
192 // set focus to the correct element in Chrome.
193 ::SetFocus(m_hWnd);
194 return S_OK;
198 return S_FALSE;
200 // Override IPersistStorageImpl::IsDirty
201 STDMETHODIMP ChromeActiveDocument::IsDirty() {
202 DVLOG(1) << __FUNCTION__;
203 return S_FALSE;
206 void ChromeActiveDocument::OnAutomationServerReady() {
207 BaseActiveX::OnAutomationServerReady();
208 BaseActiveX::GiveFocusToChrome(true);
211 STDMETHODIMP ChromeActiveDocument::Load(BOOL fully_avalable,
212 IMoniker* moniker_name,
213 LPBC bind_context,
214 DWORD mode) {
215 if (NULL == moniker_name)
216 return E_INVALIDARG;
218 base::win::ScopedComPtr<IOleClientSite> client_site;
219 if (bind_context) {
220 base::win::ScopedComPtr<IUnknown> site;
221 bind_context->GetObjectParam(SZ_HTML_CLIENTSITE_OBJECTPARAM,
222 site.Receive());
223 if (site)
224 client_site.QueryFrom(site);
227 if (client_site) {
228 SetClientSite(client_site);
229 DoQueryService(IID_INewWindowManager, client_site,
230 popup_manager_.Receive());
232 // See if mshtml parsed the html header for us. If so, we need to
233 // clear the browser service flag that we use to indicate that this
234 // browser instance is navigating to a CF document.
235 base::win::ScopedComPtr<IBrowserService> browser_service;
236 DoQueryService(SID_SShellBrowser, client_site, browser_service.Receive());
237 if (browser_service) {
238 bool flagged = CheckForCFNavigation(browser_service, true);
239 DVLOG_IF(1, flagged) << "Cleared flagged browser service";
243 NavigationManager* mgr = NavigationManager::GetThreadInstance();
244 DLOG_IF(ERROR, !mgr) << "Couldn't get instance of NavigationManager";
246 std::wstring url;
248 base::win::ScopedComPtr<BindContextInfo> info;
249 BindContextInfo::FromBindContext(bind_context, info.Receive());
250 DCHECK(info);
251 if (info && !info->GetUrl().empty()) {
252 url = info->GetUrl();
253 if (mgr) {
254 // If the original URL contains an anchor, then the URL queried
255 // from the protocol sink wrapper does not contain the anchor. To
256 // workaround this we retrieve the anchor from the navigation manager
257 // and append it to the url retrieved from the protocol sink wrapper.
258 GURL url_for_anchor(mgr->url());
259 if (url_for_anchor.has_ref()) {
260 url += L"#";
261 url += UTF8ToWide(url_for_anchor.ref());
264 } else {
265 // If the original URL contains an anchor, then the URL queried
266 // from the moniker does not contain the anchor. To workaround
267 // this we retrieve the URL from our BHO.
268 url = GetActualUrlFromMoniker(moniker_name, bind_context,
269 mgr ? mgr->url(): std::wstring());
272 ChromeFrameUrl cf_url;
273 if (!cf_url.Parse(url)) {
274 DLOG(WARNING) << __FUNCTION__ << " Failed to parse url:" << url;
275 return E_INVALIDARG;
278 std::string referrer(mgr ? mgr->referrer() : EmptyString());
279 RendererType renderer_type = cf_url.is_chrome_protocol() ?
280 RENDERER_TYPE_CHROME_GCF_PROTOCOL : RENDERER_TYPE_UNDETERMINED;
282 // With CTransaction patch we have more robust way to grab the referrer for
283 // each top-level-switch-to-CF request by peeking at our sniffing data
284 // object that lives inside the bind context. We also remember the reason
285 // we're rendering the document in Chrome.
286 if (g_patch_helper.state() == PatchHelper::PATCH_PROTOCOL && info) {
287 scoped_refptr<ProtData> prot_data = info->get_prot_data();
288 if (prot_data) {
289 referrer = prot_data->referrer();
290 renderer_type = prot_data->renderer_type();
294 // For gcf: URLs allow only about and view-source schemes to pass through for
295 // further inspection.
296 bool is_safe_scheme = cf_url.gurl().SchemeIs(chrome::kAboutScheme) ||
297 cf_url.gurl().SchemeIs(chrome::kViewSourceScheme);
298 if (cf_url.is_chrome_protocol() && !is_safe_scheme &&
299 !GetConfigBool(false, kAllowUnsafeURLs)) {
300 DLOG(ERROR) << __FUNCTION__ << " gcf: not allowed:" << url;
301 return E_INVALIDARG;
304 if (!LaunchUrl(cf_url, referrer)) {
305 DLOG(ERROR) << __FUNCTION__ << " Failed to launch url:" << url;
306 return E_INVALIDARG;
309 if (!cf_url.is_chrome_protocol() && !cf_url.attach_to_external_tab())
310 url_fetcher_->SetInfoForUrl(url.c_str(), moniker_name, bind_context);
312 // Log a metric indicating why GCF is rendering in Chrome.
313 // (Note: we only track the renderer type when using the CTransaction patch.
314 // When the code for the browser service patch and for the moniker patch is
315 // removed, this conditional can also go away.)
316 if (RENDERER_TYPE_UNDETERMINED != renderer_type) {
317 UMA_LAUNCH_TYPE_COUNT(renderer_type);
320 return S_OK;
323 STDMETHODIMP ChromeActiveDocument::Save(IMoniker* moniker_name,
324 LPBC bind_context,
325 BOOL remember) {
326 return E_NOTIMPL;
329 STDMETHODIMP ChromeActiveDocument::SaveCompleted(IMoniker* moniker_name,
330 LPBC bind_context) {
331 return E_NOTIMPL;
334 STDMETHODIMP ChromeActiveDocument::GetCurMoniker(IMoniker** moniker_name) {
335 return E_NOTIMPL;
338 STDMETHODIMP ChromeActiveDocument::GetClassID(CLSID* class_id) {
339 if (NULL == class_id)
340 return E_POINTER;
341 *class_id = GetObjectCLSID();
342 return S_OK;
345 STDMETHODIMP ChromeActiveDocument::QueryStatus(const GUID* cmd_group_guid,
346 ULONG number_of_commands,
347 OLECMD commands[],
348 OLECMDTEXT* command_text) {
349 DVLOG(1) << __FUNCTION__;
351 CommandStatusMap* command_map = NULL;
353 if (cmd_group_guid) {
354 if (IsEqualGUID(*cmd_group_guid, GUID_NULL)) {
355 command_map = &null_group_commands_map_;
356 } else if (IsEqualGUID(*cmd_group_guid, CGID_MSHTML)) {
357 command_map = &mshtml_group_commands_map_;
358 } else if (IsEqualGUID(*cmd_group_guid, CGID_Explorer)) {
359 command_map = &explorer_group_commands_map_;
360 } else if (IsEqualGUID(*cmd_group_guid, CGID_ShellDocView)) {
361 command_map = &shdoc_view_group_commands_map_;
363 } else {
364 command_map = &null_group_commands_map_;
367 if (!command_map) {
368 DVLOG(1) << "unsupported command group: " << GuidToString(*cmd_group_guid);
369 return OLECMDERR_E_NOTSUPPORTED;
372 for (ULONG command_index = 0; command_index < number_of_commands;
373 command_index++) {
374 DVLOG(1) << "Command id = " << commands[command_index].cmdID;
375 CommandStatusMap::iterator index =
376 command_map->find(commands[command_index].cmdID);
377 if (index != command_map->end())
378 commands[command_index].cmdf = index->second;
380 return S_OK;
383 STDMETHODIMP ChromeActiveDocument::Exec(const GUID* cmd_group_guid,
384 DWORD command_id,
385 DWORD cmd_exec_opt,
386 VARIANT* in_args,
387 VARIANT* out_args) {
388 DVLOG(1) << __FUNCTION__ << " Cmd id =" << command_id;
389 // Bail out if we have been uninitialized.
390 if (automation_client_.get() && automation_client_->tab()) {
391 return ProcessExecCommand(cmd_group_guid, command_id, cmd_exec_opt,
392 in_args, out_args);
393 } else if (command_id == OLECMDID_REFRESH && cmd_group_guid == NULL) {
394 // If the automation server has crashed and the user is refreshing the
395 // page, let OnRefreshPage attempt to recover.
396 OnRefreshPage(cmd_group_guid, command_id, cmd_exec_opt, in_args, out_args);
399 return OLECMDERR_E_NOTSUPPORTED;
402 STDMETHODIMP ChromeActiveDocument::LoadHistory(IStream* stream,
403 IBindCtx* bind_context) {
404 // Read notes in ChromeActiveDocument::SaveHistory
405 DCHECK(stream);
406 LARGE_INTEGER offset = {0};
407 ULARGE_INTEGER cur_pos = {0};
408 STATSTG statstg = {0};
410 stream->Seek(offset, STREAM_SEEK_CUR, &cur_pos);
411 stream->Stat(&statstg, STATFLAG_NONAME);
413 DWORD url_size = statstg.cbSize.LowPart - cur_pos.LowPart;
414 base::win::ScopedBstr url_bstr;
415 DWORD bytes_read = 0;
416 stream->Read(url_bstr.AllocateBytes(url_size), url_size, &bytes_read);
417 std::wstring url(url_bstr);
419 ChromeFrameUrl cf_url;
420 if (!cf_url.Parse(url)) {
421 DLOG(WARNING) << __FUNCTION__ << " Failed to parse url:" << url;
422 return E_INVALIDARG;
425 const std::string& referrer = EmptyString();
426 if (!LaunchUrl(cf_url, referrer)) {
427 NOTREACHED() << __FUNCTION__ << " Failed to launch url:" << url;
428 return E_INVALIDARG;
430 return S_OK;
433 STDMETHODIMP ChromeActiveDocument::SaveHistory(IStream* stream) {
434 // TODO(sanjeevr): We need to fetch the entire list of navigation entries
435 // from Chrome and persist it in the stream. And in LoadHistory we need to
436 // pass this list back to Chrome which will recreate the list. This will allow
437 // Back-Forward navigation to anchors to work correctly when we navigate to a
438 // page outside of ChromeFrame and then come back.
439 if (!stream) {
440 NOTREACHED();
441 return E_INVALIDARG;
444 LARGE_INTEGER offset = {0};
445 ULARGE_INTEGER new_pos = {0};
446 DWORD written = 0;
447 std::wstring url = UTF8ToWide(navigation_info_->url.spec());
448 return stream->Write(url.c_str(), (url.length() + 1) * sizeof(wchar_t),
449 &written);
452 STDMETHODIMP ChromeActiveDocument::SetPositionCookie(DWORD position_cookie) {
453 if (automation_client_.get()) {
454 int index = static_cast<int>(position_cookie);
455 navigation_info_->navigation_index = index;
456 automation_client_->NavigateToIndex(index);
457 } else {
458 DLOG(WARNING) << "Invalid automation client instance";
460 return S_OK;
463 STDMETHODIMP ChromeActiveDocument::GetPositionCookie(DWORD* position_cookie) {
464 if (!position_cookie)
465 return E_INVALIDARG;
467 *position_cookie = navigation_info_->navigation_index;
468 return S_OK;
471 STDMETHODIMP ChromeActiveDocument::GetUrlForEvents(BSTR* url) {
472 if (NULL == url)
473 return E_POINTER;
474 *url = ::SysAllocString(url_);
475 return S_OK;
478 STDMETHODIMP ChromeActiveDocument::GetAddressBarUrl(BSTR* url) {
479 return GetUrlForEvents(url);
482 STDMETHODIMP ChromeActiveDocument::Reset() {
483 next_privacy_record_ = privacy_info_.privacy_records.begin();
484 return S_OK;
487 STDMETHODIMP ChromeActiveDocument::GetSize(DWORD* size) {
488 if (!size)
489 return E_POINTER;
491 *size = privacy_info_.privacy_records.size();
492 return S_OK;
495 STDMETHODIMP ChromeActiveDocument::GetPrivacyImpacted(BOOL* privacy_impacted) {
496 if (!privacy_impacted)
497 return E_POINTER;
499 *privacy_impacted = privacy_info_.privacy_impacted;
500 return S_OK;
503 STDMETHODIMP ChromeActiveDocument::Next(BSTR* url, BSTR* policy,
504 LONG* reserved, DWORD* flags) {
505 if (!url || !policy || !flags)
506 return E_POINTER;
508 if (next_privacy_record_ == privacy_info_.privacy_records.end())
509 return HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS);
511 *url = SysAllocString(next_privacy_record_->first.c_str());
512 *policy = SysAllocString(next_privacy_record_->second.policy_ref.c_str());
513 *flags = next_privacy_record_->second.flags;
515 next_privacy_record_++;
516 return S_OK;
519 bool ChromeActiveDocument::IsSchemeAllowed(const GURL& url) {
520 bool allowed = BaseActiveX::IsSchemeAllowed(url);
521 if (allowed)
522 return true;
524 if (url.SchemeIs(chrome::kAboutScheme)) {
525 if (LowerCaseEqualsASCII(url.spec(), chrome::kAboutPluginsURL))
526 return true;
528 return false;
531 HRESULT ChromeActiveDocument::GetInPlaceFrame(
532 IOleInPlaceFrame** in_place_frame) {
533 DCHECK(in_place_frame);
534 if (in_place_frame_) {
535 *in_place_frame = in_place_frame_.get();
536 (*in_place_frame)->AddRef();
537 return S_OK;
538 } else {
539 return S_FALSE;
543 HRESULT ChromeActiveDocument::IOleObject_SetClientSite(
544 IOleClientSite* client_site) {
545 if (client_site == NULL) {
546 ChromeActiveDocument* cached_document = g_active_doc_cache.Get();
547 if (cached_document) {
548 DCHECK(this == cached_document);
549 g_active_doc_cache.Set(NULL);
550 cached_document->Release();
553 base::win::ScopedComPtr<IDocHostUIHandler> doc_host_handler;
554 if (doc_site_)
555 doc_host_handler.QueryFrom(doc_site_);
557 if (doc_host_handler.get())
558 doc_host_handler->HideUI();
560 doc_site_.Release();
563 if (client_site != m_spClientSite)
564 return BaseActiveX::IOleObject_SetClientSite(client_site);
566 return S_OK;
569 HRESULT ChromeActiveDocument::ActiveXDocActivate(LONG verb) {
570 HRESULT hr = S_OK;
571 m_bNegotiatedWnd = TRUE;
572 if (!m_bInPlaceActive) {
573 hr = m_spInPlaceSite->CanInPlaceActivate();
574 if (FAILED(hr))
575 return hr;
576 m_spInPlaceSite->OnInPlaceActivate();
578 m_bInPlaceActive = TRUE;
579 // get location in the parent window,
580 // as well as some information about the parent
581 base::win::ScopedComPtr<IOleInPlaceUIWindow> in_place_ui_window;
582 frame_info_.cb = sizeof(OLEINPLACEFRAMEINFO);
583 HWND parent_window = NULL;
584 if (m_spInPlaceSite->GetWindow(&parent_window) == S_OK) {
585 in_place_frame_.Release();
586 RECT position_rect = {0};
587 RECT clip_rect = {0};
588 m_spInPlaceSite->GetWindowContext(in_place_frame_.Receive(),
589 in_place_ui_window.Receive(),
590 &position_rect,
591 &clip_rect,
592 &frame_info_);
593 if (!m_bWndLess) {
594 if (IsWindow()) {
595 ::ShowWindow(m_hWnd, SW_SHOW);
596 SetFocus();
597 } else {
598 m_hWnd = Create(parent_window, position_rect);
599 if (!IsWindow()) {
600 // This might happen if the automation server couldn't be
601 // instantiated. If so, a NOTREACHED() will have already been hit.
602 DLOG(ERROR) << "Failed to create Ax window";
603 return AtlHresultFromLastError();
607 SetObjectRects(&position_rect, &clip_rect);
610 base::win::ScopedComPtr<IOleInPlaceActiveObject> in_place_active_object(this);
612 // Gone active by now, take care of UIACTIVATE
613 if (DoesVerbUIActivate(verb)) {
614 if (!m_bUIActive) {
615 m_bUIActive = TRUE;
616 hr = m_spInPlaceSite->OnUIActivate();
617 if (FAILED(hr))
618 return hr;
619 // set ourselves up in the host
620 if (in_place_active_object) {
621 if (in_place_frame_)
622 in_place_frame_->SetActiveObject(in_place_active_object, NULL);
623 if (in_place_ui_window)
624 in_place_ui_window->SetActiveObject(in_place_active_object, NULL);
628 m_spClientSite->ShowObject();
629 return S_OK;
632 void ChromeActiveDocument::OnNavigationStateChanged(
633 int flags, const NavigationInfo& nav_info) {
634 // TODO(joshia): handle INVALIDATE_TAB,INVALIDATE_LOAD etc.
635 DVLOG(1) << __FUNCTION__
636 << "\n Flags: " << flags
637 << ", Url: " << nav_info.url
638 << ", Title: " << nav_info.title
639 << ", Type: " << nav_info.navigation_type
640 << ", Relative Offset: " << nav_info.relative_offset
641 << ", Index: " << nav_info.navigation_index;
643 UpdateNavigationState(nav_info, flags);
646 void ChromeActiveDocument::OnUpdateTargetUrl(
647 const std::wstring& new_target_url) {
648 if (in_place_frame_)
649 in_place_frame_->SetStatusText(new_target_url.c_str());
652 bool IsFindAccelerator(const MSG& msg) {
653 // TODO(robertshield): This may not stand up to localization. Fix if this
654 // is the case.
655 return msg.message == WM_KEYDOWN && msg.wParam == 'F' &&
656 base::win::IsCtrlPressed() &&
657 !(base::win::IsAltPressed() || base::win::IsShiftPressed());
660 void ChromeActiveDocument::OnAcceleratorPressed(const MSG& accel_message) {
661 if (::TranslateAccelerator(m_hWnd, accelerator_table_,
662 const_cast<MSG*>(&accel_message)))
663 return;
665 bool handled_accel = false;
666 if (in_place_frame_ != NULL) {
667 handled_accel = (S_OK == in_place_frame_->TranslateAcceleratorW(
668 const_cast<MSG*>(&accel_message), 0));
671 if (!handled_accel) {
672 if (IsFindAccelerator(accel_message)) {
673 // Handle the showing of the find dialog explicitly.
674 OnFindInPage();
675 } else {
676 BaseActiveX::OnAcceleratorPressed(accel_message);
678 } else {
679 DVLOG(1) << "IE handled accel key " << accel_message.wParam;
683 void ChromeActiveDocument::OnTabbedOut(bool reverse) {
684 DVLOG(1) << __FUNCTION__;
685 if (in_place_frame_) {
686 MSG msg = { NULL, WM_KEYDOWN, VK_TAB };
687 in_place_frame_->TranslateAcceleratorW(&msg, 0);
691 void ChromeActiveDocument::OnDidNavigate(const NavigationInfo& nav_info) {
692 DVLOG(1) << __FUNCTION__ << std::endl
693 << "Url: " << nav_info.url
694 << ", Title: " << nav_info.title
695 << ", Type: " << nav_info.navigation_type
696 << ", Relative Offset: " << nav_info.relative_offset
697 << ", Index: " << nav_info.navigation_index;
699 CrashMetricsReporter::GetInstance()->IncrementMetric(
700 CrashMetricsReporter::CHROME_FRAME_NAVIGATION_COUNT);
702 UpdateNavigationState(nav_info, 0);
705 void ChromeActiveDocument::OnCloseTab() {
706 // Base class will fire DIChromeFrameEvents::onclose.
707 BaseActiveX::OnCloseTab();
709 // Close the container window.
710 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
711 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
712 if (web_browser2)
713 web_browser2->Quit();
716 void ChromeActiveDocument::UpdateNavigationState(
717 const NavigationInfo& new_navigation_info, int flags) {
718 // This could be NULL if the active document instance is being destroyed.
719 if (!m_spInPlaceSite) {
720 DVLOG(1) << __FUNCTION__ << "m_spInPlaceSite is NULL. Returning";
721 return;
724 HRESULT hr = S_OK;
725 bool is_title_changed =
726 (navigation_info_->title != new_navigation_info.title);
727 bool is_ssl_state_changed =
728 (navigation_info_->security_style !=
729 new_navigation_info.security_style) ||
730 (navigation_info_->displayed_insecure_content !=
731 new_navigation_info.displayed_insecure_content) ||
732 (navigation_info_->ran_insecure_content !=
733 new_navigation_info.ran_insecure_content);
735 if (is_ssl_state_changed) {
736 int lock_status = SECURELOCK_SET_UNSECURE;
737 switch (new_navigation_info.security_style) {
738 case SECURITY_STYLE_AUTHENTICATED:
739 lock_status = new_navigation_info.displayed_insecure_content ?
740 SECURELOCK_SET_MIXED : SECURELOCK_SET_SECUREUNKNOWNBIT;
741 break;
742 default:
743 break;
746 base::win::ScopedVariant secure_lock_status(lock_status);
747 IEExec(&CGID_ShellDocView, INTERNAL_CMDID_SET_SSL_LOCK,
748 OLECMDEXECOPT_DODEFAULT, secure_lock_status.AsInput(), NULL);
751 // A number of poorly written bho's crash in their event sink callbacks if
752 // chrome frame is the currently loaded document. This is because they expect
753 // chrome frame to implement interfaces like IHTMLDocument, etc. We patch the
754 // event sink's of these bho's and don't invoke the event sink if chrome
755 // frame is the currently loaded document.
756 if (GetConfigBool(true, kEnableBuggyBhoIntercept)) {
757 base::win::ScopedComPtr<IWebBrowser2> wb2;
758 DoQueryService(SID_SWebBrowserApp, m_spClientSite, wb2.Receive());
759 if (wb2 && buggy_bho::BuggyBhoTls::GetInstance()) {
760 buggy_bho::BuggyBhoTls::GetInstance()->PatchBuggyBHOs(wb2);
764 // Ideally all navigations should come to Chrome Frame so that we can call
765 // BeforeNavigate2 on installed BHOs and give them a chance to cancel the
766 // navigation. However, in practice what happens is as below:
767 // The very first navigation that happens in CF happens via a Load or a
768 // LoadHistory call. In this case, IE already has the correct information for
769 // its travel log as well address bar. For other internal navigations (navs
770 // that only happen within Chrome such as anchor navigations) we need to
771 // update IE's internal state after the fact. In the case of internal
772 // navigations, we notify the BHOs but ignore the should_cancel flag.
774 // Another case where we need to issue BeforeNavigate2 calls is as below:-
775 // We get notified after the fact, when navigations are initiated within
776 // Chrome via window.open calls. These navigations are handled by creating
777 // an external tab container within chrome and then connecting to it from IE.
778 // We still want to update the address bar/history, etc, to ensure that
779 // the special URL used by Chrome to indicate this is updated correctly.
780 ChromeFrameUrl cf_url;
781 bool is_attach_external_tab_url = cf_url.Parse(std::wstring(url_)) &&
782 cf_url.attach_to_external_tab();
784 bool is_internal_navigation =
785 IsNewNavigation(new_navigation_info, flags) || is_attach_external_tab_url;
787 if (new_navigation_info.url.is_valid())
788 url_.Allocate(UTF8ToWide(new_navigation_info.url.spec()).c_str());
790 if (is_internal_navigation) {
791 base::win::ScopedComPtr<IDocObjectService> doc_object_svc;
792 base::win::ScopedComPtr<IWebBrowserEventsService> web_browser_events_svc;
794 DoQueryService(__uuidof(web_browser_events_svc), m_spClientSite,
795 web_browser_events_svc.Receive());
797 if (!web_browser_events_svc.get()) {
798 DoQueryService(SID_SShellBrowser, m_spClientSite,
799 doc_object_svc.Receive());
802 // web_browser_events_svc can be NULL on IE6.
803 if (web_browser_events_svc) {
804 VARIANT_BOOL should_cancel = VARIANT_FALSE;
805 web_browser_events_svc->FireBeforeNavigate2Event(&should_cancel);
806 } else if (doc_object_svc) {
807 BOOL should_cancel = FALSE;
808 doc_object_svc->FireBeforeNavigate2(NULL, url_, 0, NULL, NULL, 0,
809 NULL, FALSE, &should_cancel);
812 // We need to tell IE that we support navigation so that IE will query us
813 // for IPersistHistory and call GetPositionCookie to save our navigation
814 // index.
815 base::win::ScopedVariant html_window(static_cast<IUnknown*>(
816 static_cast<IHTMLWindow2*>(this)));
817 IEExec(&CGID_DocHostCmdPriv, DOCHOST_DOCCANNAVIGATE, 0,
818 html_window.AsInput(), NULL);
820 // We pass the HLNF_INTERNALJUMP flag to INTERNAL_CMDID_FINALIZE_TRAVEL_LOG
821 // since we want to make IE treat all internal navigations within this page
822 // (including anchor navigations and subframe navigations) as anchor
823 // navigations. This will ensure that IE calls GetPositionCookie
824 // to save the current position cookie in the travel log and then call
825 // SetPositionCookie when the user hits Back/Forward to come back here.
826 base::win::ScopedVariant internal_navigation(HLNF_INTERNALJUMP);
827 IEExec(&CGID_Explorer, INTERNAL_CMDID_FINALIZE_TRAVEL_LOG, 0,
828 internal_navigation.AsInput(), NULL);
830 // We no longer need to lie to IE. If we lie persistently to IE, then
831 // IE reuses us for new navigations.
832 IEExec(&CGID_DocHostCmdPriv, DOCHOST_DOCCANNAVIGATE, 0, NULL, NULL);
834 if (doc_object_svc) {
835 // Now call the FireNavigateCompleteEvent which makes IE update the text
836 // in the address-bar.
837 doc_object_svc->FireNavigateComplete2(this, 0);
838 doc_object_svc->FireDocumentComplete(this, 0);
839 } else if (web_browser_events_svc) {
840 web_browser_events_svc->FireNavigateComplete2Event();
841 web_browser_events_svc->FireDocumentCompleteEvent();
845 if (is_title_changed) {
846 base::win::ScopedVariant title(new_navigation_info.title.c_str());
847 IEExec(NULL, OLECMDID_SETTITLE, OLECMDEXECOPT_DONTPROMPTUSER,
848 title.AsInput(), NULL);
851 // It is important that we only update the navigation_info_ after we have
852 // finalized the travel log. This is because IE will ask for information
853 // such as navigation index when the travel log is finalized and we need
854 // supply the old index and not the new one.
855 *navigation_info_ = new_navigation_info;
856 // Update the IE zone here. Ideally we would like to do it when the active
857 // document is activated. However that does not work at times as the frame we
858 // get there is not the actual frame which handles the command.
859 IEExec(&CGID_Explorer, SBCMDID_MIXEDZONE, 0, NULL, NULL);
862 void ChromeActiveDocument::OnFindInPage() {
863 TabProxy* tab = GetTabProxy();
864 if (tab) {
865 if (!find_dialog_.IsWindow())
866 find_dialog_.Create(m_hWnd);
868 find_dialog_.ShowWindow(SW_SHOW);
872 void ChromeActiveDocument::OnViewSource() {
873 DCHECK(navigation_info_->url.is_valid());
874 HostNavigate(GURL(chrome::kViewSourceScheme + std::string(":") +
875 navigation_info_->url.spec()), GURL(), NEW_WINDOW);
878 void ChromeActiveDocument::OnDetermineSecurityZone(const GUID* cmd_group_guid,
879 DWORD command_id,
880 DWORD cmd_exec_opt,
881 VARIANT* in_args,
882 VARIANT* out_args) {
883 // Always return URLZONE_INTERNET since that is the Chrome's behaviour.
884 // Correct step is to use MapUrlToZone().
885 if (out_args != NULL) {
886 out_args->vt = VT_UI4;
887 out_args->ulVal = URLZONE_INTERNET;
891 void ChromeActiveDocument::OnDisplayPrivacyInfo() {
892 privacy_info_ = url_fetcher_->privacy_info();
893 Reset();
894 DoPrivacyDlg(m_hWnd, url_, this, TRUE);
897 void ChromeActiveDocument::OnGetZoomRange(const GUID* cmd_group_guid,
898 DWORD command_id,
899 DWORD cmd_exec_opt,
900 VARIANT* in_args,
901 VARIANT* out_args) {
902 if (out_args != NULL) {
903 out_args->vt = VT_I4;
904 out_args->lVal = 0;
908 void ChromeActiveDocument::OnSetZoomRange(const GUID* cmd_group_guid,
909 DWORD command_id,
910 DWORD cmd_exec_opt,
911 VARIANT* in_args,
912 VARIANT* out_args) {
913 const int kZoomIn = 125;
914 const int kZoomOut = 75;
916 if (in_args && V_VT(in_args) == VT_I4 && IsValid()) {
917 if (in_args->lVal == kZoomIn) {
918 automation_client_->SetZoomLevel(PageZoom::ZOOM_IN);
919 } else if (in_args->lVal == kZoomOut) {
920 automation_client_->SetZoomLevel(PageZoom::ZOOM_OUT);
921 } else {
922 DLOG(WARNING) << "Unsupported zoom level:" << in_args->lVal;
927 void ChromeActiveDocument::OnUnload(const GUID* cmd_group_guid,
928 DWORD command_id,
929 DWORD cmd_exec_opt,
930 VARIANT* in_args,
931 VARIANT* out_args) {
932 if (IsValid() && out_args) {
933 // If the navigation is attempted to the url loaded in CF, with the only
934 // difference being the addition of an anchor, IE will attempt to unload
935 // the currently loaded document which basically would end up running
936 // unload handlers on the currently loaded document thus rendering it non
937 // functional. We handle this as below:-
938 // The BHO receives the new url in the BeforeNavigate event.
939 // We compare the non anchor portions of the url in the BHO with the loaded
940 // url and if they match, we initiate a Chrome navigation to the url with
941 // the anchor which works nicely.
942 // We don't want to continue processing the unload in this case.
943 // Note:-
944 // IE handles these navigations by querying the loaded document for
945 // IHTMLDocument which then handles the new navigation. That won't work for
946 // us as we don't implement IHTMLDocument.
947 NavigationManager* mgr = NavigationManager::GetThreadInstance();
948 DLOG_IF(ERROR, !mgr) << "Couldn't get instance of NavigationManager";
949 if (mgr) {
950 ChromeFrameUrl url;
951 url.Parse(mgr->url());
952 if (url.gurl().has_ref()) {
953 url_canon::Replacements<char> replacements;
954 replacements.ClearRef();
956 if (url.gurl().ReplaceComponents(replacements) ==
957 GURL(static_cast<BSTR>(url_))) {
958 // We want to reuse the existing automation client and channel for
959 // initiating the new navigation. Setting the
960 // is_automation_client_reused_ flag to true before calling the
961 // LaunchUrl function achieves that.
962 is_automation_client_reused_ = true;
963 LaunchUrl(url, mgr->referrer());
964 out_args->vt = VT_BOOL;
965 out_args->boolVal = VARIANT_FALSE;
966 return;
970 bool should_unload = true;
971 automation_client_->OnUnload(&should_unload);
972 out_args->vt = VT_BOOL;
973 out_args->boolVal = should_unload ? VARIANT_TRUE : VARIANT_FALSE;
977 void ChromeActiveDocument::OnOpenURL(const GURL& url_to_open,
978 const GURL& referrer,
979 int open_disposition) {
980 // If the disposition indicates that we should be opening the URL in the
981 // current tab, then we can reuse the ChromeFrameAutomationClient instance
982 // maintained by the current ChromeActiveDocument instance. We cache this
983 // instance so that it can be used by the new ChromeActiveDocument instance
984 // which may be instantiated for handling the new URL.
985 if (open_disposition == CURRENT_TAB) {
986 // Grab a reference to ensure that the document remains valid.
987 AddRef();
988 g_active_doc_cache.Set(this);
991 BaseActiveX::OnOpenURL(url_to_open, referrer, open_disposition);
994 void ChromeActiveDocument::OnAttachExternalTab(
995 const AttachExternalTabParams& params) {
996 if (!automation_client_.get()) {
997 DLOG(WARNING) << "Invalid automation client instance";
998 return;
1000 DWORD flags = 0;
1001 if (params.user_gesture)
1002 flags = NWMF_USERREQUESTED;
1003 else if (popup_allowed_)
1004 flags = NWMF_USERALLOWED;
1006 HRESULT hr = S_OK;
1007 if (popup_manager_) {
1008 const std::wstring& url_wide = UTF8ToWide(params.url.spec());
1009 hr = popup_manager_->EvaluateNewWindow(url_wide.c_str(), NULL, url_,
1010 NULL, FALSE, flags, 0);
1012 // Allow popup
1013 if (hr == S_OK) {
1014 BaseActiveX::OnAttachExternalTab(params);
1015 return;
1018 automation_client_->BlockExternalTab(params.cookie);
1021 bool ChromeActiveDocument::PreProcessContextMenu(HMENU menu) {
1022 base::win::ScopedComPtr<IBrowserService> browser_service;
1023 base::win::ScopedComPtr<ITravelLog> travel_log;
1024 GetBrowserServiceAndTravelLog(browser_service.Receive(),
1025 travel_log.Receive());
1026 if (!browser_service || !travel_log)
1027 return true;
1029 EnableMenuItem(menu, IDC_BACK, MF_BYCOMMAND |
1030 (SUCCEEDED(travel_log->GetTravelEntry(browser_service, TLOG_BACK,
1031 NULL)) ?
1032 MF_ENABLED : MF_DISABLED));
1033 EnableMenuItem(menu, IDC_FORWARD, MF_BYCOMMAND |
1034 (SUCCEEDED(travel_log->GetTravelEntry(browser_service, TLOG_FORE,
1035 NULL)) ?
1036 MF_ENABLED : MF_DISABLED));
1037 // Call base class (adds 'About' item)
1038 return BaseActiveX::PreProcessContextMenu(menu);
1041 bool ChromeActiveDocument::HandleContextMenuCommand(
1042 UINT cmd, const MiniContextMenuParams& params) {
1043 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1044 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
1046 if (cmd == IDC_BACK)
1047 web_browser2->GoBack();
1048 else if (cmd == IDC_FORWARD)
1049 web_browser2->GoForward();
1050 else if (cmd == IDC_RELOAD)
1051 web_browser2->Refresh();
1052 else
1053 return BaseActiveX::HandleContextMenuCommand(cmd, params);
1055 return true;
1058 HRESULT ChromeActiveDocument::IEExec(const GUID* cmd_group_guid,
1059 DWORD command_id, DWORD cmd_exec_opt,
1060 VARIANT* in_args, VARIANT* out_args) {
1061 HRESULT hr = E_FAIL;
1063 base::win::ScopedComPtr<IOleCommandTarget> frame_cmd_target;
1065 base::win::ScopedComPtr<IOleInPlaceSite> in_place_site(m_spInPlaceSite);
1066 if (!in_place_site.get() && m_spClientSite != NULL)
1067 in_place_site.QueryFrom(m_spClientSite);
1069 if (in_place_site)
1070 hr = frame_cmd_target.QueryFrom(in_place_site);
1072 if (frame_cmd_target) {
1073 hr = frame_cmd_target->Exec(cmd_group_guid, command_id, cmd_exec_opt,
1074 in_args, out_args);
1077 return hr;
1080 bool ChromeActiveDocument::LaunchUrl(const ChromeFrameUrl& cf_url,
1081 const std::string& referrer) {
1082 DCHECK(!cf_url.gurl().is_empty());
1084 if (!automation_client_.get()) {
1085 // http://code.google.com/p/chromium/issues/detail?id=52894
1086 // Still not sure how this happens.
1087 DLOG(ERROR) << "No automation client!";
1088 if (!Initialize()) {
1089 NOTREACHED() << "...and failed to start a new one >:(";
1090 return false;
1094 document_url_ = cf_url.gurl().spec();
1096 url_.Allocate(UTF8ToWide(cf_url.gurl().spec()).c_str());
1097 if (cf_url.attach_to_external_tab()) {
1098 automation_client_->AttachExternalTab(cf_url.cookie());
1099 OnMoveWindow(cf_url.dimensions());
1100 } else if (!automation_client_->InitiateNavigation(cf_url.gurl().spec(),
1101 referrer,
1102 this)) {
1103 DLOG(ERROR) << "Invalid URL: " << url_;
1104 Error(L"Invalid URL");
1105 url_.Reset();
1106 return false;
1109 if (is_automation_client_reused_)
1110 return true;
1112 automation_client_->SetUrlFetcher(url_fetcher_.get());
1113 if (launch_params_) {
1114 return automation_client_->Initialize(this, launch_params_);
1115 } else {
1116 std::wstring profile = UTF8ToWide(cf_url.profile_name());
1117 // If no profile was given, then make use of the host process's name.
1118 if (profile.empty())
1119 profile = GetHostProcessName(false);
1120 return InitializeAutomation(profile, L"", IsIEInPrivate(),
1121 false, cf_url.gurl(), GURL(referrer),
1122 false);
1126 HRESULT ChromeActiveDocument::OnRefreshPage(const GUID* cmd_group_guid,
1127 DWORD command_id, DWORD cmd_exec_opt, VARIANT* in_args, VARIANT* out_args) {
1128 DVLOG(1) << __FUNCTION__;
1129 popup_allowed_ = false;
1130 if (in_args->vt == VT_I4 &&
1131 in_args->lVal & OLECMDIDF_REFRESH_PAGEACTION_POPUPWINDOW) {
1132 popup_allowed_ = true;
1134 // Ask the yellow security band to change the text and icon and to remain
1135 // visible.
1136 IEExec(&CGID_DocHostCommandHandler, OLECMDID_PAGEACTIONBLOCKED,
1137 0x80000000 | OLECMDIDF_WINDOWSTATE_USERVISIBLE_VALID, NULL, NULL);
1140 NavigationManager* mgr = NavigationManager::GetThreadInstance();
1141 DLOG_IF(ERROR, !mgr) << "Couldn't get instance of NavigationManager";
1143 // If ChromeFrame was activated on this page as a result of a document
1144 // received in response to a top level post, then we ask the user for
1145 // permission to repost and issue a navigation with the saved post data
1146 // which reinitates the whole sequence, i.e. the server receives the top
1147 // level post and chrome frame will be reactivated in response.
1148 if (mgr && mgr->post_data().type() != VT_EMPTY) {
1149 if (MessageBox(
1150 SimpleResourceLoader::Get(IDS_HTTP_POST_WARNING).c_str(),
1151 SimpleResourceLoader::Get(IDS_HTTP_POST_WARNING_TITLE).c_str(),
1152 MB_YESNO | MB_ICONEXCLAMATION) == IDYES) {
1153 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1154 DoQueryService(SID_SWebBrowserApp, m_spClientSite,
1155 web_browser2.Receive());
1156 DCHECK(web_browser2);
1157 VARIANT empty = base::win::ScopedVariant::kEmptyVariant;
1158 VARIANT flags = { VT_I4 };
1159 V_I4(&flags) = navNoHistory;
1161 return web_browser2->Navigate2(base::win::ScopedVariant(url_).AsInput(),
1162 &flags,
1163 &empty,
1164 const_cast<VARIANT*>(&mgr->post_data()),
1165 const_cast<VARIANT*>(&mgr->headers()));
1166 } else {
1167 return S_OK;
1171 TabProxy* tab_proxy = GetTabProxy();
1172 if (tab_proxy) {
1173 tab_proxy->ReloadAsync();
1174 } else {
1175 DLOG(ERROR) << "No automation proxy";
1176 DCHECK(automation_client_.get() != NULL) << "how did it get freed?";
1177 // The current url request manager (url_fetcher_) has been switched to
1178 // a stopping state so we need to reset it and get a new one for the new
1179 // automation server.
1180 ResetUrlRequestManager();
1181 url_fetcher_->set_frame_busting(false);
1182 // And now launch the current URL again. This starts a new server process.
1183 DCHECK(navigation_info_->url.is_valid());
1184 ChromeFrameUrl cf_url;
1185 cf_url.Parse(UTF8ToWide(navigation_info_->url.spec()));
1186 LaunchUrl(cf_url, navigation_info_->referrer.spec());
1189 return S_OK;
1192 HRESULT ChromeActiveDocument::SetPageFontSize(const GUID* cmd_group_guid,
1193 DWORD command_id,
1194 DWORD cmd_exec_opt,
1195 VARIANT* in_args,
1196 VARIANT* out_args) {
1197 if (!automation_client_.get()) {
1198 NOTREACHED() << "Invalid automation client";
1199 return E_FAIL;
1202 switch (command_id) {
1203 case IDM_BASELINEFONT1:
1204 automation_client_->SetPageFontSize(SMALLEST_FONT);
1205 break;
1207 case IDM_BASELINEFONT2:
1208 automation_client_->SetPageFontSize(SMALL_FONT);
1209 break;
1211 case IDM_BASELINEFONT3:
1212 automation_client_->SetPageFontSize(MEDIUM_FONT);
1213 break;
1215 case IDM_BASELINEFONT4:
1216 automation_client_->SetPageFontSize(LARGE_FONT);
1217 break;
1219 case IDM_BASELINEFONT5:
1220 automation_client_->SetPageFontSize(LARGEST_FONT);
1221 break;
1223 default:
1224 NOTREACHED() << "Invalid font size command: "
1225 << command_id;
1226 return E_FAIL;
1229 // Forward the command back to IEFrame with group set to
1230 // CGID_ExplorerBarDoc. This is probably needed to update the menu state to
1231 // indicate that the font size was set. This currently fails with error
1232 // 0x80040104.
1233 // TODO(iyengar)
1234 // Do some investigation into why this Exec call fails.
1235 IEExec(&CGID_ExplorerBarDoc, command_id, cmd_exec_opt, NULL, NULL);
1236 return S_OK;
1239 HRESULT ChromeActiveDocument::OnEncodingChange(const GUID* cmd_group_guid,
1240 DWORD command_id,
1241 DWORD cmd_exec_opt,
1242 VARIANT* in_args,
1243 VARIANT* out_args) {
1244 const struct EncodingMapData {
1245 DWORD ie_encoding_id;
1246 const char* chrome_encoding_name;
1247 } kEncodingTestDatas[] = {
1248 #define DEFINE_ENCODING_MAP(encoding_name, id, chrome_name) \
1249 { encoding_name, chrome_name },
1250 INTERNAL_IE_ENCODINGMENU_IDS(DEFINE_ENCODING_MAP)
1251 #undef DEFINE_ENCODING_MAP
1254 if (!automation_client_.get()) {
1255 NOTREACHED() << "Invalid automtion client";
1256 return E_FAIL;
1259 // Using ARRAYSIZE_UNSAFE in here is because we define the struct
1260 // EncodingMapData inside function.
1261 const char* chrome_encoding_name = NULL;
1262 for (int i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) {
1263 const struct EncodingMapData* encoding_data = &kEncodingTestDatas[i];
1264 if (command_id == encoding_data->ie_encoding_id) {
1265 chrome_encoding_name = encoding_data->chrome_encoding_name;
1266 break;
1269 // Return E_FAIL when encountering invalid encoding id.
1270 if (!chrome_encoding_name)
1271 return E_FAIL;
1273 TabProxy* tab = GetTabProxy();
1274 if (!tab) {
1275 NOTREACHED() << "Can not get TabProxy";
1276 return E_FAIL;
1279 if (chrome_encoding_name)
1280 tab->OverrideEncoding(chrome_encoding_name);
1282 // Like we did on SetPageFontSize, we may forward the command back to IEFrame
1283 // to update the menu state to indicate that which encoding was set.
1284 // TODO(iyengar)
1285 // Do some investigation into why this Exec call fails.
1286 IEExec(&CGID_ExplorerBarDoc, command_id, cmd_exec_opt, NULL, NULL);
1287 return S_OK;
1290 void ChromeActiveDocument::OnGoToHistoryEntryOffset(int offset) {
1291 DVLOG(1) << __FUNCTION__ << " - offset:" << offset;
1293 base::win::ScopedComPtr<IBrowserService> browser_service;
1294 base::win::ScopedComPtr<ITravelLog> travel_log;
1295 GetBrowserServiceAndTravelLog(browser_service.Receive(),
1296 travel_log.Receive());
1298 if (browser_service && travel_log)
1299 travel_log->Travel(browser_service, offset);
1302 void ChromeActiveDocument::OnMoveWindow(const gfx::Rect& dimensions) {
1303 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1304 DoQueryService(SID_SWebBrowserApp, m_spClientSite,
1305 web_browser2.Receive());
1306 if (!web_browser2)
1307 return;
1308 DVLOG(1) << "this:" << this << "\ndimensions: width:" << dimensions.width()
1309 << " height:" << dimensions.height();
1310 if (!dimensions.IsEmpty()) {
1311 web_browser2->put_MenuBar(VARIANT_FALSE);
1312 web_browser2->put_ToolBar(VARIANT_FALSE);
1314 int width = dimensions.width();
1315 int height = dimensions.height();
1316 // Compute the size of the browser window given the desired size of the
1317 // content area. As per MSDN, the WebBrowser object returns an error from
1318 // this method. As a result the code below is best effort.
1319 web_browser2->ClientToWindow(&width, &height);
1321 web_browser2->put_Width(width);
1322 web_browser2->put_Height(height);
1323 web_browser2->put_Left(dimensions.x());
1324 web_browser2->put_Top(dimensions.y());
1328 HRESULT ChromeActiveDocument::GetBrowserServiceAndTravelLog(
1329 IBrowserService** browser_service, ITravelLog** travel_log) {
1330 DCHECK(browser_service || travel_log);
1331 base::win::ScopedComPtr<IBrowserService> browser_service_local;
1332 HRESULT hr = DoQueryService(SID_SShellBrowser, m_spClientSite,
1333 browser_service_local.Receive());
1334 if (!browser_service_local) {
1335 NOTREACHED() << "DoQueryService for IBrowserService failed: " << hr;
1336 return hr;
1339 if (travel_log) {
1340 hr = browser_service_local->GetTravelLog(travel_log);
1341 DVLOG_IF(1, !travel_log) << "browser_service->GetTravelLog failed: " << hr;
1344 if (browser_service)
1345 *browser_service = browser_service_local.Detach();
1347 return hr;
1350 LRESULT ChromeActiveDocument::OnForward(WORD notify_code, WORD id,
1351 HWND control_window,
1352 BOOL& bHandled) {
1353 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1354 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
1355 DCHECK(web_browser2);
1357 if (web_browser2)
1358 web_browser2->GoForward();
1359 return 0;
1362 LRESULT ChromeActiveDocument::OnBack(WORD notify_code, WORD id,
1363 HWND control_window,
1364 BOOL& bHandled) {
1365 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1366 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
1367 DCHECK(web_browser2);
1369 if (web_browser2)
1370 web_browser2->GoBack();
1371 return 0;
1374 LRESULT ChromeActiveDocument::OnFirePrivacyChange(UINT message, WPARAM wparam,
1375 LPARAM lparam,
1376 BOOL& handled) {
1377 if (!m_spClientSite)
1378 return 0;
1380 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1381 DoQueryService(SID_SWebBrowserApp, m_spClientSite,
1382 web_browser2.Receive());
1383 if (!web_browser2) {
1384 NOTREACHED() << "Failed to retrieve IWebBrowser2 interface.";
1385 return 0;
1388 base::win::ScopedComPtr<IShellBrowser> shell_browser;
1389 DoQueryService(SID_STopLevelBrowser, web_browser2,
1390 shell_browser.Receive());
1391 DCHECK(shell_browser.get() != NULL);
1392 base::win::ScopedComPtr<ITridentService2> trident_services;
1393 trident_services.QueryFrom(shell_browser);
1394 if (trident_services)
1395 trident_services->FirePrivacyImpactedStateChange(wparam);
1396 else
1397 NOTREACHED() << "Failed to retrieve IWebBrowser2 interface.";
1398 return 0;
1401 LRESULT ChromeActiveDocument::OnShowWindow(UINT message, WPARAM wparam,
1402 LPARAM lparam,
1403 BOOL& handled) { // NO_LINT
1404 if (wparam)
1405 SetFocus();
1406 return 0;
1409 LRESULT ChromeActiveDocument::OnSetFocus(UINT message, WPARAM wparam,
1410 LPARAM lparam,
1411 BOOL& handled) { // NO_LINT
1412 if (!ignore_setfocus_)
1413 GiveFocusToChrome(false);
1414 return 0;
1417 bool ChromeActiveDocument::IsNewNavigation(
1418 const NavigationInfo& new_navigation_info, int flags) const {
1419 // A new navigation is typically an internal navigation which is initiated by
1420 // the renderer(WebKit). Condition 1 below has to be true along with the
1421 // any of the other conditions below.
1422 // 1. The navigation notification flags passed in as the flags parameter
1423 // is not INVALIDATE_LOAD which indicates that the loading state of the
1424 // tab changed.
1425 // 2. The navigation index is greater than 0 which means that a top level
1426 // navigation was initiated on the current external tab.
1427 // 3. The navigation type has changed.
1428 // 4. The url or the referrer are different.
1429 if (flags == TabContents::INVALIDATE_LOAD)
1430 return false;
1432 if (new_navigation_info.navigation_index <= 0)
1433 return false;
1435 if (new_navigation_info.navigation_index ==
1436 navigation_info_->navigation_index)
1437 return false;
1439 if (new_navigation_info.navigation_type != navigation_info_->navigation_type)
1440 return true;
1442 if (new_navigation_info.url != navigation_info_->url)
1443 return true;
1445 if (new_navigation_info.referrer != navigation_info_->referrer)
1446 return true;
1448 return false;