Don't override system malloc when built with MemorySanitizer.
[chromium-blink-merge.git] / chrome_frame / chrome_active_document.cc
blob7ee002667c929093ccd605c0b521ea75b4a251a2
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/logging.h"
23 #include "base/string_util.h"
24 #include "base/utf_string_conversions.h"
25 #include "base/win/scoped_variant.h"
26 #include "chrome/app/chrome_command_ids.h"
27 #include "chrome/app/chrome_dll_resource.h"
28 #include "chrome/common/automation_messages.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/test/automation/browser_proxy.h"
31 #include "chrome/test/automation/tab_proxy.h"
32 #include "chrome_frame/bho.h"
33 #include "chrome_frame/bind_context_info.h"
34 #include "chrome_frame/buggy_bho_handling.h"
35 #include "chrome_frame/crash_reporting/crash_metrics.h"
36 #include "chrome_frame/utils.h"
37 #include "content/public/browser/invalidate_type.h"
38 #include "content/public/browser/web_contents.h"
39 #include "content/public/common/page_zoom.h"
40 #include "grit/generated_resources.h"
42 DEFINE_GUID(CGID_DocHostCmdPriv, 0x000214D4L, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0,
43 0x46);
45 bool g_first_launch_by_process_ = true;
47 const DWORD kIEEncodingIdArray[] = {
48 #define DEFINE_ENCODING_ID_ARRAY(encoding_name, id, chrome_name) encoding_name,
49 INTERNAL_IE_ENCODINGMENU_IDS(DEFINE_ENCODING_ID_ARRAY)
50 #undef DEFINE_ENCODING_ID_ARRAY
51 0 // The Last data must be 0 to indicate the end of the encoding id array.
54 ChromeActiveDocument::ChromeActiveDocument()
55 : navigation_info_(new NavigationInfo()),
56 first_navigation_(true),
57 is_automation_client_reused_(false),
58 popup_allowed_(false),
59 accelerator_table_(NULL) {
60 TRACE_EVENT_BEGIN_ETW("chromeframe.createactivedocument", this, "");
62 url_fetcher_->set_frame_busting(false);
63 memset(navigation_info_.get(), 0, sizeof(NavigationInfo));
66 HRESULT ChromeActiveDocument::FinalConstruct() {
67 // The FinalConstruct implementation in the ChromeFrameActivexBase class
68 // i.e. Base creates an instance of the ChromeFrameAutomationClient class
69 // and initializes it, which would spawn a new Chrome process, etc.
70 // We don't want to be doing this if we have a cached document, whose
71 // automation client instance can be reused.
72 HRESULT hr = BaseActiveX::FinalConstruct();
73 if (FAILED(hr))
74 return hr;
76 InitializeAutomationSettings();
78 find_dialog_.Init(automation_client_.get());
80 OLECMDF flags = static_cast<OLECMDF>(OLECMDF_ENABLED | OLECMDF_SUPPORTED);
82 null_group_commands_map_[OLECMDID_PRINT] = flags;
83 null_group_commands_map_[OLECMDID_FIND] = flags;
84 null_group_commands_map_[OLECMDID_CUT] = flags;
85 null_group_commands_map_[OLECMDID_COPY] = flags;
86 null_group_commands_map_[OLECMDID_PASTE] = flags;
87 null_group_commands_map_[OLECMDID_SELECTALL] = flags;
88 null_group_commands_map_[OLECMDID_SAVEAS] = flags;
90 mshtml_group_commands_map_[IDM_BASELINEFONT1] = flags;
91 mshtml_group_commands_map_[IDM_BASELINEFONT2] = flags;
92 mshtml_group_commands_map_[IDM_BASELINEFONT3] = flags;
93 mshtml_group_commands_map_[IDM_BASELINEFONT4] = flags;
94 mshtml_group_commands_map_[IDM_BASELINEFONT5] = flags;
95 mshtml_group_commands_map_[IDM_VIEWSOURCE] = flags;
97 HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase);
98 accelerator_table_ =
99 LoadAccelerators(this_module,
100 MAKEINTRESOURCE(IDR_CHROME_FRAME_IE_FULL_TAB));
101 DCHECK(accelerator_table_ != NULL);
102 return S_OK;
105 ChromeActiveDocument::~ChromeActiveDocument() {
106 DVLOG(1) << __FUNCTION__;
107 if (find_dialog_.IsWindow())
108 find_dialog_.DestroyWindow();
109 // ChromeFramePlugin
110 BaseActiveX::Uninitialize();
112 TRACE_EVENT_END_ETW("chromeframe.createactivedocument", this, "");
115 // Override DoVerb
116 STDMETHODIMP ChromeActiveDocument::DoVerb(LONG verb,
117 LPMSG msg,
118 IOleClientSite* active_site,
119 LONG index,
120 HWND parent_window,
121 LPCRECT pos) {
122 // IE will try and in-place activate us in some cases. This happens when
123 // the user opens a new IE window with a URL that has us as the DocObject.
124 // Here we refuse to be activated in-place and we will force IE to UIActivate
125 // us.
126 if (OLEIVERB_INPLACEACTIVATE == verb)
127 return OLEOBJ_E_INVALIDVERB;
128 // Check if we should activate as a docobject or not
129 // (client supports IOleDocumentSite)
130 if (doc_site_) {
131 switch (verb) {
132 case OLEIVERB_SHOW: {
133 base::win::ScopedComPtr<IDocHostUIHandler> doc_host_handler;
134 doc_host_handler.QueryFrom(doc_site_);
135 if (doc_host_handler.get())
136 doc_host_handler->ShowUI(DOCHOSTUITYPE_BROWSE, this, this, NULL, NULL);
138 case OLEIVERB_OPEN:
139 case OLEIVERB_UIACTIVATE:
140 if (!m_bUIActive)
141 return doc_site_->ActivateMe(NULL);
142 break;
145 return IOleObjectImpl<ChromeActiveDocument>::DoVerb(verb,
146 msg,
147 active_site,
148 index,
149 parent_window,
150 pos);
153 // Override IOleInPlaceActiveObjectImpl::OnDocWindowActivate
154 STDMETHODIMP ChromeActiveDocument::OnDocWindowActivate(BOOL activate) {
155 DVLOG(1) << __FUNCTION__;
156 return S_OK;
159 STDMETHODIMP ChromeActiveDocument::TranslateAccelerator(MSG* msg) {
160 DVLOG(1) << __FUNCTION__;
161 if (msg == NULL)
162 return E_POINTER;
164 if (msg->message == WM_KEYDOWN && msg->wParam == VK_TAB) {
165 HWND focus = ::GetFocus();
166 if (focus != m_hWnd && !::IsChild(m_hWnd, focus)) {
167 // The call to SetFocus triggers a WM_SETFOCUS that makes the base class
168 // set focus to the correct element in Chrome.
169 ::SetFocus(m_hWnd);
170 return S_OK;
174 return S_FALSE;
176 // Override IPersistStorageImpl::IsDirty
177 STDMETHODIMP ChromeActiveDocument::IsDirty() {
178 DVLOG(1) << __FUNCTION__;
179 return S_FALSE;
182 void ChromeActiveDocument::OnAutomationServerReady() {
183 BaseActiveX::OnAutomationServerReady();
184 BaseActiveX::GiveFocusToChrome(true);
187 STDMETHODIMP ChromeActiveDocument::Load(BOOL fully_avalable,
188 IMoniker* moniker_name,
189 LPBC bind_context,
190 DWORD mode) {
191 if (NULL == moniker_name)
192 return E_INVALIDARG;
194 base::win::ScopedComPtr<IOleClientSite> client_site;
195 if (bind_context) {
196 base::win::ScopedComPtr<IUnknown> site;
197 bind_context->GetObjectParam(SZ_HTML_CLIENTSITE_OBJECTPARAM,
198 site.Receive());
199 if (site)
200 client_site.QueryFrom(site);
203 if (client_site) {
204 SetClientSite(client_site);
205 DoQueryService(IID_INewWindowManager, client_site,
206 popup_manager_.Receive());
208 // See if mshtml parsed the html header for us. If so, we need to
209 // clear the browser service flag that we use to indicate that this
210 // browser instance is navigating to a CF document.
211 base::win::ScopedComPtr<IBrowserService> browser_service;
212 DoQueryService(SID_SShellBrowser, client_site, browser_service.Receive());
213 if (browser_service) {
214 bool flagged = CheckForCFNavigation(browser_service, true);
215 DVLOG_IF(1, flagged) << "Cleared flagged browser service";
219 NavigationManager* mgr = NavigationManager::GetThreadInstance();
220 DLOG_IF(ERROR, !mgr) << "Couldn't get instance of NavigationManager";
222 std::wstring url;
224 base::win::ScopedComPtr<BindContextInfo> info;
225 BindContextInfo::FromBindContext(bind_context, info.Receive());
226 DCHECK(info);
227 if (info && !info->GetUrl().empty()) {
228 url = info->GetUrl();
229 if (mgr) {
230 // If the original URL contains an anchor, then the URL queried
231 // from the protocol sink wrapper does not contain the anchor. To
232 // workaround this we retrieve the anchor from the navigation manager
233 // and append it to the url retrieved from the protocol sink wrapper.
234 GURL url_for_anchor(mgr->url());
235 if (url_for_anchor.has_ref()) {
236 url += L"#";
237 url += UTF8ToWide(url_for_anchor.ref());
240 } else {
241 // If the original URL contains an anchor, then the URL queried
242 // from the moniker does not contain the anchor. To workaround
243 // this we retrieve the URL from our BHO.
244 url = GetActualUrlFromMoniker(moniker_name, bind_context,
245 mgr ? mgr->url(): std::wstring());
248 ChromeFrameUrl cf_url;
249 if (!cf_url.Parse(url)) {
250 DLOG(WARNING) << __FUNCTION__ << " Failed to parse url:" << url;
251 return E_INVALIDARG;
254 std::string referrer(mgr ? mgr->referrer() : EmptyString());
255 RendererType renderer_type = cf_url.is_chrome_protocol() ?
256 RENDERER_TYPE_CHROME_GCF_PROTOCOL : RENDERER_TYPE_UNDETERMINED;
258 // With CTransaction patch we have more robust way to grab the referrer for
259 // each top-level-switch-to-CF request by peeking at our sniffing data
260 // object that lives inside the bind context. We also remember the reason
261 // we're rendering the document in Chrome.
262 if (g_patch_helper.state() == PatchHelper::PATCH_PROTOCOL && info) {
263 scoped_refptr<ProtData> prot_data = info->get_prot_data();
264 if (prot_data) {
265 referrer = prot_data->referrer();
266 renderer_type = prot_data->renderer_type();
270 // For gcf: URLs allow only about and view-source schemes to pass through for
271 // further inspection.
272 bool is_safe_scheme = cf_url.gurl().SchemeIs(chrome::kAboutScheme) ||
273 cf_url.gurl().SchemeIs(chrome::kViewSourceScheme);
274 if (cf_url.is_chrome_protocol() && !is_safe_scheme &&
275 !GetConfigBool(false, kAllowUnsafeURLs)) {
276 DLOG(ERROR) << __FUNCTION__ << " gcf: not allowed:" << url;
277 return E_INVALIDARG;
280 if (!LaunchUrl(cf_url, referrer)) {
281 DLOG(ERROR) << __FUNCTION__ << " Failed to launch url:" << url;
282 return E_INVALIDARG;
285 if (!cf_url.is_chrome_protocol() && !cf_url.attach_to_external_tab())
286 url_fetcher_->SetInfoForUrl(url.c_str(), moniker_name, bind_context);
288 // Log a metric indicating why GCF is rendering in Chrome.
289 // (Note: we only track the renderer type when using the CTransaction patch.
290 // When the code for the browser service patch and for the moniker patch is
291 // removed, this conditional can also go away.)
292 if (RENDERER_TYPE_UNDETERMINED != renderer_type) {
293 UMA_LAUNCH_TYPE_COUNT(renderer_type);
296 return S_OK;
299 STDMETHODIMP ChromeActiveDocument::Save(IMoniker* moniker_name,
300 LPBC bind_context,
301 BOOL remember) {
302 return E_NOTIMPL;
305 STDMETHODIMP ChromeActiveDocument::SaveCompleted(IMoniker* moniker_name,
306 LPBC bind_context) {
307 return E_NOTIMPL;
310 STDMETHODIMP ChromeActiveDocument::GetCurMoniker(IMoniker** moniker_name) {
311 return E_NOTIMPL;
314 STDMETHODIMP ChromeActiveDocument::GetClassID(CLSID* class_id) {
315 if (NULL == class_id)
316 return E_POINTER;
317 *class_id = GetObjectCLSID();
318 return S_OK;
321 STDMETHODIMP ChromeActiveDocument::QueryStatus(const GUID* cmd_group_guid,
322 ULONG number_of_commands,
323 OLECMD commands[],
324 OLECMDTEXT* command_text) {
325 DVLOG(1) << __FUNCTION__;
327 CommandStatusMap* command_map = NULL;
329 if (cmd_group_guid) {
330 if (IsEqualGUID(*cmd_group_guid, GUID_NULL)) {
331 command_map = &null_group_commands_map_;
332 } else if (IsEqualGUID(*cmd_group_guid, CGID_MSHTML)) {
333 command_map = &mshtml_group_commands_map_;
334 } else if (IsEqualGUID(*cmd_group_guid, CGID_Explorer)) {
335 command_map = &explorer_group_commands_map_;
336 } else if (IsEqualGUID(*cmd_group_guid, CGID_ShellDocView)) {
337 command_map = &shdoc_view_group_commands_map_;
339 } else {
340 command_map = &null_group_commands_map_;
343 if (!command_map) {
344 DVLOG(1) << "unsupported command group: " << GuidToString(*cmd_group_guid);
345 return OLECMDERR_E_NOTSUPPORTED;
348 for (ULONG command_index = 0; command_index < number_of_commands;
349 command_index++) {
350 DVLOG(1) << "Command id = " << commands[command_index].cmdID;
351 CommandStatusMap::iterator index =
352 command_map->find(commands[command_index].cmdID);
353 if (index != command_map->end())
354 commands[command_index].cmdf = index->second;
356 return S_OK;
359 STDMETHODIMP ChromeActiveDocument::Exec(const GUID* cmd_group_guid,
360 DWORD command_id,
361 DWORD cmd_exec_opt,
362 VARIANT* in_args,
363 VARIANT* out_args) {
364 DVLOG(1) << __FUNCTION__ << " Cmd id =" << command_id;
365 // Bail out if we have been uninitialized.
366 if (automation_client_.get() && automation_client_->tab()) {
367 return ProcessExecCommand(cmd_group_guid, command_id, cmd_exec_opt,
368 in_args, out_args);
369 } else if (command_id == OLECMDID_REFRESH && cmd_group_guid == NULL) {
370 // If the automation server has crashed and the user is refreshing the
371 // page, let OnRefreshPage attempt to recover.
372 OnRefreshPage(cmd_group_guid, command_id, cmd_exec_opt, in_args, out_args);
375 return OLECMDERR_E_NOTSUPPORTED;
378 STDMETHODIMP ChromeActiveDocument::LoadHistory(IStream* stream,
379 IBindCtx* bind_context) {
380 // Read notes in ChromeActiveDocument::SaveHistory
381 DCHECK(stream);
382 LARGE_INTEGER offset = {0};
383 ULARGE_INTEGER cur_pos = {0};
384 STATSTG statstg = {0};
386 stream->Seek(offset, STREAM_SEEK_CUR, &cur_pos);
387 stream->Stat(&statstg, STATFLAG_NONAME);
389 DWORD url_size = statstg.cbSize.LowPart - cur_pos.LowPart;
390 base::win::ScopedBstr url_bstr;
391 DWORD bytes_read = 0;
392 stream->Read(url_bstr.AllocateBytes(url_size), url_size, &bytes_read);
393 std::wstring url(url_bstr);
395 ChromeFrameUrl cf_url;
396 if (!cf_url.Parse(url)) {
397 DLOG(WARNING) << __FUNCTION__ << " Failed to parse url:" << url;
398 return E_INVALIDARG;
401 const std::string& referrer = EmptyString();
402 if (!LaunchUrl(cf_url, referrer)) {
403 NOTREACHED() << __FUNCTION__ << " Failed to launch url:" << url;
404 return E_INVALIDARG;
406 return S_OK;
409 STDMETHODIMP ChromeActiveDocument::SaveHistory(IStream* stream) {
410 // TODO(sanjeevr): We need to fetch the entire list of navigation entries
411 // from Chrome and persist it in the stream. And in LoadHistory we need to
412 // pass this list back to Chrome which will recreate the list. This will allow
413 // Back-Forward navigation to anchors to work correctly when we navigate to a
414 // page outside of ChromeFrame and then come back.
415 if (!stream) {
416 NOTREACHED();
417 return E_INVALIDARG;
420 LARGE_INTEGER offset = {0};
421 ULARGE_INTEGER new_pos = {0};
422 DWORD written = 0;
423 std::wstring url = UTF8ToWide(navigation_info_->url.spec());
424 return stream->Write(url.c_str(), (url.length() + 1) * sizeof(wchar_t),
425 &written);
428 STDMETHODIMP ChromeActiveDocument::SetPositionCookie(DWORD position_cookie) {
429 if (automation_client_.get()) {
430 int index = static_cast<int>(position_cookie);
431 navigation_info_->navigation_index = index;
432 automation_client_->NavigateToIndex(index);
433 } else {
434 DLOG(WARNING) << "Invalid automation client instance";
436 return S_OK;
439 STDMETHODIMP ChromeActiveDocument::GetPositionCookie(DWORD* position_cookie) {
440 if (!position_cookie)
441 return E_INVALIDARG;
443 *position_cookie = navigation_info_->navigation_index;
444 return S_OK;
447 STDMETHODIMP ChromeActiveDocument::GetUrlForEvents(BSTR* url) {
448 if (NULL == url)
449 return E_POINTER;
450 *url = ::SysAllocString(url_);
451 return S_OK;
454 STDMETHODIMP ChromeActiveDocument::GetAddressBarUrl(BSTR* url) {
455 return GetUrlForEvents(url);
458 STDMETHODIMP ChromeActiveDocument::Reset() {
459 next_privacy_record_ = privacy_info_.privacy_records.begin();
460 return S_OK;
463 STDMETHODIMP ChromeActiveDocument::GetSize(DWORD* size) {
464 if (!size)
465 return E_POINTER;
467 *size = privacy_info_.privacy_records.size();
468 return S_OK;
471 STDMETHODIMP ChromeActiveDocument::GetPrivacyImpacted(BOOL* privacy_impacted) {
472 if (!privacy_impacted)
473 return E_POINTER;
475 *privacy_impacted = privacy_info_.privacy_impacted;
476 return S_OK;
479 STDMETHODIMP ChromeActiveDocument::Next(BSTR* url, BSTR* policy,
480 LONG* reserved, DWORD* flags) {
481 if (!url || !policy || !flags)
482 return E_POINTER;
484 if (next_privacy_record_ == privacy_info_.privacy_records.end())
485 return HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS);
487 *url = SysAllocString(next_privacy_record_->first.c_str());
488 *policy = SysAllocString(next_privacy_record_->second.policy_ref.c_str());
489 *flags = next_privacy_record_->second.flags;
491 next_privacy_record_++;
492 return S_OK;
495 bool ChromeActiveDocument::IsSchemeAllowed(const GURL& url) {
496 bool allowed = BaseActiveX::IsSchemeAllowed(url);
497 if (allowed)
498 return true;
500 if (url.SchemeIs(chrome::kAboutScheme)) {
501 if (LowerCaseEqualsASCII(url.spec(), chrome::kAboutPluginsURL))
502 return true;
504 return false;
507 HRESULT ChromeActiveDocument::GetInPlaceFrame(
508 IOleInPlaceFrame** in_place_frame) {
509 DCHECK(in_place_frame);
510 if (in_place_frame_) {
511 *in_place_frame = in_place_frame_.get();
512 (*in_place_frame)->AddRef();
513 return S_OK;
514 } else {
515 return S_FALSE;
519 HRESULT ChromeActiveDocument::IOleObject_SetClientSite(
520 IOleClientSite* client_site) {
521 if (client_site == NULL) {
522 base::win::ScopedComPtr<IDocHostUIHandler> doc_host_handler;
523 if (doc_site_)
524 doc_host_handler.QueryFrom(doc_site_);
526 if (doc_host_handler.get())
527 doc_host_handler->HideUI();
529 doc_site_.Release();
532 if (client_site != m_spClientSite)
533 return BaseActiveX::IOleObject_SetClientSite(client_site);
535 return S_OK;
538 HRESULT ChromeActiveDocument::ActiveXDocActivate(LONG verb) {
539 HRESULT hr = S_OK;
540 m_bNegotiatedWnd = TRUE;
541 if (!m_bInPlaceActive) {
542 hr = m_spInPlaceSite->CanInPlaceActivate();
543 if (FAILED(hr))
544 return hr;
545 m_spInPlaceSite->OnInPlaceActivate();
547 m_bInPlaceActive = TRUE;
548 // get location in the parent window,
549 // as well as some information about the parent
550 base::win::ScopedComPtr<IOleInPlaceUIWindow> in_place_ui_window;
551 frame_info_.cb = sizeof(OLEINPLACEFRAMEINFO);
552 HWND parent_window = NULL;
553 if (m_spInPlaceSite->GetWindow(&parent_window) == S_OK) {
554 in_place_frame_.Release();
555 RECT position_rect = {0};
556 RECT clip_rect = {0};
557 m_spInPlaceSite->GetWindowContext(in_place_frame_.Receive(),
558 in_place_ui_window.Receive(),
559 &position_rect,
560 &clip_rect,
561 &frame_info_);
562 if (!m_bWndLess) {
563 if (IsWindow()) {
564 ::ShowWindow(m_hWnd, SW_SHOW);
565 SetFocus();
566 } else {
567 m_hWnd = Create(parent_window, position_rect);
568 if (!IsWindow()) {
569 // This might happen if the automation server couldn't be
570 // instantiated. If so, a NOTREACHED() will have already been hit.
571 DLOG(ERROR) << "Failed to create Ax window";
572 return AtlHresultFromLastError();
576 SetObjectRects(&position_rect, &clip_rect);
579 base::win::ScopedComPtr<IOleInPlaceActiveObject> in_place_active_object(this);
581 // Gone active by now, take care of UIACTIVATE
582 if (DoesVerbUIActivate(verb)) {
583 if (!m_bUIActive) {
584 m_bUIActive = TRUE;
585 hr = m_spInPlaceSite->OnUIActivate();
586 if (FAILED(hr))
587 return hr;
588 // set ourselves up in the host
589 if (in_place_active_object) {
590 if (in_place_frame_)
591 in_place_frame_->SetActiveObject(in_place_active_object, NULL);
592 if (in_place_ui_window)
593 in_place_ui_window->SetActiveObject(in_place_active_object, NULL);
597 m_spClientSite->ShowObject();
598 return S_OK;
601 void ChromeActiveDocument::OnNavigationStateChanged(
602 int flags, const NavigationInfo& nav_info) {
603 // TODO(joshia): handle INVALIDATE_TYPE_TAB,INVALIDATE_TYPE_LOAD etc.
604 DVLOG(1) << __FUNCTION__
605 << "\n Flags: " << flags
606 << ", Url: " << nav_info.url
607 << ", Title: " << nav_info.title
608 << ", Type: " << nav_info.navigation_type
609 << ", Relative Offset: " << nav_info.relative_offset
610 << ", Index: " << nav_info.navigation_index;
612 UpdateNavigationState(nav_info, flags);
615 void ChromeActiveDocument::OnUpdateTargetUrl(
616 const std::wstring& new_target_url) {
617 if (in_place_frame_)
618 in_place_frame_->SetStatusText(new_target_url.c_str());
621 bool IsFindAccelerator(const MSG& msg) {
622 // TODO(robertshield): This may not stand up to localization. Fix if this
623 // is the case.
624 return msg.message == WM_KEYDOWN && msg.wParam == 'F' &&
625 base::win::IsCtrlPressed() &&
626 !(base::win::IsAltPressed() || base::win::IsShiftPressed());
629 void ChromeActiveDocument::OnAcceleratorPressed(const MSG& accel_message) {
630 if (::TranslateAccelerator(m_hWnd, accelerator_table_,
631 const_cast<MSG*>(&accel_message)))
632 return;
634 bool handled_accel = false;
635 if (in_place_frame_ != NULL) {
636 handled_accel = (S_OK == in_place_frame_->TranslateAcceleratorW(
637 const_cast<MSG*>(&accel_message), 0));
640 if (!handled_accel) {
641 if (IsFindAccelerator(accel_message)) {
642 // Handle the showing of the find dialog explicitly.
643 OnFindInPage();
644 } else {
645 BaseActiveX::OnAcceleratorPressed(accel_message);
647 } else {
648 DVLOG(1) << "IE handled accel key " << accel_message.wParam;
652 void ChromeActiveDocument::OnTabbedOut(bool reverse) {
653 DVLOG(1) << __FUNCTION__;
654 if (in_place_frame_) {
655 MSG msg = { NULL, WM_KEYDOWN, VK_TAB };
656 in_place_frame_->TranslateAcceleratorW(&msg, 0);
660 void ChromeActiveDocument::OnDidNavigate(const NavigationInfo& nav_info) {
661 DVLOG(1) << __FUNCTION__ << std::endl
662 << "Url: " << nav_info.url
663 << ", Title: " << nav_info.title
664 << ", Type: " << nav_info.navigation_type
665 << ", Relative Offset: " << nav_info.relative_offset
666 << ", Index: " << nav_info.navigation_index;
668 CrashMetricsReporter::GetInstance()->IncrementMetric(
669 CrashMetricsReporter::CHROME_FRAME_NAVIGATION_COUNT);
671 UpdateNavigationState(nav_info, 0);
674 void ChromeActiveDocument::OnCloseTab() {
675 // Base class will fire DIChromeFrameEvents::onclose.
676 BaseActiveX::OnCloseTab();
678 // Close the container window.
679 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
680 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
681 if (web_browser2)
682 web_browser2->Quit();
685 void ChromeActiveDocument::UpdateNavigationState(
686 const NavigationInfo& new_navigation_info, int flags) {
687 // This could be NULL if the active document instance is being destroyed.
688 if (!m_spInPlaceSite) {
689 DVLOG(1) << __FUNCTION__ << "m_spInPlaceSite is NULL. Returning";
690 return;
693 HRESULT hr = S_OK;
694 bool is_title_changed =
695 (navigation_info_->title != new_navigation_info.title);
696 bool is_ssl_state_changed =
697 (navigation_info_->security_style !=
698 new_navigation_info.security_style) ||
699 (navigation_info_->displayed_insecure_content !=
700 new_navigation_info.displayed_insecure_content) ||
701 (navigation_info_->ran_insecure_content !=
702 new_navigation_info.ran_insecure_content);
704 if (is_ssl_state_changed) {
705 int lock_status = SECURELOCK_SET_UNSECURE;
706 switch (new_navigation_info.security_style) {
707 case content::SECURITY_STYLE_AUTHENTICATED:
708 lock_status = new_navigation_info.displayed_insecure_content ?
709 SECURELOCK_SET_MIXED : SECURELOCK_SET_SECUREUNKNOWNBIT;
710 break;
711 default:
712 break;
715 base::win::ScopedVariant secure_lock_status(lock_status);
716 IEExec(&CGID_ShellDocView, INTERNAL_CMDID_SET_SSL_LOCK,
717 OLECMDEXECOPT_DODEFAULT, secure_lock_status.AsInput(), NULL);
720 // A number of poorly written bho's crash in their event sink callbacks if
721 // chrome frame is the currently loaded document. This is because they expect
722 // chrome frame to implement interfaces like IHTMLDocument, etc. We patch the
723 // event sink's of these bho's and don't invoke the event sink if chrome
724 // frame is the currently loaded document.
725 if (GetConfigBool(true, kEnableBuggyBhoIntercept)) {
726 base::win::ScopedComPtr<IWebBrowser2> wb2;
727 DoQueryService(SID_SWebBrowserApp, m_spClientSite, wb2.Receive());
728 if (wb2 && buggy_bho::BuggyBhoTls::GetInstance()) {
729 buggy_bho::BuggyBhoTls::GetInstance()->PatchBuggyBHOs(wb2);
733 // Ideally all navigations should come to Chrome Frame so that we can call
734 // BeforeNavigate2 on installed BHOs and give them a chance to cancel the
735 // navigation. However, in practice what happens is as below:
736 // The very first navigation that happens in CF happens via a Load or a
737 // LoadHistory call. In this case, IE already has the correct information for
738 // its travel log as well address bar. For other internal navigations (navs
739 // that only happen within Chrome such as anchor navigations) we need to
740 // update IE's internal state after the fact. In the case of internal
741 // navigations, we notify the BHOs but ignore the should_cancel flag.
743 // Another case where we need to issue BeforeNavigate2 calls is as below:-
744 // We get notified after the fact, when navigations are initiated within
745 // Chrome via window.open calls. These navigations are handled by creating
746 // an external tab container within chrome and then connecting to it from IE.
747 // We still want to update the address bar/history, etc, to ensure that
748 // the special URL used by Chrome to indicate this is updated correctly.
749 ChromeFrameUrl cf_url;
750 bool is_attach_external_tab_url = cf_url.Parse(std::wstring(url_)) &&
751 cf_url.attach_to_external_tab();
753 bool is_internal_navigation =
754 IsNewNavigation(new_navigation_info, flags) || is_attach_external_tab_url;
756 if (new_navigation_info.url.is_valid())
757 url_.Allocate(UTF8ToWide(new_navigation_info.url.spec()).c_str());
759 if (is_internal_navigation) {
760 // IE6 does not support tabs. If Chrome sent us a window open request
761 // indicating that the navigation needs to occur in a foreground tab or
762 // a popup window, then we need to ensure that the new window in IE6 is
763 // brought to the foreground.
764 if (GetIEVersion() == IE_6 &&
765 is_attach_external_tab_url &&
766 (cf_url.disposition() == NEW_FOREGROUND_TAB ||
767 cf_url.disposition() == NEW_POPUP)) {
768 base::win::ScopedComPtr<IWebBrowser2> wb2;
769 DoQueryService(SID_SWebBrowserApp, m_spClientSite, wb2.Receive());
770 if (wb2)
771 BaseActiveX::BringWebBrowserWindowToTop(wb2);
773 base::win::ScopedComPtr<IDocObjectService> doc_object_svc;
774 base::win::ScopedComPtr<IWebBrowserEventsService> web_browser_events_svc;
776 DoQueryService(__uuidof(web_browser_events_svc), m_spClientSite,
777 web_browser_events_svc.Receive());
779 if (!web_browser_events_svc.get()) {
780 DoQueryService(SID_SShellBrowser, m_spClientSite,
781 doc_object_svc.Receive());
784 // web_browser_events_svc can be NULL on IE6.
785 if (web_browser_events_svc) {
786 VARIANT_BOOL should_cancel = VARIANT_FALSE;
787 web_browser_events_svc->FireBeforeNavigate2Event(&should_cancel);
788 } else if (doc_object_svc) {
789 BOOL should_cancel = FALSE;
790 doc_object_svc->FireBeforeNavigate2(NULL, url_, 0, NULL, NULL, 0,
791 NULL, FALSE, &should_cancel);
794 // We need to tell IE that we support navigation so that IE will query us
795 // for IPersistHistory and call GetPositionCookie to save our navigation
796 // index.
797 base::win::ScopedVariant html_window(static_cast<IUnknown*>(
798 static_cast<IHTMLWindow2*>(this)));
799 IEExec(&CGID_DocHostCmdPriv, DOCHOST_DOCCANNAVIGATE, 0,
800 html_window.AsInput(), NULL);
802 // We pass the HLNF_INTERNALJUMP flag to INTERNAL_CMDID_FINALIZE_TRAVEL_LOG
803 // since we want to make IE treat all internal navigations within this page
804 // (including anchor navigations and subframe navigations) as anchor
805 // navigations. This will ensure that IE calls GetPositionCookie
806 // to save the current position cookie in the travel log and then call
807 // SetPositionCookie when the user hits Back/Forward to come back here.
808 base::win::ScopedVariant internal_navigation(HLNF_INTERNALJUMP);
809 IEExec(&CGID_Explorer, INTERNAL_CMDID_FINALIZE_TRAVEL_LOG, 0,
810 internal_navigation.AsInput(), NULL);
812 // We no longer need to lie to IE. If we lie persistently to IE, then
813 // IE reuses us for new navigations.
814 IEExec(&CGID_DocHostCmdPriv, DOCHOST_DOCCANNAVIGATE, 0, NULL, NULL);
816 if (doc_object_svc) {
817 // Now call the FireNavigateCompleteEvent which makes IE update the text
818 // in the address-bar.
819 doc_object_svc->FireNavigateComplete2(this, 0);
820 doc_object_svc->FireDocumentComplete(this, 0);
821 } else if (web_browser_events_svc) {
822 web_browser_events_svc->FireNavigateComplete2Event();
823 web_browser_events_svc->FireDocumentCompleteEvent();
827 if (is_title_changed) {
828 base::win::ScopedVariant title(new_navigation_info.title.c_str());
829 IEExec(NULL, OLECMDID_SETTITLE, OLECMDEXECOPT_DONTPROMPTUSER,
830 title.AsInput(), NULL);
833 // It is important that we only update the navigation_info_ after we have
834 // finalized the travel log. This is because IE will ask for information
835 // such as navigation index when the travel log is finalized and we need
836 // supply the old index and not the new one.
837 *navigation_info_ = new_navigation_info;
838 // Update the IE zone here. Ideally we would like to do it when the active
839 // document is activated. However that does not work at times as the frame we
840 // get there is not the actual frame which handles the command.
841 IEExec(&CGID_Explorer, SBCMDID_MIXEDZONE, 0, NULL, NULL);
844 void ChromeActiveDocument::OnFindInPage() {
845 TabProxy* tab = GetTabProxy();
846 if (tab) {
847 if (!find_dialog_.IsWindow())
848 find_dialog_.Create(m_hWnd);
850 find_dialog_.ShowWindow(SW_SHOW);
854 void ChromeActiveDocument::OnViewSource() {
855 DCHECK(navigation_info_->url.is_valid());
856 HostNavigate(GURL(chrome::kViewSourceScheme + std::string(":") +
857 navigation_info_->url.spec()), GURL(), NEW_WINDOW);
860 void ChromeActiveDocument::OnDetermineSecurityZone(const GUID* cmd_group_guid,
861 DWORD command_id,
862 DWORD cmd_exec_opt,
863 VARIANT* in_args,
864 VARIANT* out_args) {
865 // Always return URLZONE_INTERNET since that is the Chrome's behaviour.
866 // Correct step is to use MapUrlToZone().
867 if (out_args != NULL) {
868 out_args->vt = VT_UI4;
869 out_args->ulVal = URLZONE_INTERNET;
873 void ChromeActiveDocument::OnDisplayPrivacyInfo() {
874 privacy_info_ = url_fetcher_->privacy_info();
875 Reset();
876 DoPrivacyDlg(m_hWnd, url_, this, TRUE);
879 void ChromeActiveDocument::OnGetZoomRange(const GUID* cmd_group_guid,
880 DWORD command_id,
881 DWORD cmd_exec_opt,
882 VARIANT* in_args,
883 VARIANT* out_args) {
884 if (out_args != NULL) {
885 out_args->vt = VT_I4;
886 out_args->lVal = 0;
890 void ChromeActiveDocument::OnSetZoomRange(const GUID* cmd_group_guid,
891 DWORD command_id,
892 DWORD cmd_exec_opt,
893 VARIANT* in_args,
894 VARIANT* out_args) {
895 const int kZoomIn = 125;
896 const int kZoomOut = 75;
898 if (in_args && V_VT(in_args) == VT_I4 && IsValid()) {
899 if (in_args->lVal == kZoomIn) {
900 automation_client_->SetZoomLevel(content::PAGE_ZOOM_IN);
901 } else if (in_args->lVal == kZoomOut) {
902 automation_client_->SetZoomLevel(content::PAGE_ZOOM_OUT);
903 } else {
904 DLOG(WARNING) << "Unsupported zoom level:" << in_args->lVal;
909 void ChromeActiveDocument::OnUnload(const GUID* cmd_group_guid,
910 DWORD command_id,
911 DWORD cmd_exec_opt,
912 VARIANT* in_args,
913 VARIANT* out_args) {
914 if (IsValid() && out_args) {
915 // If the navigation is attempted to the url loaded in CF, with the only
916 // difference being the addition of an anchor, IE will attempt to unload
917 // the currently loaded document which basically would end up running
918 // unload handlers on the currently loaded document thus rendering it non
919 // functional. We handle this as below:-
920 // The BHO receives the new url in the BeforeNavigate event.
921 // We compare the non anchor portions of the url in the BHO with the loaded
922 // url and if they match, we initiate a Chrome navigation to the url with
923 // the anchor which works nicely.
924 // We don't want to continue processing the unload in this case.
925 // Note:-
926 // IE handles these navigations by querying the loaded document for
927 // IHTMLDocument which then handles the new navigation. That won't work for
928 // us as we don't implement IHTMLDocument.
929 NavigationManager* mgr = NavigationManager::GetThreadInstance();
930 DLOG_IF(ERROR, !mgr) << "Couldn't get instance of NavigationManager";
931 if (mgr) {
932 ChromeFrameUrl url;
933 url.Parse(mgr->url());
934 if (url.gurl().has_ref()) {
935 url_canon::Replacements<char> replacements;
936 replacements.ClearRef();
938 if (url.gurl().ReplaceComponents(replacements) ==
939 GURL(static_cast<BSTR>(url_))) {
940 // We want to reuse the existing automation client and channel for
941 // initiating the new navigation. Setting the
942 // is_automation_client_reused_ flag to true before calling the
943 // LaunchUrl function achieves that.
944 is_automation_client_reused_ = true;
945 LaunchUrl(url, mgr->referrer());
946 out_args->vt = VT_BOOL;
947 out_args->boolVal = VARIANT_FALSE;
948 return;
952 bool should_unload = true;
953 automation_client_->OnUnload(&should_unload);
954 out_args->vt = VT_BOOL;
955 out_args->boolVal = should_unload ? VARIANT_TRUE : VARIANT_FALSE;
959 void ChromeActiveDocument::OnAttachExternalTab(
960 const AttachExternalTabParams& params) {
961 if (!automation_client_.get()) {
962 DLOG(WARNING) << "Invalid automation client instance";
963 return;
965 DWORD flags = 0;
966 if (params.user_gesture)
967 flags = NWMF_USERREQUESTED;
968 else if (popup_allowed_)
969 flags = NWMF_USERALLOWED;
971 HRESULT hr = S_OK;
972 if (popup_manager_) {
973 const std::wstring& url_wide = UTF8ToWide(params.url.spec());
974 hr = popup_manager_->EvaluateNewWindow(url_wide.c_str(), NULL, url_,
975 NULL, FALSE, flags, 0);
977 // Allow popup
978 if (hr == S_OK) {
979 BaseActiveX::OnAttachExternalTab(params);
980 return;
983 automation_client_->BlockExternalTab(params.cookie);
986 bool ChromeActiveDocument::PreProcessContextMenu(HMENU menu) {
987 base::win::ScopedComPtr<IBrowserService> browser_service;
988 base::win::ScopedComPtr<ITravelLog> travel_log;
989 GetBrowserServiceAndTravelLog(browser_service.Receive(),
990 travel_log.Receive());
991 if (!browser_service || !travel_log)
992 return true;
994 EnableMenuItem(menu, IDC_BACK, MF_BYCOMMAND |
995 (SUCCEEDED(travel_log->GetTravelEntry(browser_service, TLOG_BACK,
996 NULL)) ?
997 MF_ENABLED : MF_DISABLED));
998 EnableMenuItem(menu, IDC_FORWARD, MF_BYCOMMAND |
999 (SUCCEEDED(travel_log->GetTravelEntry(browser_service, TLOG_FORE,
1000 NULL)) ?
1001 MF_ENABLED : MF_DISABLED));
1002 // Call base class (adds 'About' item)
1003 return BaseActiveX::PreProcessContextMenu(menu);
1006 bool ChromeActiveDocument::HandleContextMenuCommand(
1007 UINT cmd, const MiniContextMenuParams& params) {
1008 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1009 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
1011 if (cmd == IDC_BACK)
1012 web_browser2->GoBack();
1013 else if (cmd == IDC_FORWARD)
1014 web_browser2->GoForward();
1015 else if (cmd == IDC_RELOAD)
1016 web_browser2->Refresh();
1017 else
1018 return BaseActiveX::HandleContextMenuCommand(cmd, params);
1020 return true;
1023 HRESULT ChromeActiveDocument::IEExec(const GUID* cmd_group_guid,
1024 DWORD command_id, DWORD cmd_exec_opt,
1025 VARIANT* in_args, VARIANT* out_args) {
1026 HRESULT hr = E_FAIL;
1028 base::win::ScopedComPtr<IOleCommandTarget> frame_cmd_target;
1030 base::win::ScopedComPtr<IOleInPlaceSite> in_place_site(m_spInPlaceSite);
1031 if (!in_place_site.get() && m_spClientSite != NULL)
1032 in_place_site.QueryFrom(m_spClientSite);
1034 if (in_place_site)
1035 hr = frame_cmd_target.QueryFrom(in_place_site);
1037 if (frame_cmd_target) {
1038 hr = frame_cmd_target->Exec(cmd_group_guid, command_id, cmd_exec_opt,
1039 in_args, out_args);
1042 return hr;
1045 bool ChromeActiveDocument::LaunchUrl(const ChromeFrameUrl& cf_url,
1046 const std::string& referrer) {
1047 DCHECK(!cf_url.gurl().is_empty());
1049 if (!automation_client_.get()) {
1050 // http://code.google.com/p/chromium/issues/detail?id=52894
1051 // Still not sure how this happens.
1052 DLOG(ERROR) << "No automation client!";
1053 if (!Initialize()) {
1054 NOTREACHED() << "...and failed to start a new one >:(";
1055 return false;
1059 document_url_ = cf_url.gurl().spec();
1061 url_.Allocate(UTF8ToWide(cf_url.gurl().spec()).c_str());
1062 if (cf_url.attach_to_external_tab()) {
1063 automation_client_->AttachExternalTab(cf_url.cookie());
1064 OnMoveWindow(cf_url.dimensions());
1065 } else if (!automation_client_->InitiateNavigation(cf_url.gurl().spec(),
1066 referrer,
1067 this)) {
1068 DLOG(ERROR) << "Invalid URL: " << url_;
1069 Error(L"Invalid URL");
1070 url_.Reset();
1071 return false;
1074 if (is_automation_client_reused_)
1075 return true;
1077 automation_client_->SetUrlFetcher(url_fetcher_.get());
1078 if (launch_params_) {
1079 return automation_client_->Initialize(this, launch_params_);
1080 } else {
1081 std::wstring profile = UTF8ToWide(cf_url.profile_name());
1082 // If no profile was given, then make use of the host process's name.
1083 if (profile.empty())
1084 profile = GetHostProcessName(false);
1085 return InitializeAutomation(profile, IsIEInPrivate(),
1086 false, cf_url.gurl(), GURL(referrer),
1087 false);
1091 HRESULT ChromeActiveDocument::OnRefreshPage(const GUID* cmd_group_guid,
1092 DWORD command_id, DWORD cmd_exec_opt, VARIANT* in_args, VARIANT* out_args) {
1093 DVLOG(1) << __FUNCTION__;
1094 popup_allowed_ = false;
1095 if (in_args->vt == VT_I4 &&
1096 in_args->lVal & OLECMDIDF_REFRESH_PAGEACTION_POPUPWINDOW) {
1097 popup_allowed_ = true;
1099 // Ask the yellow security band to change the text and icon and to remain
1100 // visible.
1101 IEExec(&CGID_DocHostCommandHandler, OLECMDID_PAGEACTIONBLOCKED,
1102 0x80000000 | OLECMDIDF_WINDOWSTATE_USERVISIBLE_VALID, NULL, NULL);
1105 NavigationManager* mgr = NavigationManager::GetThreadInstance();
1106 DLOG_IF(ERROR, !mgr) << "Couldn't get instance of NavigationManager";
1108 // If ChromeFrame was activated on this page as a result of a document
1109 // received in response to a top level post, then we ask the user for
1110 // permission to repost and issue a navigation with the saved post data
1111 // which reinitates the whole sequence, i.e. the server receives the top
1112 // level post and chrome frame will be reactivated in response.
1113 if (mgr && mgr->post_data().type() != VT_EMPTY) {
1114 if (MessageBox(
1115 SimpleResourceLoader::Get(IDS_HTTP_POST_WARNING).c_str(),
1116 SimpleResourceLoader::Get(IDS_HTTP_POST_WARNING_TITLE).c_str(),
1117 MB_YESNO | MB_ICONEXCLAMATION) == IDYES) {
1118 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1119 DoQueryService(SID_SWebBrowserApp, m_spClientSite,
1120 web_browser2.Receive());
1121 DCHECK(web_browser2);
1122 VARIANT empty = base::win::ScopedVariant::kEmptyVariant;
1123 VARIANT flags = { VT_I4 };
1124 V_I4(&flags) = navNoHistory;
1126 return web_browser2->Navigate2(base::win::ScopedVariant(url_).AsInput(),
1127 &flags,
1128 &empty,
1129 const_cast<VARIANT*>(&mgr->post_data()),
1130 const_cast<VARIANT*>(&mgr->headers()));
1131 } else {
1132 return S_OK;
1136 TabProxy* tab_proxy = GetTabProxy();
1137 if (tab_proxy) {
1138 tab_proxy->ReloadAsync();
1139 } else {
1140 DLOG(ERROR) << "No automation proxy";
1141 DCHECK(automation_client_.get() != NULL) << "how did it get freed?";
1142 // The current url request manager (url_fetcher_) has been switched to
1143 // a stopping state so we need to reset it and get a new one for the new
1144 // automation server.
1145 ResetUrlRequestManager();
1146 url_fetcher_->set_frame_busting(false);
1147 // And now launch the current URL again. This starts a new server process.
1148 DCHECK(navigation_info_->url.is_valid());
1149 ChromeFrameUrl cf_url;
1150 cf_url.Parse(UTF8ToWide(navigation_info_->url.spec()));
1151 LaunchUrl(cf_url, navigation_info_->referrer.spec());
1154 return S_OK;
1157 HRESULT ChromeActiveDocument::SetPageFontSize(const GUID* cmd_group_guid,
1158 DWORD command_id,
1159 DWORD cmd_exec_opt,
1160 VARIANT* in_args,
1161 VARIANT* out_args) {
1162 if (!automation_client_.get()) {
1163 NOTREACHED() << "Invalid automation client";
1164 return E_FAIL;
1167 switch (command_id) {
1168 case IDM_BASELINEFONT1:
1169 automation_client_->SetPageFontSize(SMALLEST_FONT);
1170 break;
1172 case IDM_BASELINEFONT2:
1173 automation_client_->SetPageFontSize(SMALL_FONT);
1174 break;
1176 case IDM_BASELINEFONT3:
1177 automation_client_->SetPageFontSize(MEDIUM_FONT);
1178 break;
1180 case IDM_BASELINEFONT4:
1181 automation_client_->SetPageFontSize(LARGE_FONT);
1182 break;
1184 case IDM_BASELINEFONT5:
1185 automation_client_->SetPageFontSize(LARGEST_FONT);
1186 break;
1188 default:
1189 NOTREACHED() << "Invalid font size command: "
1190 << command_id;
1191 return E_FAIL;
1194 // Forward the command back to IEFrame with group set to
1195 // CGID_ExplorerBarDoc. This is probably needed to update the menu state to
1196 // indicate that the font size was set. This currently fails with error
1197 // 0x80040104.
1198 // TODO(iyengar)
1199 // Do some investigation into why this Exec call fails.
1200 IEExec(&CGID_ExplorerBarDoc, command_id, cmd_exec_opt, NULL, NULL);
1201 return S_OK;
1204 HRESULT ChromeActiveDocument::OnEncodingChange(const GUID* cmd_group_guid,
1205 DWORD command_id,
1206 DWORD cmd_exec_opt,
1207 VARIANT* in_args,
1208 VARIANT* out_args) {
1209 const struct EncodingMapData {
1210 DWORD ie_encoding_id;
1211 const char* chrome_encoding_name;
1212 } kEncodingTestDatas[] = {
1213 #define DEFINE_ENCODING_MAP(encoding_name, id, chrome_name) \
1214 { encoding_name, chrome_name },
1215 INTERNAL_IE_ENCODINGMENU_IDS(DEFINE_ENCODING_MAP)
1216 #undef DEFINE_ENCODING_MAP
1219 if (!automation_client_.get()) {
1220 NOTREACHED() << "Invalid automtion client";
1221 return E_FAIL;
1224 // Using ARRAYSIZE_UNSAFE in here is because we define the struct
1225 // EncodingMapData inside function.
1226 const char* chrome_encoding_name = NULL;
1227 for (int i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) {
1228 const struct EncodingMapData* encoding_data = &kEncodingTestDatas[i];
1229 if (command_id == encoding_data->ie_encoding_id) {
1230 chrome_encoding_name = encoding_data->chrome_encoding_name;
1231 break;
1234 // Return E_FAIL when encountering invalid encoding id.
1235 if (!chrome_encoding_name)
1236 return E_FAIL;
1238 TabProxy* tab = GetTabProxy();
1239 if (!tab) {
1240 NOTREACHED() << "Can not get TabProxy";
1241 return E_FAIL;
1244 if (chrome_encoding_name)
1245 tab->OverrideEncoding(chrome_encoding_name);
1247 // Like we did on SetPageFontSize, we may forward the command back to IEFrame
1248 // to update the menu state to indicate that which encoding was set.
1249 // TODO(iyengar)
1250 // Do some investigation into why this Exec call fails.
1251 IEExec(&CGID_ExplorerBarDoc, command_id, cmd_exec_opt, NULL, NULL);
1252 return S_OK;
1255 void ChromeActiveDocument::OnGoToHistoryEntryOffset(int offset) {
1256 DVLOG(1) << __FUNCTION__ << " - offset:" << offset;
1258 base::win::ScopedComPtr<IBrowserService> browser_service;
1259 base::win::ScopedComPtr<ITravelLog> travel_log;
1260 GetBrowserServiceAndTravelLog(browser_service.Receive(),
1261 travel_log.Receive());
1263 if (browser_service && travel_log)
1264 travel_log->Travel(browser_service, offset);
1267 void ChromeActiveDocument::OnMoveWindow(const gfx::Rect& dimensions) {
1268 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1269 DoQueryService(SID_SWebBrowserApp, m_spClientSite,
1270 web_browser2.Receive());
1271 if (!web_browser2)
1272 return;
1273 DVLOG(1) << "this:" << this << "\ndimensions: width:" << dimensions.width()
1274 << " height:" << dimensions.height();
1275 if (!dimensions.IsEmpty()) {
1276 web_browser2->put_MenuBar(VARIANT_FALSE);
1277 web_browser2->put_ToolBar(VARIANT_FALSE);
1279 int width = dimensions.width();
1280 int height = dimensions.height();
1281 // Compute the size of the browser window given the desired size of the
1282 // content area. As per MSDN, the WebBrowser object returns an error from
1283 // this method. As a result the code below is best effort.
1284 web_browser2->ClientToWindow(&width, &height);
1286 web_browser2->put_Width(width);
1287 web_browser2->put_Height(height);
1288 web_browser2->put_Left(dimensions.x());
1289 web_browser2->put_Top(dimensions.y());
1293 HRESULT ChromeActiveDocument::GetBrowserServiceAndTravelLog(
1294 IBrowserService** browser_service, ITravelLog** travel_log) {
1295 DCHECK(browser_service || travel_log);
1296 base::win::ScopedComPtr<IBrowserService> browser_service_local;
1297 HRESULT hr = DoQueryService(SID_SShellBrowser, m_spClientSite,
1298 browser_service_local.Receive());
1299 if (!browser_service_local) {
1300 NOTREACHED() << "DoQueryService for IBrowserService failed: " << hr;
1301 return hr;
1304 if (travel_log) {
1305 hr = browser_service_local->GetTravelLog(travel_log);
1306 DVLOG_IF(1, !travel_log) << "browser_service->GetTravelLog failed: " << hr;
1309 if (browser_service)
1310 *browser_service = browser_service_local.Detach();
1312 return hr;
1315 LRESULT ChromeActiveDocument::OnForward(WORD notify_code, WORD id,
1316 HWND control_window,
1317 BOOL& bHandled) {
1318 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1319 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
1320 DCHECK(web_browser2);
1322 if (web_browser2)
1323 web_browser2->GoForward();
1324 return 0;
1327 LRESULT ChromeActiveDocument::OnBack(WORD notify_code, WORD id,
1328 HWND control_window,
1329 BOOL& bHandled) {
1330 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1331 DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
1332 DCHECK(web_browser2);
1334 if (web_browser2)
1335 web_browser2->GoBack();
1336 return 0;
1339 LRESULT ChromeActiveDocument::OnFirePrivacyChange(UINT message, WPARAM wparam,
1340 LPARAM lparam,
1341 BOOL& handled) {
1342 if (!m_spClientSite)
1343 return 0;
1345 base::win::ScopedComPtr<IWebBrowser2> web_browser2;
1346 DoQueryService(SID_SWebBrowserApp, m_spClientSite,
1347 web_browser2.Receive());
1348 if (!web_browser2) {
1349 NOTREACHED() << "Failed to retrieve IWebBrowser2 interface.";
1350 return 0;
1353 base::win::ScopedComPtr<IShellBrowser> shell_browser;
1354 DoQueryService(SID_STopLevelBrowser, web_browser2,
1355 shell_browser.Receive());
1356 DCHECK(shell_browser.get() != NULL);
1357 base::win::ScopedComPtr<ITridentService2> trident_services;
1358 trident_services.QueryFrom(shell_browser);
1359 if (trident_services)
1360 trident_services->FirePrivacyImpactedStateChange(wparam);
1361 else
1362 NOTREACHED() << "Failed to retrieve IWebBrowser2 interface.";
1363 return 0;
1366 LRESULT ChromeActiveDocument::OnShowWindow(UINT message, WPARAM wparam,
1367 LPARAM lparam,
1368 BOOL& handled) { // NO_LINT
1369 if (wparam)
1370 SetFocus();
1371 return 0;
1374 LRESULT ChromeActiveDocument::OnSetFocus(UINT message, WPARAM wparam,
1375 LPARAM lparam,
1376 BOOL& handled) { // NO_LINT
1377 if (!ignore_setfocus_)
1378 GiveFocusToChrome(false);
1379 return 0;
1382 bool ChromeActiveDocument::IsNewNavigation(
1383 const NavigationInfo& new_navigation_info, int flags) const {
1384 // A new navigation is typically an internal navigation which is initiated by
1385 // the renderer(WebKit). Condition 1 below has to be true along with the
1386 // any of the other conditions below.
1387 // 1. The navigation notification flags passed in as the flags parameter
1388 // is not INVALIDATE_TYPE_LOAD which indicates that the loading state of
1389 // the tab changed.
1390 // 2. The navigation index is greater than 0 which means that a top level
1391 // navigation was initiated on the current external tab.
1392 // 3. The navigation type has changed.
1393 // 4. The url or the referrer are different.
1394 if (flags == content::INVALIDATE_TYPE_LOAD)
1395 return false;
1397 if (new_navigation_info.navigation_index <= 0)
1398 return false;
1400 if (new_navigation_info.navigation_index ==
1401 navigation_info_->navigation_index)
1402 return false;
1404 if (new_navigation_info.navigation_type != navigation_info_->navigation_type)
1405 return true;
1407 if (new_navigation_info.url != navigation_info_->url)
1408 return true;
1410 if (new_navigation_info.referrer != navigation_info_->referrer)
1411 return true;
1413 return false;