Fullscreen support for Lion.
[chromium-blink-merge.git] / chrome_frame / utils.h
bloba41978e70a152573068d75dcc4f5c1a3cc338de8
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 #ifndef CHROME_FRAME_UTILS_H_
6 #define CHROME_FRAME_UTILS_H_
8 #include <OAidl.h>
9 #include <objidl.h>
10 #include <windows.h>
11 #include <wininet.h>
12 #include <string>
13 #include <vector>
15 #include "base/basictypes.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/threading/thread.h"
19 #include "base/win/scoped_comptr.h"
20 #include "googleurl/src/gurl.h"
21 #include "ui/gfx/rect.h"
23 class FilePath;
24 interface IBrowserService;
25 interface IWebBrowser2;
26 struct ContextMenuModel;
28 // utils.h : Various utility functions and classes
30 extern const wchar_t kChromeContentPrefix[];
31 extern const char kGCFProtocol[];
32 extern const wchar_t kChromeProtocolPrefix[];
33 extern const wchar_t kChromeFrameHeadlessMode[];
34 extern const wchar_t kChromeFrameAccessibleMode[];
35 extern const wchar_t kChromeFrameUnpinnedMode[];
36 extern const wchar_t kAllowUnsafeURLs[];
37 extern const wchar_t kEnableBuggyBhoIntercept[];
38 extern const wchar_t kChromeMimeType[];
39 extern const wchar_t kChromeFrameAttachTabPattern[];
40 extern const wchar_t kChromeFrameConfigKey[];
41 extern const wchar_t kRenderInGCFUrlList[];
42 extern const wchar_t kRenderInHostUrlList[];
43 extern const wchar_t kEnableGCFRendererByDefault[];
44 extern const wchar_t kIexploreProfileName[];
45 extern const wchar_t kRundllProfileName[];
47 // This function is very similar to the AtlRegisterTypeLib function except
48 // that it takes a parameter that specifies whether to register the typelib
49 // for the current user only or on a machine-wide basis
50 // Refer to the MSDN documentation for AtlRegisterTypeLib for a description of
51 // the arguments
52 HRESULT UtilRegisterTypeLib(HINSTANCE tlb_instance,
53 LPCOLESTR index,
54 bool for_current_user_only);
56 // This function is very similar to the AtlUnRegisterTypeLib function except
57 // that it takes a parameter that specifies whether to unregister the typelib
58 // for the current user only or on a machine-wide basis
59 // Refer to the MSDN documentation for AtlUnRegisterTypeLib for a description
60 // of the arguments
61 HRESULT UtilUnRegisterTypeLib(HINSTANCE tlb_instance,
62 LPCOLESTR index,
63 bool for_current_user_only);
65 HRESULT UtilRegisterTypeLib(LPCWSTR typelib_path, bool for_current_user_only);
67 HRESULT UtilUnRegisterTypeLib(LPCWSTR typelib_path, bool for_current_user_only);
69 HRESULT UtilRegisterTypeLib(ITypeLib* typelib,
70 LPCWSTR typelib_path,
71 LPCWSTR help_dir,
72 bool for_current_user_only);
74 HRESULT UtilUnRegisterTypeLib(ITypeLib* typelib,
75 bool for_current_user_only);
77 // Clears a marker that causes legacy NPAPI registration to persist across
78 // updates. Returns false if the marker could not be removed.
79 bool UtilRemovePersistentNPAPIMarker();
81 // Given an HTML fragment, this function looks for the
82 // <meta http-equiv="X-UA-Compatible"> tag and extracts the value of the
83 // "content" attribute
84 // This method will currently return a false positive if the tag appears
85 // inside a string in a <SCRIPT> block.
86 HRESULT UtilGetXUACompatContentValue(const std::wstring& html_string,
87 std::wstring* content_value);
89 // Returns a string from ChromeFrame's string table by resource. Must be
90 // provided with a valid resource id.
91 std::wstring GetResourceString(int resource_id);
93 // Displays a message box indicating that there was a version mismatch between
94 // ChromeFrame and the running instance of Chrome.
95 // server_version is the version of the running instance of Chrome.
96 void DisplayVersionMismatchWarning(HWND parent,
97 const std::string& server_version);
99 // This class provides a base implementation for ATL modules which want to
100 // perform all their registration under HKCU. This class overrides the
101 // RegisterServer and UnregisterServer methods and registers the type libraries
102 // under HKCU (the rest of the registration is made under HKCU by changing the
103 // appropriate .RGS files)
104 template < class BaseAtlModule >
105 class AtlPerUserModule : public BaseAtlModule {
106 public:
107 HRESULT RegisterServer(BOOL reg_typelib = FALSE,
108 const CLSID* clsid = NULL) throw() {
109 HRESULT hr = BaseAtlModule::RegisterServer(FALSE, clsid);
110 if (FAILED(hr)) {
111 return hr;
113 if (reg_typelib) {
114 hr = UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib, NULL, false);
116 return hr;
119 HRESULT UnregisterServer(BOOL unreg_typelib,
120 const CLSID* clsid = NULL) throw() {
121 HRESULT hr = BaseAtlModule::UnregisterServer(FALSE, clsid);
122 if (FAILED(hr)) {
123 return hr;
125 if (unreg_typelib) {
126 hr = UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib, NULL, false);
128 return hr;
132 // Creates a javascript statement for execution from the function name and
133 // arguments passed in.
134 std::string CreateJavascript(const std::string& function_name,
135 const std::string args);
137 // Use to prevent the DLL from being unloaded while there are still living
138 // objects with outstanding references.
139 class AddRefModule {
140 public:
141 AddRefModule();
142 ~AddRefModule();
145 // Retrieves the executable name of the process hosting us. If
146 // |include_extension| is false, then we strip the extension from the name.
147 std::wstring GetHostProcessName(bool include_extension);
149 typedef enum BrowserType {
150 BROWSER_INVALID = -1,
151 BROWSER_UNKNOWN,
152 BROWSER_IE,
155 BrowserType GetBrowserType();
157 typedef enum IEVersion {
158 IE_INVALID,
159 NON_IE,
160 IE_UNSUPPORTED,
161 IE_6,
162 IE_7,
163 IE_8,
164 IE_9,
167 // The renderer to be used for a page. Values for Chrome also convey the
168 // reason why Chrome is used.
169 enum RendererType {
170 RENDERER_TYPE_UNDETERMINED = 0,
171 RENDERER_TYPE_CHROME_MIN,
172 // NOTE: group all _CHROME_ values together below here, as they are used for
173 // generating metrics reported via UMA (adjust MIN/MAX as needed).
174 RENDERER_TYPE_CHROME_GCF_PROTOCOL = RENDERER_TYPE_CHROME_MIN,
175 RENDERER_TYPE_CHROME_HTTP_EQUIV,
176 RENDERER_TYPE_CHROME_RESPONSE_HEADER,
177 RENDERER_TYPE_CHROME_DEFAULT_RENDERER,
178 RENDERER_TYPE_CHROME_OPT_IN_URL,
179 RENDERER_TYPE_CHROME_WIDGET,
180 // NOTE: all _CHOME_ values must go above here (adjust MIN/MAX as needed).
181 RENDERER_TYPE_CHROME_MAX = RENDERER_TYPE_CHROME_WIDGET,
182 RENDERER_TYPE_OTHER,
185 // Returns true if the given RendererType represents Chrome.
186 bool IsChrome(RendererType renderer_type);
188 // Convenience macro for logging a sample for the launch type metric.
189 #define UMA_LAUNCH_TYPE_COUNT(sample) \
190 UMA_HISTOGRAM_CUSTOM_COUNTS("ChromeFrame.LaunchType", sample, \
191 RENDERER_TYPE_CHROME_MIN, RENDERER_TYPE_CHROME_MAX, \
192 RENDERER_TYPE_CHROME_MAX + 1 - RENDERER_TYPE_CHROME_MIN)
194 // To get the IE version when Chrome Frame is hosted in IE. Make sure that
195 // the hosting browser is IE before calling this function, otherwise NON_IE
196 // will be returned.
198 // Versions newer than the newest supported version are reported as the newest
199 // supported version.
200 IEVersion GetIEVersion();
202 // Returns the actual major version of the IE in which the current process is
203 // hosted. Returns 0 if the current process is not IE or any other error occurs.
204 uint32 GetIEMajorVersion();
206 FilePath GetIETemporaryFilesFolder();
208 // Retrieves the file version from a module handle without extra round trips
209 // to the disk (as happens with the regular GetFileVersionInfo API).
211 // @param module A handle to the module for which to retrieve the version info.
212 // @param high On successful return holds the most significant part of the file
213 // version. Must be non-null.
214 // @param low On successful return holds the least significant part of the file
215 // version. May be NULL.
216 // @returns true if the version info was successfully retrieved.
217 bool GetModuleVersion(HMODULE module, uint32* high, uint32* low);
219 // @returns the module handle to which an address belongs.
220 HMODULE GetModuleFromAddress(void* address);
222 // Return if the IEXPLORE is in private mode. The IEIsInPrivateBrowsing() checks
223 // whether current process is IEXPLORE.
224 bool IsIEInPrivate();
226 // Calls [ieframe|shdocvw]!DoFileDownload to initiate a download.
227 HRESULT DoFileDownloadInIE(const wchar_t* url);
229 // Construct a menu from the model sent from Chrome.
230 HMENU BuildContextMenu(const ContextMenuModel& menu_model);
232 // Uses GURL internally to append 'relative' to 'document'
233 std::string ResolveURL(const std::string& document,
234 const std::string& relative);
236 // Returns true iff the two urls have the same scheme, same host and same port.
237 bool HaveSameOrigin(const std::string& url1, const std::string& url2);
239 // Get a boolean configuration value from registry.
240 bool GetConfigBool(bool default_value, const wchar_t* value_name);
242 // Gets an integer configuration value from the registry.
243 int GetConfigInt(int default_value, const wchar_t* value_name);
245 // Sets an integer configuration value in the registry.
246 bool SetConfigInt(const wchar_t* value_name, int value);
248 // Sets a boolean integer configuration value in the registry.
249 bool SetConfigBool(const wchar_t* value_name, bool value);
251 // Deletes the configuration value passed in.
252 bool DeleteConfigValue(const wchar_t* value_name);
254 // Returns true if we are running in headless mode in which case we need to
255 // gather crash dumps, etc to send them to the crash server.
256 bool IsHeadlessMode();
258 // Returns true if we are running in accessible mode in which we need to enable
259 // renderer accessibility for use in automation.
260 bool IsAccessibleMode();
262 // Returns true if we are running in unpinned mode in which case DLL
263 // eviction should be possible.
264 bool IsUnpinnedMode();
266 // Returns true if all HTML pages should be rendered in GCF by default.
267 bool IsGcfDefaultRenderer();
269 // Check if this url is opting into Chrome Frame based on static settings.
270 // Returns one of:
271 // - RENDERER_TYPE_UNDETERMINED if not opt-in or if explicit opt-out
272 // - RENDERER_TYPE_CHROME_DEFAULT_RENDERER
273 // - RENDERER_TYPE_CHROME_OPT_IN_URL
274 RendererType RendererTypeForUrl(const std::wstring& url);
276 // A shortcut for QueryService
277 template <typename T>
278 HRESULT DoQueryService(const IID& service_id, IUnknown* unk, T** service) {
279 DCHECK(service);
280 if (!unk)
281 return E_INVALIDARG;
283 base::win::ScopedComPtr<IServiceProvider> service_provider;
284 HRESULT hr = service_provider.QueryFrom(unk);
285 if (service_provider)
286 hr = service_provider->QueryService(service_id, service);
288 DCHECK(FAILED(hr) || *service);
289 return hr;
292 // Navigates an IWebBrowser2 object to a moniker.
293 // |headers| can be NULL.
294 HRESULT NavigateBrowserToMoniker(IUnknown* browser, IMoniker* moniker,
295 const wchar_t* headers, IBindCtx* bind_ctx,
296 const wchar_t* fragment, IStream* post_data,
297 VARIANT* flags);
299 // Raises a flag on the current thread (using TLS) to indicate that an
300 // in-progress navigation should be rendered in chrome frame.
301 void MarkBrowserOnThreadForCFNavigation(IBrowserService* browser);
303 // Checks if this browser instance has been marked as currently navigating
304 // to a CF document. If clear_flag is set to true, the tls flag is cleared but
305 // only if the browser has been marked.
306 bool CheckForCFNavigation(IBrowserService* browser, bool clear_flag);
308 // Returns true if the URL passed in is something which can be handled by
309 // Chrome. If this function returns false then we should fail the navigation.
310 // When is_privileged is true, chrome extension URLs will be considered valid.
311 bool IsValidUrlScheme(const GURL& url, bool is_privileged);
313 // Returns the raw http headers for the current request given an
314 // IWinInetHttpInfo pointer.
315 std::string GetRawHttpHeaders(IWinInetHttpInfo* info);
317 // Can be used to determine whether a given request is being performed for
318 // a sub-frame or iframe in Internet Explorer. This can be called
319 // from various places, notably in request callbacks and the like.
321 // |service_provider| must not be NULL and should be a pointer to something
322 // that implements IServiceProvider (if it isn't this method returns false).
324 // Returns true if this method can determine with some certainty that the
325 // request did NOT originate from a top level frame, returns false otherwise.
326 bool IsSubFrameRequest(IUnknown* service_provider);
328 // See COM_INTERFACE_BLIND_DELEGATE below for details.
329 template <class T>
330 STDMETHODIMP CheckOutgoingInterface(void* obj, REFIID iid, void** ret,
331 DWORD cookie) {
332 T* instance = reinterpret_cast<T*>(obj);
333 HRESULT hr = E_NOINTERFACE;
334 IUnknown* delegate = instance ? instance->delegate() : NULL;
335 if (delegate) {
336 hr = delegate->QueryInterface(iid, ret);
337 #if !defined(NDEBUG)
338 if (SUCCEEDED(hr)) {
339 wchar_t iid_string[64] = {0};
340 StringFromGUID2(iid, iid_string, arraysize(iid_string));
341 DVLOG(1) << __FUNCTION__ << " Giving out wrapped interface: "
342 << iid_string;
344 #endif
347 return hr;
350 // See COM_INTERFACE_ENTRY_IF_DELEGATE_SUPPORTS below for details.
351 template <class T>
352 STDMETHODIMP QueryInterfaceIfDelegateSupports(void* obj, REFIID iid,
353 void** ret, DWORD cookie) {
354 HRESULT hr = E_NOINTERFACE;
355 T* instance = reinterpret_cast<T*>(obj);
356 IUnknown* delegate = instance ? instance->delegate() : NULL;
357 if (delegate) {
358 base::win::ScopedComPtr<IUnknown> original;
359 hr = delegate->QueryInterface(iid,
360 reinterpret_cast<void**>(original.Receive()));
361 if (original) {
362 IUnknown* supported_interface = reinterpret_cast<IUnknown*>(
363 reinterpret_cast<DWORD_PTR>(obj) + cookie);
364 supported_interface->AddRef();
365 *ret = supported_interface;
366 hr = S_OK;
370 return hr;
373 // Same as COM_INTERFACE_ENTRY but relies on the class to implement a
374 // delegate() method that returns a pointer to the delegated COM object.
375 #define COM_INTERFACE_ENTRY_IF_DELEGATE_SUPPORTS(x) \
376 COM_INTERFACE_ENTRY_FUNC(_ATL_IIDOF(x), \
377 offsetofclass(x, _ComMapClass), \
378 QueryInterfaceIfDelegateSupports<_ComMapClass>)
380 // Queries the delegated COM object for an interface, bypassing the wrapper.
381 #define COM_INTERFACE_BLIND_DELEGATE() \
382 COM_INTERFACE_ENTRY_FUNC_BLIND(0, CheckOutgoingInterface<_ComMapClass>)
384 // Thread that enters STA and has a UI message loop.
385 class STAThread : public base::Thread {
386 public:
387 explicit STAThread(const char *name) : Thread(name) {}
388 bool Start() {
389 return StartWithOptions(Options(MessageLoop::TYPE_UI, 0));
391 protected:
392 // Called just prior to starting the message loop
393 virtual void Init() {
394 ::CoInitialize(0);
397 // Called just after the message loop ends
398 virtual void CleanUp() {
399 ::CoUninitialize();
403 std::wstring GuidToString(const GUID& guid);
405 // The urls retrieved from the IMoniker interface don't contain the anchor
406 // portion of the actual url navigated to. This function checks whether the
407 // url passed in the bho_url parameter contains an anchor and if yes checks
408 // whether it matches the url retrieved from the moniker. If yes it returns
409 // the bho url, if not the moniker url.
410 std::wstring GetActualUrlFromMoniker(IMoniker* moniker,
411 IBindCtx* bind_context,
412 const std::wstring& bho_url);
414 // Checks if a window is a top level window
415 bool IsTopLevelWindow(HWND window);
417 // Seeks a stream back to position 0.
418 HRESULT RewindStream(IStream* stream);
420 // Fired when we want to notify IE about privacy changes.
421 #define WM_FIRE_PRIVACY_CHANGE_NOTIFICATION (WM_APP + 1)
423 // Sent (not posted) when a request needs to be downloaded in the host browser
424 // instead of Chrome. WPARAM is 0 and LPARAM is a pointer to an IMoniker
425 // object.
426 // NOTE: Since the message is sent synchronously, the handler should only
427 // start asynchronous operations in order to not block the sender unnecessarily.
428 #define WM_DOWNLOAD_IN_HOST (WM_APP + 2)
430 // This structure contains the parameters sent over to initiate a download
431 // request in the host browser.
432 struct DownloadInHostParams {
433 base::win::ScopedComPtr<IBindCtx> bind_ctx;
434 base::win::ScopedComPtr<IMoniker> moniker;
435 base::win::ScopedComPtr<IStream> post_data;
436 std::string request_headers;
439 // Maps the InternetCookieState enum to the corresponding CookieAction values
440 // used for IE privacy stuff.
441 int32 MapCookieStateToCookieAction(InternetCookieState cookie_state);
443 // Parses the url passed in and returns a GURL instance without the fragment.
444 GURL GetUrlWithoutFragment(const wchar_t* url);
446 // Compares the URLs passed in after removing the fragments from them.
447 bool CompareUrlsWithoutFragment(const wchar_t* url1, const wchar_t* url2);
449 // Returns the Referrer from the HTTP headers and additional headers.
450 std::string FindReferrerFromHeaders(const wchar_t* headers,
451 const wchar_t* additional_headers);
453 // Returns the HTTP headers from the binding passed in.
454 std::string GetHttpHeadersFromBinding(IBinding* binding);
456 // Returns the HTTP response code from the binding passed in.
457 int GetHttpResponseStatusFromBinding(IBinding* binding);
459 // Returns the clipboard format for text/html.
460 CLIPFORMAT GetTextHtmlClipboardFormat();
462 // Returns true iff the mime type is text/html.
463 bool IsTextHtmlMimeType(const wchar_t* mime_type);
465 // Returns true iff the clipboard format is text/html.
466 bool IsTextHtmlClipFormat(CLIPFORMAT cf);
468 // Returns true if we can detect that we are running as SYSTEM, false otherwise.
469 bool IsSystemProcess();
471 // STL helper class that implements a functor to delete objects.
472 // E.g: std::for_each(v.begin(), v.end(), utils::DeleteObject());
473 namespace utils {
474 class DeleteObject {
475 public:
476 template <typename T>
477 void operator()(T* obj) {
478 delete obj;
483 // Convert various protocol flags to text representation. Used for logging.
484 std::string BindStatus2Str(ULONG bind_status);
485 std::string PiFlags2Str(DWORD flags);
486 std::string Bscf2Str(DWORD flags);
488 // Reads data from a stream into a string.
489 HRESULT ReadStream(IStream* stream, size_t size, std::string* data);
491 // Parses urls targeted at ChromeFrame. This class maintains state like
492 // whether a url is prefixed with the gcf: prefix, whether it is being
493 // attached to an existing external tab, etc.
494 class ChromeFrameUrl {
495 public:
496 ChromeFrameUrl();
498 // Parses the url passed in. Returns true on success.
499 bool Parse(const std::wstring& url);
501 bool is_chrome_protocol() const {
502 return is_chrome_protocol_;
505 bool attach_to_external_tab() const {
506 return attach_to_external_tab_;
509 uint64 cookie() const {
510 return cookie_;
513 int disposition() const {
514 return disposition_;
517 const gfx::Rect& dimensions() const {
518 return dimensions_;
521 const GURL& gurl() const {
522 return parsed_url_;
525 const std::string& profile_name() const {
526 return profile_name_;
529 private:
530 // If we are attaching to an existing external tab, this function parses the
531 // suffix portion of the URL which contains the attach_external_tab prefix.
532 bool ParseAttachExternalTabUrl();
534 // Clear state.
535 void Reset();
537 bool attach_to_external_tab_;
538 bool is_chrome_protocol_;
539 uint64 cookie_;
540 gfx::Rect dimensions_;
541 int disposition_;
543 GURL parsed_url_;
544 std::string profile_name_;
547 class NavigationConstraints;
548 // Returns true if we can navigate to this URL.
549 // These decisions are controlled by the NavigationConstraints object passed
550 // in.
551 bool CanNavigate(const GURL& url,
552 NavigationConstraints* navigation_constraints);
554 // Utility function that prevents the current module from ever being unloaded.
555 // Call if you make irreversible patches.
556 void PinModule();
558 // Helper function to spin a message loop and dispatch messages while waiting
559 // for a handle to be signaled.
560 void WaitWithMessageLoop(HANDLE* handles, int count, DWORD timeout);
562 // Enumerates values in a key and adds them to an array.
563 // The names of the values are not returned.
564 void EnumerateKeyValues(HKEY parent_key, const wchar_t* sub_key_name,
565 std::vector<std::wstring>* values);
567 // Interprets the value of an X-UA-Compatible header (or <meta> tag equivalent)
568 // and indicates whether the header value contains a Chrome Frame directive
569 // matching a given host browser version.
571 // The header is a series of name-value pairs, with the names being HTTP tokens
572 // and the values being either tokens or quoted-strings. Names and values are
573 // joined by '=' and pairs are delimited by either ';' or ','. LWS may be used
574 // liberally before and between names, values, '=', and ';' or ','. See RFC 2616
575 // for definitions of token, quoted-string, and LWS. See Microsoft's
576 // documentation of the X-UA-COMPATIBLE header here:
577 // http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
579 // At most one 'Chrome=<FILTER>' entry is expected in the header value. The
580 // first valid instance is used. The value of "<FILTER>" (possibly after
581 // unquoting) is interpreted as follows:
583 // "1" - Always active
584 // "IE7" - Active for IE major version 7 or lower
586 // For example:
587 // X-UA-Compatible: IE=8; Chrome=IE6
589 // The string is first interpreted using ';' as a delimiter. It is reevaluated
590 // using ',' iff no valid 'chrome=' value is found.
591 bool CheckXUaCompatibleDirective(const std::string& directive,
592 int ie_major_version);
594 // Returns the version of the current module as a string.
595 std::wstring GetCurrentModuleVersion();
597 // Returns true if ChromeFrame is the currently loaded document.
598 bool IsChromeFrameDocument(IWebBrowser2* web_browser);
600 // Increases the wininet connection limit for HTTP 1.0/1.1 connections to the
601 // value passed in. This is only done if the existing connection limit is
602 // lesser than the connection limit passed in. This function attempts to
603 // increase the connection count once per process.
604 // Returns true on success.
605 bool IncreaseWinInetConnections(DWORD connections);
607 #endif // CHROME_FRAME_UTILS_H_