code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview This file defines a singleton which provides access to all data * that is available as soon as the page's resources are loaded (before DOM * content has finished loading). This data includes both localized strings and * any data that is important to have ready from a very early stage (e.g. things * that must be displayed right away). * * Note that loadTimeData is not guaranteed to be consistent between page * refreshes (https://crbug.com/740629) and should not contain values that might * change if the page is re-opened later. */ import {assert} from './assert_ts.js'; interface LoadTimeDataRaw { [key: string]: any; } class LoadTimeData { private data_: LoadTimeDataRaw|null = null; /** * Sets the backing object. * * Note that there is no getter for |data_| to discourage abuse of the form: * * var value = loadTimeData.data()['key']; */ set data(value: LoadTimeDataRaw) { assert(!this.data_, 'Re-setting data.'); this.data_ = value; } /** * @param id An ID of a value that might exist. * @return True if |id| is a key in the dictionary. */ valueExists(id: string): boolean { assert(this.data_, 'No data. Did you remember to include strings.js?'); return id in this.data_; } /** * Fetches a value, expecting that it exists. * @param id The key that identifies the desired value. * @return The corresponding value. */ getValue(id: string): any { assert(this.data_, 'No data. Did you remember to include strings.js?'); const value = this.data_[id]; assert(typeof value !== 'undefined', 'Could not find value for ' + id); return value; } /** * As above, but also makes sure that the value is a string. * @param id The key that identifies the desired string. * @return The corresponding string value. */ getString(id: string): string { const value = this.getValue(id); assert(typeof value === 'string', `[${value}] (${id}) is not a string`); return value; } /** * Returns a formatted localized string where $1 to $9 are replaced by the * second to the tenth argument. * @param id The ID of the string we want. * @param args The extra values to include in the formatted output. * @return The formatted string. */ getStringF(id: string, ...args: Array<string|number>): string { const value = this.getString(id); if (!value) { return ''; } return this.substituteString(value, ...args); } /** * Returns a formatted localized string where $1 to $9 are replaced by the * second to the tenth argument. Any standalone $ signs must be escaped as * $$. * @param label The label to substitute through. This is not an resource ID. * @param args The extra values to include in the formatted output. * @return The formatted string. */ substituteString(label: string, ...args: Array<string|number>): string { return label.replace(/\$(.|$|\n)/g, function(m) { assert(m.match(/\$[$1-9]/), 'Unescaped $ found in localized string.'); if (m === '$$') { return '$'; } const substitute = args[Number(m[1]) - 1]; if (substitute === undefined || substitute === null) { // Not all callers actually provide values for all substitutes. Return // an empty value for this case. return ''; } return substitute.toString(); }); } /** * Returns a formatted string where $1 to $9 are replaced by the second to * tenth argument, split apart into a list of pieces describing how the * substitution was performed. Any standalone $ signs must be escaped as $$. * @param label A localized string to substitute through. * This is not an resource ID. * @param args The extra values to include in the formatted output. * @return The formatted string pieces. */ getSubstitutedStringPieces(label: string, ...args: Array<string|number>): Array<{value: string, arg: (string|null)}> { // Split the string by separately matching all occurrences of $1-9 and of // non $1-9 pieces. const pieces = (label.match(/(\$[1-9])|(([^$]|\$([^1-9]|$))+)/g) || []).map(function(p) { // Pieces that are not $1-9 should be returned after replacing $$ // with $. if (!p.match(/^\$[1-9]$/)) { assert( (p.match(/\$/g) || []).length % 2 === 0, 'Unescaped $ found in localized string.'); return {value: p.replace(/\$\$/g, '$'), arg: null}; } // Otherwise, return the substitution value. const substitute = args[Number(p[1]) - 1]; if (substitute === undefined || substitute === null) { // Not all callers actually provide values for all substitutes. Return // an empty value for this case. return {value: '', arg: p}; } return {value: substitute.toString(), arg: p}; }); return pieces; } /** * As above, but also makes sure that the value is a boolean. * @param id The key that identifies the desired boolean. * @return The corresponding boolean value. */ getBoolean(id: string): boolean { const value = this.getValue(id); assert(typeof value === 'boolean', `[${value}] (${id}) is not a boolean`); return value; } /** * As above, but also makes sure that the value is an integer. * @param id The key that identifies the desired number. * @return The corresponding number value. */ getInteger(id: string): number { const value = this.getValue(id); assert(typeof value === 'number', `[${value}] (${id}) is not a number`); assert(value === Math.floor(value), 'Number isn\'t integer: ' + value); return value; } /** * Override values in loadTimeData with the values found in |replacements|. * @param replacements The dictionary object of keys to replace. */ overrideValues(replacements: LoadTimeDataRaw) { assert( typeof replacements === 'object', 'Replacements must be a dictionary object.'); assert(this.data_, 'Data must exist before being overridden'); for (const key in replacements) { this.data_[key] = replacements[key]; } } /** * Reset loadTimeData's data. Should only be used in tests. * @param newData The data to restore to, when null restores to unset state. */ resetForTesting(newData: LoadTimeDataRaw|null = null) { this.data_ = newData; } /** * @return Whether loadTimeData.data has been set. */ isInitialized(): boolean { return this.data_ !== null; } } export const loadTimeData = new LoadTimeData();
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/load_time_data.ts
TypeScript
unknown
6,774
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * NOTE: This file is deprecated, and provides only the minimal LoadTimeData * functions for places in the code still not using JS modules. Use * load_time_data.ts in all new code. * * This file defines a singleton which provides access to all data * that is available as soon as the page's resources are loaded (before DOM * content has finished loading). This data includes both localized strings and * any data that is important to have ready from a very early stage (e.g. things * that must be displayed right away). * * Note that loadTimeData is not guaranteed to be consistent between page * refreshes (https://crbug.com/740629) and should not contain values that might * change if the page is re-opened later. */ /** @type {!LoadTimeData} */ // eslint-disable-next-line no-var var loadTimeData; class LoadTimeData { constructor() { /** @type {?Object} */ this.data_ = null; } /** * Sets the backing object. * * Note that there is no getter for |data_| to discourage abuse of the form: * * var value = loadTimeData.data()['key']; * * @param {Object} value The de-serialized page data. */ set data(value) { expect(!this.data_, 'Re-setting data.'); this.data_ = value; } /** * @param {string} id An ID of a value that might exist. * @return {boolean} True if |id| is a key in the dictionary. */ valueExists(id) { return id in this.data_; } /** * Fetches a value, expecting that it exists. * @param {string} id The key that identifies the desired value. * @return {*} The corresponding value. */ getValue(id) { expect(this.data_, 'No data. Did you remember to include strings.js?'); const value = this.data_[id]; expect(typeof value !== 'undefined', 'Could not find value for ' + id); return value; } /** * As above, but also makes sure that the value is a string. * @param {string} id The key that identifies the desired string. * @return {string} The corresponding string value. */ getString(id) { const value = this.getValue(id); expectIsType(id, value, 'string'); return /** @type {string} */ (value); } /** * Returns a formatted localized string where $1 to $9 are replaced by the * second to the tenth argument. * @param {string} id The ID of the string we want. * @param {...(string|number)} var_args The extra values to include in the * formatted output. * @return {string} The formatted string. */ getStringF(id, var_args) { const value = this.getString(id); if (!value) { return ''; } const args = Array.prototype.slice.call(arguments); args[0] = value; return this.substituteString.apply(this, args); } /** * Returns a formatted localized string where $1 to $9 are replaced by the * second to the tenth argument. Any standalone $ signs must be escaped as * $$. * @param {string} label The label to substitute through. * This is not an resource ID. * @param {...(string|number)} var_args The extra values to include in the * formatted output. * @return {string} The formatted string. */ substituteString(label, var_args) { const varArgs = arguments; return label.replace(/\$(.|$|\n)/g, function(m) { expect(m.match(/\$[$1-9]/), 'Unescaped $ found in localized string.'); return m === '$$' ? '$' : varArgs[m[1]]; }); } /** * As above, but also makes sure that the value is a boolean. * @param {string} id The key that identifies the desired boolean. * @return {boolean} The corresponding boolean value. */ getBoolean(id) { const value = this.getValue(id); expectIsType(id, value, 'boolean'); return /** @type {boolean} */ (value); } /** * As above, but also makes sure that the value is an integer. * @param {string} id The key that identifies the desired number. * @return {number} The corresponding number value. */ getInteger(id) { const value = this.getValue(id); expectIsType(id, value, 'number'); expect(value === Math.floor(value), 'Number isn\'t integer: ' + value); return /** @type {number} */ (value); } /** * Override values in loadTimeData with the values found in |replacements|. * @param {Object} replacements The dictionary object of keys to replace. */ overrideValues(replacements) { expect( typeof replacements === 'object', 'Replacements must be a dictionary object.'); for (const key in replacements) { this.data_[key] = replacements[key]; } } } /** * Checks condition, throws error message if expectation fails. * @param {*} condition The condition to check for truthiness. * @param {string} message The message to display if the check fails. */ function expect(condition, message) { if (!condition) { throw new Error( 'Unexpected condition on ' + document.location.href + ': ' + message); } } /** * Checks that the given value has the given type. * @param {string} id The id of the value (only used for error message). * @param {*} value The value to check the type on. * @param {string} type The type we expect |value| to be. */ function expectIsType(id, value, type) { expect( typeof value === type, '[' + value + '] (' + id + ') is not a ' + type); } expect(!loadTimeData, 'should only include this file once'); loadTimeData = new LoadTimeData(); // Expose |loadTimeData| directly on |window|, since within a JS module the // scope is local and not all files have been updated to import the exported // |loadTimeData| explicitly. window.loadTimeData = loadTimeData; console.warn('crbug/1173575, non-JS module files deprecated.');
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/load_time_data_deprecated.js
JavaScript
unknown
5,871
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {TimeDelta} from '//resources/mojo/mojo/public/mojom/base/time.mojom-webui.js'; import {PageMetricsCallbackRouter, PageMetricsHost, PageMetricsHostRemote} from '../metrics_reporter.mojom-webui.js'; export interface BrowserProxy { getMark(name: string): Promise<{markedTime: TimeDelta | null}>; clearMark(name: string): void; umaReportTime(name: string, time: TimeDelta): void; getCallbackRouter(): PageMetricsCallbackRouter; now(): bigint; } export class BrowserProxyImpl implements BrowserProxy { callbackRouter: PageMetricsCallbackRouter; host: PageMetricsHostRemote; constructor() { this.callbackRouter = new PageMetricsCallbackRouter(); this.host = PageMetricsHost.getRemote(); this.host.onPageRemoteCreated( this.callbackRouter.$.bindNewPipeAndPassRemote()); } getMark(name: string) { return this.host.onGetMark(name); } clearMark(name: string) { this.host.onClearMark(name); } umaReportTime(name: string, time: TimeDelta) { this.host.onUmaReportTime(name, time); } now(): bigint { return chrome.timeTicks.nowInMicroseconds(); } getCallbackRouter() { return this.callbackRouter; } static getInstance(): BrowserProxy { return instance || (instance = new BrowserProxyImpl()); } static setInstance(obj: BrowserProxy) { instance = obj; } } let instance: BrowserProxy|null = null;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/metrics_reporter/browser_proxy.ts
TypeScript
unknown
1,538
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {TimeDelta} from '//resources/mojo/mojo/public/mojom/base/time.mojom-webui.js'; import {assert} from '../assert_ts.js'; import {BrowserProxy, BrowserProxyImpl} from './browser_proxy.js'; function timeFromMojo(delta: TimeDelta): bigint { return delta.microseconds; } function timeToMojo(mark: bigint): TimeDelta { return {microseconds: mark}; } /* * MetricsReporter: A Time Measuring Utility. * * Usages: * - Use getInstance() to acquire the singleton of MetricsReporter. * - Use mark(markName) to mark a timestamp. * Use measure(startMark[, endMark]) to measure the duration between two * marks. If `endMark` is not given, current time will be used. * - Use umaReportTime(metricsName, duration) to record UMA histogram. * - You can call these functions from the C++ side. The marks are accessible * from both C++ and WebUI Javascript. * * Examples: * 1. Pure JS. * metricsReporter.mark('StartMark'); * // your code to be measured ... * metricsReporter.umaReportTime( * 'Your.Histogram', await metricsReporter.measure('StartMark')); * * 2. C++ & JS. * // In C++ * void PageAction() { * metrics_reporter_.Mark("StartMark"); * page->PageAction(); * } * // In JS * pageAction() { * // your code to be measure ... * metricsReporter.umaReportTime( * metricsReporter.measure('StartMark')); * } * * Caveats: * 1. measure() will assert if the mark is not available. You can use * catch() to prevent execution from being interrupted, e.g. * * metricsReporter.measure('StartMark').then(duration => * metricsReporter.umaReportTime('Your.Histogram', duration)) * .catch(() => {}) * * 2. measure() will record inaccurate time if a mark is reused for * overlapping measurements. To prevent this, you can: * * a. check if a mark exists using hasLocalMark() before calling mark(). * b. check if a mark exists using hasMark() before calling measure(). * c. erase a mark using clearMark() after calling measure(). * * Alternative to b., you can use an empty catch() to ignore * missing marks (due to the mark deletion by c.). */ export interface MetricsReporter { mark(name: string): void; measure(startMark: string, endMark?: string): Promise<bigint>; hasMark(name: string): Promise<boolean>; hasLocalMark(name: string): boolean; clearMark(name: string): void; umaReportTime(histogram: string, time: bigint): void; } export class MetricsReporterImpl implements MetricsReporter { private marks_: Map<string, bigint> = new Map(); private browserProxy_: BrowserProxy = BrowserProxyImpl.getInstance(); constructor() { const callbackRouter = this.browserProxy_.getCallbackRouter(); callbackRouter.onGetMark.addListener( (name: string) => ({ markedTime: this.marks_.has(name) ? timeToMojo(this.marks_.get(name)!) : null, })); callbackRouter.onClearMark.addListener( (name: string) => this.marks_.delete(name)); } static getInstance(): MetricsReporter { return instance || (instance = new MetricsReporterImpl()); } static setInstanceForTest(newInstance: MetricsReporter) { instance = newInstance; } mark(name: string) { this.marks_.set(name, this.browserProxy_.now()); } async measure(startMark: string, endMark?: string): Promise<bigint> { let endTime: bigint; if (endMark) { const entry = this.marks_.get(endMark); assert(entry, `Mark "${endMark}" does not exist locally.`); endTime = entry; } else { endTime = this.browserProxy_.now(); } let startTime: bigint; if (this.marks_.has(startMark)) { startTime = this.marks_.get(startMark)!; } else { const remoteStartTime = await this.browserProxy_.getMark(startMark); assert( remoteStartTime.markedTime, `Mark "${startMark}" does not exist locally or remotely.`); startTime = timeFromMojo(remoteStartTime.markedTime); } return endTime - startTime; } async hasMark(name: string): Promise<boolean> { if (this.marks_.has(name)) { return true; } const remoteMark = await this.browserProxy_.getMark(name); return remoteMark !== null && remoteMark.markedTime !== null; } hasLocalMark(name: string): boolean { return this.marks_.has(name); } clearMark(name: string) { this.marks_.delete(name); this.browserProxy_.clearMark(name); } umaReportTime(histogram: string, time: bigint) { this.browserProxy_.umaReportTime(histogram, timeToMojo(time)); } } let instance: MetricsReporter|null = null;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/metrics_reporter/metrics_reporter.ts
TypeScript
unknown
4,845
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {String16} from 'chrome://resources/mojo/mojo/public/mojom/base/string16.mojom-webui.js'; import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js'; export function stringToMojoString16(s: string): String16 { return {data: Array.from(s, c => c.charCodeAt(0))}; } export function mojoString16ToString(str16: String16): string { return str16.data.map((ch: number) => String.fromCodePoint(ch)).join(''); } // Note: This does not do any validation of the URL string. export function stringToMojoUrl(s: string): Url { return {url: s}; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/mojo_type_util.ts
TypeScript
unknown
708
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview A helper object used to open a URL in a new tab. * the browser. */ export interface OpenWindowProxy { /** * Opens the specified URL in a new tab. */ openUrl(url: string): void; } export class OpenWindowProxyImpl implements OpenWindowProxy { openUrl(url: string) { window.open(url); } static getInstance(): OpenWindowProxy { return instance || (instance = new OpenWindowProxyImpl()); } static setInstance(obj: OpenWindowProxy) { instance = obj; } } let instance: OpenWindowProxy|null = null;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/open_window_proxy.ts
TypeScript
unknown
697
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {getRequiredElement} from './util_ts.js'; getRequiredElement('os-link-href').onclick = crosUrlAboutRedirect; function crosUrlAboutRedirect() { chrome.send('crosUrlAboutRedirect'); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/os_about.ts
TypeScript
unknown
337
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert, assertNotReached} from './assert_ts.js'; export interface SanitizeInnerHtmlOpts { substitutions?: string[]; attrs?: string[]; tags?: string[]; } /** * Make a string safe for Polymer bindings that are inner-h-t-m-l or other * innerHTML use. * @param rawString The unsanitized string * @param opts Optional additional allowed tags and attributes. */ function sanitizeInnerHtmlInternal( rawString: string, opts?: SanitizeInnerHtmlOpts): string { opts = opts || {}; const html = parseHtmlSubset(`<b>${rawString}</b>`, opts.tags, opts.attrs) .firstElementChild!; return html.innerHTML; } // <if expr="not is_ios"> let sanitizedPolicy: TrustedTypePolicy|null = null; /** * Same as |sanitizeInnerHtmlInternal|, but it passes through sanitizedPolicy * to create a TrustedHTML. */ export function sanitizeInnerHtml( rawString: string, opts?: SanitizeInnerHtmlOpts): TrustedHTML { assert(window.trustedTypes); if (sanitizedPolicy === null) { // Initialize |sanitizedPolicy| lazily. sanitizedPolicy = window.trustedTypes.createPolicy('sanitize-inner-html', { createHTML: sanitizeInnerHtmlInternal, createScript: () => assertNotReached(), createScriptURL: () => assertNotReached(), }); } return sanitizedPolicy.createHTML(rawString, opts); } // </if> // <if expr="is_ios"> /** * Delegates to sanitizeInnerHtmlInternal() since on iOS there is no * window.trustedTypes support yet. */ export function sanitizeInnerHtml( rawString: string, opts?: SanitizeInnerHtmlOpts): string { assert(!window.trustedTypes); return sanitizeInnerHtmlInternal(rawString, opts); } // </if> type AllowFunction = (node: Node, value: string) => boolean; const allowAttribute: AllowFunction = (_node, _value) => true; /** Allow-list of attributes in parseHtmlSubset. */ const allowedAttributes: Map<string, AllowFunction> = new Map([ [ 'href', (node, value) => { // Only allow a[href] starting with chrome:// or https:// or equaling // to #. return (node as HTMLElement).tagName === 'A' && (value.startsWith('chrome://') || value.startsWith('https://') || value === '#'); }, ], [ 'target', (node, value) => { // Only allow a[target='_blank']. // TODO(dbeam): are there valid use cases for target !== '_blank'? return (node as HTMLElement).tagName === 'A' && value === '_blank'; }, ], ]); /** Allow-list of optional attributes in parseHtmlSubset. */ const allowedOptionalAttributes: Map<string, AllowFunction> = new Map([ ['class', allowAttribute], ['id', allowAttribute], ['is', (_node, value) => value === 'action-link' || value === ''], ['role', (_node, value) => value === 'link'], [ 'src', (node, value) => { // Only allow img[src] starting with chrome:// return (node as HTMLElement).tagName === 'IMG' && value.startsWith('chrome://'); }, ], ['tabindex', allowAttribute], ['aria-hidden', allowAttribute], ['aria-label', allowAttribute], ['aria-labelledby', allowAttribute], ]); /** Allow-list of tag names in parseHtmlSubset. */ const allowedTags: Set<string> = new Set(['A', 'B', 'BR', 'DIV', 'KBD', 'P', 'PRE', 'SPAN', 'STRONG']); /** Allow-list of optional tag names in parseHtmlSubset. */ const allowedOptionalTags: Set<string> = new Set(['IMG', 'LI', 'UL']); /** * This policy maps a given string to a `TrustedHTML` object * without performing any validation. Callsites must ensure * that the resulting object will only be used in inert * documents. Initialized lazily. */ let unsanitizedPolicy: TrustedTypePolicy; /** * @param optTags an Array to merge. * @return Set of allowed tags. */ function mergeTags(optTags: string[]): Set<string> { const clone = new Set(allowedTags); optTags.forEach(str => { const tag = str.toUpperCase(); if (allowedOptionalTags.has(tag)) { clone.add(tag); } }); return clone; } /** * @param optAttrs an Array to merge. * @return Map of allowed attributes. */ function mergeAttrs(optAttrs: string[]): Map<string, AllowFunction> { const clone = new Map(allowedAttributes); optAttrs.forEach(key => { if (allowedOptionalAttributes.has(key)) { clone.set(key, allowedOptionalAttributes.get(key)!); } }); return clone; } function walk(n: Node, f: (p: Node) => void) { f(n); for (let i = 0; i < n.childNodes.length; i++) { walk(n.childNodes[i]!, f); } } function assertElement(tags: Set<string>, node: Node) { if (!tags.has((node as HTMLElement).tagName)) { throw Error((node as HTMLElement).tagName + ' is not supported'); } } function assertAttribute( attrs: Map<string, AllowFunction>, attrNode: Attr, node: Node) { const n = attrNode.nodeName; const v = attrNode.nodeValue || ''; if (!attrs.has(n) || !attrs.get(n)!(node, v)) { throw Error( (node as HTMLElement).tagName + '[' + n + '="' + v + '"] is not supported'); } } /** * Parses a very small subset of HTML. This ensures that insecure HTML / * javascript cannot be injected into WebUI. * @param s The string to parse. * @param extraTags Optional extra allowed tags. * @param extraAttrs * Optional extra allowed attributes (all tags are run through these). * @throws an Error in case of non supported markup. * @return A document fragment containing the DOM tree. */ export function parseHtmlSubset( s: string, extraTags?: string[], extraAttrs?: string[]): DocumentFragment { const tags = extraTags ? mergeTags(extraTags) : allowedTags; const attrs = extraAttrs ? mergeAttrs(extraAttrs) : allowedAttributes; const doc = document.implementation.createHTMLDocument(''); const r = doc.createRange(); r.selectNode(doc.body); if (window.trustedTypes) { if (!unsanitizedPolicy) { unsanitizedPolicy = window.trustedTypes.createPolicy('parse-html-subset', { createHTML: (untrustedHTML: string) => untrustedHTML, createScript: () => assertNotReached(), createScriptURL: () => assertNotReached(), }); } s = unsanitizedPolicy.createHTML(s) as unknown as string; } // This does not execute any scripts because the document has no view. const df = r.createContextualFragment(s); walk(df, function(node) { switch (node.nodeType) { case Node.ELEMENT_NODE: assertElement(tags, node); const nodeAttrs = (node as HTMLElement).attributes; for (let i = 0; i < nodeAttrs.length; ++i) { assertAttribute(attrs, nodeAttrs[i]!, node); } break; case Node.COMMENT_NODE: case Node.DOCUMENT_FRAGMENT_NODE: case Node.TEXT_NODE: break; default: throw Error('Node type ' + node.nodeType + ' is not supported'); } }); return df; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/parse_html_subset.ts
TypeScript
unknown
7,006
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* @fileoverview Utilities for determining the current platform. */ /** Whether we are using a Mac or not. */ export const isMac = /Mac/.test(navigator.platform); /** Whether this is on the Windows platform or not. */ export const isWindows = /Win/.test(navigator.platform); /** Whether this is the ChromeOS/ash web browser. */ export const isChromeOS = (() => { let returnValue = false; // <if expr="chromeos_ash"> returnValue = true; // </if> return returnValue; })(); /** Whether this is the ChromeOS/Lacros web browser. */ export const isLacros = (() => { let returnValue = false; // <if expr="chromeos_lacros"> returnValue = true; // </if> return returnValue; })(); /** Whether this is on vanilla Linux (not chromeOS). */ export const isLinux = /Linux/.test(navigator.userAgent); /** Whether this is on Android. */ export const isAndroid = /Android/.test(navigator.userAgent); /** Whether this is on iOS. */ export const isIOS = /CriOS/.test(navigator.userAgent);
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/platform.ts
TypeScript
unknown
1,140
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview A helper object used to get a pluralized string. */ // clang-format off import {sendWithPromise} from './cr.js'; // clang-format on export interface PluralStringProxy { /** * Obtains a pluralized string for |messageName| with |itemCount| items. * @param messageName The name of the message. * @param itemCount The number of items. * @return Promise resolved with the appropriate plural string for * |messageName| with |itemCount| items. */ getPluralString(messageName: string, itemCount: number): Promise<string>; /** * Fetches both plural strings, concatenated to one string with a comma. * @param messageName1 The name of the first message. * @param itemCount1 The number of items in the first message. * @param messageName2 The name of the second message. * @param itemCount2 The number of items in the second message. * @return Promise resolved with the appropriate plural * strings for both messages, concatenated with a comma+whitespace in * between them. */ getPluralStringTupleWithComma( messageName1: string, itemCount1: number, messageName2: string, itemCount2: number): Promise<string>; /** * Fetches both plural strings, concatenated to one string with periods. * @param messageName1 The name of the first message. * @param itemCount1 The number of items in the first message. * @param messageName2 The name of the second message. * @param itemCount2 The number of items in the second message. * @return Promise resolved with the appropriate plural * strings for both messages, concatenated with a period+whitespace after * the first message, and a period after the second message. */ getPluralStringTupleWithPeriods( messageName1: string, itemCount1: number, messageName2: string, itemCount2: number): Promise<string>; } export class PluralStringProxyImpl implements PluralStringProxy { getPluralString(messageName: string, itemCount: number) { return sendWithPromise('getPluralString', messageName, itemCount); } getPluralStringTupleWithComma( messageName1: string, itemCount1: number, messageName2: string, itemCount2: number) { return sendWithPromise( 'getPluralStringTupleWithComma', messageName1, itemCount1, messageName2, itemCount2); } getPluralStringTupleWithPeriods( messageName1: string, itemCount1: number, messageName2: string, itemCount2: number) { return sendWithPromise( 'getPluralStringTupleWithPeriods', messageName1, itemCount1, messageName2, itemCount2); } static getInstance(): PluralStringProxy { return instance || (instance = new PluralStringProxyImpl()); } static setInstance(obj: PluralStringProxy) { instance = obj; } } let instance: PluralStringProxy|null = null;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/plural_string_proxy.ts
TypeScript
unknown
3,004
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview PromiseResolver is a helper class that allows creating a * Promise that will be fulfilled (resolved or rejected) some time later. * * Example: * const resolver = new PromiseResolver(); * resolver.promise.then(function(result) { * console.log('resolved with', result); * }); * ... * ... * resolver.resolve({hello: 'world'}); */ export class PromiseResolver<T> { private resolve_: (arg: T) => void = () => {}; private reject_: (arg: any) => void = () => {}; private isFulfilled_: boolean = false; private promise_: Promise<T>; constructor() { this.promise_ = new Promise((resolve, reject) => { this.resolve_ = (resolution: T) => { resolve(resolution); this.isFulfilled_ = true; }; this.reject_ = (reason: any) => { reject(reason); this.isFulfilled_ = true; }; }); } /** Whether this resolver has been resolved or rejected. */ get isFulfilled(): boolean { return this.isFulfilled_; } get promise(): Promise<T> { return this.promise_; } get resolve(): ((arg: T) => void) { return this.resolve_; } get reject(): ((arg?: any) => void) { return this.reject_; } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/promise_resolver.ts
TypeScript
unknown
1,357
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert} from './assert_ts.js'; const WRAPPER_CSS_CLASS: string = 'search-highlight-wrapper'; const ORIGINAL_CONTENT_CSS_CLASS: string = 'search-highlight-original-content'; const HIT_CSS_CLASS: string = 'search-highlight-hit'; const SEARCH_BUBBLE_CSS_CLASS: string = 'search-bubble'; export interface Range { start: number; length: number; } /** * Replaces the the highlight wrappers given in |wrappers| with the original * search nodes. */ export function removeHighlights(wrappers: HTMLElement[]) { for (const wrapper of wrappers) { // If wrapper is already removed, do nothing. if (!wrapper.parentElement) { continue; } const originalContent = wrapper.querySelector(`.${ORIGINAL_CONTENT_CSS_CLASS}`); assert(originalContent); const textNode = originalContent.firstChild; assert(textNode); wrapper.parentElement.replaceChild(textNode, wrapper); } } /** * Finds all previous highlighted nodes under |node| and replaces the * highlights (yellow rectangles) with the original search node. Searches only * within the same shadowRoot and assumes that only one highlight wrapper * exists under |node|. */ export function findAndRemoveHighlights(node: Node) { const wrappers = Array.from((node as HTMLElement) .querySelectorAll<HTMLElement>(`.${WRAPPER_CSS_CLASS}`)); assert(wrappers.length === 1); removeHighlights(wrappers); } /** * Applies the highlight UI (yellow rectangle) around all matches in |node|. * @param node The text node to be highlighted. |node| ends up * being hidden. * @return The new highlight wrapper. */ export function highlight(node: Node, ranges: Range[]): HTMLElement { assert(ranges.length > 0); const wrapper = document.createElement('span'); wrapper.classList.add(WRAPPER_CSS_CLASS); // Use existing node as placeholder to determine where to insert the // replacement content. assert(node.parentNode); node.parentNode.replaceChild(wrapper, node); // Keep the existing node around for when the highlights are removed. The // existing text node might be involved in data-binding and therefore should // not be discarded. const span = document.createElement('span'); span.classList.add(ORIGINAL_CONTENT_CSS_CLASS); span.style.display = 'none'; span.appendChild(node); wrapper.appendChild(span); const text = node.textContent!; const tokens: string[] = []; for (let i = 0; i < ranges.length; ++i) { const range = ranges[i]!; const prev = ranges[i - 1]! || {start: 0, length: 0}; const start = prev.start + prev.length; const length = range.start - start; tokens.push(text.substr(start, length)); tokens.push(text.substr(range.start, range.length)); } const last = ranges.slice(-1)[0]!; tokens.push(text.substr(last.start + last.length)); for (let i = 0; i < tokens.length; ++i) { if (i % 2 === 0) { wrapper.appendChild(document.createTextNode(tokens[i]!)); } else { const hitSpan = document.createElement('span'); hitSpan.classList.add(HIT_CSS_CLASS); // Defaults to the color associated with --paper-yellow-500. hitSpan.style.backgroundColor = 'var(--search-highlight-hit-background-color, #ffeb3b)'; // Defaults to the color associated with --google-grey-900. hitSpan.style.color = 'var(--search-highlight-hit-color, #202124)'; hitSpan.textContent = tokens[i]!; wrapper.appendChild(hitSpan); } } return wrapper; } /** * Creates an empty search bubble (styled HTML element without text). * |node| should already be visible or the bubble will render incorrectly. * @param node The node to be highlighted. * @param horizontallyCenter Whether or not to horizontally center * the shown search bubble (if any) based on |node|'s left and width. * @return The search bubble that was added, or null if no new * bubble was added. */ export function createEmptySearchBubble( node: Node, horizontallyCenter?: boolean): HTMLElement { let anchor = node; if (node.nodeName === 'SELECT') { anchor = node.parentNode!; } if (anchor instanceof ShadowRoot) { anchor = anchor.host.parentNode!; } let searchBubble = (anchor as HTMLElement) .querySelector<HTMLElement>(`.${SEARCH_BUBBLE_CSS_CLASS}`); // If the node has already been highlighted, there is no need to do // anything. if (searchBubble) { return searchBubble; } searchBubble = document.createElement('div'); searchBubble.classList.add(SEARCH_BUBBLE_CSS_CLASS); const innards = document.createElement('div'); innards.classList.add('search-bubble-innards'); innards.textContent = '\u00a0'; // Non-breaking space for offsetHeight. searchBubble.appendChild(innards); anchor.appendChild(searchBubble); const updatePosition = function() { const nodeEl = node as HTMLElement; assert(searchBubble); assert(typeof nodeEl.offsetTop === 'number'); searchBubble.style.top = nodeEl.offsetTop + (innards.classList.contains('above') ? -searchBubble.offsetHeight : nodeEl.offsetHeight) + 'px'; if (horizontallyCenter) { const width = nodeEl.offsetWidth - searchBubble.offsetWidth; searchBubble.style.left = nodeEl.offsetLeft + width / 2 + 'px'; } }; updatePosition(); searchBubble.addEventListener('mouseover', function() { innards.classList.toggle('above'); updatePosition(); }); // TODO(crbug.com/355446): create a way to programmatically update these // bubbles (i.e. call updatePosition()) when outer scope knows they need to // be repositioned. return searchBubble; } export function stripDiacritics(text: string): string { return text.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/search_highlight_utils.ts
TypeScript
unknown
5,973
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert} from './assert_ts.js'; /** * @return Whether the passed tagged template literal is a valid array. */ function isValidArray(arr: TemplateStringsArray|readonly string[]): boolean { if (arr instanceof Array && Object.isFrozen(arr)) { return true; } return false; } /** * Checks if the passed tagged template literal only contains static string. * And return the string in the literal if so. * Throws an Error if the passed argument is not supported literals. */ function getStaticString(literal: TemplateStringsArray): string { const isStaticString = isValidArray(literal) && !!literal.raw && isValidArray(literal.raw) && literal.length === literal.raw.length && literal.length === 1; assert(isStaticString, 'static_types.js only allows static strings'); return literal.join(''); } function createTypes(_ignore: string, literal: TemplateStringsArray): string { return getStaticString(literal); } /** * Rules used to enforce static literal checks. */ const rules: TrustedTypePolicyOptions = { createHTML: createTypes, createScript: createTypes, createScriptURL: createTypes, }; /** * This policy returns Trusted Types if the passed literal is static. */ let staticPolicy: TrustedTypePolicy|TrustedTypePolicyOptions; if (window.trustedTypes) { staticPolicy = window.trustedTypes.createPolicy('static-types', rules); } else { staticPolicy = rules; } /** * Returns TrustedHTML if the passed literal is static. */ export function getTrustedHTML(literal: TemplateStringsArray): (TrustedHTML| string) { return staticPolicy.createHTML!('', literal); } /** * Returns TrustedScript if the passed literal is static. */ export function getTrustedScript(literal: TemplateStringsArray): (TrustedScript| string) { return staticPolicy.createScript!('', literal); } /** * Returns TrustedScriptURL if the passed literal is static. */ export function getTrustedScriptURL(literal: TemplateStringsArray): (TrustedScriptURL|string) { return staticPolicy.createScriptURL!('', literal); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/static_types.ts
TypeScript
unknown
2,328
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. export interface Action { name: string; } export type DeferredAction = (callback: (p: Action|null) => void) => void; export interface StoreObserver<T> { onStateChanged(newState: T): void; } /** * A generic datastore for the state of a page, where the state is publicly * readable but can only be modified by dispatching an Action. * The Store should be extended by specifying T, the page state type * associated with the store. */ export class Store<T> { data: T; private reducer_: (state: T, action: Action) => T; protected initialized_: boolean = false; private queuedActions_: DeferredAction[] = []; private observers_: Array<StoreObserver<T>> = []; private batchMode_: boolean = false; constructor(emptyState: T, reducer: (state: T, action: Action) => T) { this.data = emptyState; this.reducer_ = reducer; } init(initialState: T) { this.data = initialState; this.queuedActions_.forEach((action) => { this.dispatchInternal_(action); }); this.queuedActions_ = []; this.initialized_ = true; this.notifyObservers_(this.data); } isInitialized(): boolean { return this.initialized_; } addObserver(observer: StoreObserver<T>) { this.observers_.push(observer); } removeObserver(observer: StoreObserver<T>) { const index = this.observers_.indexOf(observer); this.observers_.splice(index, 1); } /** * Begin a batch update to store data, which will disable updates to the * UI until `endBatchUpdate` is called. This is useful when a single UI * operation is likely to cause many sequential model updates (eg, deleting * 100 bookmarks). */ beginBatchUpdate() { this.batchMode_ = true; } /** * End a batch update to the store data, notifying the UI of any changes * which occurred while batch mode was enabled. */ endBatchUpdate() { this.batchMode_ = false; this.notifyObservers_(this.data); } /** * Handles a 'deferred' action, which can asynchronously dispatch actions * to the Store in order to reach a new UI state. DeferredActions have the * form `dispatchAsync(function(dispatch) { ... })`). Inside that function, * the |dispatch| callback can be called asynchronously to dispatch Actions * directly to the Store. */ dispatchAsync(action: DeferredAction) { if (!this.initialized_) { this.queuedActions_.push(action); return; } this.dispatchInternal_(action); } /** * Transition to a new UI state based on the supplied |action|, and notify * observers of the change. If the Store has not yet been initialized, the * action will be queued and performed upon initialization. */ dispatch(action: Action|null) { this.dispatchAsync(function(dispatch) { dispatch(action); }); } private dispatchInternal_(action: DeferredAction) { action(this.reduce.bind(this)); } reduce(action: Action|null) { if (!action) { return; } this.data = this.reducer_(this.data, action); // Batch notifications until after all initialization queuedActions are // resolved. if (this.isInitialized() && !this.batchMode_) { this.notifyObservers_(this.data); } } protected notifyObservers_(state: T) { this.observers_.forEach(function(o) { o.onStateChanged(state); }); } }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/store_ts.ts
TypeScript
unknown
3,492
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // @fileoverview Helper script used to load a JS module test into a WebUI page. // // Example usage: // chrome://welcome/test_loader.html?module=my_test.js // // will load the JS module at chrome/test/data/webui/my_test.js // // test_loader.html and test_loader.js should be registered with the // WebUIDataSource corresponding to the WebUI being tested, such that the // testing code is loaded from the same origin. Also note that the // chrome://test/ data source only exists in a testing context, so using this // script in production will result in a failed network request. import {loadTestModule} from './test_loader_util.js'; loadTestModule().then(loaded => { if (!loaded) { throw new Error('Failed to load test module'); } });
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/test_loader.ts
TypeScript
unknown
891
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const scriptPolicy: TrustedTypePolicy = window.trustedTypes!.createPolicy('webui-test-script', { createHTML: () => '', createScriptURL: urlString => { const url = new URL(urlString); if (url.protocol === 'chrome:') { return urlString; } console.error(`Invalid test URL ${urlString} found.`); return ''; }, createScript: () => '', }); /** * @return Whether a test module was loaded. * - In case where a module was not specified, returns false (used for * providing a way for UIs to wait for any test initialization, if run * within the context of a test). * - In case where loading failed (either incorrect URL or incorrect "host=" * parameter) a rejected Promise is returned. */ export function loadTestModule(): Promise<boolean> { const params = new URLSearchParams(window.location.search); const module = params.get('module'); if (!module) { return Promise.resolve(false); } const host = params.get('host') || 'webui-test'; if (host !== 'test' && host !== 'webui-test') { return Promise.reject(new Error(`Invalid host=${host} parameter`)); } return new Promise((resolve, reject) => { const script = document.createElement('script'); script.type = 'module'; const src = `chrome://${host}/${module}`; script.src = scriptPolicy.createScriptURL(src) as unknown as string; script.onerror = function() { reject(new Error(`test_loader_util: Failed to load ${src}`)); }; script.onload = function() { resolve(true); }; document.body.appendChild(script); }); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/test_loader_util.ts
TypeScript
unknown
1,780
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* @filedescription Minimal utils and assertion support for places in the code * that are still not updated to JS modules. Do not use in new code. Use * assert_ts and util_ts instead. */ /** * Note: This method is deprecated. Use the equivalent method in assert_ts.ts * instead. * Verify |condition| is truthy and return |condition| if so. * @template T * @param {T} condition A condition to check for truthiness. Note that this * may be used to test whether a value is defined or not, and we don't want * to force a cast to Boolean. * @param {string=} opt_message A message to show on failure. * @return {T} A non-null |condition|. * @closurePrimitive {asserts.truthy} * @suppress {reportUnknownTypes} because T is not sufficiently constrained. */ function assert(condition, opt_message) { if (!condition) { let message = 'Assertion failed'; if (opt_message) { message = message + ': ' + opt_message; } const error = new Error(message); const global = function() { const thisOrSelf = this || self; /** @type {boolean} */ thisOrSelf.traceAssertionsForTesting; return thisOrSelf; }(); if (global.traceAssertionsForTesting) { console.warn(error.stack); } throw error; } return condition; } /** * Note: This method is deprecated. Use the equivalent method in assert_ts.ts * instead. * Call this from places in the code that should never be reached. * * For example, handling all the values of enum with a switch() like this: * * function getValueFromEnum(enum) { * switch (enum) { * case ENUM_FIRST_OF_TWO: * return first * case ENUM_LAST_OF_TWO: * return last; * } * assertNotReached(); * return document; * } * * This code should only be hit in the case of serious programmer error or * unexpected input. * * @param {string=} message A message to show when this is hit. * @closurePrimitive {asserts.fail} */ function assertNotReached(message) { assert(false, message || 'Unreachable code hit'); } /** * @param {*} value The value to check. * @param {function(new: T, ...)} type A user-defined constructor. * @param {string=} message A message to show when this is hit. * @return {T} * @template T */ function assertInstanceof(value, type, message) { // We don't use assert immediately here so that we avoid constructing an error // message if we don't have to. if (!(value instanceof type)) { assertNotReached( message || 'Value ' + value + ' is not a[n] ' + (type.name || typeof type)); } return value; } /** * Alias for document.getElementById. Found elements must be HTMLElements. * @param {string} id The ID of the element to find. * @return {HTMLElement} The found element or null if not found. */ function $(id) { // Disable getElementById restriction here, since we are instructing other // places to re-use the $() that is defined here. // eslint-disable-next-line no-restricted-properties const el = document.getElementById(id); return el ? assertInstanceof(el, HTMLElement) : null; } /** * Return the first ancestor for which the {@code predicate} returns true. * @param {Node} node The node to check. * @param {function(Node):boolean} predicate The function that tests the * nodes. * @param {boolean=} includeShadowHosts * @return {Node} The found ancestor or null if not found. */ function findAncestor(node, predicate, includeShadowHosts) { while (node !== null) { if (predicate(node)) { break; } node = includeShadowHosts && node instanceof ShadowRoot ? node.host : node.parentNode; } return node; } console.warn('crbug/1173575, non-JS module files deprecated.');
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/util_deprecated.js
JavaScript
unknown
3,948
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert} from './assert_ts.js'; /** * Alias for document.getElementById. Found elements must be HTMLElements. */ export function $<T extends HTMLElement = HTMLElement>(id: string): (T|null) { const el = document.querySelector<T>(`#${id}`); if (el) { assert(el instanceof HTMLElement); return el; } return null; } /** * Alias for document.getElementById. Found elements must be HTMLElements. */ export function getRequiredElement<T extends HTMLElement = HTMLElement>( id: string): T { const el = document.querySelector<T>(`#${id}`); assert(el); assert(el instanceof HTMLElement); return el; } /** * @return The currently focused element (including elements that are * behind a shadow root), or null if nothing is focused. */ export function getDeepActiveElement(): (Element|null) { let a = document.activeElement; while (a && a.shadowRoot && a.shadowRoot.activeElement) { a = a.shadowRoot.activeElement; } return a; } /** * Check the directionality of the page. * @return True if Chrome is running an RTL UI. */ export function isRTL(): boolean { return document.documentElement.dir === 'rtl'; } /** * Creates a new URL which is the old URL with a GET param of key=value. * @param url The base URL. There is no validation checking on the URL * so it must be passed in a proper format. * @param key The key of the param. * @param value The value of the param. * @return The new URL. */ export function appendParam(url: string, key: string, value: string): string { const param = encodeURIComponent(key) + '=' + encodeURIComponent(value); if (url.indexOf('?') === -1) { return url + '?' + param; } return url + '&' + param; } /** * Replaces '&', '<', '>', '"', and ''' characters with their HTML encoding. * @param original The original string. * @return The string with all the characters mentioned above replaced. */ export function htmlEscape(original: string): string { return original.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } /** * Quote a string so it can be used in a regular expression. * @param str The source string. * @return The escaped string. */ export function quoteString(str: string): string { return str.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, '\\$1'); } /** * Calls |callback| and stops listening the first time any event in |eventNames| * is triggered on |target|. * @param eventNames Array or space-delimited string of event names to listen to * (e.g. 'click mousedown'). * @param callback Called at most once. The optional return value is passed on * by the listener. */ export function listenOnce(target: EventTarget, eventNames: string[]|string, callback: (e: Event) => any) { const eventNamesArray: string[] = Array.isArray(eventNames) ? eventNames as string[] : (eventNames as string).split(/ +/); const removeAllAndCallCallback = function(event: Event) { eventNamesArray.forEach(function(eventName: string) { target.removeEventListener(eventName, removeAllAndCallCallback, false); }); return callback(event); }; eventNamesArray.forEach(function(eventName: string) { target.addEventListener(eventName, removeAllAndCallCallback, false); }); } /** * @return Whether a modifier key was down when processing |e|. */ export function hasKeyModifiers(e: KeyboardEvent): boolean { return !!(e.altKey || e.ctrlKey || e.metaKey || e.shiftKey); } /** * @return Whether a given KeyboardEvent resembles an undo action, on different * platforms. */ export function isUndoKeyboardEvent(event: KeyboardEvent): boolean { if (event.key !== 'z') { return false; } const excludedModifiers = [ event.altKey, event.shiftKey, // <if expr="is_macosx"> event.ctrlKey, // </if> // <if expr="not is_macosx"> event.metaKey, // </if> ]; let targetModifier = event.ctrlKey; // <if expr="is_macosx"> targetModifier = event.metaKey; // </if> return targetModifier && !excludedModifiers.some(modifier => modifier); }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/js/util_ts.ts
TypeScript
unknown
4,355
<!DOCTYPE html> <html> <body> <script src="chrome://webui-test/mocha.js"></script> <script src="chrome://webui-test/mocha_adapter.js"></script> <script type="module" src="test_loader.js"></script> </body> </html>
Zhao-PengFei35/chromium_src_4
ui/webui/resources/test_loader.html
HTML
unknown
220
# Copyright 2021 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. USE_PYTHON3 = True def _CheckChangeOnUploadOrCommit(input_api, output_api): results = [] webui_sources = set([ 'optimize_webui.py', 'rollup_plugin.js', 'generate_grd.py', 'minify_js.py' ]) affected = input_api.AffectedFiles() affected_files = [input_api.os_path.basename(f.LocalPath()) for f in affected] if webui_sources.intersection(set(affected_files)): results += RunPresubmitTests(input_api, output_api) return results def RunPresubmitTests(input_api, output_api): presubmit_path = input_api.PresubmitLocalPath() sources = [ 'optimize_webui_test.py', 'generate_grd_test.py', 'minify_js_test.py' ] tests = [input_api.os_path.join(presubmit_path, s) for s in sources] return input_api.canned_checks.RunUnitTests( input_api, output_api, tests, run_on_python2=False) def CheckChangeOnUpload(input_api, output_api): return _CheckChangeOnUploadOrCommit(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return _CheckChangeOnUploadOrCommit(input_api, output_api)
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/PRESUBMIT.py
Python
unknown
1,181
# Copyright 2020 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Generates a grit grd file from a list of input manifest files. This is useful # for preventing the need to list JS files in multiple locations, as files can # be listed just once in the BUILD.gn file as inputs for a build rule that knows # how to output such a manifest (e.g. preprocess_if_expr). # # Variables: # manifest-files: # List of paths to manifest files. Each must contain a JSON object with # 2 fields: # - base_dir, the base directory where the files are located # - files, a list of file paths from the base directory # # out_grd: # Path where the generated grd file should be written. # # grd_prefix: # Used to generate both grit IDs for included files and names for the # header/pak/resource map files specified in the <outputs> section of the # grd file. For example, prefix "foo" will result in a grd file that has # as output "foo_resources.pak", "grit/foo_resources.h", etc, and has grit # IDs prefixed by IDS_FOO. # # root_gen_dir: # Path to the root generated directory. Used to compute the relative path # from the root generated directory for setting file paths, as grd files # with generated file paths must specify these paths as # "${root_gen_dir}/<path_to_file>" # # input_files: # List of file paths (from |input_files_base_dir|) that are not included in # any manifest files, but should be added to the grd. # # input_files_base_dir: # The base directory for the paths in |input_files|. |input_files| and # |input_files_base_dir| must either both be provided or both be omitted. import argparse import json import os import sys _CWD = os.getcwd() GRD_BEGIN_TEMPLATE = '<?xml version="1.0" encoding="UTF-8"?>\n'\ '<grit latest_public_release="0" current_release="1" '\ 'output_all_resource_defines="false">\n'\ ' <outputs>\n'\ ' <output filename="{out_dir}/{prefix}_resources.h" '\ 'type="rc_header">\n'\ ' <emit emit_type=\'prepend\'></emit>\n'\ ' </output>\n'\ ' <output filename="{out_dir}/{prefix}_resources_map.cc"\n'\ ' type="resource_file_map_source" />\n'\ ' <output filename="{out_dir}/{prefix}_resources_map.h"\n'\ ' type="resource_map_header" />\n'\ ' <output filename="{prefix}_resources.pak" '\ 'type="data_package" />\n'\ ' </outputs>\n'\ ' <release seq="1">\n'\ ' <includes>\n' GRD_INCLUDE_TEMPLATE = ' <include name="{name}" ' \ 'file="{file}" resource_path="{path}" ' \ 'use_base_dir="false" type="{type}" />\n' GRD_END_TEMPLATE = ' </includes>\n'\ ' </release>\n'\ '</grit>\n' GRDP_BEGIN_TEMPLATE = '<?xml version="1.0" encoding="UTF-8"?>\n'\ '<grit-part>\n' GRDP_END_TEMPLATE = '</grit-part>\n' # Generates an <include .... /> row for the given file. def _generate_include_row(grd_prefix, filename, pathname, \ resource_path_rewrites, resource_path_prefix): assert '\\' not in filename assert '\\' not in pathname name_suffix = filename.upper().replace('/', '_').replace('.', '_'). \ replace('-', '_').replace('@', '_AT_') name = 'IDR_%s_%s' % (grd_prefix.upper(), name_suffix) extension = os.path.splitext(filename)[1] type = 'chrome_html' if extension == '.html' or extension == '.js' \ else 'BINDATA' resource_path = resource_path_rewrites[filename] \ if filename in resource_path_rewrites else filename if resource_path_prefix != None: resource_path = resource_path_prefix + '/' + resource_path assert '\\' not in resource_path return GRD_INCLUDE_TEMPLATE.format( file=pathname, path=resource_path, name=name, type=type) def _generate_part_row(filename): return ' <part file="%s" />\n' % filename def main(argv): parser = argparse.ArgumentParser() parser.add_argument('--manifest-files', nargs="*") parser.add_argument('--out-grd', required=True) parser.add_argument('--grd-prefix', required=True) parser.add_argument('--root-gen-dir', required=True) parser.add_argument('--input-files', nargs="*") parser.add_argument('--input-files-base-dir') parser.add_argument('--output-files-base-dir', default='grit') parser.add_argument('--grdp-files', nargs="*") parser.add_argument('--resource-path-rewrites', nargs="*") parser.add_argument('--resource-path-prefix') args = parser.parse_args(argv) grd_path = os.path.normpath(os.path.join(_CWD, args.out_grd)) with open(grd_path, 'w', newline='') as grd_file: begin_template = GRDP_BEGIN_TEMPLATE if args.out_grd.endswith('.grdp') else \ GRD_BEGIN_TEMPLATE grd_file.write(begin_template.format(prefix=args.grd_prefix, out_dir=args.output_files_base_dir)) if args.grdp_files != None: for grdp_file in args.grdp_files: grdp_path = os.path.relpath(grdp_file, os.path.dirname(args.out_grd)).replace('\\', '/') grd_file.write(_generate_part_row(grdp_path)) resource_path_rewrites = {} if args.resource_path_rewrites != None: for r in args.resource_path_rewrites: [original, rewrite] = r.split("|") resource_path_rewrites[original] = rewrite if args.input_files != None: assert(args.input_files_base_dir) args.input_files_base_dir = args.input_files_base_dir.replace('\\', '/') args.root_gen_dir = args.root_gen_dir.replace('\\', '/') # Detect whether the input files reside under $root_src_dir or # $root_gen_dir. base_dir = os.path.join('${root_src_dir}', args.input_files_base_dir) if args.input_files_base_dir.startswith(args.root_gen_dir + '/'): base_dir = args.input_files_base_dir.replace( args.root_gen_dir + '/', '${root_gen_dir}/') for filename in args.input_files: norm_base = os.path.normpath(args.input_files_base_dir) norm_path = os.path.normpath(os.path.join(args.input_files_base_dir, filename)) assert os.path.commonprefix([norm_base, norm_path]) == norm_base, \ f'Error: input_file {filename} found outside of ' + \ 'input_files_base_dir' filepath = os.path.join(base_dir, filename).replace('\\', '/') grd_file.write(_generate_include_row( args.grd_prefix, filename, filepath, resource_path_rewrites, args.resource_path_prefix)) if args.manifest_files != None: for manifest_file in args.manifest_files: manifest_path = os.path.normpath(os.path.join(_CWD, manifest_file)) with open(manifest_path, 'r') as f: data = json.load(f) base_dir= os.path.normpath(os.path.join(_CWD, data['base_dir'])) for filename in data['files']: filepath = os.path.join(base_dir, filename) rebased_path = os.path.relpath(filepath, args.root_gen_dir).replace('\\', '/') grd_file.write(_generate_include_row( args.grd_prefix, filename, '${root_gen_dir}/' + rebased_path, resource_path_rewrites, args.resource_path_prefix)) end_template = GRDP_END_TEMPLATE if args.out_grd.endswith('.grdp') else \ GRD_END_TEMPLATE grd_file.write(end_template) return if __name__ == '__main__': main(sys.argv[1:])
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/generate_grd.py
Python
unknown
7,802
#!/usr/bin/env python3 # Copyright 2019 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import generate_grd import os import shutil import sys import tempfile import unittest _CWD = os.getcwd() _HERE_DIR = os.path.dirname(__file__) pathToHere = os.path.relpath(_HERE_DIR, _CWD) # This needs to be a constant, because if this expected file is checked into # the repo, translation.py will try to find the dummy grdp files, which don't # exist. We can't alter the translation script, so work around it by # hardcoding this string, instead of checking in even more dummy files. EXPECTED_GRD_WITH_GRDP_FILES = '''<?xml version="1.0" encoding="UTF-8"?> <grit latest_public_release="0" current_release="1" output_all_resource_defines="false"> <outputs> <output filename="grit/test_resources.h" type="rc_header"> <emit emit_type='prepend'></emit> </output> <output filename="grit/test_resources_map.cc" type="resource_file_map_source" /> <output filename="grit/test_resources_map.h" type="resource_map_header" /> <output filename="test_resources.pak" type="data_package" /> </outputs> <release seq="1"> <includes> <part file="foo_resources.grdp" /> <part file="foo/bar_resources.grdp" /> </includes> </release> </grit>\n''' class GenerateGrdTest(unittest.TestCase): def setUp(self): self.maxDiff = None self._out_folder = tempfile.mkdtemp(dir=_HERE_DIR) def tearDown(self): shutil.rmtree(self._out_folder) def _read_out_file(self, file_name): assert self._out_folder file_path = os.path.join(self._out_folder, file_name) with open(file_path, 'r', newline='') as f: return f.read() def _run_test_(self, grd_expected, out_grd='test_resources.grd', manifest_files=None, input_files=None, input_files_base_dir=None, output_files_base_dir=None, grdp_files=None, resource_path_rewrites=None, resource_path_prefix=None): args = [ '--out-grd', os.path.join(self._out_folder, out_grd), '--grd-prefix', 'test', '--root-gen-dir', os.path.join(_CWD, pathToHere, 'tests'), ] if manifest_files != None: args += [ '--manifest-files', ] + manifest_files if grdp_files != None: args += [ '--grdp-files', ] + grdp_files if (input_files_base_dir): args += [ '--input-files-base-dir', input_files_base_dir, '--input-files', ] + input_files if (output_files_base_dir): args += [ '--output-files-base-dir', output_files_base_dir, ] if (resource_path_rewrites): args += [ '--resource-path-rewrites' ] + resource_path_rewrites if (resource_path_prefix): args += [ '--resource-path-prefix', resource_path_prefix ] generate_grd.main(args) actual_grd = self._read_out_file(out_grd) if (grd_expected.endswith('.grd') or grd_expected.endswith('.grdp')): expected_grd_path = os.path.join(_HERE_DIR, 'tests', grd_expected) with open(expected_grd_path, 'r', newline='') as f: expected_grd_content = f.read() self.assertMultiLineEqual(expected_grd_content, actual_grd) else: self.assertMultiLineEqual(grd_expected, actual_grd) def testSuccess(self): self._run_test_( 'expected_grd.grd', manifest_files = [ os.path.join(pathToHere, 'tests', 'test_manifest_1.json'), os.path.join(pathToHere, 'tests', 'test_manifest_2.json'), ]) def testSuccessWithInputFiles(self): self._run_test_( 'expected_grd_with_input_files.grd', manifest_files = [ os.path.join(pathToHere, 'tests', 'test_manifest_1.json'), os.path.join(pathToHere, 'tests', 'test_manifest_2.json'), ], input_files = [ 'images/test_svg.svg', 'test_html_in_src.html' ], input_files_base_dir = 'test_src_dir') def testSuccessWithGeneratedInputFiles(self): # For generated |input_files|, |input_files_base_dir| must be a # sub-directory of |root_gen_dir|. base_dir = os.path.join(_CWD, pathToHere, 'tests', 'foo', 'bar') self._run_test_( 'expected_grd_with_generated_input_files.grd', input_files = [ 'baz/a.svg', 'b.svg' ], input_files_base_dir = base_dir) def testSuccessWithGrdpFiles(self): self._run_test_( EXPECTED_GRD_WITH_GRDP_FILES, grdp_files = [ os.path.join(self._out_folder, 'foo_resources.grdp'), os.path.join(self._out_folder, 'foo', 'bar_resources.grdp'), ]) def testSuccessGrdpWithInputFiles(self): self._run_test_( 'expected_grdp_with_input_files.grdp', out_grd = 'test_resources.grdp', input_files = [ 'images/test_svg.svg', 'test_html_in_src.html' ], input_files_base_dir = 'test_src_dir') def testSuccessGrdpWithResourcePathPrefix(self): self._run_test_( 'expected_grdp_with_resource_path_prefix.grdp', out_grd = 'test_resources.grdp', input_files = [ 'foo.js', 'bar.svg' ], input_files_base_dir = 'test_src_dir', resource_path_prefix = 'baz') def testSuccessWithRewrites(self): self._run_test_( 'expected_grd_with_rewrites.grd', manifest_files = [ os.path.join(pathToHere, 'tests', 'test_manifest_1.json'), os.path.join(pathToHere, 'tests', 'test_manifest_2.json'), ], resource_path_rewrites=[ 'test.rollup.js|test.js', 'dir/another_element_in_dir.js|dir2/another_element_in_dir_renamed.js', ]) def testSuccessWithOutputFilesBaseDir(self): self._run_test_( 'expected_grd_with_output_files_base_dir.grd', input_files = [ 'images/test_svg.svg' ], input_files_base_dir = 'test_src_dir', output_files_base_dir = 'foo/bar') if __name__ == '__main__': unittest.main()
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/generate_grd_test.py
Python
unknown
5,944
#!/usr/bin/env python3 # Copyright 2023 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import json import sys import os _HERE_PATH = os.path.dirname(__file__) _SRC_PATH = os.path.normpath(os.path.join(_HERE_PATH, '..', '..', '..', '..')) _CWD = os.getcwd() sys.path.append(os.path.join(_SRC_PATH, 'third_party', 'node')) import node import node_modules def main(argv): parser = argparse.ArgumentParser() parser.add_argument('--in_folder', required=True) parser.add_argument('--out_folder', required=True) parser.add_argument('--in_files', nargs='*', required=True) parser.add_argument('--out_manifest', required=True) args = parser.parse_args(argv) out_path = os.path.normpath( os.path.join(_CWD, args.out_folder).replace('\\', '/')) in_path = os.path.normpath( os.path.join(_CWD, args.in_folder).replace('\\', '/')) for input_file in args.in_files: node.RunNode([ node_modules.PathToTerser(), os.path.join(in_path, input_file), '--comments', '/Copyright|license|LICENSE/', '--output', os.path.join(out_path, input_file), '--module' ]) manifest_data = {} manifest_data['base_dir'] = args.out_folder manifest_data['files'] = args.in_files with open(os.path.normpath(os.path.join(_CWD, args.out_manifest)), 'w') \ as manifest_file: json.dump(manifest_data, manifest_file) if __name__ == '__main__': main(sys.argv[1:])
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/minify_js.py
Python
unknown
1,508
#!/usr/bin/env python3 # Copyright 2023 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import minify_js import os import tempfile import shutil import unittest _HERE_DIR = os.path.dirname(__file__) class MinifyJsTest(unittest.TestCase): def setUp(self): self._out_dir = tempfile.mkdtemp(dir=_HERE_DIR) def tearDown(self): shutil.rmtree(self._out_dir) def _read_file(self, path): with open(path, 'r') as file: return file.read() def _run_test(self, in_files, expected_files): manifest_path = os.path.join(self._out_dir, "manifest.json") args = [ "--in_folder", os.path.join(_HERE_DIR, "tests", "minify_js"), "--out_folder", self._out_dir, "--out_manifest", manifest_path, "--in_files", *in_files, ] minify_js.main(args) manifest_contents = self._read_file(manifest_path) manifest_data = json.loads(self._read_file(manifest_path)) self.assertEqual(manifest_data['base_dir'], self._out_dir) for index, in_file in enumerate(in_files): actual_contents = self._read_file(os.path.join(self._out_dir, in_file)) expected_contents = self._read_file(expected_files[index]) self.assertMultiLineEqual(expected_contents, actual_contents) self.assertTrue(in_file in manifest_data['files']) def testMinifySimpleFile(self): self._run_test(["foo.js"], ["tests/minify_js/foo_expected.js"]) def testMinifyComplexFile(self): self._run_test(["bar.js"], ["tests/minify_js/bar_expected.js"]) def testMinifyMultipleFiles(self): self._run_test( ["foo.js", "bar.js"], ["tests/minify_js/foo_expected.js", "tests/minify_js/bar_expected.js"]) if __name__ == "__main__": unittest.main()
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/minify_js_test.py
Python
unknown
1,843
#!/usr/bin/env python3 # Copyright 2016 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import itertools import json import os import glob import platform import re import shutil import sys import tempfile _HERE_PATH = os.path.dirname(__file__) _SRC_PATH = os.path.normpath(os.path.join(_HERE_PATH, '..', '..', '..', '..')) _CWD = os.getcwd() # NOTE(dbeam): this is typically out/<gn_name>/. sys.path.append(os.path.join(_SRC_PATH, 'third_party', 'node')) import node import node_modules # These files are already combined and minified. _BASE_EXCLUDES = [] for excluded_file in [ 'resources/mojo/mojo/public/js/bindings.js', 'resources/mojo/mojo/public/mojom/base/time.mojom-lite.js', 'resources/polymer/v3_0/polymer/polymer_bundled.min.js', 'resources/js/cr.js', # This file relies on globals. 'resources/js/load_time_data.js', 'resources/ash/common/load_time_data.m.js', 'resources/mwc/lit/index.js', ]: # Exclude both the chrome://resources form and the scheme-relative form for # files used in Polymer 3. _BASE_EXCLUDES.append("chrome://" + excluded_file) _BASE_EXCLUDES.append("//" + excluded_file) def _request_list_path(out_path, target_name): # Using |target_name| as a prefix which is guaranteed to be unique within the # same folder, to avoid problems when multiple optimize_webui() targets in the # same BUILD.gn file exist. return os.path.join(out_path, target_name + '_requestlist.txt') def _get_dep_path(dep, host_url, in_path): if dep.startswith(host_url): return dep.replace(host_url, os.path.relpath(in_path, _CWD)) elif not (dep.startswith('chrome://') or dep.startswith('//')): return os.path.relpath(in_path, _CWD) + '/' + dep return dep # Get a list of all files that were bundled with rollup and update the # depfile accordingly such that Ninja knows when to re-trigger. def _update_dep_file(in_folder, args, out_file_path, manifest): in_path = os.path.join(_CWD, in_folder) # Gather the dependencies of all bundled root files. request_list = [] for out_file in manifest: request_list += manifest[out_file] # Add a slash in front of every dependency that is not a chrome:// URL, so # that we can map it to the correct source file path below. request_list = map(lambda dep: _get_dep_path(dep, args.host_url, in_path), request_list) deps = map(os.path.normpath, request_list) with open(os.path.join(_CWD, args.depfile), 'w') as f: f.write(out_file_path + ': ' + ' '.join(deps)) # Autogenerate a rollup config file so that we can import the plugin and # pass it information about the location of the directories and files to # exclude from the bundle. # Arguments: # tmp_out_dir: The root directory for the output (i.e. corresponding to # host_url at runtime). # path_to_plugin: Path to the rollup plugin. # in_path: Root directory for the input files. # bundle_path: Path to the output files from the root output directory. # E.g. if bundle is chrome://foo/bundle.js, this is |foo|. # host_url: URL of the host. Usually something like "chrome://settings". # excludes: Imports to exclude from the bundle. # external_paths: Path mappings for import paths that are outside of # |in_path|. For example: # chrome://resources/|gen/ui/webui/resources/tsc def _generate_rollup_config(tmp_out_dir, path_to_plugin, in_path, bundle_path, host_url, excludes, external_paths): rollup_config_file = os.path.join(tmp_out_dir, bundle_path, 'rollup.config.mjs') config_content = r''' import plugin from '{plugin_path}'; export default ({{ plugins: [ plugin('{in_path}', '{bundle_path}', '{host_url}', {exclude_list}, {external_path_list}) ] }}); '''.format( plugin_path=path_to_plugin.replace('\\', '/'), in_path=in_path.replace('\\', '/'), bundle_path=bundle_path.replace('\\', '/'), host_url=host_url, exclude_list=json.dumps(excludes), external_path_list=json.dumps(external_paths)) with open(rollup_config_file, 'w') as f: f.write(config_content) return rollup_config_file # Create the manifest file from the sourcemap generated by rollup and return the # list of bundles. def _generate_manifest_file(out_dir, in_path, bundle_path, manifest_out_path): generated_sourcemaps = glob.glob('%s/*.map' % out_dir) manifest = {} output_filenames = [] for sourcemap_file in generated_sourcemaps: with open(sourcemap_file, 'r') as f: sourcemap = json.loads(f.read()) if not 'sources' in sourcemap: raise Exception('rollup could not construct source map') sources = sourcemap['sources'] replaced_sources = [] # Normalize everything to be relative to the input directory. This is # where the conversion to a dependency file expects it to be. output_to_input = os.path.relpath(in_path, out_dir) + "/" bundle_to_input = os.path.relpath(in_path, os.path.join(in_path, bundle_path)) for source in sources: if output_to_input in source: replaced_sources.append(source.replace(output_to_input, "", 1)) elif bundle_to_input != ".": replaced_sources.append(source.replace(bundle_to_input + "/", "", 1)) else: replaced_sources.append(source) filename = sourcemap_file[:-len('.map')] filepath = os.path.join(bundle_path, os.path.basename(filename)). \ replace('\\', '/') manifest[filepath] = replaced_sources output_filenames.append(filename) with open(manifest_out_path, 'w') as f: f.write(json.dumps(manifest)) return output_filenames def _bundle_v3(tmp_out_dir, in_path, out_path, manifest_out_path, args, excludes, external_paths): bundle_path = os.path.dirname(args.js_module_in_files[0]) out_dir = tmp_out_dir if not bundle_path else os.path.join( tmp_out_dir, bundle_path) if not os.path.exists(out_dir): os.makedirs(out_dir) path_to_plugin = os.path.join( os.path.relpath(_HERE_PATH, os.path.join(tmp_out_dir, bundle_path)), 'rollup_plugin.mjs') rollup_config_file = _generate_rollup_config(tmp_out_dir, path_to_plugin, in_path, bundle_path, args.host_url, excludes, external_paths) rollup_args = [os.path.join(in_path, f) for f in args.js_module_in_files] # Confirm names are as expected. This is necessary to avoid having to replace # import statements in the generated output files. # TODO(rbpotter): Is it worth adding import statement replacement to support # arbitrary names? bundled_paths = [] bundle_names = [] assert len(args.js_module_in_files) < 3, '3+ input files not supported' for index, js_file in enumerate(args.js_module_in_files): bundle_name = '%s.rollup.js' % js_file[:-len('.js')] assert os.path.dirname(js_file) == bundle_path, \ 'All input files must be in the same directory.' bundled_paths.append(os.path.join(tmp_out_dir, bundle_name)) bundle_names.append(bundle_name) # This indicates that rollup is expected to generate a shared chunk file as # well as one file per module. Set its name using --chunkFileNames. Note: # Currently, this only supports 2 entry points, which generate 2 corresponding # outputs and 1 shared output. if (len(args.js_module_in_files) == 2): shared_file_name = 'shared.rollup.js' rollup_args += ['--chunkFileNames', shared_file_name] bundled_paths.append(os.path.join(out_dir, shared_file_name)) bundle_names.append(os.path.join(bundle_path, shared_file_name)) node.RunNode([node_modules.PathToRollup()] + rollup_args + [ '--format', 'esm', '--dir', out_dir, '--entryFileNames', '[name].rollup.js', '--sourcemap', '--sourcemapExcludeSources', '--config', rollup_config_file, ]) # Create the manifest file from the sourcemaps generated by rollup. generated_paths = _generate_manifest_file(out_dir, in_path, bundle_path, manifest_out_path) assert len(generated_paths) == len(bundled_paths), \ 'unexpected number of bundles - %s - generated by rollup' % \ (len(generated_paths)) for bundled_file in bundled_paths: with open(bundled_file, 'r', encoding='utf-8') as f: output = f.read() assert "<if expr" not in output, \ 'Unexpected <if expr> found in bundled output. Check that all ' + \ 'input files using such expressions are preprocessed.' return bundle_names def _optimize(in_folder, args): in_path = os.path.normpath(os.path.join(_CWD, in_folder)).replace('\\', '/') out_path = os.path.join(_CWD, args.out_folder).replace('\\', '/') manifest_out_path = _request_list_path(out_path, args.target_name) tmp_out_dir = tempfile.mkdtemp(dir=out_path).replace('\\', '/') excludes = _BASE_EXCLUDES + [ # This file is dynamically created by C++. Should always be imported with # a relative path. 'strings.m.js', ] excludes.extend(args.exclude or []) for exclude in excludes: extension = os.path.splitext(exclude)[1] assert extension == '.js', f'Unexpected |excludes| entry: {exclude}.' + \ ' Only .js files can appear in |excludes|.' external_paths = args.external_paths or [] js_module_out_files = [] try: js_module_out_files = _bundle_v3(tmp_out_dir, in_path, out_path, manifest_out_path, args, excludes, external_paths) # Pass the JS files through Terser and write the output to its final # destination. for index, js_out_file in enumerate(js_module_out_files): node.RunNode([ node_modules.PathToTerser(), os.path.join(tmp_out_dir, js_out_file), '--comments', '/Copyright|license|LICENSE|\<\/?if/', '--output', os.path.join(out_path, js_out_file) ]) finally: shutil.rmtree(tmp_out_dir) return { 'manifest_out_path': manifest_out_path, 'js_module_out_files': js_module_out_files, } def main(argv): parser = argparse.ArgumentParser() parser.add_argument('--depfile', required=True) parser.add_argument('--target_name', required=True) parser.add_argument('--exclude', nargs='*') parser.add_argument('--external_paths', nargs='*') parser.add_argument('--host', required=True) parser.add_argument('--input', required=True) parser.add_argument('--out_folder', required=True) parser.add_argument('--js_module_in_files', nargs='*', required=True) parser.add_argument('--out-manifest') args = parser.parse_args(argv) # NOTE(dbeam): on Windows, GN can send dirs/like/this. When joined, you might # get dirs/like/this\file.txt. This looks odd to windows. Normalize to right # the slashes. args.depfile = os.path.normpath(args.depfile) args.input = os.path.normpath(args.input) args.out_folder = os.path.normpath(args.out_folder) scheme_end_index = args.host.find('://') if (scheme_end_index == -1): args.host_url = 'chrome://%s/' % args.host else: args.host_url = args.host optimize_output = _optimize(args.input, args) # Prior call to _optimize() generated an output manifest file, containing # information about all files that were bundled. Grab it from there. with open(optimize_output['manifest_out_path'], 'r') as f: manifest = json.loads(f.read()) # Output a manifest file that will be used to auto-generate a grd file # later. if args.out_manifest: manifest_data = { 'base_dir': args.out_folder.replace('\\', '/'), 'files': list(manifest.keys()), } with open(os.path.normpath(os.path.join(_CWD, args.out_manifest)), 'w') \ as manifest_file: json.dump(manifest_data, manifest_file) dep_file_header = os.path.join(args.out_folder, optimize_output['js_module_out_files'][0]) _update_dep_file(args.input, args, dep_file_header, manifest) if __name__ == '__main__': main(sys.argv[1:])
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/optimize_webui.py
Python
unknown
12,416
#!/usr/bin/env python3 # Copyright 2017 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import optimize_webui import os import shutil import tempfile import unittest _CWD = os.getcwd() _HERE_DIR = os.path.dirname(__file__) class OptimizeWebUiTest(unittest.TestCase): def setUp(self): self._tmp_dirs = [] self._tmp_src_dir = None self._out_folder = self._create_tmp_dir() def tearDown(self): for tmp_dir in self._tmp_dirs: shutil.rmtree(tmp_dir) def _write_file_to_dir(self, file_path, file_contents): file_dir = os.path.dirname(file_path) if not os.path.exists(file_dir): os.makedirs(file_dir) with open(file_path, 'w') as tmp_file: tmp_file.write(file_contents) def _write_file_to_src_dir(self, file_path, file_contents): if not self._tmp_src_dir: self._tmp_src_dir = self._create_tmp_dir() file_path_normalized = os.path.normpath( os.path.join(self._tmp_src_dir, file_path)) self._write_file_to_dir(file_path_normalized, file_contents) def _create_tmp_dir(self): # TODO(dbeam): support cross-drive paths (i.e. d:\ vs c:\). tmp_dir = tempfile.mkdtemp(dir=_HERE_DIR) self._tmp_dirs.append(tmp_dir) return tmp_dir def _read_out_file(self, file_name): assert self._out_folder with open(os.path.join(self._out_folder, file_name), 'r') as f: return f.read() def _run_optimize(self, input_args): # TODO(dbeam): make it possible to _run_optimize twice? Is that useful? args = input_args + [ '--depfile', os.path.join(self._out_folder, 'depfile.d'), '--target_name', 'dummy_target_name', '--input', self._tmp_src_dir, '--out_folder', self._out_folder, ] optimize_webui.main(args) def _write_v3_files_to_src_dir(self): self._write_file_to_src_dir('element.js', "alert('yay');") self._write_file_to_src_dir('element_in_dir/element_in_dir.js', "alert('hello from element_in_dir');") self._write_file_to_src_dir( 'ui.js', ''' import './element.js'; import './element_in_dir/element_in_dir.js'; ''') self._write_file_to_src_dir( 'ui.html', ''' <script type="module" src="ui.js"></script> ''') def _write_v3_files_with_custom_path_to_src_dir(self, custom_path): self._write_file_to_dir( os.path.join(custom_path, 'external_dir', 'external_element.js'), ''' import './sub_dir/external_element_dep.js'; alert('hello from external_element'); ''') self._write_file_to_dir( os.path.join(custom_path, 'external_dir', 'sub_dir', 'external_element_dep.js'), "alert('hello from external_element_dep');") self._write_file_to_src_dir('element.js', "alert('yay');") self._write_file_to_src_dir( 'ui.js', ''' import './element.js'; import 'some-fake-scheme://foo/external_dir/external_element.js'; ''') self._write_file_to_src_dir( 'ui.html', ''' <script type="module" src="ui.js"></script> ''') def _write_v3_files_with_resources_to_src_dir(self, resources_scheme): resources_path = os.path.join( _HERE_DIR.replace('\\', '/'), 'gen', 'ui', 'webui', 'resources', 'tsc', 'js') fake_resource_path = os.path.join(resources_path, 'fake_resource.js') scheme_relative_resource_path = os.path.join(resources_path, 'scheme_relative_resource.js') os.makedirs(os.path.dirname(resources_path)) self._tmp_dirs.append('gen') self._write_file_to_dir( fake_resource_path, ''' export const foo = 5; alert('hello from shared resource');''') self._write_file_to_dir( scheme_relative_resource_path, ''' export const bar = 6; alert('hello from another shared resource');''') self._write_file_to_src_dir( 'element.js', ''' import '%s//resources/js/fake_resource.js'; import {bar} from '//resources/js/scheme_relative_resource.js'; alert('yay ' + bar); ''' % resources_scheme) self._write_file_to_src_dir( 'element_in_dir/element_in_dir.js', ''' import {foo} from '%s//resources/js/fake_resource.js'; import '../strings.m.js'; alert('hello from element_in_dir ' + foo); ''' % resources_scheme) self._write_file_to_src_dir( 'ui.js', ''' import './strings.m.js'; import './element.js'; import './element_in_dir/element_in_dir.js'; ''') self._write_file_to_src_dir( 'ui.html', ''' <script type="module" src="ui.js"></script> ''') def _check_output_html(self, out_html): self.assertNotIn('element.html', out_html) self.assertNotIn('element.js', out_html) self.assertNotIn('element_in_dir.html', out_html) self.assertNotIn('element_in_dir.js', out_html) self.assertIn('got here!', out_html) def _check_output_js(self, output_js_name): output_js = self._read_out_file(output_js_name) self.assertIn('yay', output_js) self.assertIn('hello from element_in_dir', output_js) def _check_output_depfile(self, has_html): depfile_d = self._read_out_file('depfile.d') self.assertIn('element.js', depfile_d) self.assertIn( os.path.normpath('element_in_dir/element_in_dir.js'), depfile_d) if (has_html): self.assertIn('element.html', depfile_d) self.assertIn( os.path.normpath('element_in_dir/element_in_dir.html'), depfile_d) def testV3SimpleOptimize(self): self._write_v3_files_to_src_dir() args = [ '--host', 'fake-host', '--js_module_in_files', 'ui.js', ] self._run_optimize(args) self._check_output_js('ui.rollup.js') self._check_output_depfile(False) def testV3OptimizeWithResources(self): self._write_v3_files_with_resources_to_src_dir('chrome:') resources_path = os.path.join('gen', 'ui', 'webui', 'resources', 'tsc') args = [ '--host', 'fake-host', '--js_module_in_files', 'ui.js', '--external_paths', 'chrome://resources|%s' % resources_path, ] self._run_optimize(args) ui_rollup_js = self._read_out_file('ui.rollup.js') self.assertIn('yay', ui_rollup_js) self.assertIn('hello from element_in_dir', ui_rollup_js) self.assertIn('hello from shared resource', ui_rollup_js) depfile_d = self._read_out_file('depfile.d') self.assertIn('element.js', depfile_d) self.assertIn( os.path.normpath('element_in_dir/element_in_dir.js'), depfile_d) self.assertIn( os.path.normpath( '../gen/ui/webui/resources/tsc/js/scheme_relative_resource.js'), depfile_d) self.assertIn( os.path.normpath('../gen/ui/webui/resources/tsc/js/fake_resource.js'), depfile_d) def testV3MultiBundleOptimize(self): self._write_v3_files_to_src_dir() self._write_file_to_src_dir('lazy_element.js', "alert('hello from lazy_element');") self._write_file_to_src_dir( 'lazy.js', ''' import './lazy_element.js'; import './element_in_dir/element_in_dir.js'; ''') args = [ '--host', 'fake-host', '--js_module_in_files', 'ui.js', 'lazy.js', '--out-manifest', os.path.join(self._out_folder, 'out_manifest.json'), ] self._run_optimize(args) # Check that the shared element is in the shared bundle and the non-shared # elements are in the individual bundles. ui_js = self._read_out_file('ui.rollup.js') self.assertIn('yay', ui_js) self.assertNotIn('hello from lazy_element', ui_js) self.assertNotIn('hello from element_in_dir', ui_js) lazy_js = self._read_out_file('lazy.rollup.js') self.assertNotIn('yay', lazy_js) self.assertIn('hello from lazy_element', lazy_js) self.assertNotIn('hello from element_in_dir', lazy_js) shared_js = self._read_out_file('shared.rollup.js') self.assertNotIn('yay', shared_js) self.assertNotIn('hello from lazy_element', shared_js) self.assertIn('hello from element_in_dir', shared_js) # All 3 JS files should be in the depfile. self._check_output_depfile(False) depfile_d = self._read_out_file('depfile.d') self.assertIn('lazy_element.js', depfile_d) manifest = json.loads(self._read_out_file('out_manifest.json')) self.assertEqual(3, len(manifest['files'])) self.assertTrue('lazy.rollup.js' in manifest['files']) self.assertTrue('ui.rollup.js' in manifest['files']) self.assertTrue('shared.rollup.js' in manifest['files']) self.assertEqual( os.path.relpath(self._out_folder, _CWD).replace('\\', '/'), os.path.relpath(manifest['base_dir'], _CWD)) def testV3OptimizeWithCustomPaths(self): custom_dir = os.path.join(self._create_tmp_dir(), 'foo_root') self._write_v3_files_with_custom_path_to_src_dir(custom_dir) resources_path = os.path.join('gen', 'ui', 'webui', 'resources', 'tsc') args = [ '--host', 'fake-host', '--js_module_in_files', 'ui.js', '--external_paths', 'chrome://resources|%s' % resources_path, 'some-fake-scheme://foo|%s' % os.path.abspath(custom_dir), ] self._run_optimize(args) ui_rollup_js = self._read_out_file('ui.rollup.js') self.assertIn('yay', ui_rollup_js) self.assertIn('hello from external_element', ui_rollup_js) self.assertIn('hello from external_element_dep', ui_rollup_js) depfile_d = self._read_out_file('depfile.d') self.assertIn('element.js', depfile_d) # Relative path from the src of the root module to the external root dir relpath = os.path.relpath(custom_dir, self._tmp_src_dir) self.assertIn( os.path.normpath( os.path.join(relpath, 'external_dir', 'external_element.js')), depfile_d) self.assertIn( os.path.normpath( os.path.join(relpath, 'external_dir', 'sub_dir', 'external_element_dep.js')), depfile_d) def testV3SimpleOptimizeExcludes(self): self._write_v3_files_to_src_dir() args = [ '--host', 'chrome-extension://myextensionid/', '--js_module_in_files', 'ui.js', '--exclude', 'element_in_dir/element_in_dir.js', ] self._run_optimize(args) output_js = self._read_out_file('ui.rollup.js') self.assertIn('yay', output_js) self.assertNotIn('hello from element_in_dir', output_js) depfile_d = self._read_out_file('depfile.d') self.assertIn('element.js', depfile_d) self.assertNotIn('element_in_dir', depfile_d) # Tests that bundling resources for an untrusted UI can successfully exclude # resources imported from both chrome-untrusted://resources and scheme # relative paths. def testV3SimpleOptimizeExcludesResources(self): self._write_v3_files_with_resources_to_src_dir('chrome-untrusted:') resources_path = os.path.join('gen', 'ui', 'webui', 'resources', 'tsc') args = [ '--host', 'chrome-untrusted://fake-host', '--js_module_in_files', 'ui.js', '--external_paths', '//resources|%s' % resources_path, 'chrome-untrusted://resources|%s' % resources_path, '--exclude', '//resources/js/scheme_relative_resource.js', 'chrome-untrusted://resources/js/fake_resource.js', ] self._run_optimize(args) output_js = self._read_out_file('ui.rollup.js') self.assertIn('yay', output_js) self.assertIn('//resources/js/scheme_relative_resource.js', output_js) self.assertIn('chrome-untrusted://resources/js/fake_resource.js', output_js) self.assertNotIn('hello from another shared resource', output_js) self.assertNotIn('hello from shared resource', output_js) depfile_d = self._read_out_file('depfile.d') self.assertNotIn('fake_resource', depfile_d) self.assertNotIn('scheme_relative_resource', depfile_d) # Tests that bundling resources for an untrusted UI successfully bundles # resources from both chrome-untrusted://resources and //resources. def testV3SimpleOptimizeUntrustedResources(self): self._write_v3_files_with_resources_to_src_dir('chrome-untrusted:') resources_path = os.path.join('gen', 'ui', 'webui', 'resources', 'tsc') args = [ '--host', 'chrome-untrusted://fake-host', '--js_module_in_files', 'ui.js', '--external_paths', '//resources|%s' % resources_path, 'chrome-untrusted://resources|%s' % resources_path, ] self._run_optimize(args) output_js = self._read_out_file('ui.rollup.js') self.assertIn('yay', output_js) self.assertIn('hello from another shared resource', output_js) self.assertIn('hello from shared resource', output_js) depfile_d = self._read_out_file('depfile.d') self.assertIn('fake_resource', depfile_d) self.assertIn('scheme_relative_resource', depfile_d) def testV3OptimizeWithCustomLayeredPaths(self): tmp_dir = self._create_tmp_dir() custom_dir_foo = os.path.join(tmp_dir, 'foo_root') custom_dir_bar = os.path.join(tmp_dir, 'bar_root') self._write_v3_files_with_custom_path_to_src_dir(custom_dir_foo) # Overwrite one of the foo files to import something from # some-fake-scheme://bar. self._write_file_to_dir( os.path.join(custom_dir_foo, 'external_dir', 'sub_dir', 'external_element_dep.js'), ''' import 'some-fake-scheme://bar/another_element.js'; alert('hello from external_element_dep');''') # Write that file to the bar_root directory. self._write_file_to_dir( os.path.join(custom_dir_bar, 'another_element.js'), "alert('hello from another external dep');") resources_path = os.path.join('gen', 'ui', 'webui', 'resources', 'tsc') args = [ '--host', 'fake-host', '--js_module_in_files', 'ui.js', '--external_paths', '//resources|%s' % resources_path, 'some-fake-scheme://foo|%s' % os.path.abspath(custom_dir_foo), 'some-fake-scheme://bar|%s' % os.path.abspath(custom_dir_bar), ] self._run_optimize(args) ui_rollup_js = self._read_out_file('ui.rollup.js') self.assertIn('yay', ui_rollup_js) self.assertIn('hello from external_element', ui_rollup_js) self.assertIn('hello from external_element_dep', ui_rollup_js) self.assertIn('hello from another external dep', ui_rollup_js) depfile_d = self._read_out_file('depfile.d') self.assertIn('element.js', depfile_d) # Relative path from the src of the root module to the external root dir relpath = os.path.relpath(custom_dir_foo, self._tmp_src_dir) self.assertIn( os.path.normpath( os.path.join(relpath, 'external_dir', 'external_element.js')), depfile_d) self.assertIn( os.path.normpath( os.path.join(relpath, 'external_dir', 'sub_dir', 'external_element_dep.js')), depfile_d) # Relative path from the src of the root module to the secondary dependency # root dir. relpath_bar = os.path.relpath(custom_dir_bar, self._tmp_src_dir) self.assertIn( os.path.normpath(os.path.join(relpath_bar, 'another_element.js')), depfile_d) if __name__ == '__main__': unittest.main()
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/optimize_webui_test.py
Python
unknown
15,340
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Plugin for rollup to correctly resolve resources. */ import * as path from 'path'; function normalizeSlashes(filepath) { return filepath.replace(/\\/gi, '/'); } function relativePath(from, to) { return normalizeSlashes(path.relative(from, to)); } function joinPaths(a, b) { return normalizeSlashes(path.join(a, b)); } /** * Determines the path to |source| from the root directory based on the origin * of the request for it. For example, if ../a/b.js is requested from * c/d/e/f.js, the returned path will be c/d/a/b.js. * @param {string} origin The origin of the request. * @param {string} source The requested resource * @return {string} Path to source from the root directory. */ function combinePaths(origin, source) { const originDir = origin ? path.dirname(origin) : ''; return normalizeSlashes(path.normalize(path.join(originDir, source))); } /** * @param {string} source Requested resource * @param {string} origin The origin of the request * @param {string} urlPrefix The URL prefix to check |source| for. * @param {string} urlSrcPath The path that corresponds to the URL prefix. * @param {!Array<string>} excludes List of paths that should be excluded from * bundling. * @return {string} The path to |source|. If |source| does not map to * |urlSrcPath|, returns an empty string. If |source| maps to a location * in |urlSrcPath| but is listed in |excludes|, returns the URL * corresponding to |source|. Otherwise, returns the full path for |source|. */ function getPathForUrl(source, origin, urlPrefix, urlSrcPath, excludes) { let schemeRelativeUrl = urlPrefix; if (urlPrefix.includes('://')) { const url = new URL(urlPrefix); schemeRelativeUrl = '//' + url.host + url.pathname; } let pathFromUrl = ''; if (source.startsWith(urlPrefix)) { pathFromUrl = source.slice(urlPrefix.length); } else if (source.startsWith(schemeRelativeUrl)) { pathFromUrl = source.slice(schemeRelativeUrl.length); } else if ( !source.includes('://') && !source.startsWith('//') && !!origin && origin.startsWith(urlSrcPath)) { // Relative import from a file that lives in urlSrcPath. pathFromUrl = combinePaths(relativePath(urlSrcPath, origin), source); } if (!pathFromUrl) { return ''; } if (excludes.includes(urlPrefix + pathFromUrl) || excludes.includes(schemeRelativeUrl + pathFromUrl)) { return urlPrefix + pathFromUrl; } return joinPaths(urlSrcPath, pathFromUrl); } /** * @param rootPath Path to the root directory of the set of files being * bundled. * @param bundlePath Path from the root directory to the bundled file(s) * being generated. E.g. if the output bundle is ROOT/foo/bundle.js, * this is "foo". * @param hostUrl The URL for the WebUI host, e.g. chrome://settings. * Used to support absolute "/" style imports that are excluded from * the bundle. * @param excludes Imports that should be excluded from the bundle. * @param externalPaths Array of mappings from URLs to paths where the * files imported from the URLs can be found, e.g. * chrome://resources|gen/ui/webui/resources/tsc/ */ export default function plugin( rootPath, bundlePath, hostUrl, excludes, externalPaths) { const urlsToPaths = new Map(); for (const externalPath of externalPaths) { const [url, path] = externalPath.split('|', 2); urlsToPaths.set(url, path); } const parentPath = '../'; const outputToRoot = bundlePath ? parentPath.repeat(bundlePath.split('/').length) : './'; return { name: 'webui-path-resolver-plugin', resolveId(source, origin) { if (path.extname(source) === '') { this.error( `Invalid path (missing file extension) was found: ${source}`); } // Normalize origin paths to use forward slashes. if (origin) { origin = normalizeSlashes(origin); } for (const [url, path] of urlsToPaths) { const resultPath = getPathForUrl(source, origin, url, path, excludes); if (resultPath.includes('://') || resultPath.startsWith('//')) { return {id: resultPath, external: 'absolute'}; } else if (resultPath) { return resultPath; } } // Check if the URL is an external path that isn't mapped. if (source.includes('://') || source.startsWith('//')) { if (excludes.includes(source)) { return {id: source, external: 'absolute'}; } else { this.error(`Invalid absolute path: ${source} is not in |excludes| ` + `or |external_paths|`); } } // Not in the URL path map -> should be in the root directory. // Check if it should be excluded from the bundle. Check for an absolute // path before combining with the origin path. const fullSourcePath = (source.startsWith('/') && !source.startsWith(rootPath)) ? path.join(rootPath, source) : combinePaths(origin, source); if (fullSourcePath.startsWith(rootPath)) { const pathFromRoot = relativePath(rootPath, fullSourcePath); if (excludes.includes(pathFromRoot)) { const url = new URL(pathFromRoot, hostUrl); return source.startsWith('/') ? {id: url.href, external: 'absolute'} : {id: outputToRoot + pathFromRoot, external: 'relative'}; } } return null; }, }; }
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/rollup_plugin.mjs
JavaScript
unknown
5,598
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // comments should be removed const foo = { 'bar': 0, baz: 5, }; const qux = foo.bar + foo.baz;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/tests/minify_js/bar.js
JavaScript
unknown
248
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const foo={bar:0,baz:5};const qux=foo.bar+foo.baz;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/tests/minify_js/bar_expected.js
JavaScript
unknown
193
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const foo = 0;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/tests/minify_js/foo.js
JavaScript
unknown
159
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const foo=0;
Zhao-PengFei35/chromium_src_4
ui/webui/resources/tools/tests/minify_js/foo_expected.js
JavaScript
unknown
155
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/webui/untrusted_bubble_web_ui_controller.h" #include "content/public/browser/web_ui.h" #include "content/public/common/bindings_policy.h" namespace ui { UntrustedBubbleWebUIController::UntrustedBubbleWebUIController( content::WebUI* web_ui, bool enable_chrome_send) : MojoBubbleWebUIController(web_ui, enable_chrome_send) { // chrome.send() will not work without bindings. CHECK(!enable_chrome_send); // UntrustedWebUIController should never enable WebUI bindings that expose // all of the browser interfaces. web_ui->SetBindings(content::BINDINGS_POLICY_NONE); } UntrustedBubbleWebUIController::~UntrustedBubbleWebUIController() = default; } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_bubble_web_ui_controller.cc
C++
unknown
843
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WEBUI_UNTRUSTED_BUBBLE_WEB_UI_CONTROLLER_H_ #define UI_WEBUI_UNTRUSTED_BUBBLE_WEB_UI_CONTROLLER_H_ #include "ui/webui/mojo_bubble_web_ui_controller.h" namespace content { class WebUI; } namespace ui { // UntrustedWebUIController is intended for WebUI pages that process untrusted // content. These WebUIController should never request WebUI bindings, but // should instead use the WebUI Interface Broker to expose the individual // interface needed. class UntrustedBubbleWebUIController : public MojoBubbleWebUIController { public: explicit UntrustedBubbleWebUIController(content::WebUI* contents, bool enable_chrome_send = false); ~UntrustedBubbleWebUIController() override; UntrustedBubbleWebUIController(UntrustedBubbleWebUIController&) = delete; UntrustedBubbleWebUIController& operator=( const UntrustedBubbleWebUIController&) = delete; }; } // namespace ui #endif // UI_WEBUI_UNTRUSTED_WEB_UI_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_bubble_web_ui_controller.h
C++
unknown
1,133
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/webui/untrusted_web_ui_browsertest_util.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "ui/webui/untrusted_web_ui_controller.h" namespace ui { namespace { class TestUntrustedWebUIController : public ui::UntrustedWebUIController { public: TestUntrustedWebUIController( content::WebUI* web_ui, const std::string& host, const content::TestUntrustedDataSourceHeaders& headers) : ui::UntrustedWebUIController(web_ui) { content::AddUntrustedDataSource( web_ui->GetWebContents()->GetBrowserContext(), host, headers); } ~TestUntrustedWebUIController() override = default; }; } // namespace TestUntrustedWebUIConfig::TestUntrustedWebUIConfig(base::StringPiece host) : WebUIConfig(content::kChromeUIUntrustedScheme, host) {} TestUntrustedWebUIConfig::TestUntrustedWebUIConfig( base::StringPiece host, const content::TestUntrustedDataSourceHeaders& headers) : WebUIConfig(content::kChromeUIUntrustedScheme, host), headers_(headers) {} TestUntrustedWebUIConfig::~TestUntrustedWebUIConfig() = default; std::unique_ptr<content::WebUIController> TestUntrustedWebUIConfig::CreateWebUIController(content::WebUI* web_ui, const GURL& url) { return std::make_unique<TestUntrustedWebUIController>(web_ui, host(), headers_); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_web_ui_browsertest_util.cc
C++
unknown
1,621
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WEBUI_UNTRUSTED_WEB_UI_BROWSERTEST_UTIL_H_ #define UI_WEBUI_UNTRUSTED_WEB_UI_BROWSERTEST_UTIL_H_ #include "content/public/browser/webui_config.h" #include "content/public/test/web_ui_browsertest_util.h" namespace content { class WebUIController; } namespace ui { class TestUntrustedWebUIConfig : public content::WebUIConfig { public: explicit TestUntrustedWebUIConfig(base::StringPiece host); TestUntrustedWebUIConfig( base::StringPiece host, const content::TestUntrustedDataSourceHeaders& headers); ~TestUntrustedWebUIConfig() override; std::unique_ptr<content::WebUIController> CreateWebUIController( content::WebUI* web_ui, const GURL& url) override; const content::TestUntrustedDataSourceHeaders headers_; }; } // namespace ui #endif // UI_WEBUI_UNTRUSTED_WEB_UI_BROWSERTEST_UTIL_H_
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_web_ui_browsertest_util.h
C++
unknown
987
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/webui/untrusted_web_ui_controller.h" #include "content/public/browser/web_ui.h" #include "content/public/common/bindings_policy.h" namespace ui { UntrustedWebUIController::UntrustedWebUIController(content::WebUI* web_ui) : content::WebUIController(web_ui) { // UntrustedWebUIController should never enable bindings. web_ui->SetBindings(content::BINDINGS_POLICY_NONE); } UntrustedWebUIController::~UntrustedWebUIController() = default; } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_web_ui_controller.cc
C++
unknown
624
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WEBUI_UNTRUSTED_WEB_UI_CONTROLLER_H_ #define UI_WEBUI_UNTRUSTED_WEB_UI_CONTROLLER_H_ #include "content/public/browser/web_ui_controller.h" namespace content { class WebUI; } namespace ui { // UntrustedWebUIController is intended for WebUI pages that process untrusted // content. These WebUIController should never request WebUI bindings. class UntrustedWebUIController : public content::WebUIController { public: explicit UntrustedWebUIController(content::WebUI* contents); ~UntrustedWebUIController() override; UntrustedWebUIController(UntrustedWebUIController&) = delete; UntrustedWebUIController& operator=(const UntrustedWebUIController&) = delete; }; } // namespace ui #endif // UI_WEBUI_UNTRUSTED_WEB_UI_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_web_ui_controller.h
C++
unknown
897
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/webui/untrusted_web_ui_controller_factory.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_controller.h" #include "content/public/browser/webui_config.h" #include "content/public/common/url_constants.h" #include "url/gurl.h" namespace ui { UntrustedWebUIControllerFactory::UntrustedWebUIControllerFactory() = default; UntrustedWebUIControllerFactory::~UntrustedWebUIControllerFactory() = default; content::WebUI::TypeID UntrustedWebUIControllerFactory::GetWebUIType( content::BrowserContext* browser_context, const GURL& url) { auto* config = GetConfigIfWebUIEnabled(browser_context, url); if (!config) return content::WebUI::kNoWebUI; return reinterpret_cast<content::WebUI::TypeID>(config); } bool UntrustedWebUIControllerFactory::UseWebUIForURL( content::BrowserContext* browser_context, const GURL& url) { return GetConfigIfWebUIEnabled(browser_context, url); } std::unique_ptr<content::WebUIController> UntrustedWebUIControllerFactory::CreateWebUIControllerForURL( content::WebUI* web_ui, const GURL& url) { auto* browser_context = web_ui->GetWebContents()->GetBrowserContext(); auto* config = GetConfigIfWebUIEnabled(browser_context, url); if (!config) return nullptr; return config->CreateWebUIController(web_ui, url); } content::WebUIConfig* UntrustedWebUIControllerFactory::GetConfigIfWebUIEnabled( content::BrowserContext* browser_context, const GURL& url) { // This factory doesn't support non chrome-untrusted:// WebUIs. if (!url.SchemeIs(content::kChromeUIUntrustedScheme)) return nullptr; auto it = GetWebUIConfigMap().find(url.host_piece()); if (it == GetWebUIConfigMap().end()) return nullptr; if (!it->second->IsWebUIEnabled(browser_context)) return nullptr; return it->second.get(); } } // namespace ui
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_web_ui_controller_factory.cc
C++
unknown
2,059
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WEBUI_UNTRUSTED_WEB_UI_CONTROLLER_FACTORY_H_ #define UI_WEBUI_UNTRUSTED_WEB_UI_CONTROLLER_FACTORY_H_ #include "content/public/browser/web_ui_controller_factory.h" class GURL; namespace content { class BrowserContext; class WebUIController; class WebUIConfig; } // namespace content namespace ui { // Factory class for WebUIControllers for chrome-untrusted:// URLs. // // To add a new WebUIController, subclass ui::WebUIConfig and add it to // `CreateConfigs()` in the .cc. class UntrustedWebUIControllerFactory : public content::WebUIControllerFactory { public: UntrustedWebUIControllerFactory(); ~UntrustedWebUIControllerFactory() override; UntrustedWebUIControllerFactory(const UntrustedWebUIControllerFactory&) = delete; UntrustedWebUIControllerFactory& operator=( const UntrustedWebUIControllerFactory&) = delete; content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context, const GURL& url) final; bool UseWebUIForURL(content::BrowserContext* browser_context, const GURL& url) final; std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL( content::WebUI* web_ui, const GURL& url) final; protected: // Map of hosts to their corresponding WebUIConfigs. using WebUIConfigMap = base::flat_map<std::string, std::unique_ptr<content::WebUIConfig>>; virtual const WebUIConfigMap& GetWebUIConfigMap() = 0; private: // Returns the WebUIConfig for |url| if it's registered and the WebUI is // enabled. (WebUIs can be disabled based on the profile or feature flags.) content::WebUIConfig* GetConfigIfWebUIEnabled( content::BrowserContext* browser_context, const GURL& url); }; } // namespace ui #endif // UI_WEBUI_UNTRUSTED_WEB_UI_CONTROLLER_FACTORY_H_
Zhao-PengFei35/chromium_src_4
ui/webui/untrusted_web_ui_controller_factory.h
C++
unknown
1,978
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/webui/webui_allowlist.h" #include <memory> #include "base/memory/scoped_refptr.h" #include "base/sequence_checker.h" #include "base/supports_user_data.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/url_constants.h" #include "content/public/common/url_utils.h" #include "ui/webui/webui_allowlist_provider.h" #include "url/gurl.h" const char kWebUIAllowlistKeyName[] = "WebUIAllowlist"; namespace { struct WebUIAllowlistHolder : base::SupportsUserData::Data { explicit WebUIAllowlistHolder(scoped_refptr<WebUIAllowlist> list) : allow_list(std::move(list)) {} const scoped_refptr<WebUIAllowlist> allow_list; }; } // namespace // static WebUIAllowlist* WebUIAllowlist::GetOrCreate( content::BrowserContext* browser_context) { if (!browser_context->GetUserData(kWebUIAllowlistKeyName)) { auto list = base::MakeRefCounted<WebUIAllowlist>(); browser_context->SetUserData( kWebUIAllowlistKeyName, std::make_unique<WebUIAllowlistHolder>(std::move(list))); } return static_cast<WebUIAllowlistHolder*>( browser_context->GetUserData(kWebUIAllowlistKeyName)) ->allow_list.get(); } WebUIAllowlist::WebUIAllowlist() = default; WebUIAllowlist::~WebUIAllowlist() = default; void WebUIAllowlist::RegisterAutoGrantedPermission(const url::Origin& origin, ContentSettingsType type, ContentSetting setting) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(content::HasWebUIOrigin(origin)); // It doesn't make sense to grant a default content setting. DCHECK_NE(CONTENT_SETTING_DEFAULT, setting); SetContentSettingsAndNotifyProvider( ContentSettingsPattern::FromURLNoWildcard(origin.GetURL()), ContentSettingsPattern::Wildcard(), type, setting); } void WebUIAllowlist::RegisterAutoGrantedPermissions( const url::Origin& origin, std::initializer_list<ContentSettingsType> types) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); for (const ContentSettingsType& type : types) RegisterAutoGrantedPermission(origin, type); } void WebUIAllowlist::RegisterAutoGrantedThirdPartyCookies( const url::Origin& top_level_origin, const std::vector<ContentSettingsPattern>& origin_patterns) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(content::HasWebUIOrigin(top_level_origin)); const auto top_level_origin_pattern = ContentSettingsPattern::FromURLNoWildcard(top_level_origin.GetURL()); for (const auto& pattern : origin_patterns) { // For COOKIES content setting, |primary_pattern| is the origin setting the // cookie, |secondary_pattern| is the top-level document's origin. SetContentSettingsAndNotifyProvider(pattern, top_level_origin_pattern, ContentSettingsType::COOKIES, CONTENT_SETTING_ALLOW); } } void WebUIAllowlist::SetWebUIAllowlistProvider( WebUIAllowlistProvider* provider) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); provider_ = provider; } void WebUIAllowlist::ResetWebUIAllowlistProvider() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); provider_ = nullptr; } std::unique_ptr<content_settings::RuleIterator> WebUIAllowlist::GetRuleIterator( ContentSettingsType content_type) const NO_THREAD_SAFETY_ANALYSIS { // NO_THREAD_SAFETY_ANALYSIS: GetRuleIterator immediately locks the lock. return value_map_.GetRuleIterator(content_type, &lock_); } void WebUIAllowlist::SetContentSettingsAndNotifyProvider( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType type, ContentSetting setting) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); { base::AutoLock auto_lock(lock_); value_map_.SetValue(primary_pattern, secondary_pattern, type, base::Value(setting), /* metadata */ {}); } // Notify the provider. |provider_| can be nullptr if // HostContentSettingsRegistry is shutting down i.e. when Chrome shuts down. // // It's okay to notify the provider multiple times even if the setting isn't // changed. if (provider_) { provider_->NotifyContentSettingChange(primary_pattern, secondary_pattern, type); } }
Zhao-PengFei35/chromium_src_4
ui/webui/webui_allowlist.cc
C++
unknown
4,927
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WEBUI_WEBUI_ALLOWLIST_H_ #define UI_WEBUI_WEBUI_ALLOWLIST_H_ #include <initializer_list> #include <map> #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/thread_annotations.h" #include "base/threading/thread_checker.h" #include "components/content_settings/core/browser/content_settings_origin_identifier_value_map.h" #include "components/content_settings/core/browser/content_settings_rule.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/content_settings/core/common/content_settings_types.h" #include "url/origin.h" namespace content { class BrowserContext; } class WebUIAllowlistProvider; // This class is the underlying storage for WebUIAllowlistProvider, it stores a // list of origins and permissions to be auto-granted to WebUIs. This class is // created before HostContentSettingsMap is registered and has the same lifetime // as the profile it's attached to. It outlives WebUIAllowlistProvider. class WebUIAllowlist : public base::RefCountedThreadSafe<WebUIAllowlist> { public: static WebUIAllowlist* GetOrCreate(content::BrowserContext* browser_context); WebUIAllowlist(); WebUIAllowlist(const WebUIAllowlist&) = delete; void operator=(const WebUIAllowlist&) = delete; // Register auto-granted |type| permission for WebUI |origin|. The |origin| // will have the permission even if it's embedded in a different origin. // // WebUIAllowlist comes with no permission by default. Users can deny // permissions (e.g. Settings > Site Settings) unless they are registered // here. // // Most WebUIs would want to declare these: // COOKIES: use persistent storage (e.g. localStorage) // JAVASCRIPT: run JavaScript // IMAGES: show images // SOUND: play sounds void RegisterAutoGrantedPermission( const url::Origin& origin, ContentSettingsType type, ContentSetting setting = CONTENT_SETTING_ALLOW); // Register auto-granted |types| permissions for |origin|. See comments above. void RegisterAutoGrantedPermissions( const url::Origin& origin, std::initializer_list<ContentSettingsType> types); // Grant the use of third-party cookies on origins matching // |third_party_origin_pattern|. The third-party origins must be embedded // (e.g. an iframe), or being requested (e.g. Fetch API) by the WebUI's // |top_level_origin|. // // See ContentSettingsPattern for how to construct such a pattern. void RegisterAutoGrantedThirdPartyCookies( const url::Origin& top_level_origin, const std::vector<ContentSettingsPattern>& origin_patterns); // Returns a content_settings::RuleIterator. The iterator keeps this list // alive while it is alive. This method is thread-safe. std::unique_ptr<content_settings::RuleIterator> GetRuleIterator( ContentSettingsType content_type) const; void SetWebUIAllowlistProvider(WebUIAllowlistProvider* provider); void ResetWebUIAllowlistProvider(); private: friend class base::RefCountedThreadSafe<WebUIAllowlist>; ~WebUIAllowlist(); THREAD_CHECKER(thread_checker_); mutable base::Lock lock_; content_settings::OriginIdentifierValueMap value_map_ GUARDED_BY(lock_); raw_ptr<WebUIAllowlistProvider> provider_ GUARDED_BY_CONTEXT(thread_checker_) = nullptr; void SetContentSettingsAndNotifyProvider( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType type, ContentSetting value); }; #endif // UI_WEBUI_WEBUI_ALLOWLIST_H_
Zhao-PengFei35/chromium_src_4
ui/webui/webui_allowlist.h
C++
unknown
3,800
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/webui/webui_allowlist_provider.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "ui/webui/webui_allowlist.h" WebUIAllowlistProvider::WebUIAllowlistProvider( scoped_refptr<WebUIAllowlist> allowlist) : allowlist_(std::move(allowlist)) { DCHECK(allowlist_); allowlist_->SetWebUIAllowlistProvider(this); } WebUIAllowlistProvider::~WebUIAllowlistProvider() = default; std::unique_ptr<content_settings::RuleIterator> WebUIAllowlistProvider::GetRuleIterator(ContentSettingsType content_type, bool incognito) const { return allowlist_->GetRuleIterator(content_type); } void WebUIAllowlistProvider::NotifyContentSettingChange( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type) { NotifyObservers(primary_pattern, secondary_pattern, content_type); } bool WebUIAllowlistProvider::SetWebsiteSetting( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, base::Value&& value, const content_settings::ContentSettingConstraints& constraints) { // WebUIAllowlistProvider doesn't support settings Website settings. return false; } void WebUIAllowlistProvider::ClearAllContentSettingsRules( ContentSettingsType content_type) { // WebUIAllowlistProvider doesn't support changing content settings directly. } void WebUIAllowlistProvider::ShutdownOnUIThread() { DCHECK(CalledOnValidThread()); RemoveAllObservers(); allowlist_->ResetWebUIAllowlistProvider(); }
Zhao-PengFei35/chromium_src_4
ui/webui/webui_allowlist_provider.cc
C++
unknown
1,805
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WEBUI_WEBUI_ALLOWLIST_PROVIDER_H_ #define UI_WEBUI_WEBUI_ALLOWLIST_PROVIDER_H_ #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "components/content_settings/core/browser/content_settings_observable_provider.h" #include "components/content_settings/core/common/content_settings.h" #include "ui/webui/webui_allowlist.h" class ContentSettingsPattern; // A provider that supplies HostContentSettingsMap with a list of auto-granted // permissions from the underlying WebUIAllowlist. class WebUIAllowlistProvider : public content_settings::ObservableProvider { public: explicit WebUIAllowlistProvider(scoped_refptr<WebUIAllowlist> allowlist); WebUIAllowlistProvider(const WebUIAllowlistProvider&) = delete; void operator=(const WebUIAllowlistProvider&) = delete; ~WebUIAllowlistProvider() override; void NotifyContentSettingChange( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type); // content_settings::ObservableProvider: // The following methods are thread-safe. std::unique_ptr<content_settings::RuleIterator> GetRuleIterator( ContentSettingsType content_type, bool incognito) const override; void ShutdownOnUIThread() override; bool SetWebsiteSetting( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, base::Value&& value, const content_settings::ContentSettingConstraints& constraints) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override; private: const scoped_refptr<WebUIAllowlist> allowlist_; }; #endif // UI_WEBUI_WEBUI_ALLOWLIST_PROVIDER_H_
Zhao-PengFei35/chromium_src_4
ui/webui/webui_allowlist_provider.h
C++
unknown
1,926
include_rules = [ "+ui/base", "+ui/aura", "+ui/events", "+ui/display", "+ui/gfx", ]
Zhao-PengFei35/chromium_src_4
ui/wm/DEPS
Python
unknown
94
include_rules = [ "+third_party/skia", "+ui/aura", "+ui/compositor", "+ui/compositor_extra", "+ui/gfx", "+ui/platform_window", "+ui/resources/grit/ui_resources.h", ]
Zhao-PengFei35/chromium_src_4
ui/wm/core/DEPS
Python
unknown
180
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_ACCELERATOR_DELEGATE_H_ #define UI_WM_CORE_ACCELERATOR_DELEGATE_H_ namespace ui { class Accelerator; class KeyEvent; } namespace wm { class AcceleratorDelegate { public: virtual ~AcceleratorDelegate() {} // Return true if the |accelerator| has been processed. virtual bool ProcessAccelerator(const ui::KeyEvent& event, const ui::Accelerator& accelerator) = 0; }; } // namespace wm #endif // UI_WM_CORE_ACCELERATOR_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/accelerator_delegate.h
C++
unknown
638
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/accelerator_filter.h" #include <utility> #include "build/build_config.h" #include "ui/base/accelerators/accelerator.h" #include "ui/events/event.h" #include "ui/wm/core/accelerator_delegate.h" namespace wm { //////////////////////////////////////////////////////////////////////////////// // AcceleratorFilter, public: AcceleratorFilter::AcceleratorFilter( std::unique_ptr<AcceleratorDelegate> delegate) : delegate_(std::move(delegate)) {} AcceleratorFilter::~AcceleratorFilter() { } bool AcceleratorFilter::ShouldFilter(ui::KeyEvent* event) { const ui::EventType type = event->type(); if (!event->target() || (type != ui::ET_KEY_PRESSED && type != ui::ET_KEY_RELEASED) || event->is_char() || !event->target() || // Key events with key code of VKEY_PROCESSKEY, usually created by virtual // keyboard (like handwriting input), have no effect on accelerator and // they may disturb the accelerator history. So filter them out. (see // https://crbug.com/918317) event->key_code() == ui::VKEY_PROCESSKEY) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // AcceleratorFilter, EventFilter implementation: void AcceleratorFilter::OnKeyEvent(ui::KeyEvent* event) { DCHECK(event->target()); if (ShouldFilter(event)) return; ui::Accelerator accelerator(*event); if (delegate_->ProcessAccelerator(*event, accelerator)) event->StopPropagation(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/accelerator_filter.cc
C++
unknown
1,676
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_ACCELERATOR_FILTER_H_ #define UI_WM_CORE_ACCELERATOR_FILTER_H_ #include <memory> #include "base/component_export.h" #include "ui/events/event_handler.h" namespace wm { class AcceleratorDelegate; // AcceleratorFilter filters key events for AcceleratorControler handling global // keyboard accelerators. class COMPONENT_EXPORT(UI_WM) AcceleratorFilter : public ui::EventHandler { public: // AcceleratorFilter doesn't own |accelerator_history|, it's owned by // AcceleratorController. explicit AcceleratorFilter(std::unique_ptr<AcceleratorDelegate> delegate); AcceleratorFilter(const AcceleratorFilter&) = delete; AcceleratorFilter& operator=(const AcceleratorFilter&) = delete; ~AcceleratorFilter() override; // If the return value is true, |event| should be filtered out. static bool ShouldFilter(ui::KeyEvent* event); // Overridden from ui::EventHandler: void OnKeyEvent(ui::KeyEvent* event) override; private: std::unique_ptr<AcceleratorDelegate> delegate_; }; } // namespace wm #endif // UI_WM_CORE_ACCELERATOR_FILTER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/accelerator_filter.h
C++
unknown
1,223
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/base_focus_rules.h" #include "base/containers/adapters.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/window.h" #include "ui/wm/core/window_modality_controller.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/activation_delegate.h" namespace wm { namespace { aura::Window* GetFocusedWindow(aura::Window* context) { aura::client::FocusClient* focus_client = aura::client::GetFocusClient(context); return focus_client ? focus_client->GetFocusedWindow() : nullptr; } } // namespace //////////////////////////////////////////////////////////////////////////////// // BaseFocusRules, protected: BaseFocusRules::BaseFocusRules() = default; BaseFocusRules::~BaseFocusRules() = default; bool BaseFocusRules::IsWindowConsideredVisibleForActivation( const aura::Window* window) const { return window->IsVisible(); } //////////////////////////////////////////////////////////////////////////////// // BaseFocusRules, FocusRules implementation: bool BaseFocusRules::IsToplevelWindow(const aura::Window* window) const { // The window must in a valid hierarchy. if (!window->GetRootWindow()) return false; // The window must exist within a container that supports activation. // The window cannot be blocked by a modal transient. return SupportsChildActivation(window->parent()); } bool BaseFocusRules::CanActivateWindow(const aura::Window* window) const { // It is possible to activate a NULL window, it is equivalent to clearing // activation. if (!window) return true; // A window that is being destroyed should not be activatable. if (window->is_destroying()) return false; // Only toplevel windows can be activated. if (!IsToplevelWindow(window)) return false; // The window must be visible. if (!IsWindowConsideredVisibleForActivation(window)) return false; // The window's activation delegate must allow this window to be activated. if (GetActivationDelegate(window) && !GetActivationDelegate(window)->ShouldActivate()) { return false; } // A window must be focusable to be activatable. We don't call // CanFocusWindow() from here because it will call back to us via // GetActivatableWindow(). if (!window->CanFocus()) return false; // The window cannot be blocked by a modal transient. return !GetModalTransient(window); } bool BaseFocusRules::CanFocusWindow(const aura::Window* window, const ui::Event* event) const { // It is possible to focus a NULL window, it is equivalent to clearing focus. if (!window) return true; // The focused window is always inside the active window, so windows that // aren't activatable can't contain the focused window. const aura::Window* activatable = GetActivatableWindow(window); if (!activatable || !activatable->Contains(window)) return false; return window->CanFocus(); } const aura::Window* BaseFocusRules::GetToplevelWindow( const aura::Window* window) const { const aura::Window* parent = window->parent(); const aura::Window* child = window; while (parent) { if (IsToplevelWindow(child)) return child; parent = parent->parent(); child = child->parent(); } return nullptr; } aura::Window* BaseFocusRules::GetActivatableWindow(aura::Window* window) const { return const_cast<aura::Window*>( GetActivatableWindow(const_cast<const aura::Window*>(window))); } aura::Window* BaseFocusRules::GetFocusableWindow(aura::Window* window) const { if (CanFocusWindow(window, nullptr)) return window; // |window| may be in a hierarchy that is non-activatable, in which case we // need to cut over to the activatable hierarchy. aura::Window* activatable = GetActivatableWindow(window); if (!activatable) { // There may not be a related activatable hierarchy to cut over to, in which // case we try an unrelated one. aura::Window* toplevel = GetToplevelWindow(window); if (toplevel) activatable = GetNextActivatableWindow(toplevel); if (!activatable) return nullptr; } if (!activatable->Contains(window)) { // If there's already a child window focused in the activatable hierarchy, // just use that (i.e. don't shift focus), otherwise we need to at least cut // over to the activatable hierarchy. aura::Window* focused = GetFocusedWindow(activatable); return activatable->Contains(focused) ? focused : activatable; } while (window && !CanFocusWindow(window, nullptr)) window = window->parent(); return window; } aura::Window* BaseFocusRules::GetNextActivatableWindow( aura::Window* ignore) const { DCHECK(ignore); // Can be called from the RootWindow's destruction, which has a NULL parent. if (!ignore->parent()) return nullptr; // In the basic scenarios handled by BasicFocusRules, the pool of activatable // windows is limited to the |ignore|'s siblings. const aura::Window::Windows& siblings = ignore->parent()->children(); DCHECK(!siblings.empty()); for (aura::Window* cur : base::Reversed(siblings)) { if (cur == ignore) continue; if (CanActivateWindow(cur)) return cur; } return nullptr; } const aura::Window* BaseFocusRules::GetActivatableWindow( const aura::Window* window) const { const aura::Window* parent = window->parent(); const aura::Window* child = window; while (parent) { if (CanActivateWindow(child)) return child; // CanActivateWindow() above will return false if |child| is blocked by a // modal transient. In this case the modal is or contains the activatable // window. We recurse because the modal may itself be blocked by a modal // transient. const aura::Window* modal_transient = GetModalTransient(child); if (modal_transient) return GetActivatableWindow(modal_transient); if (wm::GetTransientParent(child)) { // To avoid infinite recursion, if |child| has a transient parent // whose own modal transient is |child| itself, just return |child|. const aura::Window* parent_modal_transient = GetModalTransient(wm::GetTransientParent(child)); if (parent_modal_transient == child) return child; return GetActivatableWindow(wm::GetTransientParent(child)); } parent = parent->parent(); child = child->parent(); } return nullptr; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/base_focus_rules.cc
C++
unknown
6,564
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_BASE_FOCUS_RULES_H_ #define UI_WM_CORE_BASE_FOCUS_RULES_H_ #include "base/component_export.h" #include "ui/wm/core/focus_rules.h" namespace wm { // A set of basic focus and activation rules. Specializations should most likely // subclass this and call up to these methods rather than reimplementing them. class COMPONENT_EXPORT(UI_WM) BaseFocusRules : public FocusRules { public: BaseFocusRules(const BaseFocusRules&) = delete; BaseFocusRules& operator=(const BaseFocusRules&) = delete; protected: BaseFocusRules(); ~BaseFocusRules() override; // Returns true if the children of |window| can be activated. virtual bool SupportsChildActivation(const aura::Window* window) const = 0; // Returns true if |window| is considered visible for activation purposes. virtual bool IsWindowConsideredVisibleForActivation( const aura::Window* window) const; // Overridden from FocusRules: bool IsToplevelWindow(const aura::Window* window) const override; bool CanActivateWindow(const aura::Window* window) const override; bool CanFocusWindow(const aura::Window* window, const ui::Event* event) const override; const aura::Window* GetToplevelWindow( const aura::Window* window) const override; aura::Window* GetActivatableWindow(aura::Window* window) const override; aura::Window* GetFocusableWindow(aura::Window* window) const override; aura::Window* GetNextActivatableWindow(aura::Window* ignore) const override; private: aura::Window* GetToplevelWindow(aura::Window* window) const { return const_cast<aura::Window*>( GetToplevelWindow(const_cast<const aura::Window*>(window))); } const aura::Window* GetActivatableWindow(const aura::Window* window) const; }; } // namespace wm #endif // UI_WM_CORE_BASE_FOCUS_RULES_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/base_focus_rules.h
C++
unknown
1,969
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/capture_controller.h" #include "base/observer_list.h" #include "ui/aura/client/capture_client_observer.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tracker.h" #include "ui/aura/window_tree_host.h" namespace wm { // static CaptureController* CaptureController::instance_ = nullptr; //////////////////////////////////////////////////////////////////////////////// // CaptureController, public: CaptureController::CaptureController() : capture_window_(nullptr), capture_delegate_(nullptr) { DCHECK(!instance_); instance_ = this; } CaptureController::~CaptureController() { DCHECK_EQ(instance_, this); instance_ = nullptr; } void CaptureController::Attach(aura::Window* root) { DCHECK_EQ(0u, delegates_.count(root)); delegates_[root] = root->GetHost()->dispatcher(); aura::client::SetCaptureClient(root, this); } void CaptureController::Detach(aura::Window* root) { delegates_.erase(root); aura::client::SetCaptureClient(root, nullptr); } //////////////////////////////////////////////////////////////////////////////// // CaptureController, aura::client::CaptureClient implementation: void CaptureController::SetCapture(aura::Window* new_capture_window) { if (capture_window_ == new_capture_window) return; // Make sure window has a root window. DCHECK(!new_capture_window || new_capture_window->GetRootWindow()); DCHECK(!capture_window_ || capture_window_->GetRootWindow()); aura::Window* old_capture_window = capture_window_; aura::client::CaptureDelegate* old_capture_delegate = capture_delegate_; // Copy the map in case it's modified out from under us. std::map<aura::Window*, aura::client::CaptureDelegate*> delegates = delegates_; aura::WindowTracker tracker; if (new_capture_window) tracker.Add(new_capture_window); if (old_capture_window) tracker.Add(old_capture_window); // If we're starting a new capture, cancel all touches that aren't // targeted to the capturing window. if (new_capture_window) { aura::Env::GetInstance()->gesture_recognizer()->CancelActiveTouchesExcept( new_capture_window); // Cancelling touches might cause |new_capture_window| to get deleted. // Track |new_capture_window| and check if it still exists before // committing |capture_window_|. if (!tracker.Contains(new_capture_window)) new_capture_window = nullptr; if (old_capture_window && !tracker.Contains(old_capture_window)) old_capture_window = nullptr; } capture_window_ = new_capture_window; aura::Window* capture_root_window = capture_window_ ? capture_window_->GetRootWindow() : nullptr; capture_delegate_ = delegates_.find(capture_root_window) == delegates_.end() ? nullptr : delegates_[capture_root_window]; // With more than one delegate (e.g. multiple displays), an earlier // UpdateCapture() call could cancel an existing capture and destroy // |old_capture_window|, causing a later UpdateCapture() call to access // a dangling pointer, so detect and handle it. for (const auto& it : delegates) { it.second->UpdateCapture(old_capture_window, new_capture_window); if (old_capture_window && !tracker.Contains(old_capture_window)) old_capture_window = nullptr; } if (capture_delegate_ != old_capture_delegate) { if (old_capture_delegate) old_capture_delegate->ReleaseNativeCapture(); if (capture_delegate_) capture_delegate_->SetNativeCapture(); } for (aura::client::CaptureClientObserver& observer : observers_) observer.OnCaptureChanged(old_capture_window, capture_window_); } void CaptureController::ReleaseCapture(aura::Window* window) { if (capture_window_ != window) return; SetCapture(nullptr); } aura::Window* CaptureController::GetCaptureWindow() { return capture_window_; } aura::Window* CaptureController::GetGlobalCaptureWindow() { return capture_window_; } void CaptureController::AddObserver( aura::client::CaptureClientObserver* observer) { observers_.AddObserver(observer); } void CaptureController::RemoveObserver( aura::client::CaptureClientObserver* observer) { observers_.RemoveObserver(observer); } //////////////////////////////////////////////////////////////////////////////// // ScopedCaptureClient: ScopedCaptureClient::ScopedCaptureClient(aura::Window* root) : root_window_(root) { root->AddObserver(this); CaptureController::Get()->Attach(root); } ScopedCaptureClient::~ScopedCaptureClient() { Shutdown(); } void ScopedCaptureClient::OnWindowDestroyed(aura::Window* window) { DCHECK_EQ(window, root_window_); Shutdown(); } void ScopedCaptureClient::Shutdown() { if (!root_window_) return; root_window_->RemoveObserver(this); CaptureController::Get()->Detach(root_window_); root_window_ = nullptr; } /////////////////////////////////////////////////////////////////////////////// // CaptureController::TestApi void ScopedCaptureClient::TestApi::SetDelegate( aura::client::CaptureDelegate* delegate) { CaptureController::Get()->delegates_[client_->root_window_] = delegate; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/capture_controller.cc
C++
unknown
5,384
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_CAPTURE_CONTROLLER_H_ #define UI_WM_CORE_CAPTURE_CONTROLLER_H_ #include <map> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "base/observer_list.h" #include "ui/aura/client/capture_client.h" #include "ui/aura/window_observer.h" namespace aura { namespace client { class CaptureDelegate; } } namespace wm { // Internal CaptureClient implementation. See ScopedCaptureClient for details. class COMPONENT_EXPORT(UI_WM) CaptureController : public aura::client::CaptureClient { public: CaptureController(); CaptureController(const CaptureController&) = delete; CaptureController& operator=(const CaptureController&) = delete; ~CaptureController() override; static CaptureController* Get() { return instance_; } // Adds |root| to the list of root windows notified when capture changes. void Attach(aura::Window* root); // Removes |root| from the list of root windows notified when capture changes. void Detach(aura::Window* root); // Returns true if this CaptureController is installed on at least one // root window. bool is_active() const { return !delegates_.empty(); } // Overridden from aura::client::CaptureClient: void SetCapture(aura::Window* window) override; void ReleaseCapture(aura::Window* window) override; aura::Window* GetCaptureWindow() override; aura::Window* GetGlobalCaptureWindow() override; void AddObserver(aura::client::CaptureClientObserver* observer) override; void RemoveObserver(aura::client::CaptureClientObserver* observer) override; private: friend class ScopedCaptureClient; static CaptureController* instance_; // The current capture window. NULL if there is no capture window. raw_ptr<aura::Window> capture_window_; // The capture delegate for the root window with native capture. The root // window with native capture may not contain |capture_window_|. This occurs // if |capture_window_| is reparented to a different root window while it has // capture. raw_ptr<aura::client::CaptureDelegate> capture_delegate_; // The delegates notified when capture changes. std::map<aura::Window*, aura::client::CaptureDelegate*> delegates_; base::ObserverList<aura::client::CaptureClientObserver>::Unchecked observers_; }; // ScopedCaptureClient is responsible for creating a CaptureClient for a // RootWindow. Specifically it creates a single CaptureController that is shared // among all ScopedCaptureClients and adds the RootWindow to it. class COMPONENT_EXPORT(UI_WM) ScopedCaptureClient : public aura::WindowObserver { public: class COMPONENT_EXPORT(UI_WM) TestApi { public: explicit TestApi(ScopedCaptureClient* client) : client_(client) {} TestApi(const TestApi&) = delete; TestApi& operator=(const TestApi&) = delete; ~TestApi() {} // Sets the delegate. void SetDelegate(aura::client::CaptureDelegate* delegate); private: // Not owned. raw_ptr<ScopedCaptureClient> client_; }; explicit ScopedCaptureClient(aura::Window* root); ScopedCaptureClient(const ScopedCaptureClient&) = delete; ScopedCaptureClient& operator=(const ScopedCaptureClient&) = delete; ~ScopedCaptureClient() override; // Overridden from aura::WindowObserver: void OnWindowDestroyed(aura::Window* window) override; private: // Invoked from destructor and OnWindowDestroyed() to cleanup. void Shutdown(); // RootWindow this ScopedCaptureClient was create for. raw_ptr<aura::Window> root_window_; }; } // namespace wm #endif // UI_WM_CORE_CAPTURE_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/capture_controller.h
C++
unknown
3,714
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/capture_controller.h" #include <memory> #include <utility> #include "base/memory/raw_ptr_exclusion.h" #include "ui/aura/client/capture_delegate.h" #include "ui/aura/env.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_screen.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tracker.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/test/event_generator.h" #include "ui/platform_window/platform_window_init_properties.h" #include "ui/wm/core/capture_controller.h" namespace wm { namespace { // aura::client::CaptureDelegate which allows querying whether native capture // has been acquired. class TestCaptureDelegate : public aura::client::CaptureDelegate { public: TestCaptureDelegate() = default; TestCaptureDelegate(const TestCaptureDelegate&) = delete; TestCaptureDelegate& operator=(const TestCaptureDelegate&) = delete; ~TestCaptureDelegate() override = default; bool HasNativeCapture() const { return has_capture_; } aura::Window* old_capture() { return old_capture_; } aura::Window* new_capture() { return new_capture_; } void SetDestroyOldCapture(bool destroy) { destroy_old_capture_ = destroy; } // aura::client::CaptureDelegate: void UpdateCapture(aura::Window* old_capture, aura::Window* new_capture) override { old_capture_ = old_capture; new_capture_ = new_capture; if (old_capture && destroy_old_capture_) delete old_capture; } void OnOtherRootGotCapture() override {} void SetNativeCapture() override { has_capture_ = true; } void ReleaseNativeCapture() override { has_capture_ = false; } private: bool has_capture_ = false; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #constexpr-ctor-field-initializer RAW_PTR_EXCLUSION aura::Window* old_capture_ = nullptr; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #constexpr-ctor-field-initializer RAW_PTR_EXCLUSION aura::Window* new_capture_ = nullptr; bool destroy_old_capture_ = false; }; } // namespace class CaptureControllerTest : public aura::test::AuraTestBase { public: CaptureControllerTest() {} CaptureControllerTest(const CaptureControllerTest&) = delete; CaptureControllerTest& operator=(const CaptureControllerTest&) = delete; void SetUp() override { AuraTestBase::SetUp(); capture_client_ = std::make_unique<ScopedCaptureClient>(root_window()); second_host_ = aura::WindowTreeHost::Create( ui::PlatformWindowInitProperties{gfx::Rect(0, 0, 800, 600)}); second_host_->InitHost(); second_host_->window()->Show(); second_host_->SetBoundsInPixels(gfx::Rect(800, 600)); second_capture_client_ = std::make_unique<ScopedCaptureClient>(second_host_->window()); } void TearDown() override { RunAllPendingInMessageLoop(); second_capture_client_.reset(); // Kill any active compositors before we hit the compositor shutdown paths. second_host_.reset(); capture_client_.reset(); AuraTestBase::TearDown(); } aura::Window* CreateNormalWindowWithBounds(int id, aura::Window* parent, const gfx::Rect& bounds, aura::WindowDelegate* delegate) { aura::Window* window = new aura::Window( delegate ? delegate : aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate()); window->SetId(id); window->Init(ui::LAYER_TEXTURED); parent->AddChild(window); window->SetBounds(bounds); window->Show(); return window; } aura::Window* GetCaptureWindow() { return CaptureController::Get()->GetCaptureWindow(); } std::unique_ptr<ScopedCaptureClient> capture_client_; std::unique_ptr<aura::WindowTreeHost> second_host_; std::unique_ptr<ScopedCaptureClient> second_capture_client_; }; // Makes sure that internal details that are set on mouse down (such as // mouse_pressed_handler()) are cleared when another root window takes capture. TEST_F(CaptureControllerTest, ResetMouseEventHandlerOnCapture) { // Create a window inside the WindowEventDispatcher. std::unique_ptr<aura::Window> w1( CreateNormalWindow(1, root_window(), nullptr)); // Make a synthesized mouse down event. Ensure that the WindowEventDispatcher // will dispatch further mouse events to |w1|. ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(5, 5), gfx::Point(5, 5), ui::EventTimeForNow(), 0, 0); DispatchEventUsingWindowDispatcher(&mouse_pressed_event); EXPECT_EQ(w1.get(), host()->dispatcher()->mouse_pressed_handler()); // Build a window in the second WindowEventDispatcher. std::unique_ptr<aura::Window> w2( CreateNormalWindow(2, second_host_->window(), nullptr)); // The act of having the second window take capture should clear out mouse // pressed handler in the first WindowEventDispatcher. w2->SetCapture(); EXPECT_EQ(nullptr, host()->dispatcher()->mouse_pressed_handler()); } // Makes sure that when one window gets capture, it forces the release on the // other. This is needed has to be handled explicitly on Linux, and is a sanity // check on Windows. TEST_F(CaptureControllerTest, ResetOtherWindowCaptureOnCapture) { // Create a window inside the WindowEventDispatcher. std::unique_ptr<aura::Window> w1( CreateNormalWindow(1, root_window(), nullptr)); w1->SetCapture(); EXPECT_EQ(w1.get(), GetCaptureWindow()); // Build a window in the second WindowEventDispatcher and give it capture. std::unique_ptr<aura::Window> w2( CreateNormalWindow(2, second_host_->window(), nullptr)); w2->SetCapture(); EXPECT_EQ(w2.get(), GetCaptureWindow()); } // Verifies the touch target for the WindowEventDispatcher gets reset on // releasing capture. TEST_F(CaptureControllerTest, TouchTargetResetOnCaptureChange) { // Create a window inside the WindowEventDispatcher. std::unique_ptr<aura::Window> w1( CreateNormalWindow(1, root_window(), nullptr)); ui::test::EventGenerator event_generator1(root_window()); event_generator1.PressTouch(); w1->SetCapture(); EXPECT_EQ(w1.get(), GetCaptureWindow()); // Build a window in the second WindowEventDispatcher and give it capture. std::unique_ptr<aura::Window> w2( CreateNormalWindow(2, second_host_->window(), nullptr)); w2->SetCapture(); EXPECT_EQ(w2.get(), GetCaptureWindow()); // Release capture on the window. Releasing capture should reset the touch // target of the first WindowEventDispatcher (as it no longer contains the // capture target). w2->ReleaseCapture(); EXPECT_EQ(nullptr, GetCaptureWindow()); } // Test that native capture is released properly when the window with capture // is reparented to a different root window while it has capture. TEST_F(CaptureControllerTest, ReparentedWhileCaptured) { std::unique_ptr<TestCaptureDelegate> delegate(new TestCaptureDelegate); ScopedCaptureClient::TestApi(capture_client_.get()) .SetDelegate(delegate.get()); std::unique_ptr<TestCaptureDelegate> delegate2(new TestCaptureDelegate); ScopedCaptureClient::TestApi(second_capture_client_.get()) .SetDelegate(delegate2.get()); std::unique_ptr<aura::Window> w( CreateNormalWindow(1, root_window(), nullptr)); w->SetCapture(); EXPECT_EQ(w.get(), GetCaptureWindow()); EXPECT_TRUE(delegate->HasNativeCapture()); EXPECT_FALSE(delegate2->HasNativeCapture()); second_host_->window()->AddChild(w.get()); EXPECT_EQ(w.get(), GetCaptureWindow()); EXPECT_TRUE(delegate->HasNativeCapture()); EXPECT_FALSE(delegate2->HasNativeCapture()); w->ReleaseCapture(); EXPECT_EQ(nullptr, GetCaptureWindow()); EXPECT_FALSE(delegate->HasNativeCapture()); EXPECT_FALSE(delegate2->HasNativeCapture()); } // A delegate that deletes a window on scroll cancel gesture event. class GestureEventDeleteWindowOnScrollEnd : public aura::test::TestWindowDelegate { public: GestureEventDeleteWindowOnScrollEnd() {} GestureEventDeleteWindowOnScrollEnd( const GestureEventDeleteWindowOnScrollEnd&) = delete; GestureEventDeleteWindowOnScrollEnd& operator=( const GestureEventDeleteWindowOnScrollEnd&) = delete; void SetWindow(std::unique_ptr<aura::Window> window) { window_ = std::move(window); } aura::Window* window() { return window_.get(); } // aura::test::TestWindowDelegate: void OnGestureEvent(ui::GestureEvent* gesture) override { TestWindowDelegate::OnGestureEvent(gesture); if (gesture->type() != ui::ET_GESTURE_SCROLL_END) return; window_.reset(); } private: std::unique_ptr<aura::Window> window_; }; // Tests a scenario when a window gets deleted while a capture is being set on // it and when that window releases its capture prior to being deleted. // This scenario should end safely without capture being set. TEST_F(CaptureControllerTest, GestureResetWithCapture) { std::unique_ptr<GestureEventDeleteWindowOnScrollEnd> delegate( new GestureEventDeleteWindowOnScrollEnd()); const int kWindowWidth = 123; const int kWindowHeight = 45; gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); std::unique_ptr<aura::Window> window1( CreateNormalWindowWithBounds(-1235, root_window(), bounds, nullptr)); bounds.Offset(0, 100); std::unique_ptr<aura::Window> window2(CreateNormalWindowWithBounds( -1234, root_window(), bounds, delegate.get())); delegate->SetWindow(std::move(window1)); ui::test::EventGenerator event_generator(root_window()); const int position_x = bounds.x() + 1; int position_y = bounds.y() + 1; event_generator.MoveTouch(gfx::Point(position_x, position_y)); event_generator.PressTouch(); for (int idx = 0 ; idx < 20 ; idx++, position_y++) event_generator.MoveTouch(gfx::Point(position_x, position_y)); // Setting capture on |window1| cancels touch gestures that are active on // |window2|. GestureEventDeleteWindowOnScrollEnd will then delete |window1| // and should release capture on it. delegate->window()->SetCapture(); // capture should not be set upon exit from SetCapture() above. aura::client::CaptureClient* capture_client = aura::client::GetCaptureClient(root_window()); ASSERT_NE(nullptr, capture_client); EXPECT_EQ(nullptr, capture_client->GetCaptureWindow()); // Send a mouse click. We no longer hold capture so this should not crash. ui::MouseEvent mouse_press(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), base::TimeTicks(), 0, 0); DispatchEventUsingWindowDispatcher(&mouse_press); } TEST_F(CaptureControllerTest, UpdateCaptureDestroysOldCaptureWindow) { TestCaptureDelegate delegate; ScopedCaptureClient::TestApi(capture_client_.get()).SetDelegate(&delegate); TestCaptureDelegate delegate2; ScopedCaptureClient::TestApi(second_capture_client_.get()) .SetDelegate(&delegate2); // Since delegate iteration order is not deterministic, use this to assert // that the two scenarios below have opposite order. aura::Window* first_old_capture = nullptr; { // Create a window inside the WindowEventDispatcher. std::unique_ptr<aura::Window> capture_window( CreateNormalWindow(1, root_window(), nullptr)); ui::test::EventGenerator event_generator(root_window()); event_generator.PressTouch(); capture_window->SetCapture(); delegate.SetDestroyOldCapture(true); delegate2.SetDestroyOldCapture(false); aura::WindowTracker tracker({capture_window.get()}); CaptureController::Get()->SetCapture(nullptr); EXPECT_EQ(delegate.old_capture(), capture_window.get()); first_old_capture = delegate2.old_capture(); EXPECT_FALSE(tracker.Contains(capture_window.get())); if (!tracker.Contains(capture_window.get())) capture_window.release(); } { // Create a window inside the WindowEventDispatcher. std::unique_ptr<aura::Window> capture_window( CreateNormalWindow(1, root_window(), nullptr)); ui::test::EventGenerator event_generator(root_window()); event_generator.PressTouch(); capture_window->SetCapture(); // Change order to account for map traversal order. delegate.SetDestroyOldCapture(false); delegate2.SetDestroyOldCapture(true); aura::WindowTracker tracker({capture_window.get()}); CaptureController::Get()->SetCapture(nullptr); EXPECT_NE(delegate.old_capture(), first_old_capture); EXPECT_EQ(delegate2.old_capture(), capture_window.get()); EXPECT_FALSE(tracker.Contains(capture_window.get())); if (!tracker.Contains(capture_window.get())) capture_window.release(); } } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/capture_controller_unittest.cc
C++
unknown
13,051
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/compound_event_filter.h" #include "base/check.h" #include "base/observer_list.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/cursor_client.h" #include "ui/aura/client/drag_drop_client.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/base/hit_test.h" #include "ui/events/event.h" #include "ui/wm/public/activation_client.h" namespace wm { //////////////////////////////////////////////////////////////////////////////// // CompoundEventFilter, public: CompoundEventFilter::CompoundEventFilter() { } CompoundEventFilter::~CompoundEventFilter() { // Additional filters are not owned by CompoundEventFilter and they // should all be removed when running here. |handlers_| has // check_empty == true and will DCHECK failure if it is not empty. } // static gfx::NativeCursor CompoundEventFilter::CursorForWindowComponent( int window_component) { switch (window_component) { case HTBOTTOM: return ui::mojom::CursorType::kSouthResize; case HTBOTTOMLEFT: return ui::mojom::CursorType::kSouthWestResize; case HTBOTTOMRIGHT: return ui::mojom::CursorType::kSouthEastResize; case HTLEFT: return ui::mojom::CursorType::kWestResize; case HTRIGHT: return ui::mojom::CursorType::kEastResize; case HTTOP: return ui::mojom::CursorType::kNorthResize; case HTTOPLEFT: return ui::mojom::CursorType::kNorthWestResize; case HTTOPRIGHT: return ui::mojom::CursorType::kNorthEastResize; default: return ui::mojom::CursorType::kNull; } } gfx::NativeCursor CompoundEventFilter::NoResizeCursorForWindowComponent( int window_component) { switch (window_component) { case HTBOTTOM: return ui::mojom::CursorType::kNorthSouthNoResize; case HTBOTTOMLEFT: return ui::mojom::CursorType::kNorthEastSouthWestNoResize; case HTBOTTOMRIGHT: return ui::mojom::CursorType::kNorthWestSouthEastNoResize; case HTLEFT: return ui::mojom::CursorType::kEastWestNoResize; case HTRIGHT: return ui::mojom::CursorType::kEastWestNoResize; case HTTOP: return ui::mojom::CursorType::kNorthSouthNoResize; case HTTOPLEFT: return ui::mojom::CursorType::kNorthWestSouthEastNoResize; case HTTOPRIGHT: return ui::mojom::CursorType::kNorthEastSouthWestNoResize; default: return ui::mojom::CursorType::kNull; } } void CompoundEventFilter::AddHandler(ui::EventHandler* handler) { handlers_.AddObserver(handler); } void CompoundEventFilter::RemoveHandler(ui::EventHandler* handler) { handlers_.RemoveObserver(handler); } //////////////////////////////////////////////////////////////////////////////// // CompoundEventFilter, private: void CompoundEventFilter::UpdateCursor(aura::Window* target, ui::MouseEvent* event) { // If drag and drop is in progress, let the drag drop client set the cursor // instead of setting the cursor here. aura::Window* root_window = target->GetRootWindow(); aura::client::DragDropClient* drag_drop_client = aura::client::GetDragDropClient(root_window); if (drag_drop_client && drag_drop_client->IsDragDropInProgress()) return; aura::client::CursorClient* cursor_client = aura::client::GetCursorClient(root_window); if (cursor_client) { gfx::NativeCursor cursor = target->GetCursor(event->location()); if ((event->flags() & ui::EF_IS_NON_CLIENT)) { if (target->delegate()) { int window_component = target->delegate()->GetNonClientComponent(event->location()); if ((target->GetProperty(aura::client::kResizeBehaviorKey) & aura::client::kResizeBehaviorCanResize) != 0) { cursor = CursorForWindowComponent(window_component); } else { cursor = NoResizeCursorForWindowComponent(window_component); } } else { // Allow the OS to handle non client cursors if we don't have a // a delegate to handle the non client hittest. return; } } // For ET_MOUSE_ENTERED, force the update of the cursor because it may have // changed without |cursor_client| knowing about it. if (event->type() == ui::ET_MOUSE_ENTERED) cursor_client->SetCursorForced(cursor); else cursor_client->SetCursor(cursor); } } void CompoundEventFilter::FilterKeyEvent(ui::KeyEvent* event) { for (ui::EventHandler& handler : handlers_) { if (event->stopped_propagation()) break; handler.OnKeyEvent(event); } } void CompoundEventFilter::FilterMouseEvent(ui::MouseEvent* event) { for (ui::EventHandler& handler : handlers_) { if (event->stopped_propagation()) break; handler.OnMouseEvent(event); } } void CompoundEventFilter::FilterTouchEvent(ui::TouchEvent* event) { for (ui::EventHandler& handler : handlers_) { if (event->stopped_propagation()) break; handler.OnTouchEvent(event); } } void CompoundEventFilter::SetCursorVisibilityOnEvent(aura::Window* target, ui::Event* event, bool show) { if (event->flags() & ui::EF_IS_SYNTHESIZED) return; aura::client::CursorClient* client = aura::client::GetCursorClient(target->GetRootWindow()); if (!client) return; if (show) client->ShowCursor(); else client->HideCursor(); } void CompoundEventFilter::SetMouseEventsEnableStateOnEvent(aura::Window* target, ui::Event* event, bool enable) { TRACE_EVENT2("ui,input", "CompoundEventFilter::SetMouseEventsEnableStateOnEvent", "event_flags", event->flags(), "enable", enable); if (event->flags() & ui::EF_IS_SYNTHESIZED) return; aura::client::CursorClient* client = aura::client::GetCursorClient(target->GetRootWindow()); if (!client) { TRACE_EVENT_INSTANT0( "ui,input", "CompoundEventFilter::SetMouseEventsEnableStateOnEvent - No Client", TRACE_EVENT_SCOPE_THREAD); return; } if (enable) client->EnableMouseEvents(); else client->DisableMouseEvents(); } //////////////////////////////////////////////////////////////////////////////// // CompoundEventFilter, ui::EventHandler implementation: void CompoundEventFilter::OnKeyEvent(ui::KeyEvent* event) { aura::Window* target = static_cast<aura::Window*>(event->target()); aura::client::CursorClient* client = aura::client::GetCursorClient(target->GetRootWindow()); if (client && client->ShouldHideCursorOnKeyEvent(*event)) SetCursorVisibilityOnEvent(target, event, false); FilterKeyEvent(event); } void CompoundEventFilter::OnMouseEvent(ui::MouseEvent* event) { TRACE_EVENT2("ui,input", "CompoundEventFilter::OnMouseEvent", "event_type", event->type(), "event_flags", event->flags()); aura::Window* window = static_cast<aura::Window*>(event->target()); // We must always update the cursor, otherwise the cursor can get stuck if an // event filter registered with us consumes the event. // It should also update the cursor for clicking and wheels for ChromeOS boot. // When ChromeOS is booted, it hides the mouse cursor but immediate mouse // operation will show the cursor. // We also update the cursor for mouse enter in case a mouse cursor is sent to // outside of the root window and moved back for some reasons (e.g. running on // on Desktop for testing, or a bug in pointer barrier). if (!(event->flags() & ui::EF_FROM_TOUCH) && (event->type() == ui::ET_MOUSE_ENTERED || event->type() == ui::ET_MOUSE_MOVED || event->type() == ui::ET_MOUSE_PRESSED || event->type() == ui::ET_MOUSEWHEEL)) { SetMouseEventsEnableStateOnEvent(window, event, true); SetCursorVisibilityOnEvent(window, event, true); UpdateCursor(window, event); } FilterMouseEvent(event); } void CompoundEventFilter::OnScrollEvent(ui::ScrollEvent* event) { } void CompoundEventFilter::OnTouchEvent(ui::TouchEvent* event) { TRACE_EVENT2("ui,input", "CompoundEventFilter::OnTouchEvent", "event_type", event->type(), "event_handled", event->handled()); FilterTouchEvent(event); if (!event->handled() && event->type() == ui::ET_TOUCH_PRESSED) { aura::Window* target = static_cast<aura::Window*>(event->target()); DCHECK(target); auto* client = aura::client::GetCursorClient(target->GetRootWindow()); if (client && client->ShouldHideCursorOnTouchEvent(*event) && !aura::Env::GetInstance()->IsMouseButtonDown()) { SetMouseEventsEnableStateOnEvent(target, event, false); SetCursorVisibilityOnEvent(target, event, false); } } } void CompoundEventFilter::OnGestureEvent(ui::GestureEvent* event) { for (ui::EventHandler& handler : handlers_) { if (event->stopped_propagation()) break; handler.OnGestureEvent(event); } } base::StringPiece CompoundEventFilter::GetLogContext() const { return "CompoundEventFilter"; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/compound_event_filter.cc
C++
unknown
9,563
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_COMPOUND_EVENT_FILTER_H_ #define UI_WM_CORE_COMPOUND_EVENT_FILTER_H_ #include "base/component_export.h" #include "base/observer_list.h" #include "base/strings/string_piece.h" #include "ui/events/event.h" #include "ui/events/event_handler.h" #include "ui/gfx/native_widget_types.h" namespace ui { class GestureEvent; class KeyEvent; class MouseEvent; class TouchEvent; } namespace wm { // TODO(beng): This class should die. AddEventHandler() on the root Window // should be used instead. // CompoundEventFilter gets all events first and can provide actions to those // events. It implements global features such as click to activate a window and // cursor change when moving mouse. // Additional event filters can be added to CompoundEventFilter. Events will // pass through those additional filters in their addition order and could be // consumed by any of those filters. If an event is consumed by a filter, the // rest of the filter(s) and CompoundEventFilter will not see the consumed // event. class COMPONENT_EXPORT(UI_WM) CompoundEventFilter : public ui::EventHandler { public: CompoundEventFilter(); CompoundEventFilter(const CompoundEventFilter&) = delete; CompoundEventFilter& operator=(const CompoundEventFilter&) = delete; ~CompoundEventFilter() override; // Returns the cursor for the specified component. static gfx::NativeCursor CursorForWindowComponent(int window_component); // Returns the not-resizable cursor for the specified component. static gfx::NativeCursor NoResizeCursorForWindowComponent( int window_component); // Adds/removes additional event filters. This does not take ownership of // the EventHandler. // NOTE: These handlers are deprecated. Use env::AddPreTargetEventHandler etc. // instead. void AddHandler(ui::EventHandler* filter); void RemoveHandler(ui::EventHandler* filter); private: // Updates the cursor if the target provides a custom one, and provides // default resize cursors for window edges. void UpdateCursor(aura::Window* target, ui::MouseEvent* event); // Dispatches event to additional filters. void FilterKeyEvent(ui::KeyEvent* event); void FilterMouseEvent(ui::MouseEvent* event); void FilterTouchEvent(ui::TouchEvent* event); // Sets the visibility of the cursor if the event is not synthesized. void SetCursorVisibilityOnEvent(aura::Window* target, ui::Event* event, bool show); // Enables or disables mouse events if the event is not synthesized. void SetMouseEventsEnableStateOnEvent(aura::Window* target, ui::Event* event, bool enable); // Overridden from ui::EventHandler: void OnKeyEvent(ui::KeyEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; void OnScrollEvent(ui::ScrollEvent* event) override; void OnTouchEvent(ui::TouchEvent* event) override; void OnGestureEvent(ui::GestureEvent* event) override; base::StringPiece GetLogContext() const override; // Additional pre-target event handlers. base::ObserverList<ui::EventHandler, true>::Unchecked handlers_; }; } // namespace wm #endif // UI_WM_CORE_COMPOUND_EVENT_FILTER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/compound_event_filter.h
C++
unknown
3,430
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/compound_event_filter.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "ui/aura/client/cursor_client.h" #include "ui/aura/env.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_cursor_client.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/test/event_generator.h" #include "ui/wm/public/activation_client.h" namespace { #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_WIN) base::TimeTicks GetTime() { return ui::EventTimeForNow(); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_WIN) } namespace wm { namespace { // An event filter that consumes all gesture events. class ConsumeGestureEventFilter : public ui::EventHandler { public: ConsumeGestureEventFilter() {} ConsumeGestureEventFilter(const ConsumeGestureEventFilter&) = delete; ConsumeGestureEventFilter& operator=(const ConsumeGestureEventFilter&) = delete; ~ConsumeGestureEventFilter() override {} private: // Overridden from ui::EventHandler: void OnGestureEvent(ui::GestureEvent* e) override { e->StopPropagation(); } }; } // namespace typedef aura::test::AuraTestBase CompoundEventFilterTest; #if BUILDFLAG(IS_CHROMEOS_ASH) // A keypress only hides the cursor on ChromeOS (crbug.com/304296). TEST_F(CompoundEventFilterTest, CursorVisibilityChange) { std::unique_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); aura::test::TestWindowDelegate delegate; std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); window->Show(); window->SetCapture(); aura::test::TestCursorClient cursor_client(root_window()); // Send key event to hide the cursor. ui::KeyEvent key('a', ui::VKEY_A, ui::DomCode::NONE, ui::EF_NONE); DispatchEventUsingWindowDispatcher(&key); EXPECT_FALSE(cursor_client.IsCursorVisible()); // Synthesized mouse event should not show the cursor. ui::MouseEvent enter(ui::ET_MOUSE_ENTERED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EventTimeForNow(), 0, 0); enter.set_flags(enter.flags() | ui::EF_IS_SYNTHESIZED); DispatchEventUsingWindowDispatcher(&enter); EXPECT_FALSE(cursor_client.IsCursorVisible()); ui::MouseEvent move(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EventTimeForNow(), 0, 0); move.set_flags(enter.flags() | ui::EF_IS_SYNTHESIZED); DispatchEventUsingWindowDispatcher(&move); EXPECT_FALSE(cursor_client.IsCursorVisible()); // A real mouse event should show the cursor. ui::MouseEvent real_move(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EventTimeForNow(), 0, 0); DispatchEventUsingWindowDispatcher(&real_move); EXPECT_TRUE(cursor_client.IsCursorVisible()); // Disallow hiding the cursor on keypress. cursor_client.set_should_hide_cursor_on_key_event(false); key = ui::KeyEvent('a', ui::VKEY_A, ui::DomCode::NONE, ui::EF_NONE); DispatchEventUsingWindowDispatcher(&key); EXPECT_TRUE(cursor_client.IsCursorVisible()); // Allow hiding the cursor on keypress. cursor_client.set_should_hide_cursor_on_key_event(true); key = ui::KeyEvent('a', ui::VKEY_A, ui::DomCode::NONE, ui::EF_NONE); DispatchEventUsingWindowDispatcher(&key); EXPECT_FALSE(cursor_client.IsCursorVisible()); // Mouse synthesized exit event should not show the cursor. ui::MouseEvent exit(ui::ET_MOUSE_EXITED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EventTimeForNow(), 0, 0); exit.set_flags(enter.flags() | ui::EF_IS_SYNTHESIZED); DispatchEventUsingWindowDispatcher(&exit); EXPECT_FALSE(cursor_client.IsCursorVisible()); aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_WIN) // Touch visually hides the cursor on ChromeOS and Windows. TEST_F(CompoundEventFilterTest, TouchHidesCursor) { std::unique_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); aura::test::TestWindowDelegate delegate; std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); window->Show(); window->SetCapture(); aura::test::TestCursorClient cursor_client(root_window()); ui::MouseEvent mouse0(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EventTimeForNow(), 0, 0); DispatchEventUsingWindowDispatcher(&mouse0); EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); EXPECT_TRUE(cursor_client.IsCursorVisible()); // This press is required for the GestureRecognizer to associate a target // with kTouchId ui::TouchEvent press0(ui::ET_TOUCH_PRESSED, gfx::Point(90, 90), GetTime(), ui::PointerDetails(ui::EventPointerType::kTouch, 1)); DispatchEventUsingWindowDispatcher(&press0); EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); EXPECT_FALSE(cursor_client.IsCursorVisible()); ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(10, 10), GetTime(), ui::PointerDetails(ui::EventPointerType::kTouch, 1)); DispatchEventUsingWindowDispatcher(&move); EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); EXPECT_FALSE(cursor_client.IsCursorVisible()); ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(10, 10), GetTime(), ui::PointerDetails(ui::EventPointerType::kTouch, 1)); DispatchEventUsingWindowDispatcher(&release); EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); EXPECT_FALSE(cursor_client.IsCursorVisible()); ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EventTimeForNow(), 0, 0); // Move the cursor again. The cursor should be visible. DispatchEventUsingWindowDispatcher(&mouse1); EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); EXPECT_TRUE(cursor_client.IsCursorVisible()); // Now activate the window and press on it again. ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(90, 90), GetTime(), ui::PointerDetails(ui::EventPointerType::kTouch, 1)); GetActivationClient(root_window())->ActivateWindow(window.get()); DispatchEventUsingWindowDispatcher(&press1); EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); EXPECT_FALSE(cursor_client.IsCursorVisible()); aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_WIN) // Tests that if an event filter consumes a gesture, then it doesn't focus the // window. TEST_F(CompoundEventFilterTest, FilterConsumedGesture) { std::unique_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); std::unique_ptr<ui::EventHandler> gesure_handler( new ConsumeGestureEventFilter); compound_filter->AddHandler(gesure_handler.get()); aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); aura::test::TestWindowDelegate delegate; DCHECK(root_window()); std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); window->Show(); EXPECT_TRUE(window->CanFocus()); EXPECT_FALSE(window->HasFocus()); // Tap on the window should not focus it since the filter will be consuming // the gestures. ui::test::EventGenerator generator(root_window(), gfx::Point(50, 50)); generator.PressTouch(); EXPECT_FALSE(window->HasFocus()); compound_filter->RemoveHandler(gesure_handler.get()); aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); } // Verifies we don't attempt to hide the mouse when the mouse is down and a // touch event comes in. TEST_F(CompoundEventFilterTest, DontHideWhenMouseDown) { ui::test::EventGenerator event_generator(root_window()); std::unique_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); aura::test::TestWindowDelegate delegate; std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); window->Show(); aura::test::TestCursorClient cursor_client(root_window()); // Move and press the mouse over the window. event_generator.MoveMouseTo(10, 10); EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); event_generator.PressLeftButton(); EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); EXPECT_TRUE(aura::Env::GetInstance()->IsMouseButtonDown()); // Do a touch event. As the mouse button is down this should not disable mouse // events. event_generator.PressTouch(); EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); } #if BUILDFLAG(IS_WIN) // Windows synthesizes mouse messages for touch events. We should not be // showing the cursor when we receive such messages. TEST_F(CompoundEventFilterTest, DontShowCursorOnMouseMovesFromTouch) { std::unique_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); aura::test::TestWindowDelegate delegate; std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); window->Show(); window->SetCapture(); aura::test::TestCursorClient cursor_client(root_window()); cursor_client.DisableMouseEvents(); EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); ui::MouseEvent mouse0(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EventTimeForNow(), 0, 0); mouse0.set_flags(mouse0.flags() | ui::EF_FROM_TOUCH); DispatchEventUsingWindowDispatcher(&mouse0); EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); mouse0.set_flags(mouse0.flags() & ~ui::EF_FROM_TOUCH); DispatchEventUsingWindowDispatcher(&mouse0); EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); } #endif } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/compound_event_filter_unittest.cc
C++
unknown
10,631
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/coordinate_conversion.h" #include "ui/aura/client/screen_position_client.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/transform.h" namespace wm { void ConvertPointToScreen(const aura::Window* window, gfx::Point* point) { DCHECK(window); DCHECK(window->GetRootWindow()); DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); aura::client::GetScreenPositionClient(window->GetRootWindow())-> ConvertPointToScreen(window, point); } void ConvertPointToScreen(const aura::Window* window, gfx::PointF* point) { DCHECK(window); DCHECK(window->GetRootWindow()); DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); aura::client::GetScreenPositionClient(window->GetRootWindow()) ->ConvertPointToScreen(window, point); } void ConvertPointFromScreen(const aura::Window* window, gfx::Point* point_in_screen) { DCHECK(window); DCHECK(window->GetRootWindow()); DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); aura::client::GetScreenPositionClient(window->GetRootWindow())-> ConvertPointFromScreen(window, point_in_screen); } void ConvertPointFromScreen(const aura::Window* window, gfx::PointF* point_in_screen) { DCHECK(window); DCHECK(window->GetRootWindow()); DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); aura::client::GetScreenPositionClient(window->GetRootWindow()) ->ConvertPointFromScreen(window, point_in_screen); } void ConvertRectToScreen(const aura::Window* window, gfx::Rect* rect) { gfx::Point origin = rect->origin(); ConvertPointToScreen(window, &origin); rect->set_origin(origin); } void TranslateRectToScreen(const aura::Window* window, gfx::RectF* rect) { gfx::PointF origin = rect->origin(); ConvertPointToScreen(window, &origin); rect->set_origin(origin); } void ConvertRectFromScreen(const aura::Window* window, gfx::Rect* rect_in_screen) { gfx::Point origin = rect_in_screen->origin(); ConvertPointFromScreen(window, &origin); rect_in_screen->set_origin(origin); } void TranslateRectFromScreen(const aura::Window* window, gfx::RectF* rect) { gfx::PointF origin = rect->origin(); ConvertPointFromScreen(window, &origin); rect->set_origin(origin); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/coordinate_conversion.cc
C++
unknown
2,672
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_COORDINATE_CONVERSION_H_ #define UI_WM_CORE_COORDINATE_CONVERSION_H_ #include "base/component_export.h" namespace aura { class Window; } // namespace aura namespace gfx { class Point; class PointF; class Rect; class RectF; } // namespace gfx namespace wm { // Converts the |point| from a given |window|'s coordinates into the screen // coordinates. // TODO: Remove the integer versions of these functions. See crbug.com/773331. COMPONENT_EXPORT(UI_WM) void ConvertPointToScreen(const aura::Window* window, gfx::Point* point); COMPONENT_EXPORT(UI_WM) void ConvertPointToScreen(const aura::Window* window, gfx::PointF* point); // Converts the |point| from the screen coordinates to a given |window|'s // coordinates. COMPONENT_EXPORT(UI_WM) void ConvertPointFromScreen(const aura::Window* window, gfx::Point* point_in_screen); COMPONENT_EXPORT(UI_WM) void ConvertPointFromScreen(const aura::Window* window, gfx::PointF* point_in_screen); // Converts |rect| from |window|'s coordinates to the virtual screen // coordinates. // TODO: Change the Rect versions to TranslateRect(To|From)Screen since they // do not handle size changes. COMPONENT_EXPORT(UI_WM) void ConvertRectToScreen(const aura::Window* window, gfx::Rect* rect); COMPONENT_EXPORT(UI_WM) void TranslateRectToScreen(const aura::Window* window, gfx::RectF* rect); // Converts |rect| from virtual screen coordinates to the |window|'s // coordinates. COMPONENT_EXPORT(UI_WM) void ConvertRectFromScreen(const aura::Window* window, gfx::Rect* rect_in_screen); COMPONENT_EXPORT(UI_WM) void TranslateRectFromScreen(const aura::Window* window, gfx::RectF* rect_in_screen); } // namespace wm #endif // UI_WM_CORE_COORDINATE_CONVERSION_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/coordinate_conversion.h
C++
unknown
1,981
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/coordinate_conversion.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_windows.h" namespace wm { typedef aura::test::AuraTestBase CoordinateConversionTest; TEST_F(CoordinateConversionTest, ConvertRect) { aura::Window* w = aura::test::CreateTestWindowWithBounds( gfx::Rect(10, 20, 100, 200), root_window()); gfx::Rect r1(10, 20, 100, 120); ConvertRectFromScreen(w, &r1); EXPECT_EQ("0,0 100x120", r1.ToString()); gfx::Rect r2(0, 0, 100, 200); ConvertRectFromScreen(w, &r2); EXPECT_EQ("-10,-20 100x200", r2.ToString()); gfx::Rect r3(30, 30, 100, 200); ConvertRectToScreen(w, &r3); EXPECT_EQ("40,50 100x200", r3.ToString()); gfx::Rect r4(-10, -20, 100, 200); ConvertRectToScreen(w, &r4); EXPECT_EQ("0,0 100x200", r4.ToString()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/coordinate_conversion_unittest.cc
C++
unknown
1,022
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/cursor_loader.h" #include <map> #include <vector> #include "base/check.h" #include "base/memory/scoped_refptr.h" #include "base/time/time.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/cursor/mojom/cursor_type.mojom.h" #include "ui/base/cursor/platform_cursor.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_scale_factor.h" #include "ui/gfx/geometry/point.h" #include "ui/wm/core/cursor_util.h" namespace wm { namespace { using ::ui::mojom::CursorType; constexpr base::TimeDelta kAnimatedCursorFrameDelay = base::Milliseconds(25); } // namespace CursorLoader::CursorLoader(bool use_platform_cursors) : use_platform_cursors_(use_platform_cursors), factory_(ui::CursorFactory::GetInstance()) { factory_->AddObserver(this); } CursorLoader::~CursorLoader() { factory_->RemoveObserver(this); } void CursorLoader::OnThemeLoaded() { UnloadCursors(); } void CursorLoader::UnloadCursors() { image_cursors_.clear(); } bool CursorLoader::SetDisplay(const display::Display& display) { const display::Display::Rotation rotation = display.panel_rotation(); const float scale = display.device_scale_factor(); if (rotation_ == rotation && scale_ == scale) { return false; } rotation_ = rotation; scale_ = scale; resource_scale_ = ui::GetScaleForResourceScaleFactor( ui::GetSupportedResourceScaleFactor(scale_)); UnloadCursors(); if (use_platform_cursors_) factory_->SetDeviceScaleFactor(scale_); return true; } void CursorLoader::SetSize(ui::CursorSize size) { if (size_ == size) return; size_ = size; UnloadCursors(); } void CursorLoader::SetPlatformCursor(ui::Cursor* cursor) { DCHECK(cursor); // The platform cursor was already set via WebCursor::GetNativeCursor. if (cursor->type() == CursorType::kCustom) { return; } cursor->SetPlatformCursor(CursorFromType(cursor->type())); } absl::optional<ui::CursorData> CursorLoader::GetCursorData( const ui::Cursor& cursor) const { CursorType type = cursor.type(); if (type == CursorType::kNone) return ui::CursorData(); if (type == CursorType::kCustom) { return ui::CursorData({cursor.custom_bitmap()}, cursor.custom_hotspot(), cursor.image_scale_factor()); } if (use_platform_cursors_) { auto cursor_data = factory_->GetCursorData(type); if (cursor_data) { // TODO(https://crbug.com/1193775): consider either passing `scale_` to // `CursorFactory::GetCursorData`, or relying on having called // `CursorFactory::SetDeviceScaleFactor`, instead of appending it here. return ui::CursorData(std::move(cursor_data->bitmaps), std::move(cursor_data->hotspot), scale_); } } // TODO(https://crbug.com/1193775): use the actual `rotation_` if that makes // sense for the current use cases of `GetCursorData` (e.g. Chrome Remote // Desktop, WebRTC and VideoRecordingWatcher). return wm::GetCursorData(type, size_, resource_scale_, display::Display::ROTATE_0); } scoped_refptr<ui::PlatformCursor> CursorLoader::CursorFromType( CursorType type) { // An image cursor is loaded for this type. if (image_cursors_.count(type)) return image_cursors_[type]; // Check if there's a default platform cursor available. // For the none cursor, we also need to use the platform factory to take // into account the different ways of creating an invisible cursor. scoped_refptr<ui::PlatformCursor> cursor; if (use_platform_cursors_ || type == CursorType::kNone) { cursor = factory_->GetDefaultCursor(type); if (cursor) return cursor; // The cursor may fail to load if the cursor theme has just been reset. // We will be notified when the theme is loaded, but at this time we have to // fall back to the assets. LOG(WARNING) << "Failed to load a platform cursor of type " << type; } // Loads the default Aura cursor bitmap for the cursor type. Falls back on // pointer cursor if this fails. cursor = LoadCursorFromAsset(type); if (!cursor && type != CursorType::kPointer) { cursor = CursorFromType(CursorType::kPointer); image_cursors_[type] = cursor; } DCHECK(cursor) << "Failed to load a bitmap for the pointer cursor."; return cursor; } scoped_refptr<ui::PlatformCursor> CursorLoader::LoadCursorFromAsset( CursorType type) { absl::optional<ui::CursorData> cursor_data = wm::GetCursorData(type, size_, resource_scale_, rotation_); if (!cursor_data) { return nullptr; } if (cursor_data->bitmaps.size() == 1) { image_cursors_[type] = factory_->CreateImageCursor( type, cursor_data->bitmaps[0], cursor_data->hotspot); } else { image_cursors_[type] = factory_->CreateAnimatedCursor( type, cursor_data->bitmaps, cursor_data->hotspot, kAnimatedCursorFrameDelay); } return image_cursors_[type]; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_loader.cc
C++
unknown
5,287
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_CURSOR_LOADER_H_ #define UI_WM_CORE_CURSOR_LOADER_H_ #include <map> #include <memory> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "ui/aura/client/cursor_shape_client.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/cursor/mojom/cursor_type.mojom-forward.h" #include "ui/display/display.h" namespace ui { class PlatformCursor; } namespace wm { class COMPONENT_EXPORT(UI_WM) CursorLoader : public aura::client::CursorShapeClient, public ui::CursorFactoryObserver { public: explicit CursorLoader(bool use_platform_cursors = true); CursorLoader(const CursorLoader&) = delete; CursorLoader& operator=(const CursorLoader&) = delete; ~CursorLoader() override; // ui::CursorFactoryObserver: void OnThemeLoaded() override; // Returns the rotation of the currently loaded cursor. display::Display::Rotation rotation() const { return rotation_; } // Sets the rotation and scale the cursors are loaded for. // Returns true if the cursor needs to be reset. bool SetDisplay(const display::Display& display); // Returns the size of the currently loaded cursor. ui::CursorSize size() const { return size_; } // Sets the size of the mouse cursor icon. void SetSize(ui::CursorSize size); // Sets the platform cursor based on the type of |cursor|. void SetPlatformCursor(ui::Cursor* cursor); // aura::client::CursorShapeClient: absl::optional<ui::CursorData> GetCursorData( const ui::Cursor& cursor) const override; private: // Resets the cursor cache. void UnloadCursors(); scoped_refptr<ui::PlatformCursor> CursorFromType(ui::mojom::CursorType type); scoped_refptr<ui::PlatformCursor> LoadCursorFromAsset( ui::mojom::CursorType type); // Whether to use cursors provided by the underlying platform (e.g. X11 // cursors). If false or in the case of a failure, Chromium assets will be // used instead. const bool use_platform_cursors_; std::map<ui::mojom::CursorType, scoped_refptr<ui::PlatformCursor>> image_cursors_; raw_ptr<ui::CursorFactory> factory_ = nullptr; // The scale of the current display, used for system cursors. The selection // of the particular cursor is platform-dependent. float scale_ = 1.0f; // The scale used for cursor resources provided by Chromium. It will be set // to the closest value to `scale_` for which there are resources available. float resource_scale_ = 1.0f; // The current rotation of the mouse cursor icon. display::Display::Rotation rotation_ = display::Display::ROTATE_0; // The preferred size of the mouse cursor icon. ui::CursorSize size_ = ui::CursorSize::kNormal; }; } // namespace wm #endif // UI_WM_CORE_CURSOR_LOADER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_loader.h
C++
unknown
3,004
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/cursor_loader.h" #include "base/memory/scoped_refptr.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/aura/client/cursor_shape_client.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/base/cursor/platform_cursor.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_scale_factor.h" #include "ui/display/display.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/skia_util.h" #include "ui/wm/core/cursor_util.h" namespace wm { namespace { using ::ui::mojom::CursorType; SkBitmap GetTestBitmap() { SkBitmap bitmap; bitmap.allocN32Pixels(10, 10); return bitmap; } } // namespace TEST(CursorLoaderTest, InvisibleCursor) { CursorLoader cursor_loader; ui::Cursor invisible_cursor(CursorType::kNone); cursor_loader.SetPlatformCursor(&invisible_cursor); EXPECT_EQ( invisible_cursor.platform(), ui::CursorFactory::GetInstance()->GetDefaultCursor(CursorType::kNone)); } TEST(CursorLoaderTest, GetCursorData) { // Make sure we always use the fallback cursors, so the test works the same // in all platforms. CursorLoader cursor_loader(/*use_platform_cursors=*/false); display::Display display = display::Display::GetDefaultDisplay(); for (const float scale : {0.8f, 1.0f, 1.25f, 1.5f, 2.0f, 3.0f}) { SCOPED_TRACE(testing::Message() << "scale " << scale); display.set_device_scale_factor(scale); cursor_loader.SetDisplay(display); const float resource_scale = ui::GetScaleForResourceScaleFactor( ui::GetSupportedResourceScaleFactor(scale)); for (const ui::CursorSize cursor_size : {ui::CursorSize::kNormal, ui::CursorSize::kLarge}) { SCOPED_TRACE(testing::Message() << "size " << static_cast<int>(cursor_size)); cursor_loader.SetSize(cursor_size); const ui::Cursor invisible_cursor = CursorType::kNone; absl::optional<ui::CursorData> cursor_loader_data = cursor_loader.GetCursorData(invisible_cursor); ASSERT_TRUE(cursor_loader_data); EXPECT_TRUE(cursor_loader_data->bitmaps[0].isNull()); EXPECT_TRUE(cursor_loader_data->hotspot.IsOrigin()); for (const ui::Cursor cursor : {CursorType::kPointer, CursorType::kWait}) { SCOPED_TRACE(cursor.type()); cursor_loader_data = cursor_loader.GetCursorData(cursor); ASSERT_TRUE(cursor_loader_data); const auto cursor_data = GetCursorData(cursor.type(), cursor_size, resource_scale, display.panel_rotation()); ASSERT_TRUE(cursor_data); ASSERT_EQ(cursor_loader_data->bitmaps.size(), cursor_data->bitmaps.size()); for (size_t i = 0; i < cursor_data->bitmaps.size(); i++) { EXPECT_TRUE(gfx::BitmapsAreEqual(cursor_loader_data->bitmaps[i], cursor_data->bitmaps[i])); } EXPECT_EQ(cursor_loader_data->hotspot, cursor_data->hotspot); } } } const SkBitmap kBitmap = GetTestBitmap(); constexpr gfx::Point kHotspot = gfx::Point(10, 10); const ui::Cursor custom_cursor = ui::Cursor::NewCustom(kBitmap, kHotspot); absl::optional<ui::CursorData> cursor_data = cursor_loader.GetCursorData(custom_cursor); ASSERT_TRUE(cursor_data); EXPECT_EQ(cursor_data->bitmaps[0].getGenerationID(), kBitmap.getGenerationID()); EXPECT_EQ(cursor_data->hotspot, kHotspot); } // Test the cursor image cache when fallbacks for system cursors are used. TEST(CursorLoaderTest, ImageCursorCache) { display::Display display = display::Display::GetDefaultDisplay(); CursorLoader cursor_loader(/*use_platform_cursors=*/false); cursor_loader.SetDisplay(display); ui::Cursor cursor(CursorType::kPointer); cursor_loader.SetPlatformCursor(&cursor); // CursorLoader should keep a ref in its cursor cache. auto platform_cursor = cursor.platform(); cursor.SetPlatformCursor(nullptr); EXPECT_FALSE(platform_cursor->HasOneRef()); // Invalidate the cursor cache by changing the rotation. display.set_panel_rotation(display::Display::ROTATE_90); cursor_loader.SetDisplay(display); EXPECT_TRUE(platform_cursor->HasOneRef()); // Invalidate the cursor cache by changing the scale. cursor_loader.SetPlatformCursor(&cursor); platform_cursor = cursor.platform(); cursor.SetPlatformCursor(nullptr); EXPECT_FALSE(platform_cursor->HasOneRef()); display.set_device_scale_factor(display.device_scale_factor() * 2); cursor_loader.SetDisplay(display); EXPECT_TRUE(platform_cursor->HasOneRef()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_loader_unittest.cc
C++
unknown
4,933
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/cursor_manager.h" #include <utility> #include "base/check_op.h" #include "base/observer_list.h" #include "base/trace_event/trace_event.h" #include "ui/aura/client/cursor_client_observer.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/wm/core/native_cursor_manager.h" #include "ui/wm/core/native_cursor_manager_delegate.h" namespace wm { namespace internal { // Represents the cursor state which is composed of cursor type, visibility, and // mouse events enable state. When mouse events are disabled, the cursor is // always invisible. class CursorState { public: CursorState() : visible_(true), cursor_size_(ui::CursorSize::kNormal), mouse_events_enabled_(true), visible_on_mouse_events_enabled_(true) {} CursorState(const CursorState&) = delete; CursorState& operator=(const CursorState&) = delete; gfx::NativeCursor cursor() const { return cursor_; } void set_cursor(gfx::NativeCursor cursor) { cursor_ = cursor; } bool visible() const { return visible_; } void SetVisible(bool visible) { if (mouse_events_enabled_) visible_ = visible; // Ignores the call when mouse events disabled. } ui::CursorSize cursor_size() const { return cursor_size_; } void set_cursor_size(ui::CursorSize cursor_size) { cursor_size_ = cursor_size; } const gfx::Size& system_cursor_size() const { return system_cursor_size_; } void set_system_cursor_size(const gfx::Size& system_cursor_size) { system_cursor_size_ = system_cursor_size; } bool mouse_events_enabled() const { return mouse_events_enabled_; } void SetMouseEventsEnabled(bool enabled) { if (mouse_events_enabled_ == enabled) return; mouse_events_enabled_ = enabled; // Restores the visibility when mouse events are enabled. if (enabled) { visible_ = visible_on_mouse_events_enabled_; } else { visible_on_mouse_events_enabled_ = visible_; visible_ = false; } } private: gfx::NativeCursor cursor_; bool visible_; ui::CursorSize cursor_size_; bool mouse_events_enabled_; // The visibility to set when mouse events are enabled. bool visible_on_mouse_events_enabled_; gfx::Size system_cursor_size_; }; } // namespace internal bool CursorManager::last_cursor_visibility_state_ = true; CursorManager::CursorManager(std::unique_ptr<NativeCursorManager> delegate) : delegate_(std::move(delegate)), cursor_lock_count_(0), current_state_(new internal::CursorState), state_on_unlock_(new internal::CursorState) { // Restore the last cursor visibility state. current_state_->SetVisible(last_cursor_visibility_state_); } CursorManager::~CursorManager() { } // static void CursorManager::ResetCursorVisibilityStateForTest() { last_cursor_visibility_state_ = true; } void CursorManager::SetCursor(gfx::NativeCursor cursor) { SetCursorImpl(cursor, /*forced=*/false); } gfx::NativeCursor CursorManager::GetCursor() const { return current_state_->cursor(); } void CursorManager::SetCursorForced(gfx::NativeCursor cursor) { SetCursorImpl(cursor, /*forced=*/true); } void CursorManager::ShowCursor() { last_cursor_visibility_state_ = true; state_on_unlock_->SetVisible(true); if (cursor_lock_count_ == 0 && IsCursorVisible() != state_on_unlock_->visible()) { delegate_->SetVisibility(state_on_unlock_->visible(), this); if (GetCursor().type() != ui::mojom::CursorType::kNone) { // If the cursor is a visible type, notify the observers. for (auto& observer : observers_) observer.OnCursorVisibilityChanged(true); } } } void CursorManager::HideCursor() { last_cursor_visibility_state_ = false; state_on_unlock_->SetVisible(false); if (cursor_lock_count_ == 0 && IsCursorVisible() != state_on_unlock_->visible()) { delegate_->SetVisibility(state_on_unlock_->visible(), this); for (auto& observer : observers_) observer.OnCursorVisibilityChanged(false); } } bool CursorManager::IsCursorVisible() const { return current_state_->visible(); } void CursorManager::SetCursorSize(ui::CursorSize cursor_size) { state_on_unlock_->set_cursor_size(cursor_size); if (GetCursorSize() != state_on_unlock_->cursor_size()) { delegate_->SetCursorSize(state_on_unlock_->cursor_size(), this); for (auto& observer : observers_) observer.OnCursorSizeChanged(cursor_size); } } ui::CursorSize CursorManager::GetCursorSize() const { return current_state_->cursor_size(); } void CursorManager::EnableMouseEvents() { TRACE_EVENT0("ui,input", "CursorManager::EnableMouseEvents"); state_on_unlock_->SetMouseEventsEnabled(true); if (cursor_lock_count_ == 0 && IsMouseEventsEnabled() != state_on_unlock_->mouse_events_enabled()) { delegate_->SetMouseEventsEnabled(state_on_unlock_->mouse_events_enabled(), this); } } void CursorManager::DisableMouseEvents() { TRACE_EVENT0("ui,input", "CursorManager::DisableMouseEvents"); state_on_unlock_->SetMouseEventsEnabled(false); if (cursor_lock_count_ == 0 && IsMouseEventsEnabled() != state_on_unlock_->mouse_events_enabled()) { delegate_->SetMouseEventsEnabled(state_on_unlock_->mouse_events_enabled(), this); } } bool CursorManager::IsMouseEventsEnabled() const { return current_state_->mouse_events_enabled(); } void CursorManager::SetDisplay(const display::Display& display) { display_ = display; for (auto& observer : observers_) observer.OnCursorDisplayChanged(display); delegate_->SetDisplay(display, this); } const display::Display& CursorManager::GetDisplay() const { return display_; } void CursorManager::LockCursor() { cursor_lock_count_++; } void CursorManager::UnlockCursor() { cursor_lock_count_--; DCHECK_GE(cursor_lock_count_, 0); if (cursor_lock_count_ > 0) return; if (GetCursor() != state_on_unlock_->cursor()) { delegate_->SetCursor(state_on_unlock_->cursor(), this); } if (IsMouseEventsEnabled() != state_on_unlock_->mouse_events_enabled()) { delegate_->SetMouseEventsEnabled(state_on_unlock_->mouse_events_enabled(), this); } if (IsCursorVisible() != state_on_unlock_->visible()) { delegate_->SetVisibility(state_on_unlock_->visible(), this); } } bool CursorManager::IsCursorLocked() const { return cursor_lock_count_ > 0; } void CursorManager::AddObserver( aura::client::CursorClientObserver* observer) { observers_.AddObserver(observer); } void CursorManager::RemoveObserver( aura::client::CursorClientObserver* observer) { observers_.RemoveObserver(observer); } bool CursorManager::ShouldHideCursorOnKeyEvent( const ui::KeyEvent& event) const { return false; } bool CursorManager::ShouldHideCursorOnTouchEvent( const ui::TouchEvent& event) const { #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS) return true; #else // Linux Aura does not hide the cursor on touch by default. // TODO(tdanderson): Change this if having consistency across // all platforms which use Aura is desired. return false; #endif } void CursorManager::CommitCursor(gfx::NativeCursor cursor) { current_state_->set_cursor(cursor); } void CursorManager::CommitVisibility(bool visible) { // TODO(tdanderson): Find a better place for this so we don't // notify the observers more than is necessary. for (auto& observer : observers_) { observer.OnCursorVisibilityChanged( GetCursor().type() == ui::mojom::CursorType::kNone ? false : visible); } current_state_->SetVisible(visible); } void CursorManager::CommitCursorSize(ui::CursorSize cursor_size) { current_state_->set_cursor_size(cursor_size); } void CursorManager::CommitMouseEventsEnabled(bool enabled) { current_state_->SetMouseEventsEnabled(enabled); } gfx::Size CursorManager::GetSystemCursorSize() const { return current_state_->system_cursor_size(); } void CursorManager::CommitSystemCursorSize( const gfx::Size& system_cursor_size) { current_state_->set_system_cursor_size(system_cursor_size); for (auto& observer : observers_) { observer.OnSystemCursorSizeChanged(system_cursor_size); } } void CursorManager::SetCursorImpl(gfx::NativeCursor cursor, bool forced) { bool previously_visible = GetCursor().type() != ui::mojom::CursorType::kNone; state_on_unlock_->set_cursor(cursor); if (cursor_lock_count_ == 0 && (forced || GetCursor() != state_on_unlock_->cursor())) { delegate_->SetCursor(state_on_unlock_->cursor(), this); bool is_visible = cursor.type() != ui::mojom::CursorType::kNone; if (is_visible != previously_visible) { for (auto& observer : observers_) observer.OnCursorVisibilityChanged(is_visible); } } } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_manager.cc
C++
unknown
9,033
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_CURSOR_MANAGER_H_ #define UI_WM_CORE_CURSOR_MANAGER_H_ #include <memory> #include "base/component_export.h" #include "base/observer_list.h" #include "ui/aura/client/cursor_client.h" #include "ui/display/display.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/native_widget_types.h" #include "ui/wm/core/native_cursor_manager_delegate.h" namespace ui { class KeyEvent; class TouchEvent; enum class CursorSize; } namespace wm { namespace internal { class CursorState; } class NativeCursorManager; // This class receives requests to change cursor properties, as well as // requests to queue any further changes until a later time. It sends changes // to the NativeCursorManager, which communicates back to us when these changes // were made through the NativeCursorManagerDelegate interface. class COMPONENT_EXPORT(UI_WM) CursorManager : public aura::client::CursorClient, public NativeCursorManagerDelegate { public: explicit CursorManager(std::unique_ptr<NativeCursorManager> delegate); CursorManager(const CursorManager&) = delete; CursorManager& operator=(const CursorManager&) = delete; ~CursorManager() override; // Resets the last visibility state, etc. Currently only called by tests. static void ResetCursorVisibilityStateForTest(); // Overridden from aura::client::CursorClient: void SetCursor(gfx::NativeCursor) override; gfx::NativeCursor GetCursor() const override; void SetCursorForced(gfx::NativeCursor) override; void ShowCursor() override; void HideCursor() override; bool IsCursorVisible() const override; void SetCursorSize(ui::CursorSize cursor_size) override; ui::CursorSize GetCursorSize() const override; void EnableMouseEvents() override; void DisableMouseEvents() override; bool IsMouseEventsEnabled() const override; void SetDisplay(const display::Display& display) override; const display::Display& GetDisplay() const override; void LockCursor() override; void UnlockCursor() override; bool IsCursorLocked() const override; void AddObserver(aura::client::CursorClientObserver* observer) override; void RemoveObserver(aura::client::CursorClientObserver* observer) override; bool ShouldHideCursorOnKeyEvent(const ui::KeyEvent& event) const override; bool ShouldHideCursorOnTouchEvent(const ui::TouchEvent& event) const override; gfx::Size GetSystemCursorSize() const override; private: // Overridden from NativeCursorManagerDelegate: void CommitCursor(gfx::NativeCursor cursor) override; void CommitVisibility(bool visible) override; void CommitCursorSize(ui::CursorSize cursor_size) override; void CommitMouseEventsEnabled(bool enabled) override; void CommitSystemCursorSize(const gfx::Size& cursor_size) override; void SetCursorImpl(gfx::NativeCursor cursor, bool forced); std::unique_ptr<NativeCursorManager> delegate_; // Display where the cursor is located. display::Display display_; // Number of times LockCursor() has been invoked without a corresponding // UnlockCursor(). int cursor_lock_count_; // The current state of the cursor. std::unique_ptr<internal::CursorState> current_state_; // The cursor state to restore when the cursor is unlocked. std::unique_ptr<internal::CursorState> state_on_unlock_; base::ObserverList<aura::client::CursorClientObserver>::Unchecked observers_; // This flag holds the cursor visibility state for the duration of the // process. Defaults to true. This flag helps ensure that when a // CursorManager instance is created it gets populated with the correct // cursor visibility state. static bool last_cursor_visibility_state_; }; } // namespace wm #endif // UI_WM_CORE_CURSOR_MANAGER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_manager.h
C++
unknown
3,861
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/cursor_manager.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "ui/aura/client/cursor_client_observer.h" #include "ui/aura/test/aura_test_base.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/wm/core/native_cursor_manager.h" #include "ui/wm/test/testing_cursor_client_observer.h" namespace { class TestingCursorManager : public wm::NativeCursorManager { public: // Overridden from wm::NativeCursorManager: void SetDisplay(const display::Display& display, wm::NativeCursorManagerDelegate* delegate) override {} void SetCursor(gfx::NativeCursor cursor, wm::NativeCursorManagerDelegate* delegate) override { delegate->CommitCursor(cursor); } void SetVisibility(bool visible, wm::NativeCursorManagerDelegate* delegate) override { delegate->CommitVisibility(visible); } void SetMouseEventsEnabled( bool enabled, wm::NativeCursorManagerDelegate* delegate) override { delegate->CommitMouseEventsEnabled(enabled); } void SetCursorSize(ui::CursorSize cursor_size, wm::NativeCursorManagerDelegate* delegate) override { delegate->CommitCursorSize(cursor_size); } }; } // namespace class CursorManagerTest : public aura::test::AuraTestBase { protected: CursorManagerTest() : delegate_(new TestingCursorManager), cursor_manager_(base::WrapUnique(delegate_.get())) {} raw_ptr<TestingCursorManager> delegate_; wm::CursorManager cursor_manager_; }; TEST_F(CursorManagerTest, ShowHideCursor) { cursor_manager_.SetCursor(ui::mojom::CursorType::kCopy); EXPECT_EQ(ui::mojom::CursorType::kCopy, cursor_manager_.GetCursor().type()); cursor_manager_.ShowCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); cursor_manager_.HideCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); // The current cursor does not change even when the cursor is not shown. EXPECT_EQ(ui::mojom::CursorType::kCopy, cursor_manager_.GetCursor().type()); // Check if cursor visibility is locked. cursor_manager_.LockCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); cursor_manager_.ShowCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); cursor_manager_.LockCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); cursor_manager_.HideCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); cursor_manager_.UnlockCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); // Checks setting visiblity while cursor is locked does not affect the // subsequent uses of UnlockCursor. cursor_manager_.LockCursor(); cursor_manager_.HideCursor(); cursor_manager_.UnlockCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); cursor_manager_.ShowCursor(); cursor_manager_.LockCursor(); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); cursor_manager_.LockCursor(); cursor_manager_.ShowCursor(); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); cursor_manager_.HideCursor(); cursor_manager_.LockCursor(); cursor_manager_.UnlockCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); } // Verifies that LockCursor/UnlockCursor work correctly with // EnableMouseEvents and DisableMouseEvents TEST_F(CursorManagerTest, EnableDisableMouseEvents) { cursor_manager_.SetCursor(ui::mojom::CursorType::kCopy); EXPECT_EQ(ui::mojom::CursorType::kCopy, cursor_manager_.GetCursor().type()); cursor_manager_.EnableMouseEvents(); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.DisableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); // The current cursor does not change even when the cursor is not shown. EXPECT_EQ(ui::mojom::CursorType::kCopy, cursor_manager_.GetCursor().type()); // Check if cursor enable state is locked. cursor_manager_.LockCursor(); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.EnableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.LockCursor(); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.DisableMouseEvents(); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.UnlockCursor(); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); // Checks enabling cursor while cursor is locked does not affect the // subsequent uses of UnlockCursor. cursor_manager_.LockCursor(); cursor_manager_.DisableMouseEvents(); cursor_manager_.UnlockCursor(); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.EnableMouseEvents(); cursor_manager_.LockCursor(); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.LockCursor(); cursor_manager_.EnableMouseEvents(); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.DisableMouseEvents(); cursor_manager_.LockCursor(); cursor_manager_.UnlockCursor(); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); } TEST_F(CursorManagerTest, SetCursorSize) { wm::TestingCursorClientObserver observer; cursor_manager_.AddObserver(&observer); EXPECT_EQ(ui::CursorSize::kNormal, cursor_manager_.GetCursorSize()); EXPECT_EQ(ui::CursorSize::kNormal, observer.cursor_size()); cursor_manager_.SetCursorSize(ui::CursorSize::kNormal); EXPECT_EQ(ui::CursorSize::kNormal, cursor_manager_.GetCursorSize()); EXPECT_EQ(ui::CursorSize::kNormal, observer.cursor_size()); cursor_manager_.SetCursorSize(ui::CursorSize::kLarge); EXPECT_EQ(ui::CursorSize::kLarge, cursor_manager_.GetCursorSize()); EXPECT_EQ(ui::CursorSize::kLarge, observer.cursor_size()); cursor_manager_.SetCursorSize(ui::CursorSize::kNormal); EXPECT_EQ(ui::CursorSize::kNormal, cursor_manager_.GetCursorSize()); EXPECT_EQ(ui::CursorSize::kNormal, observer.cursor_size()); } TEST_F(CursorManagerTest, IsMouseEventsEnabled) { cursor_manager_.EnableMouseEvents(); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.DisableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); } // Verifies that the mouse events enable state changes correctly when // ShowCursor/HideCursor and EnableMouseEvents/DisableMouseEvents are used // together. TEST_F(CursorManagerTest, ShowAndEnable) { // Changing the visibility of the cursor does not affect the enable state. cursor_manager_.EnableMouseEvents(); cursor_manager_.ShowCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.HideCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.ShowCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); // When mouse events are disabled, it also gets invisible. EXPECT_TRUE(cursor_manager_.IsCursorVisible()); cursor_manager_.DisableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); // When mouse events are enabled, it restores the visibility state. cursor_manager_.EnableMouseEvents(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.ShowCursor(); cursor_manager_.DisableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.EnableMouseEvents(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.HideCursor(); cursor_manager_.DisableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.EnableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); // When mouse events are disabled, ShowCursor is ignored. cursor_manager_.DisableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.ShowCursor(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); cursor_manager_.DisableMouseEvents(); EXPECT_FALSE(cursor_manager_.IsCursorVisible()); EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); } // Verifies that calling DisableMouseEvents multiple times in a row makes no // difference compared with calling it once. // This is a regression test for http://crbug.com/169404. TEST_F(CursorManagerTest, MultipleDisableMouseEvents) { cursor_manager_.DisableMouseEvents(); cursor_manager_.DisableMouseEvents(); cursor_manager_.EnableMouseEvents(); cursor_manager_.LockCursor(); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); } // Verifies that calling EnableMouseEvents multiple times in a row makes no // difference compared with calling it once. TEST_F(CursorManagerTest, MultipleEnableMouseEvents) { cursor_manager_.DisableMouseEvents(); cursor_manager_.EnableMouseEvents(); cursor_manager_.EnableMouseEvents(); cursor_manager_.LockCursor(); cursor_manager_.UnlockCursor(); EXPECT_TRUE(cursor_manager_.IsCursorVisible()); } TEST_F(CursorManagerTest, TestCursorClientObserver) { cursor_manager_.SetCursor(ui::mojom::CursorType::kPointer); // Add two observers. Both should have OnCursorVisibilityChanged() // invoked when the visibility of the cursor changes. wm::TestingCursorClientObserver observer_a; wm::TestingCursorClientObserver observer_b; cursor_manager_.AddObserver(&observer_a); cursor_manager_.AddObserver(&observer_b); // Initial state before any events have been sent. observer_a.reset(); observer_b.reset(); EXPECT_FALSE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_b.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); EXPECT_FALSE(observer_b.is_cursor_visible()); EXPECT_FALSE(observer_a.did_cursor_size_change()); EXPECT_FALSE(observer_b.did_cursor_size_change()); // Hide the cursor using HideCursor(). cursor_manager_.HideCursor(); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_TRUE(observer_b.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); EXPECT_FALSE(observer_b.is_cursor_visible()); // Set the cursor size. cursor_manager_.SetCursorSize(ui::CursorSize::kLarge); EXPECT_TRUE(observer_a.did_cursor_size_change()); EXPECT_EQ(ui::CursorSize::kLarge, observer_a.cursor_size()); EXPECT_TRUE(observer_b.did_cursor_size_change()); EXPECT_EQ(ui::CursorSize::kLarge, observer_b.cursor_size()); // Show the cursor using ShowCursor(). observer_a.reset(); observer_b.reset(); cursor_manager_.ShowCursor(); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_TRUE(observer_b.did_visibility_change()); EXPECT_TRUE(observer_a.is_cursor_visible()); EXPECT_TRUE(observer_b.is_cursor_visible()); // Remove observer_b. Its OnCursorVisibilityChanged() should // not be invoked past this point. cursor_manager_.RemoveObserver(&observer_b); // Hide the cursor using HideCursor(). observer_a.reset(); observer_b.reset(); cursor_manager_.HideCursor(); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_b.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); // Set back the cursor set to normal. cursor_manager_.SetCursorSize(ui::CursorSize::kNormal); EXPECT_TRUE(observer_a.did_cursor_size_change()); EXPECT_EQ(ui::CursorSize::kNormal, observer_a.cursor_size()); EXPECT_FALSE(observer_b.did_cursor_size_change()); // Show the cursor using ShowCursor(). observer_a.reset(); observer_b.reset(); cursor_manager_.ShowCursor(); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_b.did_visibility_change()); EXPECT_TRUE(observer_a.is_cursor_visible()); // Hide the cursor by changing the cursor type. cursor_manager_.SetCursor(ui::mojom::CursorType::kPointer); observer_a.reset(); cursor_manager_.SetCursor(ui::mojom::CursorType::kNone); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); // Show the cursor by changing the cursor type. observer_a.reset(); cursor_manager_.SetCursor(ui::mojom::CursorType::kPointer); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_TRUE(observer_a.is_cursor_visible()); // Changing the type to another visible type doesn't cause unnecessary // callbacks. observer_a.reset(); cursor_manager_.SetCursor(ui::mojom::CursorType::kHand); EXPECT_FALSE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); // If the type is kNone, showing the cursor shouldn't cause observers to // think that the cursor is now visible. cursor_manager_.HideCursor(); cursor_manager_.SetCursor(ui::mojom::CursorType::kNone); observer_a.reset(); cursor_manager_.ShowCursor(); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); } // This test validates that the cursor visiblity state is restored when a // CursorManager instance is destroyed and recreated. TEST(CursorManagerCreateDestroyTest, VisibilityTest) { // This block ensures that the cursor is hidden when the CursorManager // instance is destroyed. { wm::CursorManager cursor_manager1( base::WrapUnique(new TestingCursorManager)); cursor_manager1.ShowCursor(); EXPECT_TRUE(cursor_manager1.IsCursorVisible()); cursor_manager1.HideCursor(); EXPECT_FALSE(cursor_manager1.IsCursorVisible()); } // This block validates that the cursor is hidden initially. It ensures that // the cursor is visible when the CursorManager instance is destroyed. { wm::CursorManager cursor_manager2( base::WrapUnique(new TestingCursorManager)); EXPECT_FALSE(cursor_manager2.IsCursorVisible()); cursor_manager2.ShowCursor(); EXPECT_TRUE(cursor_manager2.IsCursorVisible()); } // This block validates that the cursor is visible initially. It then // performs normal cursor visibility operations. { wm::CursorManager cursor_manager3( base::WrapUnique(new TestingCursorManager)); EXPECT_TRUE(cursor_manager3.IsCursorVisible()); cursor_manager3.HideCursor(); EXPECT_FALSE(cursor_manager3.IsCursorVisible()); } }
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_manager_unittest.cc
C++
unknown
14,978
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/cursor_util.h" #include "base/check_op.h" #include "base/notreached.h" #include "base/ranges/algorithm.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/gfx/skbitmap_operations.h" #include "ui/resources/grit/ui_resources.h" namespace wm { namespace { using ::ui::mojom::CursorType; // Converts the SkBitmap to use a different alpha type. Returns true if bitmap // was modified, otherwise returns false. bool ConvertSkBitmapAlphaType(SkBitmap* bitmap, SkAlphaType alpha_type) { if (bitmap->info().alphaType() == alpha_type) { return false; } // Copy the bitmap into a temporary buffer. This will convert alpha type. SkImageInfo image_info = SkImageInfo::MakeN32(bitmap->width(), bitmap->height(), alpha_type); size_t info_row_bytes = image_info.minRowBytes(); std::vector<char> buffer(image_info.computeByteSize(info_row_bytes)); bitmap->readPixels(image_info, &buffer[0], info_row_bytes, 0, 0); // Read the temporary buffer back into the original bitmap. bitmap->reset(); bitmap->allocPixels(image_info); // this memcpy call assumes bitmap->rowBytes() == info_row_bytes memcpy(bitmap->getPixels(), &buffer[0], buffer.size()); return true; } struct CursorResourceData { CursorType type; int id; gfx::Point hotspot_1x; gfx::Point hotspot_2x; }; // Cursor resource data indexed by CursorType. Make sure to respect the order // defined at ui/base/cursor/mojom/cursor_type.mojom. constexpr absl::optional<CursorResourceData> kNormalCursorResourceData[] = { {{CursorType::kPointer, IDR_AURA_CURSOR_PTR, {4, 4}, {7, 7}}}, {{CursorType::kCross, IDR_AURA_CURSOR_CROSSHAIR, {12, 12}, {24, 24}}}, {{CursorType::kHand, IDR_AURA_CURSOR_HAND, {9, 4}, {19, 8}}}, {{CursorType::kIBeam, IDR_AURA_CURSOR_IBEAM, {12, 12}, {24, 25}}}, {{CursorType::kWait, IDR_AURA_CURSOR_THROBBER, {7, 7}, {14, 14}}}, {{CursorType::kHelp, IDR_AURA_CURSOR_HELP, {4, 4}, {8, 9}}}, {{CursorType::kEastResize, IDR_AURA_CURSOR_EAST_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kNorthResize, IDR_AURA_CURSOR_NORTH_RESIZE, {11, 12}, {23, 23}}}, {{CursorType::kNorthEastResize, IDR_AURA_CURSOR_NORTH_EAST_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kNorthWestResize, IDR_AURA_CURSOR_NORTH_WEST_RESIZE, {11, 11}, {24, 23}}}, {{CursorType::kSouthResize, IDR_AURA_CURSOR_SOUTH_RESIZE, {11, 12}, {23, 23}}}, {{CursorType::kSouthEastResize, IDR_AURA_CURSOR_SOUTH_EAST_RESIZE, {11, 11}, {24, 23}}}, {{CursorType::kSouthWestResize, IDR_AURA_CURSOR_SOUTH_WEST_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kWestResize, IDR_AURA_CURSOR_WEST_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kNorthSouthResize, IDR_AURA_CURSOR_NORTH_SOUTH_RESIZE, {11, 12}, {23, 23}}}, {{CursorType::kEastWestResize, IDR_AURA_CURSOR_EAST_WEST_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kNorthEastSouthWestResize, IDR_AURA_CURSOR_NORTH_EAST_SOUTH_WEST_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kNorthWestSouthEastResize, IDR_AURA_CURSOR_NORTH_WEST_SOUTH_EAST_RESIZE, {11, 11}, {24, 23}}}, {{CursorType::kColumnResize, IDR_AURA_CURSOR_COL_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kRowResize, IDR_AURA_CURSOR_ROW_RESIZE, {11, 12}, {23, 23}}}, /*CursorType::kMiddlePanning*/ {}, /*CursorType::kEastPanning*/ {}, /*CursorType::kNorthPanning*/ {}, /*CursorType::kNorthEastPanning*/ {}, /*CursorType::kNorthWestPanning*/ {}, /*CursorType::kSouthPanning*/ {}, /*CursorType::kSouthEastPanning*/ {}, /*CursorType::kSouthWestPanning*/ {}, /*CursorType::kWestPanning*/ {}, {{CursorType::kMove, IDR_AURA_CURSOR_MOVE, {11, 11}, {23, 23}}}, {{CursorType::kVerticalText, IDR_AURA_CURSOR_XTERM_HORIZ, {12, 11}, {26, 23}}}, {{CursorType::kCell, IDR_AURA_CURSOR_CELL, {11, 11}, {24, 23}}}, {{CursorType::kContextMenu, IDR_AURA_CURSOR_CONTEXT_MENU, {4, 4}, {8, 9}}}, {{CursorType::kAlias, IDR_AURA_CURSOR_ALIAS, {8, 6}, {15, 11}}}, {{CursorType::kProgress, IDR_AURA_CURSOR_THROBBER, {7, 7}, {14, 14}}}, {{CursorType::kNoDrop, IDR_AURA_CURSOR_NO_DROP, {9, 9}, {18, 18}}}, {{CursorType::kCopy, IDR_AURA_CURSOR_COPY, {9, 9}, {18, 18}}}, /*CursorType::kNone*/ {}, {{CursorType::kNotAllowed, IDR_AURA_CURSOR_NO_DROP, {9, 9}, {18, 18}}}, {{CursorType::kZoomIn, IDR_AURA_CURSOR_ZOOM_IN, {10, 10}, {20, 20}}}, {{CursorType::kZoomOut, IDR_AURA_CURSOR_ZOOM_OUT, {10, 10}, {20, 20}}}, {{CursorType::kGrab, IDR_AURA_CURSOR_GRAB, {8, 5}, {16, 10}}}, {{CursorType::kGrabbing, IDR_AURA_CURSOR_GRABBING, {9, 9}, {18, 18}}}, /*CursorType::kMiddlePanningVertical*/ {}, /*CursorType::kMiddlePanningHorizontal*/ {}, /*CursorType::kCustom*/ {}, /*CursorType::kDndNone*/ {}, /*CursorType::kDndMove*/ {}, /*CursorType::kDndCopy*/ {}, /*CursorType::kDndLink*/ {}, {{CursorType::kEastWestNoResize, IDR_AURA_CURSOR_EAST_WEST_NO_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kNorthSouthNoResize, IDR_AURA_CURSOR_NORTH_SOUTH_NO_RESIZE, {11, 12}, {23, 23}}}, {{CursorType::kNorthEastSouthWestNoResize, IDR_AURA_CURSOR_NORTH_EAST_SOUTH_WEST_NO_RESIZE, {12, 11}, {25, 23}}}, {{CursorType::kNorthWestSouthEastNoResize, IDR_AURA_CURSOR_NORTH_WEST_SOUTH_EAST_NO_RESIZE, {11, 11}, {24, 23}}}, }; static_assert(std::size(kNormalCursorResourceData) == static_cast<int>(CursorType::kMaxValue) + 1); constexpr absl::optional<CursorResourceData> kLargeCursorResourceData[] = { {{CursorType::kPointer, IDR_AURA_CURSOR_BIG_PTR, {10, 10}, {20, 20}}}, {{CursorType::kCross, IDR_AURA_CURSOR_BIG_CROSSHAIR, {30, 32}, {60, 64}}}, {{CursorType::kHand, IDR_AURA_CURSOR_BIG_HAND, {25, 7}, {50, 14}}}, {{CursorType::kIBeam, IDR_AURA_CURSOR_BIG_IBEAM, {30, 32}, {60, 64}}}, {{CursorType::kWait, // TODO(https://crbug.com/336867): create IDR_AURA_CURSOR_BIG_THROBBER. IDR_AURA_CURSOR_THROBBER, {7, 7}, {14, 14}}}, {{CursorType::kHelp, IDR_AURA_CURSOR_BIG_HELP, {10, 11}, {20, 22}}}, {{CursorType::kEastResize, IDR_AURA_CURSOR_BIG_EAST_RESIZE, {35, 29}, {70, 58}}}, {{CursorType::kNorthResize, IDR_AURA_CURSOR_BIG_NORTH_RESIZE, {29, 32}, {58, 64}}}, {{CursorType::kNorthEastResize, IDR_AURA_CURSOR_BIG_NORTH_EAST_RESIZE, {31, 28}, {62, 56}}}, {{CursorType::kNorthWestResize, IDR_AURA_CURSOR_BIG_NORTH_WEST_RESIZE, {28, 28}, {56, 56}}}, {{CursorType::kSouthResize, IDR_AURA_CURSOR_BIG_SOUTH_RESIZE, {29, 32}, {58, 64}}}, {{CursorType::kSouthEastResize, IDR_AURA_CURSOR_BIG_SOUTH_EAST_RESIZE, {28, 28}, {56, 56}}}, {{CursorType::kSouthWestResize, IDR_AURA_CURSOR_BIG_SOUTH_WEST_RESIZE, {31, 28}, {62, 56}}}, {{CursorType::kWestResize, IDR_AURA_CURSOR_BIG_WEST_RESIZE, {35, 29}, {70, 58}}}, {{CursorType::kNorthSouthResize, IDR_AURA_CURSOR_BIG_NORTH_SOUTH_RESIZE, {29, 32}, {58, 64}}}, {{CursorType::kEastWestResize, IDR_AURA_CURSOR_BIG_EAST_WEST_RESIZE, {35, 29}, {70, 58}}}, {{CursorType::kNorthEastSouthWestResize, IDR_AURA_CURSOR_BIG_NORTH_EAST_SOUTH_WEST_RESIZE, {32, 30}, {64, 60}}}, {{CursorType::kNorthWestSouthEastResize, IDR_AURA_CURSOR_BIG_NORTH_WEST_SOUTH_EAST_RESIZE, {32, 31}, {64, 62}}}, {{CursorType::kColumnResize, IDR_AURA_CURSOR_BIG_COL_RESIZE, {35, 29}, {70, 58}}}, {{CursorType::kRowResize, IDR_AURA_CURSOR_BIG_ROW_RESIZE, {29, 32}, {58, 64}}}, /*CursorType::kMiddlePanning*/ {}, /*CursorType::kEastPanning*/ {}, /*CursorType::kNorthPanning*/ {}, /*CursorType::kNorthEastPanning*/ {}, /*CursorType::kNorthWestPanning*/ {}, /*CursorType::kSouthPanning*/ {}, /*CursorType::kSouthEastPanning*/ {}, /*CursorType::kSouthWestPanning*/ {}, /*CursorType::kWestPanning*/ {}, {{CursorType::kMove, IDR_AURA_CURSOR_BIG_MOVE, {32, 31}, {64, 62}}}, {{CursorType::kVerticalText, IDR_AURA_CURSOR_BIG_XTERM_HORIZ, {32, 30}, {64, 60}}}, {{CursorType::kCell, IDR_AURA_CURSOR_BIG_CELL, {30, 30}, {60, 60}}}, {{CursorType::kContextMenu, IDR_AURA_CURSOR_BIG_CONTEXT_MENU, {11, 11}, {22, 22}}}, {{CursorType::kAlias, IDR_AURA_CURSOR_BIG_ALIAS, {19, 11}, {38, 22}}}, {{CursorType::kProgress, // TODO(https://crbug.com/336867): create IDR_AURA_CURSOR_BIG_THROBBER. IDR_AURA_CURSOR_THROBBER, {7, 7}, {14, 14}}}, {{CursorType::kNoDrop, IDR_AURA_CURSOR_BIG_NO_DROP, {10, 10}, {20, 20}}}, {{CursorType::kCopy, IDR_AURA_CURSOR_BIG_COPY, {21, 11}, {42, 22}}}, /*CursorType::kNone*/ {}, {{CursorType::kNotAllowed, IDR_AURA_CURSOR_BIG_NO_DROP, {10, 10}, {20, 20}}}, {{CursorType::kZoomIn, IDR_AURA_CURSOR_BIG_ZOOM_IN, {25, 26}, {50, 52}}}, {{CursorType::kZoomOut, IDR_AURA_CURSOR_BIG_ZOOM_OUT, {26, 26}, {52, 52}}}, {{CursorType::kGrab, IDR_AURA_CURSOR_BIG_GRAB, {21, 11}, {42, 22}}}, {{CursorType::kGrabbing, IDR_AURA_CURSOR_BIG_GRABBING, {20, 12}, {40, 24}}}, /*CursorType::kMiddlePanningVertical*/ {}, /*CursorType::kMiddlePanningHorizontal*/ {}, /*CursorType::kCustom*/ {}, /*CursorType::kDndNone*/ {}, /*CursorType::kDndMove*/ {}, /*CursorType::kDndCopy*/ {}, /*CursorType::kDndLink*/ {}, {{CursorType::kEastWestNoResize, IDR_AURA_CURSOR_BIG_EAST_WEST_NO_RESIZE, {35, 29}, {70, 58}}}, {{CursorType::kNorthSouthNoResize, IDR_AURA_CURSOR_BIG_NORTH_SOUTH_NO_RESIZE, {29, 32}, {58, 64}}}, {{CursorType::kNorthEastSouthWestNoResize, IDR_AURA_CURSOR_BIG_NORTH_EAST_SOUTH_WEST_NO_RESIZE, {32, 30}, {64, 60}}}, {{CursorType::kNorthWestSouthEastNoResize, IDR_AURA_CURSOR_BIG_NORTH_WEST_SOUTH_EAST_NO_RESIZE, {32, 31}, {64, 62}}}, }; static_assert(std::size(kLargeCursorResourceData) == static_cast<int>(CursorType::kMaxValue) + 1); } // namespace absl::optional<ui::CursorData> GetCursorData( CursorType type, ui::CursorSize size, float scale, display::Display::Rotation rotation) { DCHECK_NE(type, CursorType::kNone); DCHECK_NE(type, CursorType::kCustom); int resource_id; gfx::Point hotspot; if (!GetCursorDataFor(size, type, scale, &resource_id, &hotspot)) { return absl::nullopt; } std::vector<SkBitmap> bitmaps; const gfx::ImageSkia* image = ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id); const float resource_scale = gfx::ImageSkia::MapToResourceScale(scale); const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(resource_scale); CHECK_EQ(image_rep.scale(), resource_scale); SkBitmap bitmap = image_rep.GetBitmap(); // The image is assumed to be a concatenation of animation frames from left // to right. Also, each frame is assumed to be square (width == height). const int frame_width = bitmap.height(); const int frame_height = frame_width; const int total_width = bitmap.width(); CHECK_EQ(total_width % frame_width, 0); const int frame_count = total_width / frame_width; CHECK_GT(frame_count, 0); if (frame_count == 1) { ScaleAndRotateCursorBitmapAndHotpoint(scale / image_rep.scale(), rotation, &bitmap, &hotspot); bitmaps.push_back(std::move(bitmap)); } else { // Animated cursor. bitmaps.resize(frame_count); for (int frame = 0; frame < frame_count; ++frame) { const int x_offset = frame_width * frame; SkBitmap cropped = SkBitmapOperations::CreateTiledBitmap( bitmap, x_offset, 0, frame_width, frame_height); ScaleAndRotateCursorBitmapAndHotpoint(scale / image_rep.scale(), rotation, &cropped, frame == 0 ? &hotspot : nullptr); bitmaps[frame] = std::move(cropped); } } return ui::CursorData(std::move(bitmaps), std::move(hotspot), scale); } void ScaleAndRotateCursorBitmapAndHotpoint(float scale, display::Display::Rotation rotation, SkBitmap* bitmap, gfx::Point* hotpoint) { // SkBitmapOperations::Rotate() needs the bitmap to have premultiplied alpha, // so convert bitmap alpha type if we are going to rotate. bool was_converted = false; if (rotation != display::Display::ROTATE_0 && bitmap->info().alphaType() == kUnpremul_SkAlphaType) { ConvertSkBitmapAlphaType(bitmap, kPremul_SkAlphaType); was_converted = true; } switch (rotation) { case display::Display::ROTATE_0: break; case display::Display::ROTATE_90: if (hotpoint) { hotpoint->SetPoint(bitmap->height() - hotpoint->y(), hotpoint->x()); } *bitmap = SkBitmapOperations::Rotate( *bitmap, SkBitmapOperations::ROTATION_90_CW); break; case display::Display::ROTATE_180: if (hotpoint) { hotpoint->SetPoint(bitmap->width() - hotpoint->x(), bitmap->height() - hotpoint->y()); } *bitmap = SkBitmapOperations::Rotate( *bitmap, SkBitmapOperations::ROTATION_180_CW); break; case display::Display::ROTATE_270: if (hotpoint) { hotpoint->SetPoint(hotpoint->y(), bitmap->width() - hotpoint->x()); } *bitmap = SkBitmapOperations::Rotate( *bitmap, SkBitmapOperations::ROTATION_270_CW); break; } if (was_converted) { ConvertSkBitmapAlphaType(bitmap, kUnpremul_SkAlphaType); } if (scale < FLT_EPSILON) { NOTREACHED() << "Scale must be larger than 0."; scale = 1.0f; } if (scale == 1.0f) return; gfx::Size scaled_size = gfx::ScaleToFlooredSize( gfx::Size(bitmap->width(), bitmap->height()), scale); // TODO(crbug.com/919866): skia::ImageOperations::Resize() doesn't support // unpremultiplied alpha bitmaps. SkBitmap scaled_bitmap; scaled_bitmap.setInfo( bitmap->info().makeWH(scaled_size.width(), scaled_size.height())); if (scaled_bitmap.tryAllocPixels()) { bitmap->pixmap().scalePixels( scaled_bitmap.pixmap(), {SkFilterMode::kLinear, SkMipmapMode::kNearest}); } *bitmap = scaled_bitmap; if (hotpoint) { *hotpoint = gfx::ScaleToFlooredPoint(*hotpoint, scale); } } bool GetCursorDataFor(ui::CursorSize cursor_size, CursorType type, float scale_factor, int* resource_id, gfx::Point* point) { DCHECK_NE(type, CursorType::kCustom); // TODO(https://crbug.com/1270302: temporary check until GetCursorDataFor is // replaced by GetCursorData, which is only used internally by CursorLoader. if (type == CursorType::kNone) { return false; } // TODO(htts://crbug.com/1190818): currently, kNull is treated as kPointer. CursorType t = type == CursorType::kNull ? CursorType::kPointer : type; absl::optional<CursorResourceData> resource = cursor_size == ui::CursorSize::kNormal ? kNormalCursorResourceData[static_cast<int>(t)] : kLargeCursorResourceData[static_cast<int>(t)]; if (!resource) { return false; } DCHECK_EQ(resource->type, t); *resource_id = resource->id; *point = resource->hotspot_1x; if (gfx::ImageSkia::MapToResourceScale(scale_factor) == 2.0f) { *point = resource->hotspot_2x; } return true; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_util.cc
C++
unknown
16,426
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_CURSOR_UTIL_H_ #define UI_WM_CORE_CURSOR_UTIL_H_ #include "base/component_export.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/display.h" class SkBitmap; namespace gfx { class Point; } namespace ui { enum class CursorSize; struct CursorData; } // namespace ui namespace wm { // Returns the cursor data corresponding to `type` and the rest of the // parameters. It will load the cursor resource and then scale the bitmap and // hotspot to match `scale`. COMPONENT_EXPORT(UI_WM) absl::optional<ui::CursorData> GetCursorData( ui::mojom::CursorType type, ui::CursorSize size, float scale, display::Display::Rotation rotation); // Scale and rotate the cursor's bitmap and hotpoint. // |bitmap_in_out| and |hotpoint_in_out| are used as // both input and output. COMPONENT_EXPORT(UI_WM) void ScaleAndRotateCursorBitmapAndHotpoint(float scale, display::Display::Rotation rotation, SkBitmap* bitmap_in_out, gfx::Point* hotpoint_in_out); // Returns data about the cursor `type`. The IDR will be placed in `resource_id` // and the hotspot in `point`. Returns false if resource data for `type` isn't // available. COMPONENT_EXPORT(UI_WM) bool GetCursorDataFor(ui::CursorSize cursor_size, ui::mojom::CursorType type, float scale_factor, int* resource_id, gfx::Point* point); } // namespace wm #endif // UI_WM_CORE_CURSOR_UTIL_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_util.h
C++
unknown
1,818
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/cursor_util.h" #include "base/numerics/safe_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/resource/resource_scale_factor.h" #include "ui/display/display.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/image/image_skia.h" namespace wm { namespace { using ::ui::mojom::CursorType; // Parameterized test for cursor bitmaps with premultiplied and unpremultiplied // alpha. class CursorUtilTest : public testing::TestWithParam<bool> { public: SkColor GetPixelColor() { return GetParam() ? SkColorSetARGB(128, 255, 0, 0) : SkColorSetARGB(128, 128, 0, 0); } SkImageInfo GetImageInfo() { return GetParam() ? SkImageInfo::MakeN32(10, 5, kUnpremul_SkAlphaType) : SkImageInfo::MakeN32(10, 5, kPremul_SkAlphaType); } }; TEST_P(CursorUtilTest, ScaleAndRotate) { const SkColor pixel_color = GetPixelColor(); SkBitmap bitmap; bitmap.setInfo(GetImageInfo()); bitmap.allocPixels(); bitmap.eraseColor(pixel_color); gfx::Point hotpoint(3, 4); ScaleAndRotateCursorBitmapAndHotpoint(1.0f, display::Display::ROTATE_0, &bitmap, &hotpoint); EXPECT_EQ(10, bitmap.width()); EXPECT_EQ(5, bitmap.height()); EXPECT_EQ("3,4", hotpoint.ToString()); EXPECT_EQ(pixel_color, bitmap.pixmap().getColor(0, 0)); ScaleAndRotateCursorBitmapAndHotpoint(1.0f, display::Display::ROTATE_90, &bitmap, &hotpoint); EXPECT_EQ(5, bitmap.width()); EXPECT_EQ(10, bitmap.height()); EXPECT_EQ("1,3", hotpoint.ToString()); EXPECT_EQ(pixel_color, bitmap.pixmap().getColor(0, 0)); ScaleAndRotateCursorBitmapAndHotpoint(2.0f, display::Display::ROTATE_180, &bitmap, &hotpoint); EXPECT_EQ(10, bitmap.width()); EXPECT_EQ(20, bitmap.height()); EXPECT_EQ("8,14", hotpoint.ToString()); EXPECT_EQ(pixel_color, bitmap.pixmap().getColor(0, 0)); ScaleAndRotateCursorBitmapAndHotpoint(1.0f, display::Display::ROTATE_270, &bitmap, &hotpoint); EXPECT_EQ(20, bitmap.width()); EXPECT_EQ(10, bitmap.height()); EXPECT_EQ("14,2", hotpoint.ToString()); EXPECT_EQ(pixel_color, bitmap.pixmap().getColor(0, 0)); } INSTANTIATE_TEST_SUITE_P(All, CursorUtilTest, testing::Bool()); TEST(CursorUtil, GetCursorData) { // Data from `kNormalCursorResourceData` and `kLargeCursorResourceData`. constexpr struct { CursorType cursor; gfx::Size size[2]; // indexed by cursor size. gfx::Point hotspot[2][2]; // indexed by cursor size and scale. } kTestCases[] = { {CursorType::kPointer, {gfx::Size(25, 25), gfx::Size(64, 64)}, {{gfx::Point(4, 4), gfx::Point(7, 7)}, {gfx::Point(10, 10), gfx::Point(20, 20)}}}, {CursorType::kWait, {gfx::Size(16, 16), gfx::Size(16, 16)}, {{gfx::Point(7, 7), gfx::Point(14, 14)}, {gfx::Point(7, 7), gfx::Point(14, 14)}}}, }; for (const float scale : {0.8f, 1.0f, 1.3f, 1.5f, 2.0f, 2.5f}) { SCOPED_TRACE(testing::Message() << "scale " << scale); for (const auto size : {ui::CursorSize::kNormal, ui::CursorSize::kLarge}) { SCOPED_TRACE(testing::Message() << "size " << base::checked_cast<int>(scale)); for (const auto& test : kTestCases) { SCOPED_TRACE(test.cursor); constexpr auto kDefaultRotation = display::Display::ROTATE_0; const auto pointer_data = GetCursorData(test.cursor, size, scale, kDefaultRotation); ASSERT_TRUE(pointer_data); ASSERT_GT(pointer_data->bitmaps.size(), 0u); EXPECT_EQ(gfx::SkISizeToSize(pointer_data->bitmaps[0].dimensions()), gfx::ScaleToFlooredSize( test.size[base::checked_cast<int>(size)], scale)); const float resource_scale = gfx::ImageSkia::MapToResourceScale(scale); EXPECT_EQ(pointer_data->hotspot, gfx::ScaleToFlooredPoint( test.hotspot[base::checked_cast<int>(size)] [base::checked_cast<int>(resource_scale) - 1], scale / resource_scale)); } } } } } // namespace } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/cursor_util_unittest.cc
C++
unknown
4,771
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/default_activation_client.h" #include "base/memory/raw_ptr.h" #include "base/observer_list.h" #include "ui/aura/window.h" #include "ui/wm/public/activation_change_observer.h" #include "ui/wm/public/activation_delegate.h" namespace wm { // Takes care of observing root window destruction & destroying the client. class DefaultActivationClient::Deleter : public aura::WindowObserver { public: Deleter(DefaultActivationClient* client, aura::Window* root_window) : client_(client), root_window_(root_window) { root_window_->AddObserver(this); } Deleter(const Deleter&) = delete; Deleter& operator=(const Deleter&) = delete; private: ~Deleter() override {} // Overridden from WindowObserver: void OnWindowDestroyed(aura::Window* window) override { DCHECK_EQ(window, root_window_); root_window_->RemoveObserver(this); delete client_; delete this; } raw_ptr<DefaultActivationClient, DanglingUntriaged> client_; raw_ptr<aura::Window> root_window_; }; //////////////////////////////////////////////////////////////////////////////// // DefaultActivationClient, public: DefaultActivationClient::DefaultActivationClient(aura::Window* root_window) : last_active_(nullptr) { SetActivationClient(root_window, this); new Deleter(this, root_window); } //////////////////////////////////////////////////////////////////////////////// // DefaultActivationClient, ActivationClient implementation: void DefaultActivationClient::AddObserver(ActivationChangeObserver* observer) { observers_.AddObserver(observer); } void DefaultActivationClient::RemoveObserver( ActivationChangeObserver* observer) { observers_.RemoveObserver(observer); } void DefaultActivationClient::ActivateWindow(aura::Window* window) { ActivateWindowImpl( ActivationChangeObserver::ActivationReason::ACTIVATION_CLIENT, window); } void DefaultActivationClient::ActivateWindowImpl( ActivationChangeObserver::ActivationReason reason, aura::Window* window) { aura::Window* last_active = ActivationClient::GetActiveWindow(); if (last_active == window) return; for (auto& observer : observers_) observer.OnWindowActivating(reason, window, last_active); last_active_ = last_active; if (window) { RemoveActiveWindow(window); active_windows_.push_back(window); window->parent()->StackChildAtTop(window); window->AddObserver(this); } else { ClearActiveWindows(); } for (auto& observer : observers_) observer.OnWindowActivated(reason, window, last_active); if (window) { ActivationChangeObserver* observer = GetActivationChangeObserver(last_active); if (observer) { observer->OnWindowActivated(reason, window, last_active); } observer = GetActivationChangeObserver(window); if (observer) { observer->OnWindowActivated(reason, window, last_active); } } } void DefaultActivationClient::DeactivateWindow(aura::Window* window) { ActivationChangeObserver* observer = GetActivationChangeObserver(window); if (observer) { observer->OnWindowActivated( ActivationChangeObserver::ActivationReason::ACTIVATION_CLIENT, nullptr, window); } if (last_active_) ActivateWindow(last_active_); } const aura::Window* DefaultActivationClient::GetActiveWindow() const { if (active_windows_.empty()) return nullptr; return active_windows_.back(); } aura::Window* DefaultActivationClient::GetActivatableWindow( aura::Window* window) const { return nullptr; } const aura::Window* DefaultActivationClient::GetToplevelWindow( const aura::Window* window) const { return nullptr; } bool DefaultActivationClient::CanActivateWindow( const aura::Window* window) const { return true; } //////////////////////////////////////////////////////////////////////////////// // DefaultActivationClient, aura::WindowObserver implementation: void DefaultActivationClient::OnWindowDestroyed(aura::Window* window) { if (window == last_active_) last_active_ = nullptr; if (window == GetActiveWindow()) { active_windows_.pop_back(); aura::Window* next_active = ActivationClient::GetActiveWindow(); if (next_active && GetActivationChangeObserver(next_active)) { GetActivationChangeObserver(next_active) ->OnWindowActivated(ActivationChangeObserver::ActivationReason:: WINDOW_DISPOSITION_CHANGED, next_active, nullptr); } return; } RemoveActiveWindow(window); } //////////////////////////////////////////////////////////////////////////////// // DefaultActivationClient, private: DefaultActivationClient::~DefaultActivationClient() { ClearActiveWindows(); } void DefaultActivationClient::RemoveActiveWindow(aura::Window* window) { for (unsigned int i = 0; i < active_windows_.size(); ++i) { if (active_windows_[i] == window) { active_windows_.erase(active_windows_.begin() + i); window->RemoveObserver(this); return; } } } void DefaultActivationClient::ClearActiveWindows() { for (aura::Window* window : active_windows_) window->RemoveObserver(this); active_windows_.clear(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/default_activation_client.cc
C++
unknown
5,378
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_DEFAULT_ACTIVATION_CLIENT_H_ #define UI_WM_CORE_DEFAULT_ACTIVATION_CLIENT_H_ #include <vector> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "base/observer_list.h" #include "ui/aura/window_observer.h" #include "ui/wm/public/activation_change_observer.h" #include "ui/wm/public/activation_client.h" namespace wm { class ActivationChangeObserver; // Simple ActivationClient implementation for use by tests and other targets // that just need basic behavior (e.g. activate windows whenever requested, // restack windows at the top when they're activated, etc.). This object deletes // itself when the root window it is associated with is destroyed. class COMPONENT_EXPORT(UI_WM) DefaultActivationClient : public ActivationClient, public aura::WindowObserver { public: explicit DefaultActivationClient(aura::Window* root_window); DefaultActivationClient(const DefaultActivationClient&) = delete; DefaultActivationClient& operator=(const DefaultActivationClient&) = delete; // Overridden from ActivationClient: void AddObserver(ActivationChangeObserver* observer) override; void RemoveObserver(ActivationChangeObserver* observer) override; void ActivateWindow(aura::Window* window) override; void DeactivateWindow(aura::Window* window) override; const aura::Window* GetActiveWindow() const override; aura::Window* GetActivatableWindow(aura::Window* window) const override; const aura::Window* GetToplevelWindow( const aura::Window* window) const override; bool CanActivateWindow(const aura::Window* window) const override; // Overridden from WindowObserver: void OnWindowDestroyed(aura::Window* window) override; private: class Deleter; ~DefaultActivationClient() override; void RemoveActiveWindow(aura::Window* window); void ActivateWindowImpl(ActivationChangeObserver::ActivationReason reason, aura::Window* window); void ClearActiveWindows(); // This class explicitly does NOT store the active window in a window property // to make sure that ActivationChangeObserver is not treated as part of the // aura API. Assumptions to that end will cause tests that use this client to // fail. std::vector<aura::Window*> active_windows_; // The window which was active before the currently active one. raw_ptr<aura::Window, DanglingUntriaged> last_active_; base::ObserverList<ActivationChangeObserver> observers_; }; } // namespace wm #endif // UI_WM_CORE_DEFAULT_ACTIVATION_CLIENT_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/default_activation_client.h
C++
unknown
2,685
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/default_screen_position_client.h" #include "ui/aura/window_tree_host.h" #include "ui/display/screen.h" #include "ui/gfx/geometry/point_conversions.h" #include "ui/gfx/geometry/rect.h" namespace wm { DefaultScreenPositionClient::DefaultScreenPositionClient( aura::Window* root_window) : root_window_(root_window) { DCHECK(root_window_); aura::client::SetScreenPositionClient(root_window_, this); } DefaultScreenPositionClient::~DefaultScreenPositionClient() { aura::client::SetScreenPositionClient(root_window_, nullptr); } void DefaultScreenPositionClient::ConvertPointToScreen( const aura::Window* window, gfx::PointF* point) { const aura::Window* root_window = window->GetRootWindow(); aura::Window::ConvertPointToTarget(window, root_window, point); gfx::Point origin = GetRootWindowOriginInScreen(root_window); point->Offset(origin.x(), origin.y()); } void DefaultScreenPositionClient::ConvertPointFromScreen( const aura::Window* window, gfx::PointF* point) { const aura::Window* root_window = window->GetRootWindow(); gfx::Point origin = GetRootWindowOriginInScreen(root_window); point->Offset(-origin.x(), -origin.y()); aura::Window::ConvertPointToTarget(root_window, window, point); } void DefaultScreenPositionClient::ConvertHostPointToScreen(aura::Window* window, gfx::Point* point) { aura::Window* root_window = window->GetRootWindow(); aura::client::ScreenPositionClient::ConvertPointToScreen(root_window, point); } void DefaultScreenPositionClient::SetBounds(aura::Window* window, const gfx::Rect& bounds, const display::Display& display) { window->SetBounds(bounds); } gfx::Point DefaultScreenPositionClient::GetRootWindowOriginInScreen( const aura::Window* root_window) { return root_window->GetHost()->GetBoundsInDIP().origin(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/default_screen_position_client.cc
C++
unknown
2,144
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_DEFAULT_SCREEN_POSITION_CLIENT_H_ #define UI_WM_CORE_DEFAULT_SCREEN_POSITION_CLIENT_H_ #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "ui/aura/client/screen_position_client.h" namespace wm { // Client that always offsets by the toplevel RootWindow of the passed // in child NativeWidgetAura. class COMPONENT_EXPORT(UI_WM) DefaultScreenPositionClient : public aura::client::ScreenPositionClient { public: explicit DefaultScreenPositionClient(aura::Window* root_window); DefaultScreenPositionClient(const DefaultScreenPositionClient&) = delete; DefaultScreenPositionClient& operator=(const DefaultScreenPositionClient&) = delete; ~DefaultScreenPositionClient() override; // aura::client::ScreenPositionClient overrides: void ConvertPointToScreen(const aura::Window* window, gfx::PointF* point) override; void ConvertPointFromScreen(const aura::Window* window, gfx::PointF* point) override; void ConvertHostPointToScreen(aura::Window* window, gfx::Point* point) override; void SetBounds(aura::Window* window, const gfx::Rect& bounds, const display::Display& display) override; protected: // aura::client::ScreenPositionClient: gfx::Point GetRootWindowOriginInScreen( const aura::Window* root_window) override; private: raw_ptr<aura::Window> root_window_; }; } // namespace wm #endif // UI_WM_CORE_DEFAULT_SCREEN_POSITION_CLIENT_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/default_screen_position_client.h
C++
unknown
1,700
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/easy_resize_window_targeter.h" #include <algorithm> #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/transient_window_client.h" #include "ui/aura/window.h" #include "ui/events/event.h" #include "ui/gfx/geometry/insets.h" namespace wm { EasyResizeWindowTargeter::EasyResizeWindowTargeter( const gfx::Insets& mouse_extend, const gfx::Insets& touch_extend) { SetInsets(mouse_extend, touch_extend); } EasyResizeWindowTargeter::~EasyResizeWindowTargeter() {} bool EasyResizeWindowTargeter::EventLocationInsideBounds( aura::Window* target, const ui::LocatedEvent& event) const { return WindowTargeter::EventLocationInsideBounds(target, event); } bool EasyResizeWindowTargeter::ShouldUseExtendedBounds( const aura::Window* w) const { DCHECK(window()); // Use the extended bounds only for immediate child windows of window(). // Use the default targeter otherwise. if (w->parent() != window()) return false; // Only resizable windows benefit from the extended hit-test region. if ((w->GetProperty(aura::client::kResizeBehaviorKey) & aura::client::kResizeBehaviorCanResize) == 0) { return false; } // For transient children use extended bounds if a transient parent or if // transient parent's parent is a top level window in window(). aura::client::TransientWindowClient* transient_window_client = aura::client::GetTransientWindowClient(); const aura::Window* transient_parent = transient_window_client ? transient_window_client->GetTransientParent(w) : nullptr; return !transient_parent || transient_parent == window() || transient_parent->parent() == window(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/easy_resize_window_targeter.cc
C++
unknown
1,884
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_EASY_RESIZE_WINDOW_TARGETER_H_ #define UI_WM_CORE_EASY_RESIZE_WINDOW_TARGETER_H_ #include "base/component_export.h" #include "ui/aura/window_targeter.h" namespace gfx { class Insets; } namespace wm { // An EventTargeter for a container window that uses a slightly larger // hit-target region for easier resize. It extends the hit test region for child // windows (top level Widgets that are resizable) to outside their bounds. For // Ash, this correlates to ash::kResizeOutsideBoundsSize. For the interior // resize area, see ash::InstallResizeHandleWindowTargeterForWindow(). class COMPONENT_EXPORT(UI_WM) EasyResizeWindowTargeter : public aura::WindowTargeter { public: // NOTE: the insets must be negative. EasyResizeWindowTargeter(const gfx::Insets& mouse_extend, const gfx::Insets& touch_extend); EasyResizeWindowTargeter(const EasyResizeWindowTargeter&) = delete; EasyResizeWindowTargeter& operator=(const EasyResizeWindowTargeter&) = delete; ~EasyResizeWindowTargeter() override; private: // aura::WindowTargeter: // Delegates to WindowTargeter's impl and prevents overriding in subclasses. bool EventLocationInsideBounds(aura::Window* target, const ui::LocatedEvent& event) const final; // Returns true if the hit testing (GetHitTestRects()) should use the // extended bounds. bool ShouldUseExtendedBounds(const aura::Window* w) const override; }; } // namespace wm #endif // UI_WM_CORE_EASY_RESIZE_WINDOW_TARGETER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/easy_resize_window_targeter.h
C++
unknown
1,689
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/focus_controller.h" #include "base/auto_reset.h" #include "base/observer_list.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/capture_client.h" #include "ui/aura/client/focus_change_observer.h" #include "ui/aura/env.h" #include "ui/aura/window_tracker.h" #include "ui/base/ui_base_features.h" #include "ui/events/event.h" #include "ui/wm/core/focus_rules.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/activation_change_observer.h" namespace wm { namespace { // When a modal window is activated, we bring its entire transient parent chain // to the front. This function must be called before the modal transient is // stacked at the top to ensure correct stacking order. void StackTransientParentsBelowModalWindow(aura::Window* window) { if (window->GetProperty(aura::client::kModalKey) != ui::MODAL_TYPE_WINDOW) return; aura::Window* transient_parent = wm::GetTransientParent(window); while (transient_parent) { transient_parent->parent()->StackChildAtTop(transient_parent); transient_parent = wm::GetTransientParent(transient_parent); } } } // namespace //////////////////////////////////////////////////////////////////////////////// // FocusController, public: FocusController::FocusController(FocusRules* rules) : rules_(rules), focus_follows_cursor_( base::FeatureList::IsEnabled(features::kFocusFollowsCursor)) { DCHECK(rules); } FocusController::~FocusController() = default; //////////////////////////////////////////////////////////////////////////////// // FocusController, ActivationClient implementation: void FocusController::AddObserver(ActivationChangeObserver* observer) { activation_observers_.AddObserver(observer); } void FocusController::RemoveObserver(ActivationChangeObserver* observer) { activation_observers_.RemoveObserver(observer); } void FocusController::ActivateWindow(aura::Window* window) { FocusWindow(window); } void FocusController::DeactivateWindow(aura::Window* window) { if (window) { // FocusController implements deactivation by way of activating another // window. Don't deactivate |window| if it's not active to avoid attempting // to activate another window. if (window != GetActiveWindow()) return; FocusWindow(rules_->GetNextActivatableWindow(window)); } } const aura::Window* FocusController::GetActiveWindow() const { return active_window_; } aura::Window* FocusController::GetActivatableWindow( aura::Window* window) const { return rules_->GetActivatableWindow(window); } const aura::Window* FocusController::GetToplevelWindow( const aura::Window* window) const { return rules_->GetToplevelWindow(window); } bool FocusController::CanActivateWindow(const aura::Window* window) const { return rules_->CanActivateWindow(window); } //////////////////////////////////////////////////////////////////////////////// // FocusController, aura::client::FocusClient implementation: void FocusController::AddObserver(aura::client::FocusChangeObserver* observer) { focus_observers_.AddObserver(observer); } void FocusController::RemoveObserver( aura::client::FocusChangeObserver* observer) { focus_observers_.RemoveObserver(observer); } void FocusController::FocusWindow(aura::Window* window) { FocusAndActivateWindow( ActivationChangeObserver::ActivationReason::ACTIVATION_CLIENT, window, /*no_stacking=*/false); } void FocusController::ResetFocusWithinActiveWindow(aura::Window* window) { DCHECK(window); if (!active_window_) return; if (!active_window_->Contains(window)) return; SetFocusedWindow(window); } aura::Window* FocusController::GetFocusedWindow() { return focused_window_; } //////////////////////////////////////////////////////////////////////////////// // FocusController, ui::EventHandler implementation: void FocusController::OnKeyEvent(ui::KeyEvent* event) {} void FocusController::OnMouseEvent(ui::MouseEvent* event) { if ((event->type() == ui::ET_MOUSE_PRESSED || (event->type() == ui::ET_MOUSE_ENTERED && focus_follows_cursor_)) && !event->handled()) WindowFocusedFromInputEvent(static_cast<aura::Window*>(event->target()), event); } void FocusController::OnScrollEvent(ui::ScrollEvent* event) {} void FocusController::OnTouchEvent(ui::TouchEvent* event) {} void FocusController::OnGestureEvent(ui::GestureEvent* event) { if (event->type() == ui::ET_GESTURE_BEGIN && event->details().touch_points() == 1 && !event->handled()) { WindowFocusedFromInputEvent(static_cast<aura::Window*>(event->target()), event); } } base::StringPiece FocusController::GetLogContext() const { return "FocusController"; } //////////////////////////////////////////////////////////////////////////////// // FocusController, aura::WindowObserver implementation: void FocusController::OnWindowVisibilityChanged(aura::Window* window, bool visible) { if (!visible) WindowLostFocusFromDispositionChange(window, window->parent()); } void FocusController::OnWindowDestroying(aura::Window* window) { // A window's modality state will interfere with focus restoration during its // destruction. window->ClearProperty(aura::client::kModalKey); WindowLostFocusFromDispositionChange(window, window->parent()); // We may have already stopped observing |window| if `SetActiveWindow()` was // called inside `WindowLostFocusFromDispositionChange()`. if (observation_manager_.IsObservingSource(window)) observation_manager_.RemoveObservation(window); } void FocusController::OnWindowHierarchyChanging( const HierarchyChangeParams& params) { if (params.receiver == active_window_ && params.target->Contains(params.receiver) && (!params.new_parent || aura::client::GetFocusClient(params.new_parent) != aura::client::GetFocusClient(params.receiver))) { WindowLostFocusFromDispositionChange(params.receiver, params.old_parent); } } void FocusController::OnWindowHierarchyChanged( const HierarchyChangeParams& params) { if (params.receiver == focused_window_ && params.target->Contains(params.receiver) && (!params.new_parent || aura::client::GetFocusClient(params.new_parent) != aura::client::GetFocusClient(params.receiver))) { WindowLostFocusFromDispositionChange(params.receiver, params.old_parent); } } //////////////////////////////////////////////////////////////////////////////// // FocusController, private: void FocusController::FocusAndActivateWindow( ActivationChangeObserver::ActivationReason reason, aura::Window* window, bool no_stacking) { if (window && (window->Contains(focused_window_) || window->Contains(active_window_))) { if (!no_stacking) { StackActiveWindow(); } return; } // Focusing a window also activates its containing activatable window. Note // that the rules could redirect activation and/or focus. aura::Window* focusable = rules_->GetFocusableWindow(window); aura::Window* activatable = focusable ? rules_->GetActivatableWindow(focusable) : nullptr; // We need valid focusable/activatable windows in the event we're not clearing // focus. "Clearing focus" is inferred by whether or not |window| passed to // this function is non-NULL. if (window && (!focusable || !activatable)) return; DCHECK((focusable && activatable) || !window); // Activation change observers may change the focused window. If this happens // we must not adjust the focus below since this will clobber that change. aura::Window* last_focused_window = focused_window_; if (!pending_activation_.has_value()) { aura::WindowTracker focusable_window_tracker; if (focusable) { focusable_window_tracker.Add(focusable); focusable = nullptr; } if (!SetActiveWindow(reason, window, activatable, no_stacking)) return; if (!focusable_window_tracker.windows().empty()) focusable = focusable_window_tracker.Pop(); } else { // Only allow the focused window to change, *not* the active window if // called reentrantly. DCHECK(!activatable || activatable == pending_activation_.value()); } // If the window's ActivationChangeObserver shifted focus to a valid window, // we don't want to focus the window we thought would be focused by default. if (!updating_focus_) { aura::Window* const new_active_window = pending_activation_.has_value() ? pending_activation_.value() : active_window_.get(); const bool activation_changed_focus = last_focused_window != focused_window_; if (!activation_changed_focus || !focused_window_) { if (new_active_window && focusable) DCHECK(new_active_window->Contains(focusable)); SetFocusedWindow(focusable); } if (new_active_window && focused_window_) DCHECK(new_active_window->Contains(focused_window_)); } } void FocusController::SetFocusedWindow(aura::Window* window) { if (updating_focus_ || window == focused_window_) return; DCHECK(rules_->CanFocusWindow(window, nullptr)); if (window) DCHECK_EQ(window, rules_->GetFocusableWindow(window)); base::AutoReset<bool> updating_focus(&updating_focus_, true); aura::Window* lost_focus = focused_window_; // Allow for the window losing focus to be deleted during dispatch. If it is // deleted pass NULL to observers instead of a deleted window. aura::WindowTracker window_tracker; if (lost_focus) window_tracker.Add(lost_focus); if (focused_window_ && observation_manager_.IsObservingSource(focused_window_.get()) && focused_window_ != active_window_) { observation_manager_.RemoveObservation(focused_window_.get()); } focused_window_ = window; if (focused_window_ && !observation_manager_.IsObservingSource(focused_window_.get())) observation_manager_.AddObservation(focused_window_.get()); for (auto& observer : focus_observers_) { observer.OnWindowFocused( focused_window_, window_tracker.Contains(lost_focus) ? lost_focus : nullptr); } if (window_tracker.Contains(lost_focus)) { aura::client::FocusChangeObserver* observer = aura::client::GetFocusChangeObserver(lost_focus); if (observer) observer->OnWindowFocused(focused_window_, lost_focus); } aura::client::FocusChangeObserver* observer = aura::client::GetFocusChangeObserver(focused_window_); if (observer) { observer->OnWindowFocused( focused_window_, window_tracker.Contains(lost_focus) ? lost_focus : nullptr); } } // Defines a macro that is meant to be called from SetActiveWindow(), which // checks whether the activation was interrupted by checking whether // |pending_activation_| has a value or not. In this case, it early-outs from // the SetActiveWindow() stack. // clang-format off #define MAYBE_ACTIVATION_INTERRUPTED() \ if (!pending_activation_) \ return false // clang-format on bool FocusController::SetActiveWindow( ActivationChangeObserver::ActivationReason reason, aura::Window* requested_window, aura::Window* window, bool no_stacking) { if (pending_activation_) return false; if (window == active_window_) { if (requested_window) { for (auto& observer : activation_observers_) observer.OnAttemptToReactivateWindow(requested_window, active_window_); } return true; } DCHECK(rules_->CanActivateWindow(window)); if (window) DCHECK_EQ(window, rules_->GetActivatableWindow(window)); base::AutoReset<absl::optional<aura::Window*>> updating_activation( &pending_activation_, absl::make_optional(window)); aura::Window* lost_activation = active_window_; // Allow for the window losing activation to be deleted during dispatch. If // it is deleted pass NULL to observers instead of a deleted window. aura::WindowTracker window_tracker; if (lost_activation) window_tracker.Add(lost_activation); // Start observing the window gaining activation at this point since it maybe // destroyed at an early stage, e.g. the activating phase. if (window && !observation_manager_.IsObservingSource(window)) observation_manager_.AddObservation(window); for (auto& observer : activation_observers_) { observer.OnWindowActivating(reason, window, active_window_); MAYBE_ACTIVATION_INTERRUPTED(); } if (active_window_ && observation_manager_.IsObservingSource(active_window_.get()) && focused_window_ != active_window_) { observation_manager_.RemoveObservation(active_window_.get()); } active_window_ = window; if (active_window_ && !no_stacking) StackActiveWindow(); MAYBE_ACTIVATION_INTERRUPTED(); ActivationChangeObserver* observer = nullptr; if (window_tracker.Contains(lost_activation)) { observer = GetActivationChangeObserver(lost_activation); if (observer) observer->OnWindowActivated(reason, active_window_, lost_activation); } MAYBE_ACTIVATION_INTERRUPTED(); observer = GetActivationChangeObserver(active_window_); if (observer) { observer->OnWindowActivated( reason, active_window_, window_tracker.Contains(lost_activation) ? lost_activation : nullptr); } MAYBE_ACTIVATION_INTERRUPTED(); for (auto& activation_observer : activation_observers_) { activation_observer.OnWindowActivated( reason, active_window_, window_tracker.Contains(lost_activation) ? lost_activation : nullptr); MAYBE_ACTIVATION_INTERRUPTED(); } return true; } void FocusController::StackActiveWindow() { if (active_window_) { StackTransientParentsBelowModalWindow(active_window_); active_window_->parent()->StackChildAtTop(active_window_); } } void FocusController::WindowLostFocusFromDispositionChange(aura::Window* window, aura::Window* next) { // TODO(beng): See if this function can be replaced by a call to // FocusWindow(). // Activation adjustments are handled first in the event of a disposition // changed. If an activation change is necessary, focus is reset as part of // that process so there's no point in updating focus independently. const bool is_active_window_losing_focus = window == active_window_; const bool is_pending_window_losing_focus = pending_activation_ && (window == pending_activation_.value()); if (is_active_window_losing_focus || is_pending_window_losing_focus) { if (pending_activation_) { // We're in the middle of an on-going activation. We need to determine // whether we need to abort this activation. This happens when the window // gaining activation is destroyed at any point of the activation process. if (is_pending_window_losing_focus) { // Abort this on-going activation. The below call to SetActiveWindow() // will attempt activating the next activatable window. pending_activation_.reset(); } else if (is_active_window_losing_focus) { // The window losing activation may have been destroyed before the // window gaining active is set as the active window. We need to clear // the active and focused windows temporarily, since querying the active // window now should not return a dangling pointer. active_window_ = nullptr; SetFocusedWindow(nullptr); // We should continue the on-going activation and leave // |pending_activation_| unchanged. return; } } aura::Window* next_activatable = rules_->GetNextActivatableWindow(window); if (!SetActiveWindow(ActivationChangeObserver::ActivationReason:: WINDOW_DISPOSITION_CHANGED, nullptr, next_activatable, /*no_stacking=*/false)) { return; } if (window == focused_window_ || !active_window_ || !active_window_->Contains(focused_window_)) { SetFocusedWindow(next_activatable); } } else if (window->Contains(focused_window_)) { if (pending_activation_) { // We're in the process of updating activation, most likely // ActivationChangeObserver::OnWindowActivated() is changing something // about the focused window (visibility perhaps). Temporarily set the // focus to null, we'll set it to something better when activation // completes. SetFocusedWindow(nullptr); } else { // Active window isn't changing, but focused window might be. SetFocusedWindow(rules_->GetFocusableWindow(next)); } } } void FocusController::WindowFocusedFromInputEvent(aura::Window* window, const ui::Event* event) { // For focus follows cursor: avoid activating when `window` is a child of the // currently active window. bool is_mouse_entered_event = event->type() == ui::ET_MOUSE_ENTERED; if (is_mouse_entered_event && active_window_ && active_window_->Contains(window)) { return; } // Only focus |window| if it or any of its parents can be focused. Otherwise // FocusWindow() will focus the topmost window, which may not be the // currently focused one. if (rules_->CanFocusWindow(GetToplevelWindow(window), event)) { FocusAndActivateWindow( ActivationChangeObserver::ActivationReason::INPUT_EVENT, window, /*no_stacking=*/is_mouse_entered_event); } } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/focus_controller.cc
C++
unknown
17,820
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_FOCUS_CONTROLLER_H_ #define UI_WM_CORE_FOCUS_CONTROLLER_H_ #include <memory> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "base/observer_list.h" #include "base/scoped_multi_source_observation.h" #include "base/strings/string_piece.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/window_observer.h" #include "ui/events/event_handler.h" #include "ui/wm/public/activation_change_observer.h" #include "ui/wm/public/activation_client.h" namespace wm { class FocusRules; // FocusController handles focus and activation changes for an environment // encompassing one or more RootWindows. Within an environment there can be // only one focused and one active window at a time. When focus or activation // changes notifications are sent using the // aura::client::Focus/ActivationChangeObserver interfaces. // Changes to focus and activation can be from three sources. The source can be // determined by the ActivationReason parameter in // ActivationChangeObserver::OnWindowActivated(...). // . ActivationReason::ACTIVATION_CLIENT: The Aura Client API (implemented here // in ActivationClient). (The FocusController must be set as the // ActivationClient implementation for all RootWindows). // . ActivationReason::INPUT_EVENT: Input events (implemented here in // ui::EventHandler). (The FocusController must be registered as a pre-target // handler for the applicable environment owner, either a RootWindow or // another type). // . ActivationReason::WINDOW_DISPOSITION_CHANGED: Window disposition changes // (implemented here in aura::WindowObserver). (The FocusController registers // itself as an observer of the active and focused windows). class COMPONENT_EXPORT(UI_WM) FocusController : public ActivationClient, public aura::client::FocusClient , public ui::EventHandler, public aura::WindowObserver { public: // |rules| cannot be NULL. explicit FocusController(FocusRules* rules); FocusController(const FocusController&) = delete; FocusController& operator=(const FocusController&) = delete; ~FocusController() override; // Overridden from ActivationClient: void AddObserver(ActivationChangeObserver* observer) override; void RemoveObserver(ActivationChangeObserver* observer) override; void ActivateWindow(aura::Window* window) override; void DeactivateWindow(aura::Window* window) override; const aura::Window* GetActiveWindow() const override; aura::Window* GetActivatableWindow(aura::Window* window) const override; const aura::Window* GetToplevelWindow( const aura::Window* window) const override; bool CanActivateWindow(const aura::Window* window) const override; // Overridden from aura::client::FocusClient: void AddObserver(aura::client::FocusChangeObserver* observer) override; void RemoveObserver(aura::client::FocusChangeObserver* observer) override; void FocusWindow(aura::Window* window) override; void ResetFocusWithinActiveWindow(aura::Window* window) override; aura::Window* GetFocusedWindow() override; protected: // Overridden from ui::EventHandler: void OnKeyEvent(ui::KeyEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; void OnScrollEvent(ui::ScrollEvent* event) override; void OnTouchEvent(ui::TouchEvent* event) override; void OnGestureEvent(ui::GestureEvent* event) override; base::StringPiece GetLogContext() const override; // Overridden from aura::WindowObserver: void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; void OnWindowDestroying(aura::Window* window) override; void OnWindowHierarchyChanging(const HierarchyChangeParams& params) override; void OnWindowHierarchyChanged(const HierarchyChangeParams& params) override; private: // Internal implementation that coordinates window focus and activation // changes. void FocusAndActivateWindow(ActivationChangeObserver::ActivationReason reason, aura::Window* window, bool no_stacking); // Internal implementation that sets the focused window, fires events etc. // This function must be called with a valid focusable window. void SetFocusedWindow(aura::Window* window); // Internal implementation that sets the active window, fires events etc. // This function must be called with a valid |activatable_window|. // |requested_window| refers to the window that was passed in to an external // request (e.g. FocusWindow or ActivateWindow). It may be NULL, e.g. if // SetActiveWindow was not called by an external request. |activatable_window| // refers to the actual window to be activated, which may be different. // Returns true if activation should proceed, or false if activation was // interrupted, e.g. by the destruction of the window gaining activation // during the process, and therefore activation should be aborted. If // |no_stacking| is true, the activated window is not stacked. bool SetActiveWindow(ActivationChangeObserver::ActivationReason reason, aura::Window* requested_window, aura::Window* activatable_window, bool no_stacking); // Stack the |active_window_| on top of the window stack. This function is // called when activating a window or re-activating the current active window. void StackActiveWindow(); // Called when a window's disposition changed such that it and its hierarchy // are no longer focusable/activatable. |next| is a valid window that is used // as a starting point for finding a window to focus next based on rules. void WindowLostFocusFromDispositionChange(aura::Window* window, aura::Window* next); // Called when an attempt is made to focus or activate a window via an input // event targeted at that window. Rules determine the best focusable window // for the input window. void WindowFocusedFromInputEvent(aura::Window* window, const ui::Event* event); raw_ptr<aura::Window> active_window_ = nullptr; raw_ptr<aura::Window> focused_window_ = nullptr; bool updating_focus_ = false; // An optional value. It is set to the window being activated and is unset // after it is activated. absl::optional<aura::Window*> pending_activation_; std::unique_ptr<FocusRules> rules_; base::ObserverList<ActivationChangeObserver> activation_observers_; base::ObserverList<aura::client::FocusChangeObserver> focus_observers_; base::ScopedMultiSourceObservation<aura::Window, aura::WindowObserver> observation_manager_{this}; // When true, windows can be activated (but not raised) without clicking. bool focus_follows_cursor_ = false; }; } // namespace wm #endif // UI_WM_CORE_FOCUS_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/focus_controller.h
C++
unknown
7,180
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/focus_controller.h" #include <map> #include "base/memory/raw_ptr.h" #include "base/test/scoped_feature_list.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/default_capture_client.h" #include "ui/aura/client/focus_change_observer.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tracker.h" #include "ui/base/ui_base_features.h" #include "ui/events/event.h" #include "ui/events/event_constants.h" #include "ui/events/event_handler.h" #include "ui/events/test/event_generator.h" #include "ui/wm/core/base_focus_rules.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/activation_change_observer.h" #include "ui/wm/public/activation_client.h" // EXPECT_DCHECK executes statement and expects a DCHECK death when DCHECK is // enabled. #if DCHECK_IS_ON() #define EXPECT_DCHECK(statement, regex) \ EXPECT_DEATH_IF_SUPPORTED(statement, regex) #else #define EXPECT_DCHECK(statement, regex) \ { statement; } #endif namespace wm { class FocusNotificationObserver : public ActivationChangeObserver, public aura::client::FocusChangeObserver { public: FocusNotificationObserver() : last_activation_reason_(ActivationReason::ACTIVATION_CLIENT), activation_changed_count_(0), focus_changed_count_(0), reactivation_count_(0), reactivation_requested_window_(nullptr), reactivation_actual_window_(nullptr) {} FocusNotificationObserver(const FocusNotificationObserver&) = delete; FocusNotificationObserver& operator=(const FocusNotificationObserver&) = delete; ~FocusNotificationObserver() override {} void ExpectCounts(int activation_changed_count, int focus_changed_count) { EXPECT_EQ(activation_changed_count, activation_changed_count_); EXPECT_EQ(focus_changed_count, focus_changed_count_); } ActivationReason last_activation_reason() const { return last_activation_reason_; } int reactivation_count() const { return reactivation_count_; } aura::Window* reactivation_requested_window() const { return reactivation_requested_window_; } aura::Window* reactivation_actual_window() const { return reactivation_actual_window_; } private: // Overridden from ActivationChangeObserver: void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override { last_activation_reason_ = reason; ++activation_changed_count_; } void OnAttemptToReactivateWindow(aura::Window* request_active, aura::Window* actual_active) override { ++reactivation_count_; reactivation_requested_window_ = request_active; reactivation_actual_window_ = actual_active; } // Overridden from aura::client::FocusChangeObserver: void OnWindowFocused(aura::Window* gained_focus, aura::Window* lost_focus) override { ++focus_changed_count_; } ActivationReason last_activation_reason_; int activation_changed_count_; int focus_changed_count_; int reactivation_count_; raw_ptr<aura::Window> reactivation_requested_window_; raw_ptr<aura::Window> reactivation_actual_window_; }; class WindowDeleter { public: virtual aura::Window* GetDeletedWindow() = 0; protected: virtual ~WindowDeleter() {} }; // ActivationChangeObserver and FocusChangeObserver that keeps track of whether // it was notified about activation changes or focus changes with a deleted // window. class RecordingActivationAndFocusChangeObserver : public ActivationChangeObserver, public aura::client::FocusChangeObserver { public: RecordingActivationAndFocusChangeObserver(aura::Window* root, WindowDeleter* deleter) : root_(root), deleter_(deleter), was_notified_with_deleted_window_(false) { GetActivationClient(root_)->AddObserver(this); aura::client::GetFocusClient(root_)->AddObserver(this); } RecordingActivationAndFocusChangeObserver( const RecordingActivationAndFocusChangeObserver&) = delete; RecordingActivationAndFocusChangeObserver& operator=( const RecordingActivationAndFocusChangeObserver&) = delete; ~RecordingActivationAndFocusChangeObserver() override { GetActivationClient(root_)->RemoveObserver(this); aura::client::GetFocusClient(root_)->RemoveObserver(this); } bool was_notified_with_deleted_window() const { return was_notified_with_deleted_window_; } // Overridden from ActivationChangeObserver: void OnWindowActivating(ActivationReason reason, aura::Window* gaining_active, aura::Window* losing_active) override { if (deleter_->GetDeletedWindow()) { // A deleted window during activation should never be return as either the // gaining or losing active windows, nor should it be returned as the // currently active one. auto* active_window = GetActivationClient(root_)->GetActiveWindow(); EXPECT_NE(active_window, deleter_->GetDeletedWindow()); EXPECT_NE(gaining_active, deleter_->GetDeletedWindow()); EXPECT_NE(losing_active, deleter_->GetDeletedWindow()); } } void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override { if (lost_active && lost_active == deleter_->GetDeletedWindow()) was_notified_with_deleted_window_ = true; } // Overridden from aura::client::FocusChangeObserver: void OnWindowFocused(aura::Window* gained_focus, aura::Window* lost_focus) override { if (lost_focus && lost_focus == deleter_->GetDeletedWindow()) was_notified_with_deleted_window_ = true; } private: raw_ptr<aura::Window> root_; // Not owned. raw_ptr<WindowDeleter> deleter_; // Whether the observer was notified about the loss of activation or the // loss of focus with a window already deleted by |deleter_| as the // |lost_active| or |lost_focus| parameter. bool was_notified_with_deleted_window_; }; // Hides a window when activation changes. class HideOnLoseActivationChangeObserver : public ActivationChangeObserver { public: explicit HideOnLoseActivationChangeObserver(aura::Window* window_to_hide) : root_(window_to_hide->GetRootWindow()), window_to_hide_(window_to_hide) { GetActivationClient(root_)->AddObserver(this); } HideOnLoseActivationChangeObserver( const HideOnLoseActivationChangeObserver&) = delete; HideOnLoseActivationChangeObserver& operator=( const HideOnLoseActivationChangeObserver&) = delete; ~HideOnLoseActivationChangeObserver() override { GetActivationClient(root_)->RemoveObserver(this); } aura::Window* window_to_hide() { return window_to_hide_; } private: // Overridden from ActivationChangeObserver: void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override { if (window_to_hide_) { aura::Window* window_to_hide = window_to_hide_; window_to_hide_ = nullptr; window_to_hide->Hide(); } } raw_ptr<aura::Window> root_; raw_ptr<aura::Window> window_to_hide_; }; // ActivationChangeObserver that deletes the window losing activation. class DeleteOnActivationChangeObserver : public ActivationChangeObserver, public WindowDeleter { public: // If |delete_on_activating| is true, |window| will be deleted when // OnWindowActivating() is called, otherwise, it will be deleted when // OnWindowActivated() is called. // If |delete_window_losing_active| is true, |window| will be deleted if it is // the window losing activation, otherwise, will be deleted if it is the one // gaining activation. DeleteOnActivationChangeObserver(aura::Window* window, bool delete_on_activating, bool delete_window_losing_active) : root_(window->GetRootWindow()), window_(window), delete_on_activating_(delete_on_activating), delete_window_losing_active_(delete_window_losing_active), did_delete_(false) { GetActivationClient(root_)->AddObserver(this); } DeleteOnActivationChangeObserver(const DeleteOnActivationChangeObserver&) = delete; DeleteOnActivationChangeObserver& operator=( const DeleteOnActivationChangeObserver&) = delete; ~DeleteOnActivationChangeObserver() override { GetActivationClient(root_)->RemoveObserver(this); } // Overridden from ActivationChangeObserver: void OnWindowActivating(ActivationReason reason, aura::Window* gaining_active, aura::Window* losing_active) override { if (!delete_on_activating_) return; auto* window_to_delete = delete_window_losing_active_ ? losing_active : gaining_active; if (window_ && window_to_delete == window_) { delete window_to_delete; did_delete_ = true; } } void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override { if (delete_on_activating_) return; auto* window_to_delete = delete_window_losing_active_ ? lost_active : gained_active; if (window_ && window_to_delete == window_) { delete window_to_delete; did_delete_ = true; } } // Overridden from WindowDeleter: aura::Window* GetDeletedWindow() override { return did_delete_ ? window_.get() : nullptr; } private: raw_ptr<aura::Window> root_; raw_ptr<aura::Window> window_; const bool delete_on_activating_; const bool delete_window_losing_active_; bool did_delete_; }; // FocusChangeObserver that deletes the window losing focus. class DeleteOnLoseFocusChangeObserver : public aura::client::FocusChangeObserver, public WindowDeleter { public: explicit DeleteOnLoseFocusChangeObserver(aura::Window* window) : root_(window->GetRootWindow()), window_(window), did_delete_(false) { aura::client::GetFocusClient(root_)->AddObserver(this); } DeleteOnLoseFocusChangeObserver(const DeleteOnLoseFocusChangeObserver&) = delete; DeleteOnLoseFocusChangeObserver& operator=( const DeleteOnLoseFocusChangeObserver&) = delete; ~DeleteOnLoseFocusChangeObserver() override { aura::client::GetFocusClient(root_)->RemoveObserver(this); } // Overridden from aura::client::FocusChangeObserver: void OnWindowFocused(aura::Window* gained_focus, aura::Window* lost_focus) override { if (window_ && lost_focus == window_) { delete lost_focus; did_delete_ = true; } } // Overridden from WindowDeleter: aura::Window* GetDeletedWindow() override { return did_delete_ ? window_.get() : nullptr; } private: raw_ptr<aura::Window> root_; raw_ptr<aura::Window> window_; bool did_delete_; }; class ScopedFocusNotificationObserver : public FocusNotificationObserver { public: ScopedFocusNotificationObserver(aura::Window* root_window) : root_window_(root_window) { GetActivationClient(root_window_)->AddObserver(this); aura::client::GetFocusClient(root_window_)->AddObserver(this); } ScopedFocusNotificationObserver(const ScopedFocusNotificationObserver&) = delete; ScopedFocusNotificationObserver& operator=( const ScopedFocusNotificationObserver&) = delete; ~ScopedFocusNotificationObserver() override { GetActivationClient(root_window_)->RemoveObserver(this); aura::client::GetFocusClient(root_window_)->RemoveObserver(this); } private: raw_ptr<aura::Window> root_window_; }; class ScopedTargetFocusNotificationObserver : public FocusNotificationObserver { public: ScopedTargetFocusNotificationObserver(aura::Window* root_window, int id) : target_(root_window->GetChildById(id)) { SetActivationChangeObserver(target_, this); aura::client::SetFocusChangeObserver(target_, this); tracker_.Add(target_); } ScopedTargetFocusNotificationObserver( const ScopedTargetFocusNotificationObserver&) = delete; ScopedTargetFocusNotificationObserver& operator=( const ScopedTargetFocusNotificationObserver&) = delete; ~ScopedTargetFocusNotificationObserver() override { if (tracker_.Contains(target_)) { SetActivationChangeObserver(target_, nullptr); aura::client::SetFocusChangeObserver(target_, nullptr); } } private: raw_ptr<aura::Window> target_; aura::WindowTracker tracker_; }; // Used to fake the handling of events in the pre-target phase. class SimpleEventHandler : public ui::EventHandler { public: SimpleEventHandler() {} SimpleEventHandler(const SimpleEventHandler&) = delete; SimpleEventHandler& operator=(const SimpleEventHandler&) = delete; ~SimpleEventHandler() override {} // Overridden from ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override { event->SetHandled(); } void OnGestureEvent(ui::GestureEvent* event) override { event->SetHandled(); } }; class FocusShiftingActivationObserver : public ActivationChangeObserver { public: explicit FocusShiftingActivationObserver(aura::Window* activated_window) : activated_window_(activated_window), shift_focus_to_(nullptr) {} FocusShiftingActivationObserver(const FocusShiftingActivationObserver&) = delete; FocusShiftingActivationObserver& operator=( const FocusShiftingActivationObserver&) = delete; ~FocusShiftingActivationObserver() override {} void set_shift_focus_to(aura::Window* shift_focus_to) { shift_focus_to_ = shift_focus_to; } private: // Overridden from ActivationChangeObserver: void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override { // Shift focus to a child. This should prevent the default focusing from // occurring in FocusController::FocusWindow(). if (gained_active == activated_window_) { aura::client::FocusClient* client = aura::client::GetFocusClient(gained_active); client->FocusWindow(shift_focus_to_); } } raw_ptr<aura::Window> activated_window_; raw_ptr<aura::Window> shift_focus_to_; }; class ActivateWhileActivatingObserver : public ActivationChangeObserver { public: ActivateWhileActivatingObserver(aura::Window* to_observe, aura::Window* to_activate, aura::Window* to_focus) : to_observe_(to_observe), to_activate_(to_activate), to_focus_(to_focus) { GetActivationClient(to_observe_->GetRootWindow())->AddObserver(this); } ActivateWhileActivatingObserver(const ActivateWhileActivatingObserver&) = delete; ActivateWhileActivatingObserver& operator=( const ActivateWhileActivatingObserver&) = delete; ~ActivateWhileActivatingObserver() override { GetActivationClient(to_observe_->GetRootWindow())->RemoveObserver(this); } private: // Overridden from ActivationChangeObserver: void OnWindowActivating(ActivationReason reason, aura::Window* gaining_active, aura::Window* losing_active) override { if (gaining_active != to_observe_) return; if (to_activate_) ActivateWindow(to_activate_); if (to_focus_) FocusWindow(to_focus_); } void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override {} void ActivateWindow(aura::Window* window) { GetActivationClient(to_observe_->GetRootWindow())->ActivateWindow(window); } void FocusWindow(aura::Window* window) { aura::client::GetFocusClient(to_observe_->GetRootWindow()) ->FocusWindow(window); } raw_ptr<aura::Window> to_observe_; raw_ptr<aura::Window> to_activate_; raw_ptr<aura::Window> to_focus_; }; // BaseFocusRules subclass that allows basic overrides of focus/activation to // be tested. This is intended more as a test that the override system works at // all, rather than as an exhaustive set of use cases, those should be covered // in tests for those FocusRules implementations. class TestFocusRules : public BaseFocusRules { public: TestFocusRules() : focus_restriction_(nullptr) {} TestFocusRules(const TestFocusRules&) = delete; TestFocusRules& operator=(const TestFocusRules&) = delete; // Restricts focus and activation to this window and its child hierarchy. void set_focus_restriction(aura::Window* focus_restriction) { focus_restriction_ = focus_restriction; } // Overridden from BaseFocusRules: bool SupportsChildActivation(const aura::Window* window) const override { // In FocusControllerTests, only the RootWindow has activatable children. return window->GetRootWindow() == window; } bool CanActivateWindow(const aura::Window* window) const override { // Restricting focus to a non-activatable child window means the activatable // parent outside the focus restriction is activatable. bool can_activate = CanFocusOrActivate(window) || window->Contains(focus_restriction_); return can_activate ? BaseFocusRules::CanActivateWindow(window) : false; } bool CanFocusWindow(const aura::Window* window, const ui::Event* event) const override { return CanFocusOrActivate(window) ? BaseFocusRules::CanFocusWindow(window, event) : false; } aura::Window* GetActivatableWindow(aura::Window* window) const override { return BaseFocusRules::GetActivatableWindow( CanFocusOrActivate(window) ? window : focus_restriction_.get()); } aura::Window* GetFocusableWindow(aura::Window* window) const override { return BaseFocusRules::GetFocusableWindow( CanFocusOrActivate(window) ? window : focus_restriction_.get()); } aura::Window* GetNextActivatableWindow(aura::Window* ignore) const override { aura::Window* next_activatable = BaseFocusRules::GetNextActivatableWindow(ignore); return CanFocusOrActivate(next_activatable) ? next_activatable : GetActivatableWindow(focus_restriction_); } private: bool CanFocusOrActivate(const aura::Window* window) const { return !focus_restriction_ || focus_restriction_->Contains(window); } raw_ptr<aura::Window> focus_restriction_; }; // Common infrastructure shared by all FocusController test types. class FocusControllerTestBase : public aura::test::AuraTestBase { public: FocusControllerTestBase(const FocusControllerTestBase&) = delete; FocusControllerTestBase& operator=(const FocusControllerTestBase&) = delete; protected: FocusControllerTestBase() {} // Overridden from aura::test::AuraTestBase: void SetUp() override { // FocusController registers itself as an Env observer so it can catch all // window initializations, including the root_window()'s, so we create it // before allowing the base setup. test_focus_rules_ = new TestFocusRules; focus_controller_ = std::make_unique<FocusController>(test_focus_rules_); aura::test::AuraTestBase::SetUp(); root_window()->AddPreTargetHandler(focus_controller_.get()); aura::client::SetFocusClient(root_window(), focus_controller_.get()); SetActivationClient(root_window(), focus_controller_.get()); // Hierarchy used by all tests: // root_window // +-- w1 // | +-- w11 // | +-- w12 // +-- w2 // | +-- w21 // | +-- w211 // +-- w3 aura::Window* w1 = aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 1, gfx::Rect(0, 0, 50, 50), root_window()); aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 11, gfx::Rect(5, 5, 10, 10), w1); aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 12, gfx::Rect(15, 15, 10, 10), w1); aura::Window* w2 = aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 2, gfx::Rect(75, 75, 50, 50), root_window()); aura::Window* w21 = aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 21, gfx::Rect(5, 5, 10, 10), w2); aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 211, gfx::Rect(1, 1, 5, 5), w21); aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 3, gfx::Rect(125, 125, 50, 50), root_window()); } void TearDown() override { root_window()->RemovePreTargetHandler(focus_controller_.get()); aura::test::AuraTestBase::TearDown(); test_focus_rules_ = nullptr; // Owned by FocusController. focus_controller_.reset(); } void FocusWindow(aura::Window* window) { aura::client::GetFocusClient(root_window())->FocusWindow(window); } aura::Window* GetFocusedWindow() { return aura::client::GetFocusClient(root_window())->GetFocusedWindow(); } int GetFocusedWindowId() { aura::Window* focused_window = GetFocusedWindow(); return focused_window ? focused_window->GetId() : -1; } void ActivateWindow(aura::Window* window) { GetActivationClient(root_window())->ActivateWindow(window); } void DeactivateWindow(aura::Window* window) { GetActivationClient(root_window())->DeactivateWindow(window); } aura::Window* GetActiveWindow() { return GetActivationClient(root_window())->GetActiveWindow(); } int GetActiveWindowId() { aura::Window* active_window = GetActiveWindow(); return active_window ? active_window->GetId() : -1; } TestFocusRules* test_focus_rules() { return test_focus_rules_; } // Test functions. virtual void BasicFocus() = 0; virtual void BasicActivation() = 0; virtual void FocusEvents() = 0; virtual void DuplicateFocusEvents() {} virtual void ActivationEvents() = 0; virtual void ReactivationEvents() {} virtual void DuplicateActivationEvents() {} virtual void ShiftFocusWithinActiveWindow() {} virtual void ShiftFocusToChildOfInactiveWindow() {} virtual void ShiftFocusToParentOfFocusedWindow() {} virtual void FocusRulesOverride() = 0; virtual void ActivationRulesOverride() = 0; virtual void ShiftFocusOnActivation() {} virtual void ShiftFocusOnActivationDueToHide() {} virtual void NoShiftActiveOnActivation() {} virtual void FocusChangeDuringDrag() {} virtual void ChangeFocusWhenNothingFocusedAndCaptured() {} virtual void DontPassDeletedWindow() {} virtual void StackWindowAtTopOnActivation() {} virtual void HideFocusedWindowDuringActivationLoss() {} virtual void ActivateWhileActivating() {} private: std::unique_ptr<FocusController> focus_controller_; raw_ptr<TestFocusRules> test_focus_rules_; }; // Test base for tests where focus is directly set to a target window. class FocusControllerDirectTestBase : public FocusControllerTestBase { public: FocusControllerDirectTestBase(const FocusControllerDirectTestBase&) = delete; FocusControllerDirectTestBase& operator=( const FocusControllerDirectTestBase&) = delete; protected: FocusControllerDirectTestBase() {} // Different test types shift focus in different ways. virtual void FocusWindowDirect(aura::Window* window) = 0; virtual void ActivateWindowDirect(aura::Window* window) = 0; virtual void DeactivateWindowDirect(aura::Window* window) = 0; // Input events do not change focus if the window can not be focused. virtual bool IsInputEvent() = 0; // Returns the expected ActivationReason caused by calling the // ActivatedWindowDirect(...) or DeactivateWindowDirect(...) methods. virtual ActivationChangeObserver::ActivationReason GetExpectedActivationReason() const = 0; void FocusWindowById(int id) { aura::Window* window = root_window()->GetChildById(id); DCHECK(window); FocusWindowDirect(window); } void ActivateWindowById(int id) { aura::Window* window = root_window()->GetChildById(id); DCHECK(window); ActivateWindowDirect(window); } void DeactivateWindowById(int id) { aura::Window* window = root_window()->GetChildById(id); EXPECT_TRUE(window); GetActivationClient(root_window())->DeactivateWindow(window); } // Overridden from FocusControllerTestBase: void BasicFocus() override { EXPECT_FALSE(GetFocusedWindow()); FocusWindowById(1); EXPECT_EQ(1, GetFocusedWindowId()); FocusWindowById(2); EXPECT_EQ(2, GetFocusedWindowId()); } void BasicActivation() override { EXPECT_FALSE(GetActiveWindow()); ActivateWindowById(1); EXPECT_EQ(1, GetActiveWindowId()); ActivateWindowById(2); EXPECT_EQ(2, GetActiveWindowId()); // Create a new window without activing it. Move it to the // top. aura::Window* window3 = root_window()->GetChildById(3); root_window()->StackChildAtTop(window3); // Verify that diactivating a non-active window won't affect the current // active window. DeactivateWindowById(1); EXPECT_EQ(2, GetActiveWindowId()); // Verify that attempting to deactivate NULL does not crash and does not // change activation. DeactivateWindow(nullptr); EXPECT_EQ(2, GetActiveWindowId()); DeactivateWindow(GetActiveWindow()); EXPECT_EQ(3, GetActiveWindowId()); } void FocusEvents() override { ScopedFocusNotificationObserver root_observer(root_window()); ScopedTargetFocusNotificationObserver observer1(root_window(), 1); ScopedTargetFocusNotificationObserver observer2(root_window(), 2); root_observer.ExpectCounts(0, 0); observer1.ExpectCounts(0, 0); observer2.ExpectCounts(0, 0); FocusWindowById(1); root_observer.ExpectCounts(1, 1); observer1.ExpectCounts(1, 1); observer2.ExpectCounts(0, 0); FocusWindowById(2); root_observer.ExpectCounts(2, 2); observer1.ExpectCounts(2, 2); observer2.ExpectCounts(1, 1); } void DuplicateFocusEvents() override { // Focusing an existing focused window should not resend focus events. ScopedFocusNotificationObserver root_observer(root_window()); ScopedTargetFocusNotificationObserver observer1(root_window(), 1); root_observer.ExpectCounts(0, 0); observer1.ExpectCounts(0, 0); FocusWindowById(1); root_observer.ExpectCounts(1, 1); observer1.ExpectCounts(1, 1); FocusWindowById(1); root_observer.ExpectCounts(1, 1); observer1.ExpectCounts(1, 1); } void ActivationEvents() override { ActivateWindowById(1); ScopedFocusNotificationObserver root_observer(root_window()); ScopedTargetFocusNotificationObserver observer1(root_window(), 1); ScopedTargetFocusNotificationObserver observer2(root_window(), 2); root_observer.ExpectCounts(0, 0); observer1.ExpectCounts(0, 0); observer2.ExpectCounts(0, 0); ActivateWindowById(2); root_observer.ExpectCounts(1, 1); EXPECT_EQ(GetExpectedActivationReason(), root_observer.last_activation_reason()); observer1.ExpectCounts(1, 1); observer2.ExpectCounts(1, 1); } void ReactivationEvents() override { ActivateWindowById(1); ScopedFocusNotificationObserver root_observer(root_window()); EXPECT_EQ(0, root_observer.reactivation_count()); root_window()->GetChildById(2)->Hide(); // When we attempt to activate "2", which cannot be activated because it // is not visible, "1" will be reactivated. ActivateWindowById(2); EXPECT_EQ(1, root_observer.reactivation_count()); EXPECT_EQ(root_window()->GetChildById(2), root_observer.reactivation_requested_window()); EXPECT_EQ(root_window()->GetChildById(1), root_observer.reactivation_actual_window()); } void DuplicateActivationEvents() override { // Activating an existing active window should not resend activation events. ActivateWindowById(1); ScopedFocusNotificationObserver root_observer(root_window()); ScopedTargetFocusNotificationObserver observer1(root_window(), 1); ScopedTargetFocusNotificationObserver observer2(root_window(), 2); root_observer.ExpectCounts(0, 0); observer1.ExpectCounts(0, 0); observer2.ExpectCounts(0, 0); ActivateWindowById(2); root_observer.ExpectCounts(1, 1); observer1.ExpectCounts(1, 1); observer2.ExpectCounts(1, 1); ActivateWindowById(2); root_observer.ExpectCounts(1, 1); observer1.ExpectCounts(1, 1); observer2.ExpectCounts(1, 1); } void ShiftFocusWithinActiveWindow() override { ActivateWindowById(1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); FocusWindowById(11); EXPECT_EQ(11, GetFocusedWindowId()); FocusWindowById(12); EXPECT_EQ(12, GetFocusedWindowId()); } void ShiftFocusToChildOfInactiveWindow() override { ActivateWindowById(2); EXPECT_EQ(2, GetActiveWindowId()); EXPECT_EQ(2, GetFocusedWindowId()); FocusWindowById(11); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(11, GetFocusedWindowId()); } void ShiftFocusToParentOfFocusedWindow() override { ActivateWindowById(1); EXPECT_EQ(1, GetFocusedWindowId()); FocusWindowById(11); EXPECT_EQ(11, GetFocusedWindowId()); FocusWindowById(1); // Focus should _not_ shift to the parent of the already-focused window. EXPECT_EQ(11, GetFocusedWindowId()); } void FocusRulesOverride() override { EXPECT_FALSE(GetFocusedWindow()); FocusWindowById(11); EXPECT_EQ(11, GetFocusedWindowId()); test_focus_rules()->set_focus_restriction(root_window()->GetChildById(211)); FocusWindowById(12); // Input events leave focus unchanged; direct API calls will change focus // to the restricted window. int focused_window = IsInputEvent() ? 11 : 211; EXPECT_EQ(focused_window, GetFocusedWindowId()); test_focus_rules()->set_focus_restriction(nullptr); FocusWindowById(12); EXPECT_EQ(12, GetFocusedWindowId()); } void ActivationRulesOverride() override { ActivateWindowById(1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); aura::Window* w3 = root_window()->GetChildById(3); test_focus_rules()->set_focus_restriction(w3); ActivateWindowById(2); // Input events leave activation unchanged; direct API calls will activate // the restricted window. int active_window = IsInputEvent() ? 1 : 3; EXPECT_EQ(active_window, GetActiveWindowId()); EXPECT_EQ(active_window, GetFocusedWindowId()); test_focus_rules()->set_focus_restriction(nullptr); ActivateWindowById(2); EXPECT_EQ(2, GetActiveWindowId()); EXPECT_EQ(2, GetFocusedWindowId()); } void ShiftFocusOnActivation() override { // When a window is activated, by default that window is also focused. // An ActivationChangeObserver may shift focus to another window within the // same activatable window. ActivateWindowById(2); EXPECT_EQ(2, GetFocusedWindowId()); ActivateWindowById(1); EXPECT_EQ(1, GetFocusedWindowId()); ActivateWindowById(2); aura::Window* target = root_window()->GetChildById(1); ActivationClient* client = GetActivationClient(root_window()); std::unique_ptr<FocusShiftingActivationObserver> observer( new FocusShiftingActivationObserver(target)); observer->set_shift_focus_to(target->GetChildById(11)); client->AddObserver(observer.get()); ActivateWindowById(1); // w1's ActivationChangeObserver shifted focus to this child, pre-empting // FocusController's default setting. EXPECT_EQ(11, GetFocusedWindowId()); ActivateWindowById(2); EXPECT_EQ(2, GetFocusedWindowId()); // Simulate a focus reset by the ActivationChangeObserver. This should // trigger the default setting in FocusController. observer->set_shift_focus_to(nullptr); ActivateWindowById(1); EXPECT_EQ(1, GetFocusedWindowId()); client->RemoveObserver(observer.get()); ActivateWindowById(2); EXPECT_EQ(2, GetFocusedWindowId()); ActivateWindowById(1); EXPECT_EQ(1, GetFocusedWindowId()); } void ShiftFocusOnActivationDueToHide() override { // Similar to ShiftFocusOnActivation except the activation change is // triggered by hiding the active window. ActivateWindowById(1); EXPECT_EQ(1, GetFocusedWindowId()); // Removes window 3 as candidate for next activatable window. root_window()->GetChildById(3)->Hide(); EXPECT_EQ(1, GetFocusedWindowId()); aura::Window* target = root_window()->GetChildById(2); ActivationClient* client = GetActivationClient(root_window()); std::unique_ptr<FocusShiftingActivationObserver> observer( new FocusShiftingActivationObserver(target)); observer->set_shift_focus_to(target->GetChildById(21)); client->AddObserver(observer.get()); // Hide the active window. root_window()->GetChildById(1)->Hide(); EXPECT_EQ(21, GetFocusedWindowId()); client->RemoveObserver(observer.get()); } void NoShiftActiveOnActivation() override { // When a window is activated, we need to prevent any change to activation // from being made in response to an activation change notification. } void FocusChangeDuringDrag() override { std::unique_ptr<aura::client::DefaultCaptureClient> capture_client( new aura::client::DefaultCaptureClient(root_window())); // Activating an inactive window during drag should activate the window. // This emulates the behavior of tab dragging which is merged into the // window below. ActivateWindowById(1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); aura::Window* w2 = root_window()->GetChildById(2); ui::test::EventGenerator generator(root_window(), w2); generator.PressLeftButton(); aura::client::GetCaptureClient(root_window())->SetCapture(w2); EXPECT_EQ(2, GetActiveWindowId()); EXPECT_EQ(2, GetFocusedWindowId()); generator.MoveMouseTo(gfx::Point(0, 0)); // Emulate the behavior of merging a tab into an inactive window: // transferring the mouse capture and activate the window. aura::Window* w1 = root_window()->GetChildById(1); aura::client::GetCaptureClient(root_window())->SetCapture(w1); GetActivationClient(root_window())->ActivateWindow(w1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); generator.ReleaseLeftButton(); aura::client::GetCaptureClient(root_window())->ReleaseCapture(w1); } // Verifies focus change is honored while capture held. void ChangeFocusWhenNothingFocusedAndCaptured() override { std::unique_ptr<aura::client::DefaultCaptureClient> capture_client( new aura::client::DefaultCaptureClient(root_window())); aura::Window* w1 = root_window()->GetChildById(1); aura::client::GetCaptureClient(root_window())->SetCapture(w1); EXPECT_EQ(-1, GetActiveWindowId()); EXPECT_EQ(-1, GetFocusedWindowId()); FocusWindowById(1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); aura::client::GetCaptureClient(root_window())->ReleaseCapture(w1); } // Verifies if a window that loses activation or focus is deleted during // observer notification we don't pass the deleted window to other observers. void DontPassDeletedWindow() override { FocusWindowById(1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); { aura::Window* to_delete = root_window()->GetChildById(1); DeleteOnActivationChangeObserver observer1( to_delete, /*delete_on_activating=*/true, /*delete_window_losing_active=*/true); RecordingActivationAndFocusChangeObserver observer2(root_window(), &observer1); FocusWindowById(2); EXPECT_EQ(2, GetActiveWindowId()); EXPECT_EQ(2, GetFocusedWindowId()); EXPECT_EQ(to_delete, observer1.GetDeletedWindow()); EXPECT_FALSE(observer2.was_notified_with_deleted_window()); } { aura::Window* to_delete = root_window()->GetChildById(2); DeleteOnActivationChangeObserver observer1( to_delete, /*delete_on_activating=*/false, /*delete_window_losing_active=*/true); RecordingActivationAndFocusChangeObserver observer2(root_window(), &observer1); FocusWindowById(3); EXPECT_EQ(3, GetActiveWindowId()); EXPECT_EQ(3, GetFocusedWindowId()); EXPECT_EQ(to_delete, observer1.GetDeletedWindow()); EXPECT_FALSE(observer2.was_notified_with_deleted_window()); } { aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 4, gfx::Rect(125, 125, 50, 50), root_window()); EXPECT_EQ(3, GetActiveWindowId()); EXPECT_EQ(3, GetFocusedWindowId()); aura::Window* to_delete = root_window()->GetChildById(3); DeleteOnLoseFocusChangeObserver observer1(to_delete); RecordingActivationAndFocusChangeObserver observer2(root_window(), &observer1); FocusWindowById(4); EXPECT_EQ(4, GetActiveWindowId()); EXPECT_EQ(4, GetFocusedWindowId()); EXPECT_EQ(to_delete, observer1.GetDeletedWindow()); EXPECT_FALSE(observer2.was_notified_with_deleted_window()); } { aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 5, gfx::Rect(125, 125, 50, 50), root_window()); aura::test::CreateTestWindowWithDelegate( aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 6, gfx::Rect(125, 125, 50, 50), root_window()); EXPECT_EQ(4, GetActiveWindowId()); EXPECT_EQ(4, GetFocusedWindowId()); // Delete the window that is gaining activation at both the "activating" // and "activated" phases. Make sure the activations were interrupted // properly and the correct next activatable window is activated. aura::Window* to_delete1 = root_window()->GetChildById(5); DeleteOnActivationChangeObserver observer1( to_delete1, /*delete_on_activating=*/false, /*delete_window_losing_active=*/false); RecordingActivationAndFocusChangeObserver observer2(root_window(), &observer1); // Test a recursive scenario by having another observer that would delete // the next activatable window during the "activating" phase. aura::Window* to_delete2 = root_window()->GetChildById(6); DeleteOnActivationChangeObserver observer3( to_delete2, /*delete_on_activating=*/true, /*delete_window_losing_active=*/false); RecordingActivationAndFocusChangeObserver observer4(root_window(), &observer3); FocusWindowById(5); EXPECT_EQ(4, GetActiveWindowId()); EXPECT_EQ(4, GetFocusedWindowId()); EXPECT_EQ(to_delete1, observer1.GetDeletedWindow()); EXPECT_FALSE(observer2.was_notified_with_deleted_window()); EXPECT_EQ(to_delete2, observer3.GetDeletedWindow()); EXPECT_FALSE(observer4.was_notified_with_deleted_window()); } } // Test that the activation of the current active window will bring the window // to the top of the window stack. void StackWindowAtTopOnActivation() override { // Create a window, show it and then activate it. std::unique_ptr<aura::Window> window1 = std::make_unique<aura::Window>(nullptr); window1->SetType(aura::client::WINDOW_TYPE_NORMAL); window1->Init(ui::LAYER_TEXTURED); root_window()->AddChild(window1.get()); window1->Show(); ActivateWindow(window1.get()); EXPECT_EQ(window1.get(), root_window()->children().back()); EXPECT_EQ(window1.get(), GetActiveWindow()); // Create another window, show it but don't activate it. The window is not // the active window but is placed on top of window stack. std::unique_ptr<aura::Window> window2 = std::make_unique<aura::Window>(nullptr); window2->SetType(aura::client::WINDOW_TYPE_NORMAL); window2->Init(ui::LAYER_TEXTURED); root_window()->AddChild(window2.get()); window2->Show(); EXPECT_EQ(window2.get(), root_window()->children().back()); EXPECT_EQ(window1.get(), GetActiveWindow()); // Try to reactivate the active window. It should bring the active window // to the top of the window stack. ActivateWindow(window1.get()); EXPECT_EQ(window1.get(), root_window()->children().back()); EXPECT_EQ(window1.get(), GetActiveWindow()); } // Verifies focus isn't left when during notification of an activation change // the focused window is hidden. void HideFocusedWindowDuringActivationLoss() override { aura::Window* w11 = root_window()->GetChildById(11); FocusWindow(w11); EXPECT_EQ(11, GetFocusedWindowId()); EXPECT_EQ(1, GetActiveWindowId()); { HideOnLoseActivationChangeObserver observer(w11); ActivateWindowById(2); EXPECT_EQ(nullptr, observer.window_to_hide()); EXPECT_EQ(2, GetActiveWindowId()); EXPECT_EQ(2, GetFocusedWindowId()); } } // Tests that activating a window while a window is being activated is a // no-op. void ActivateWhileActivating() override { aura::Window* w1 = root_window()->GetChildById(1); aura::Window* w2 = root_window()->GetChildById(2); ActivateWindowById(3); // Activate a window while it is being activated does not DCHECK and the // window is made active. { ActivateWhileActivatingObserver observer(/*to_observe=*/w1, /*to_activate=*/w1, /*to_focus=*/nullptr); ActivateWindow(w1); EXPECT_EQ(1, GetActiveWindowId()); } ActivateWindowById(3); // Focus a window while it is being activated does not DCHECK and the // window is made active and focused. { ActivateWhileActivatingObserver observer(/*to_observe=*/w1, /*to_activate=*/nullptr, /*to_focus=*/w1); ActivateWindow(w1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); } ActivateWindowById(3); // Shift focus while activating a window is allowed as long as it does // not attempt to activate a different window. { aura::Window* w11 = root_window()->GetChildById(11); aura::Window* w12 = root_window()->GetChildById(12); ActivateWhileActivatingObserver observer(/*to_observe=*/w1, /*to_activate=*/nullptr, /*to_focus=*/w12); FocusWindow(w11); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(12, GetFocusedWindowId()); } ActivateWindowById(3); // Activate a different window while activating one fails. The window being // activated in the 1st activation request will be activated. { ActivateWhileActivatingObserver observer(/*to_observe=*/w2, /*to_activate=*/w1, /*to_focus=*/nullptr); // This should hit a DCHECK. EXPECT_DCHECK( { ActivateWindow(w2); EXPECT_EQ(2, GetActiveWindowId()); }, ""); } } }; // Focus and Activation changes via ActivationClient API. class FocusControllerApiTest : public FocusControllerDirectTestBase { public: FocusControllerApiTest() {} FocusControllerApiTest(const FocusControllerApiTest&) = delete; FocusControllerApiTest& operator=(const FocusControllerApiTest&) = delete; private: // Overridden from FocusControllerTestBase: void FocusWindowDirect(aura::Window* window) override { FocusWindow(window); } void ActivateWindowDirect(aura::Window* window) override { ActivateWindow(window); } void DeactivateWindowDirect(aura::Window* window) override { DeactivateWindow(window); } bool IsInputEvent() override { return false; } // Overridden from FocusControllerDirectTestBase: ActivationChangeObserver::ActivationReason GetExpectedActivationReason() const override { return ActivationChangeObserver::ActivationReason::ACTIVATION_CLIENT; } }; // Focus and Activation changes via input events. class FocusControllerMouseEventTest : public FocusControllerDirectTestBase { public: FocusControllerMouseEventTest() {} FocusControllerMouseEventTest(const FocusControllerMouseEventTest&) = delete; FocusControllerMouseEventTest& operator=( const FocusControllerMouseEventTest&) = delete; // Tests that a handled mouse or gesture event does not trigger a window // activation. void IgnoreHandledEvent() { EXPECT_FALSE(GetActiveWindow()); aura::Window* w1 = root_window()->GetChildById(1); SimpleEventHandler handler; root_window()->AddPreTargetHandler(&handler, ui::EventTarget::Priority::kSystem); ui::test::EventGenerator generator(root_window(), w1); generator.ClickLeftButton(); EXPECT_FALSE(GetActiveWindow()); generator.GestureTapAt(w1->bounds().CenterPoint()); EXPECT_FALSE(GetActiveWindow()); root_window()->RemovePreTargetHandler(&handler); generator.ClickLeftButton(); EXPECT_EQ(1, GetActiveWindowId()); } private: // Overridden from FocusControllerTestBase: void FocusWindowDirect(aura::Window* window) override { ui::test::EventGenerator generator(root_window(), window); generator.ClickLeftButton(); } void ActivateWindowDirect(aura::Window* window) override { ui::test::EventGenerator generator(root_window(), window); generator.ClickLeftButton(); } void DeactivateWindowDirect(aura::Window* window) override { aura::Window* next_activatable = test_focus_rules()->GetNextActivatableWindow(window); ui::test::EventGenerator generator(root_window(), next_activatable); generator.ClickLeftButton(); } // Overridden from FocusControllerDirectTestBase: bool IsInputEvent() override { return true; } ActivationChangeObserver::ActivationReason GetExpectedActivationReason() const override { return ActivationChangeObserver::ActivationReason::INPUT_EVENT; } }; class FocusControllerMouseEnterEventTest : public FocusControllerMouseEventTest { public: FocusControllerMouseEnterEventTest() { scoped_feature_list_.InitAndEnableFeature(features::kFocusFollowsCursor); } void MouseEnteredEvent() { aura::Window::Windows children_before = root_window()->children(); aura::Window* w2 = root_window()->GetChildById(2); ui::test::EventGenerator generator(root_window(), w2); generator.SendMouseEnter(); // The enter event should activate the window, but not stack the window. EXPECT_EQ(w2, GetActiveWindow()); EXPECT_EQ(children_before, root_window()->children()); } void MouseEnteredWithActiveParent() { aura::Window* w2 = root_window()->GetChildById(2); aura::Window* w21 = root_window()->GetChildById(21); ActivateWindow(w2); // The enter event should not focus the window. ui::test::EventGenerator generator(root_window(), w21); generator.SendMouseEnter(); EXPECT_EQ(w2, GetFocusedWindow()); } base::test::ScopedFeatureList scoped_feature_list_; }; class FocusControllerGestureEventTest : public FocusControllerDirectTestBase { public: FocusControllerGestureEventTest() {} FocusControllerGestureEventTest(const FocusControllerGestureEventTest&) = delete; FocusControllerGestureEventTest& operator=( const FocusControllerGestureEventTest&) = delete; private: // Overridden from FocusControllerTestBase: void FocusWindowDirect(aura::Window* window) override { ui::test::EventGenerator generator(root_window(), window); generator.GestureTapAt(window->bounds().CenterPoint()); } void ActivateWindowDirect(aura::Window* window) override { ui::test::EventGenerator generator(root_window(), window); generator.GestureTapAt(window->bounds().CenterPoint()); } void DeactivateWindowDirect(aura::Window* window) override { aura::Window* next_activatable = test_focus_rules()->GetNextActivatableWindow(window); ui::test::EventGenerator generator(root_window(), next_activatable); generator.GestureTapAt(window->bounds().CenterPoint()); } bool IsInputEvent() override { return true; } ActivationChangeObserver::ActivationReason GetExpectedActivationReason() const override { return ActivationChangeObserver::ActivationReason::INPUT_EVENT; } }; // Test base for tests where focus is implicitly set to a window as the result // of a disposition change to the focused window or the hierarchy that contains // it. class FocusControllerImplicitTestBase : public FocusControllerTestBase { public: FocusControllerImplicitTestBase(const FocusControllerImplicitTestBase&) = delete; FocusControllerImplicitTestBase& operator=( const FocusControllerImplicitTestBase&) = delete; protected: explicit FocusControllerImplicitTestBase(bool parent) : parent_(parent) {} aura::Window* GetDispositionWindow(aura::Window* window) { return parent_ ? window->parent() : window; } // Returns the expected ActivationReason caused by calling the // ActivatedWindowDirect(...) or DeactivateWindowDirect(...) methods. ActivationChangeObserver::ActivationReason GetExpectedActivationReason() const { return ActivationChangeObserver::ActivationReason:: WINDOW_DISPOSITION_CHANGED; } // Change the disposition of |window| in such a way as it will lose focus. virtual void ChangeWindowDisposition(aura::Window* window) = 0; // Allow each disposition change test to add additional post-disposition // change expectations. virtual void PostDispositionChangeExpectations() {} // Overridden from FocusControllerTestBase: void BasicFocus() override { EXPECT_FALSE(GetFocusedWindow()); aura::Window* w211 = root_window()->GetChildById(211); FocusWindow(w211); EXPECT_EQ(211, GetFocusedWindowId()); ChangeWindowDisposition(w211); // BasicFocusRules passes focus to the parent. EXPECT_EQ(parent_ ? 2 : 21, GetFocusedWindowId()); } void BasicActivation() override { DCHECK(!parent_) << "Activation tests don't support parent changes."; EXPECT_FALSE(GetActiveWindow()); aura::Window* w2 = root_window()->GetChildById(2); ActivateWindow(w2); EXPECT_EQ(2, GetActiveWindowId()); ChangeWindowDisposition(w2); EXPECT_EQ(3, GetActiveWindowId()); PostDispositionChangeExpectations(); } void FocusEvents() override { aura::Window* w211 = root_window()->GetChildById(211); FocusWindow(w211); ScopedFocusNotificationObserver root_observer(root_window()); ScopedTargetFocusNotificationObserver observer211(root_window(), 211); root_observer.ExpectCounts(0, 0); observer211.ExpectCounts(0, 0); ChangeWindowDisposition(w211); root_observer.ExpectCounts(0, 1); observer211.ExpectCounts(0, 1); } void ActivationEvents() override { DCHECK(!parent_) << "Activation tests don't support parent changes."; aura::Window* w2 = root_window()->GetChildById(2); ActivateWindow(w2); ScopedFocusNotificationObserver root_observer(root_window()); ScopedTargetFocusNotificationObserver observer2(root_window(), 2); ScopedTargetFocusNotificationObserver observer3(root_window(), 3); root_observer.ExpectCounts(0, 0); observer2.ExpectCounts(0, 0); observer3.ExpectCounts(0, 0); ChangeWindowDisposition(w2); root_observer.ExpectCounts(1, 1); EXPECT_EQ(GetExpectedActivationReason(), root_observer.last_activation_reason()); observer2.ExpectCounts(1, 1); observer3.ExpectCounts(1, 1); } void FocusRulesOverride() override { EXPECT_FALSE(GetFocusedWindow()); aura::Window* w211 = root_window()->GetChildById(211); FocusWindow(w211); EXPECT_EQ(211, GetFocusedWindowId()); test_focus_rules()->set_focus_restriction(root_window()->GetChildById(11)); ChangeWindowDisposition(w211); // Normally, focus would shift to the parent (w21) but the override shifts // it to 11. EXPECT_EQ(11, GetFocusedWindowId()); test_focus_rules()->set_focus_restriction(nullptr); } void ActivationRulesOverride() override { DCHECK(!parent_) << "Activation tests don't support parent changes."; aura::Window* w1 = root_window()->GetChildById(1); ActivateWindow(w1); EXPECT_EQ(1, GetActiveWindowId()); EXPECT_EQ(1, GetFocusedWindowId()); aura::Window* w3 = root_window()->GetChildById(3); test_focus_rules()->set_focus_restriction(w3); // Normally, activation/focus would move to w2, but since we have a focus // restriction, it should move to w3 instead. ChangeWindowDisposition(w1); EXPECT_EQ(3, GetActiveWindowId()); EXPECT_EQ(3, GetFocusedWindowId()); test_focus_rules()->set_focus_restriction(nullptr); ActivateWindow(root_window()->GetChildById(2)); EXPECT_EQ(2, GetActiveWindowId()); EXPECT_EQ(2, GetFocusedWindowId()); } private: // When true, the disposition change occurs to the parent of the window // instead of to the window. This verifies that changes occurring in the // hierarchy that contains the window affect the window's focus. bool parent_; }; // Focus and Activation changes in response to window visibility changes. class FocusControllerHideTest : public FocusControllerImplicitTestBase { public: FocusControllerHideTest() : FocusControllerImplicitTestBase(false) {} FocusControllerHideTest(const FocusControllerHideTest&) = delete; FocusControllerHideTest& operator=(const FocusControllerHideTest&) = delete; protected: FocusControllerHideTest(bool parent) : FocusControllerImplicitTestBase(parent) {} // Overridden from FocusControllerImplicitTestBase: void ChangeWindowDisposition(aura::Window* window) override { GetDispositionWindow(window)->Hide(); } }; // Focus and Activation changes in response to window parent visibility // changes. class FocusControllerParentHideTest : public FocusControllerHideTest { public: FocusControllerParentHideTest() : FocusControllerHideTest(true) {} FocusControllerParentHideTest(const FocusControllerParentHideTest&) = delete; FocusControllerParentHideTest& operator=( const FocusControllerParentHideTest&) = delete; // The parent window's visibility change should not change its transient child // window's modality property. void TransientChildWindowActivationTest() { aura::Window* w1 = root_window()->GetChildById(1); aura::Window* w11 = root_window()->GetChildById(11); ::wm::AddTransientChild(w1, w11); w11->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_WINDOW); EXPECT_EQ(ui::MODAL_TYPE_NONE, w1->GetProperty(aura::client::kModalKey)); EXPECT_EQ(ui::MODAL_TYPE_WINDOW, w11->GetProperty(aura::client::kModalKey)); // Hide the parent window w1 and show it again. w1->Hide(); w1->Show(); // Test that child window w11 doesn't change its modality property. EXPECT_EQ(ui::MODAL_TYPE_NONE, w1->GetProperty(aura::client::kModalKey)); EXPECT_EQ(ui::MODAL_TYPE_WINDOW, w11->GetProperty(aura::client::kModalKey)); } }; // Focus and Activation changes in response to window destruction. class FocusControllerDestructionTest : public FocusControllerImplicitTestBase { public: FocusControllerDestructionTest() : FocusControllerImplicitTestBase(false) {} FocusControllerDestructionTest(const FocusControllerDestructionTest&) = delete; FocusControllerDestructionTest& operator=( const FocusControllerDestructionTest&) = delete; protected: FocusControllerDestructionTest(bool parent) : FocusControllerImplicitTestBase(parent) {} // Overridden from FocusControllerImplicitTestBase: void ChangeWindowDisposition(aura::Window* window) override { delete GetDispositionWindow(window); } }; // Focus and Activation changes in response to window parent destruction. class FocusControllerParentDestructionTest : public FocusControllerDestructionTest { public: FocusControllerParentDestructionTest() : FocusControllerDestructionTest(true) {} FocusControllerParentDestructionTest( const FocusControllerParentDestructionTest&) = delete; FocusControllerParentDestructionTest& operator=( const FocusControllerParentDestructionTest&) = delete; }; // Focus and Activation changes in response to window removal. class FocusControllerRemovalTest : public FocusControllerImplicitTestBase { public: FocusControllerRemovalTest() : FocusControllerImplicitTestBase(false) {} FocusControllerRemovalTest(const FocusControllerRemovalTest&) = delete; FocusControllerRemovalTest& operator=(const FocusControllerRemovalTest&) = delete; protected: FocusControllerRemovalTest(bool parent) : FocusControllerImplicitTestBase(parent) {} // Overridden from FocusControllerImplicitTestBase: void ChangeWindowDisposition(aura::Window* window) override { aura::Window* disposition_window = GetDispositionWindow(window); disposition_window->parent()->RemoveChild(disposition_window); window_owner_.reset(disposition_window); } void TearDown() override { window_owner_.reset(); FocusControllerImplicitTestBase::TearDown(); } private: std::unique_ptr<aura::Window> window_owner_; }; // Focus and Activation changes in response to window parent removal. class FocusControllerParentRemovalTest : public FocusControllerRemovalTest { public: FocusControllerParentRemovalTest() : FocusControllerRemovalTest(true) {} FocusControllerParentRemovalTest(const FocusControllerParentRemovalTest&) = delete; FocusControllerParentRemovalTest& operator=( const FocusControllerParentRemovalTest&) = delete; }; #define FOCUS_CONTROLLER_TEST(TESTCLASS, TESTNAME) \ TEST_F(TESTCLASS, TESTNAME) { TESTNAME(); } // Runs direct focus change tests (input events and API calls). #define DIRECT_FOCUS_CHANGE_TESTS(TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerApiTest, TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerMouseEventTest, TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerMouseEnterEventTest, TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerGestureEventTest, TESTNAME) // Runs implicit focus change tests for disposition changes to target. #define IMPLICIT_FOCUS_CHANGE_TARGET_TESTS(TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerHideTest, TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerDestructionTest, TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerRemovalTest, TESTNAME) // Runs implicit focus change tests for disposition changes to target's parent // hierarchy. #define IMPLICIT_FOCUS_CHANGE_PARENT_TESTS(TESTNAME) \ /* TODO(beng): parent destruction tests are not supported at \ present due to workspace manager issues. \ FOCUS_CONTROLLER_TEST(FocusControllerParentDestructionTest, TESTNAME) */ \ FOCUS_CONTROLLER_TEST(FocusControllerParentHideTest, TESTNAME) \ FOCUS_CONTROLLER_TEST(FocusControllerParentRemovalTest, TESTNAME) // Runs all implicit focus change tests (changes to the target and target's // parent hierarchy) #define IMPLICIT_FOCUS_CHANGE_TESTS(TESTNAME) \ IMPLICIT_FOCUS_CHANGE_TARGET_TESTS(TESTNAME) \ IMPLICIT_FOCUS_CHANGE_PARENT_TESTS(TESTNAME) // Runs all possible focus change tests. #define ALL_FOCUS_TESTS(TESTNAME) \ DIRECT_FOCUS_CHANGE_TESTS(TESTNAME) \ IMPLICIT_FOCUS_CHANGE_TESTS(TESTNAME) // Runs focus change tests that apply only to the target. For example, // implicit activation changes caused by window disposition changes do not // occur when changes to the containing hierarchy happen. #define TARGET_FOCUS_TESTS(TESTNAME) \ DIRECT_FOCUS_CHANGE_TESTS(TESTNAME) \ IMPLICIT_FOCUS_CHANGE_TARGET_TESTS(TESTNAME) // - Focuses a window, verifies that focus changed. ALL_FOCUS_TESTS(BasicFocus) // - Activates a window, verifies that activation changed. TARGET_FOCUS_TESTS(BasicActivation) // - Focuses a window, verifies that focus events were dispatched. ALL_FOCUS_TESTS(FocusEvents) // - Focuses or activates a window multiple times, verifies that events are only // dispatched when focus/activation actually changes. DIRECT_FOCUS_CHANGE_TESTS(DuplicateFocusEvents) DIRECT_FOCUS_CHANGE_TESTS(DuplicateActivationEvents) // - Activates a window, verifies that activation events were dispatched. TARGET_FOCUS_TESTS(ActivationEvents) // - Attempts to active a hidden window, verifies that current window is // attempted to be reactivated and the appropriate event dispatched. FOCUS_CONTROLLER_TEST(FocusControllerApiTest, ReactivationEvents) // - Input events/API calls shift focus between focusable windows within the // active window. DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusWithinActiveWindow) // - Input events/API calls to a child window of an inactive window shifts // activation to the activatable parent and focuses the child. DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusToChildOfInactiveWindow) // - Input events/API calls to focus the parent of the focused window do not // shift focus away from the child. DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusToParentOfFocusedWindow) // - Verifies that FocusRules determine what can be focused. ALL_FOCUS_TESTS(FocusRulesOverride) // - Verifies that FocusRules determine what can be activated. TARGET_FOCUS_TESTS(ActivationRulesOverride) // - Verifies that attempts to change focus or activation from a focus or // activation change observer are ignored. DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusOnActivation) DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusOnActivationDueToHide) DIRECT_FOCUS_CHANGE_TESTS(NoShiftActiveOnActivation) FOCUS_CONTROLLER_TEST(FocusControllerApiTest, FocusChangeDuringDrag) FOCUS_CONTROLLER_TEST(FocusControllerApiTest, ChangeFocusWhenNothingFocusedAndCaptured) // See description above DontPassDeletedWindow() for details. FOCUS_CONTROLLER_TEST(FocusControllerApiTest, DontPassDeletedWindow) FOCUS_CONTROLLER_TEST(FocusControllerApiTest, StackWindowAtTopOnActivation) FOCUS_CONTROLLER_TEST(FocusControllerApiTest, HideFocusedWindowDuringActivationLoss) FOCUS_CONTROLLER_TEST(FocusControllerApiTest, ActivateWhileActivating) // See description above TransientChildWindowActivationTest() for details. FOCUS_CONTROLLER_TEST(FocusControllerParentHideTest, TransientChildWindowActivationTest) // If a mouse event was handled, it should not activate a window. FOCUS_CONTROLLER_TEST(FocusControllerMouseEventTest, IgnoreHandledEvent) // Mouse over window should activate it. FOCUS_CONTROLLER_TEST(FocusControllerMouseEnterEventTest, MouseEnteredEvent) // Mouse over window with active parent should not focus it. FOCUS_CONTROLLER_TEST(FocusControllerMouseEnterEventTest, MouseEnteredWithActiveParent) } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/focus_controller_unittest.cc
C++
unknown
64,278
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_FOCUS_RULES_H_ #define UI_WM_CORE_FOCUS_RULES_H_ #include "base/component_export.h" namespace aura { class Window; } namespace ui { class Event; } namespace wm { // Implemented by an object that establishes the rules about what can be // focused or activated. class COMPONENT_EXPORT(UI_WM) FocusRules { public: virtual ~FocusRules() {} // Returns true if |window| is a toplevel window. Whether or not a window // is considered toplevel is determined by a similar set of rules that // govern activation and focus. Not all toplevel windows are activatable, // call CanActivateWindow() to determine if a window can be activated. virtual bool IsToplevelWindow(const aura::Window* window) const = 0; // Returns true if |window| can be activated or focused. virtual bool CanActivateWindow(const aura::Window* window) const = 0; // For CanFocusWindow(), NULL window is supported, because NULL is a valid // focusable window (in the case of clearing focus). // If |event| is non-null it is the event triggering the focus change. virtual bool CanFocusWindow(const aura::Window* window, const ui::Event* event) const = 0; // Returns the toplevel window containing |window|. Not all toplevel windows // are activatable, call GetActivatableWindow() instead to return the // activatable window, which might be in a different hierarchy. // Will return NULL if |window| is not contained by a window considered to be // a toplevel window. virtual const aura::Window* GetToplevelWindow( const aura::Window* window) const = 0; // Returns the activatable or focusable window given an attempt to activate or // focus |window|. Some possible scenarios (not intended to be exhaustive): // - |window| is a child of a non-focusable window and so focus must be set // according to rules defined by the delegate, e.g. to a parent. // - |window| is an activatable window that is the transient parent of a modal // window, so attempts to activate |window| should result in the modal // transient being activated instead. // These methods may return NULL if they are unable to find an activatable // or focusable window given |window|. virtual aura::Window* GetActivatableWindow(aura::Window* window) const = 0; virtual aura::Window* GetFocusableWindow(aura::Window* window) const = 0; // Returns the next window to activate in the event that |ignore| is no longer // activatable. This function is called when something is happening to // |ignore| that means it can no longer have focus or activation, including // but not limited to: // - it or its parent hierarchy is being hidden, or removed from the // RootWindow. // - it is being destroyed. // - it is being explicitly deactivated. // |ignore| cannot be NULL. virtual aura::Window* GetNextActivatableWindow( aura::Window* ignore) const = 0; }; } // namespace wm #endif // UI_WM_CORE_FOCUS_RULES_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/focus_rules.h
C++
unknown
3,130
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/ime_util_chromeos.h" #include "ui/aura/client/aura_constants.h" #include "ui/base/ui_base_switches.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/geometry/rect.h" #include "ui/wm/core/coordinate_conversion.h" namespace wm { namespace { void SetWindowBoundsInScreen(aura::Window* window, const gfx::Rect& bounds_in_screen) { window->SetBoundsInScreen( bounds_in_screen, display::Screen::GetScreen()->GetDisplayNearestView(window)); } // Moves the window to ensure caret not in rect. // Returns whether the window was moved or not. void MoveWindowToEnsureCaretNotInRect(aura::Window* window, const gfx::Rect& rect_in_screen) { gfx::Rect original_window_bounds = window->GetBoundsInScreen(); if (window->GetProperty(kVirtualKeyboardRestoreBoundsKey)) { original_window_bounds = *window->GetProperty(kVirtualKeyboardRestoreBoundsKey); } // Calculate vertical window shift. const int top_y = std::max(rect_in_screen.y() - original_window_bounds.height(), display::Screen::GetScreen() ->GetDisplayNearestView(window) .work_area() .y()); // No need to move the window up. if (top_y >= original_window_bounds.y()) return; // Set restore bounds and move the window. window->SetProperty(kVirtualKeyboardRestoreBoundsKey, std::make_unique<gfx::Rect>(original_window_bounds)); gfx::Rect new_bounds_in_screen = original_window_bounds; new_bounds_in_screen.set_y(top_y); SetWindowBoundsInScreen(window, new_bounds_in_screen); } } // namespace DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(gfx::Rect, kVirtualKeyboardRestoreBoundsKey, nullptr) void RestoreWindowBoundsOnClientFocusLost(aura::Window* window) { // Get restore bounds of the window gfx::Rect* vk_restore_bounds = window->GetProperty(kVirtualKeyboardRestoreBoundsKey); if (!vk_restore_bounds) return; // Restore the window bounds // TODO(yhanada): Don't move the window if a user has moved it while the // keyboard is shown. if (window->GetBoundsInScreen() != *vk_restore_bounds) { SetWindowBoundsInScreen(window, *vk_restore_bounds); } window->ClearProperty(wm::kVirtualKeyboardRestoreBoundsKey); } void EnsureWindowNotInRect(aura::Window* window, const gfx::Rect& rect_in_screen) { gfx::Rect original_window_bounds = window->GetBoundsInScreen(); if (window->GetProperty(wm::kVirtualKeyboardRestoreBoundsKey)) { original_window_bounds = *window->GetProperty(wm::kVirtualKeyboardRestoreBoundsKey); } gfx::Rect hidden_window_bounds_in_screen = gfx::IntersectRects(rect_in_screen, original_window_bounds); if (hidden_window_bounds_in_screen.IsEmpty()) { // The window isn't covered by the keyboard, restore the window position if // necessary. RestoreWindowBoundsOnClientFocusLost(window); return; } MoveWindowToEnsureCaretNotInRect(window, rect_in_screen); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/ime_util_chromeos.cc
C++
unknown
3,330
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_IME_UTIL_CHROMEOS_H_ #define UI_WM_CORE_IME_UTIL_CHROMEOS_H_ #include "base/component_export.h" #include "ui/aura/window.h" namespace gfx { class Rect; } namespace wm { // A property key to store the restore bounds for a window when moved by the // virtual keyboard. COMPONENT_EXPORT(UI_WM) extern const aura::WindowProperty<gfx::Rect*>* const kVirtualKeyboardRestoreBoundsKey; // Moves |window| to ensure it does not intersect with |rect_in_screen|. COMPONENT_EXPORT(UI_WM) void EnsureWindowNotInRect(aura::Window* window, const gfx::Rect& rect_in_screen); // Restores the window bounds when input client loses the focus on the window. COMPONENT_EXPORT(UI_WM) void RestoreWindowBoundsOnClientFocusLost(aura::Window* top_level_window); } // namespace wm #endif // UI_WM_CORE_IME_UTIL_CHROMEOS_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/ime_util_chromeos.h
C++
unknown
1,000
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/ime_util_chromeos.h" #include "base/command_line.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_screen.h" #include "ui/aura/test/test_windows.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/geometry/insets.h" namespace wm { using ImeUtilChromeosTest = aura::test::AuraTestBase; TEST_F(ImeUtilChromeosTest, RestoreWindowBounds) { const gfx::Rect bounds(10, 20, 100, 200); aura::Window* window = aura::test::CreateTestWindowWithBounds(bounds, root_window()); EXPECT_EQ(nullptr, window->GetProperty(kVirtualKeyboardRestoreBoundsKey)); EXPECT_EQ(bounds, window->bounds()); RestoreWindowBoundsOnClientFocusLost(window); EXPECT_EQ(bounds, window->bounds()); gfx::Rect r1(40, 50, 150, 200); window->SetProperty(kVirtualKeyboardRestoreBoundsKey, r1); RestoreWindowBoundsOnClientFocusLost(window); EXPECT_EQ(r1, window->bounds()); EXPECT_EQ(nullptr, window->GetProperty(kVirtualKeyboardRestoreBoundsKey)); } TEST_F(ImeUtilChromeosTest, EnsureWindowNotInRect_NotCovered) { const gfx::Rect bounds(0, 0, 100, 200); aura::Window* window = aura::test::CreateTestWindowWithBounds(bounds, root_window()); EXPECT_EQ(bounds, window->bounds()); EXPECT_EQ(bounds, window->GetBoundsInScreen()); // The rect doesn't overlap on the window. gfx::Rect rect(300, 300, 100, 100); EXPECT_TRUE(gfx::IntersectRects(window->GetBoundsInScreen(), rect).IsEmpty()); EnsureWindowNotInRect(window, rect); // The bounds should not be changed. EXPECT_EQ(bounds, window->bounds()); EXPECT_EQ(bounds, window->GetBoundsInScreen()); } TEST_F(ImeUtilChromeosTest, EnsureWindowNotInRect_MoveUp) { const gfx::Rect original_bounds(10, 100, 100, 10); aura::Window* window = aura::test::CreateTestWindowWithBounds(original_bounds, root_window()); EXPECT_EQ(original_bounds, window->bounds()); EXPECT_EQ(original_bounds, window->GetBoundsInScreen()); // The rect overlaps the window. The window is moved up by // EnsureWindowNotInRect. gfx::Rect rect(50, 50, 200, 200); EXPECT_FALSE( gfx::IntersectRects(window->GetBoundsInScreen(), rect).IsEmpty()); EnsureWindowNotInRect(window, rect); EXPECT_EQ(gfx::Rect(10, 40, 100, 10), window->bounds()); EXPECT_EQ(gfx::Rect(10, 40, 100, 10), window->GetBoundsInScreen()); } TEST_F(ImeUtilChromeosTest, EnsureWindowNotInRect_MoveToTop) { const gfx::Rect original_bounds(10, 10, 100, 100); aura::Window* window = aura::test::CreateTestWindowWithBounds(original_bounds, root_window()); EXPECT_EQ(original_bounds, window->bounds()); EXPECT_EQ(original_bounds, window->GetBoundsInScreen()); // The rect overlaps the window. The window is moved up by // EnsureWinodwNotInRect, but there is not enough space above the window. gfx::Rect rect(50, 50, 200, 200); EXPECT_FALSE( gfx::IntersectRects(window->GetBoundsInScreen(), rect).IsEmpty()); EnsureWindowNotInRect(window, rect); EXPECT_EQ(gfx::Rect(10, 0, 100, 100), window->bounds()); EXPECT_EQ(gfx::Rect(10, 0, 100, 100), window->GetBoundsInScreen()); RestoreWindowBoundsOnClientFocusLost(window); // Sets a workspace insets to simulate that something (such as docked // magnifier) occupies some space on top. Original bounds must be inside // the new work area. constexpr int kOccupiedTopHeight = 5; ASSERT_GE(original_bounds.y(), kOccupiedTopHeight); test_screen()->SetWorkAreaInsets( gfx::Insets::TLBR(kOccupiedTopHeight, 0, 0, 0)); EnsureWindowNotInRect(window, rect); EXPECT_EQ(gfx::Rect(10, kOccupiedTopHeight, 100, 100), window->bounds()); } TEST_F(ImeUtilChromeosTest, MoveUpThenRestore) { const gfx::Rect original_bounds(50, 50, 100, 100); aura::Window* window = aura::test::CreateTestWindowWithBounds(original_bounds, root_window()); EXPECT_EQ(original_bounds, window->bounds()); EXPECT_EQ(original_bounds, window->GetBoundsInScreen()); // EnsureWindowNotInRect moves up the window. gfx::Rect rect(50, 50, 200, 200); EXPECT_FALSE( gfx::IntersectRects(window->GetBoundsInScreen(), rect).IsEmpty()); EnsureWindowNotInRect(window, rect); EXPECT_EQ(gfx::Rect(50, 0, 100, 100), window->bounds()); EXPECT_EQ(gfx::Rect(50, 0, 100, 100), window->GetBoundsInScreen()); // The new rect doesn't overlap the moved window bounds, but still overlaps // the original window bounds. rect = gfx::Rect(50, 120, 200, 200); EXPECT_FALSE(gfx::IntersectRects(rect, original_bounds).IsEmpty()); EnsureWindowNotInRect(window, rect); EXPECT_EQ(gfx::Rect(50, 20, 100, 100), window->bounds()); EXPECT_EQ(gfx::Rect(50, 20, 100, 100), window->GetBoundsInScreen()); // Now the rect doesn't overlap the original window bounds. The original // window bounds should be restored. rect = gfx::Rect(200, 200, 200, 200); EXPECT_TRUE(gfx::IntersectRects(rect, original_bounds).IsEmpty()); EnsureWindowNotInRect(window, rect); EXPECT_EQ(original_bounds, window->bounds()); EXPECT_EQ(original_bounds, window->GetBoundsInScreen()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/ime_util_chromeos_unittest.cc
C++
unknown
5,276
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_NATIVE_CURSOR_MANAGER_H_ #define UI_WM_CORE_NATIVE_CURSOR_MANAGER_H_ #include "base/component_export.h" #include "ui/wm/core/native_cursor_manager_delegate.h" namespace display { class Display; } namespace ui { enum class CursorSize; } namespace wm { // Interface where platforms such as Ash or Desktop aura are notified of // requested changes to cursor state. When requested, implementer should tell // the CursorManager of any actual state changes performed through the // delegate. class COMPONENT_EXPORT(UI_WM) NativeCursorManager { public: virtual ~NativeCursorManager() {} // A request to set the screen DPI. Can cause changes in the current cursor. virtual void SetDisplay(const display::Display& display, NativeCursorManagerDelegate* delegate) = 0; // A request to set the cursor to |cursor|. At minimum, implementer should // call NativeCursorManagerDelegate::CommitCursor() with whatever cursor is // actually used. virtual void SetCursor( gfx::NativeCursor cursor, NativeCursorManagerDelegate* delegate) = 0; // A request to set the visibility of the cursor. At minimum, implementer // should call NativeCursorManagerDelegate::CommitVisibility() with whatever // the visibility is. virtual void SetVisibility( bool visible, NativeCursorManagerDelegate* delegate) = 0; // A request to set the cursor set. virtual void SetCursorSize(ui::CursorSize cursor_size, NativeCursorManagerDelegate* delegate) = 0; // A request to set whether mouse events are disabled. At minimum, // implementer should call NativeCursorManagerDelegate:: // CommitMouseEventsEnabled() with whether mouse events are actually enabled. virtual void SetMouseEventsEnabled( bool enabled, NativeCursorManagerDelegate* delegate) = 0; }; } // namespace wm #endif // UI_WM_CORE_NATIVE_CURSOR_MANAGER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/native_cursor_manager.h
C++
unknown
2,077
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_NATIVE_CURSOR_MANAGER_DELEGATE_H_ #define UI_WM_CORE_NATIVE_CURSOR_MANAGER_DELEGATE_H_ #include "base/component_export.h" #include "ui/gfx/native_widget_types.h" namespace gfx { class Size; } namespace ui { enum class CursorSize; } namespace wm { // The non-public interface that CursorManager exposes to its users. This // gives accessors to all the current state, and mutators to all the current // state. class COMPONENT_EXPORT(UI_WM) NativeCursorManagerDelegate { public: virtual ~NativeCursorManagerDelegate() {} // TODO(tdanderson): Possibly remove this interface. virtual gfx::NativeCursor GetCursor() const = 0; virtual bool IsCursorVisible() const = 0; virtual void CommitCursor(gfx::NativeCursor cursor) = 0; virtual void CommitVisibility(bool visible) = 0; virtual void CommitCursorSize(ui::CursorSize cursor_size) = 0; virtual void CommitMouseEventsEnabled(bool enabled) = 0; virtual void CommitSystemCursorSize(const gfx::Size& cursor_size) = 0; }; } // namespace wm #endif // UI_WM_CORE_NATIVE_CURSOR_MANAGER_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/native_cursor_manager_delegate.h
C++
unknown
1,228
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/shadow_controller.h" #include <utility> #include "base/check.h" #include "base/command_line.h" #include "base/containers/contains.h" #include "base/containers/flat_set.h" #include "base/memory/raw_ptr.h" #include "base/no_destructor.h" #include "base/scoped_multi_source_observation.h" #include "build/chromeos_buildflags.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/env.h" #include "ui/aura/env_observer.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #include "ui/base/class_property.h" #include "ui/base/ui_base_types.h" #include "ui/compositor/layer.h" #include "ui/compositor_extra/shadow.h" #include "ui/wm/core/shadow_controller_delegate.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/activation_client.h" using std::make_pair; DEFINE_UI_CLASS_PROPERTY_TYPE(ui::Shadow*) DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(ui::Shadow, kShadowLayerKey, nullptr) namespace wm { namespace { int GetShadowElevationForActiveState(aura::Window* window) { int elevation = window->GetProperty(kShadowElevationKey); if (elevation != kShadowElevationDefault) return elevation; if (IsActiveWindow(window)) return kShadowElevationActiveWindow; return GetDefaultShadowElevationForWindow(window); } // Returns the shadow style to be applied to |losing_active| when it is losing // active to |gaining_active|. |gaining_active| may be of a type that hides when // inactive, and as such we do not want to render |losing_active| as inactive. int GetShadowElevationForWindowLosingActive(aura::Window* losing_active, aura::Window* gaining_active) { if (gaining_active && GetHideOnDeactivate(gaining_active)) { if (base::Contains(GetTransientChildren(losing_active), gaining_active)) return kShadowElevationActiveWindow; } return kShadowElevationInactiveWindow; } } // namespace // ShadowController::Impl ------------------------------------------------------ // Real implementation of the ShadowController. ShadowController observes // ActivationChangeObserver, which are per ActivationClient, where as there is // only a single Impl (as it observes all window creation by way of an // EnvObserver). class ShadowController::Impl : public aura::EnvObserver, public aura::WindowObserver, public base::RefCounted<Impl> { public: // Returns the singleton instance for the specified Env. static Impl* GetInstance(aura::Env* env); Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; void set_delegate(std::unique_ptr<ShadowControllerDelegate> delegate) { delegate_ = std::move(delegate); } bool IsShadowVisibleForWindow(aura::Window* window); void UpdateShadowForWindow(aura::Window* window); // aura::EnvObserver override: void OnWindowInitialized(aura::Window* window) override; // aura::WindowObserver overrides: void OnWindowParentChanged(aura::Window* window, aura::Window* parent) override; void OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) override; void OnWindowVisibilityChanging(aura::Window* window, bool visible) override; void OnWindowBoundsChanged(aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) override; void OnWindowDestroyed(aura::Window* window) override; private: friend class base::RefCounted<Impl>; friend class ShadowController; explicit Impl(aura::Env* env); ~Impl() override; static base::flat_set<Impl*>* GetInstances(); // Forwarded from ShadowController. void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active); // Checks if |window| is visible and contains a property requesting a shadow. bool ShouldShowShadowForWindow(aura::Window* window) const; // Updates the shadow for windows when activation changes. void HandleWindowActivationChange(aura::Window* gaining_active, aura::Window* losing_active); // Shows or hides |window|'s shadow as needed (creating the shadow if // necessary). void HandlePossibleShadowVisibilityChange(aura::Window* window); // Creates a new shadow for |window| and stores it with the |kShadowLayerKey| // key. // The shadow's bounds are initialized and it is added to the window's layer. void CreateShadowForWindow(aura::Window* window); const raw_ptr<aura::Env> env_; base::ScopedMultiSourceObservation<aura::Window, aura::WindowObserver> observation_manager_{this}; std::unique_ptr<ShadowControllerDelegate> delegate_; }; // static ShadowController::Impl* ShadowController::Impl::GetInstance(aura::Env* env) { for (Impl* impl : *GetInstances()) { if (impl->env_ == env) return impl; } return new Impl(env); } bool ShadowController::Impl::IsShadowVisibleForWindow(aura::Window* window) { if (!observation_manager_.IsObservingSource(window)) return false; ui::Shadow* shadow = GetShadowForWindow(window); return shadow && shadow->layer()->visible(); } void ShadowController::Impl::UpdateShadowForWindow(aura::Window* window) { DCHECK(observation_manager_.IsObservingSource(window)); HandlePossibleShadowVisibilityChange(window); } void ShadowController::Impl::OnWindowInitialized(aura::Window* window) { // During initialization, the window can't reliably tell whether it will be a // root window. That must be checked in the first visibility change DCHECK(!window->parent()); DCHECK(!window->TargetVisibility()); observation_manager_.AddObservation(window); } void ShadowController::Impl::OnWindowParentChanged(aura::Window* window, aura::Window* parent) { if (parent && window->IsVisible()) HandlePossibleShadowVisibilityChange(window); } void ShadowController::Impl::OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) { bool shadow_will_change = key == kShadowElevationKey && window->GetProperty(kShadowElevationKey) != old; if (key == aura::client::kShowStateKey) { shadow_will_change = window->GetProperty(aura::client::kShowStateKey) != static_cast<ui::WindowShowState>(old); } // Check the target visibility. IsVisible() may return false if a parent layer // is hidden, but |this| only observes calls to Show()/Hide() on |window|. if (shadow_will_change && window->TargetVisibility()) HandlePossibleShadowVisibilityChange(window); } void ShadowController::Impl::OnWindowVisibilityChanging(aura::Window* window, bool visible) { // At the time of the first visibility change, |window| will give a correct // answer for whether or not it is a root window. If it is, don't bother // observing: a shadow should never be added. Root windows can only have // shadows in the WindowServer (where a corresponding aura::Window may no // longer be a root window). Without this check, a second shadow is added, // which clips to the root window bounds; filling any rounded corners the // window may have. if (window->IsRootWindow()) { observation_manager_.RemoveObservation(window); return; } HandlePossibleShadowVisibilityChange(window); } void ShadowController::Impl::OnWindowBoundsChanged( aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) { ui::Shadow* shadow = GetShadowForWindow(window); if (shadow && window->GetProperty(aura::client::kUseWindowBoundsForShadow)) shadow->SetContentBounds(gfx::Rect(new_bounds.size())); } void ShadowController::Impl::OnWindowDestroyed(aura::Window* window) { window->ClearProperty(kShadowLayerKey); observation_manager_.RemoveObservation(window); } void ShadowController::Impl::OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) { if (gained_active) { ui::Shadow* shadow = GetShadowForWindow(gained_active); if (shadow) shadow->SetElevation(GetShadowElevationForActiveState(gained_active)); } if (lost_active) { ui::Shadow* shadow = GetShadowForWindow(lost_active); if (shadow && GetShadowElevationConvertDefault(lost_active) == kShadowElevationInactiveWindow) { shadow->SetElevation( GetShadowElevationForWindowLosingActive(lost_active, gained_active)); } } } bool ShadowController::Impl::ShouldShowShadowForWindow( aura::Window* window) const { if (delegate_) { const bool should_show = delegate_->ShouldShowShadowForWindow(window); if (should_show) DCHECK(GetShadowElevationConvertDefault(window) > 0); return should_show; } ui::WindowShowState show_state = window->GetProperty(aura::client::kShowStateKey); if (show_state == ui::SHOW_STATE_FULLSCREEN || show_state == ui::SHOW_STATE_MAXIMIZED) { return false; } return GetShadowElevationConvertDefault(window) > 0; } void ShadowController::Impl::HandlePossibleShadowVisibilityChange( aura::Window* window) { const bool should_show = ShouldShowShadowForWindow(window); ui::Shadow* shadow = GetShadowForWindow(window); if (shadow) { shadow->SetElevation(GetShadowElevationForActiveState(window)); shadow->layer()->SetVisible(should_show); } else if (should_show) { CreateShadowForWindow(window); } } void ShadowController::Impl::CreateShadowForWindow(aura::Window* window) { DCHECK(!window->IsRootWindow()); ui::Shadow* shadow = window->SetProperty(kShadowLayerKey, std::make_unique<ui::Shadow>()); int corner_radius = window->GetProperty(aura::client::kWindowCornerRadiusKey); if (corner_radius >= 0) shadow->SetRoundedCornerRadius(corner_radius); shadow->Init(GetShadowElevationForActiveState(window)); #if BUILDFLAG(IS_CHROMEOS_ASH) shadow->SetShadowStyle(gfx::ShadowStyle::kChromeOSSystemUI); #endif shadow->SetContentBounds(gfx::Rect(window->bounds().size())); shadow->layer()->SetVisible(ShouldShowShadowForWindow(window)); window->layer()->Add(shadow->layer()); window->layer()->StackAtBottom(shadow->layer()); } ShadowController::Impl::Impl(aura::Env* env) : env_(env), observation_manager_(this) { GetInstances()->insert(this); env_->AddObserver(this); } ShadowController::Impl::~Impl() { env_->RemoveObserver(this); GetInstances()->erase(this); } // static base::flat_set<ShadowController::Impl*>* ShadowController::Impl::GetInstances() { static base::NoDestructor<base::flat_set<Impl*>> impls; return impls.get(); } // ShadowController ------------------------------------------------------------ ui::Shadow* ShadowController::GetShadowForWindow(aura::Window* window) { return window->GetProperty(kShadowLayerKey); } ShadowController::ShadowController( ActivationClient* activation_client, std::unique_ptr<ShadowControllerDelegate> delegate, aura::Env* env) : activation_client_(activation_client), impl_(Impl::GetInstance(env ? env : aura::Env::GetInstance())) { // Watch for window activation changes. activation_client_->AddObserver(this); if (delegate) impl_->set_delegate(std::move(delegate)); } ShadowController::~ShadowController() { activation_client_->RemoveObserver(this); } bool ShadowController::IsShadowVisibleForWindow(aura::Window* window) { return impl_->IsShadowVisibleForWindow(window); } void ShadowController::UpdateShadowForWindow(aura::Window* window) { impl_->UpdateShadowForWindow(window); } void ShadowController::OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) { impl_->OnWindowActivated(reason, gained_active, lost_active); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/shadow_controller.cc
C++
unknown
12,498
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_SHADOW_CONTROLLER_H_ #define UI_WM_CORE_SHADOW_CONTROLLER_H_ #include <map> #include <memory> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "ui/wm/public/activation_change_observer.h" namespace aura { class Env; class Window; } namespace ui { class Shadow; } namespace wm { class ActivationClient; class ShadowControllerDelegate; // ShadowController observes changes to windows and creates and updates drop // shadows as needed. ShadowController itself is light weight and per // ActivationClient. ShadowController delegates to its implementation class, // which observes all window creation. class COMPONENT_EXPORT(UI_WM) ShadowController : public ActivationChangeObserver { public: // Returns the shadow for the |window|, or NULL if no shadow exists. static ui::Shadow* GetShadowForWindow(aura::Window* window); ShadowController(ActivationClient* activation_client, std::unique_ptr<ShadowControllerDelegate> delegate, aura::Env* env = nullptr); ShadowController(const ShadowController&) = delete; ShadowController& operator=(const ShadowController&) = delete; ~ShadowController() override; bool IsShadowVisibleForWindow(aura::Window* window); // Updates the shadow for |window|. Does nothing if |window| is not observed // by the shadow controller impl. This function should be called if the shadow // needs to be modified outside of normal window changes (eg. window // activation, window property change). void UpdateShadowForWindow(aura::Window* window); // ActivationChangeObserver overrides: void OnWindowActivated(ActivationChangeObserver::ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override; private: class Impl; raw_ptr<ActivationClient> activation_client_; scoped_refptr<Impl> impl_; }; } // namespace wm #endif // UI_WM_CORE_SHADOW_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/shadow_controller.h
C++
unknown
2,177
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_SHADOW_CONTROLLER_DELEGATE_H_ #define UI_WM_CORE_SHADOW_CONTROLLER_DELEGATE_H_ #include "base/component_export.h" namespace aura { class Window; } namespace wm { // ShadowControllerDelegate allows a user to modify a shadow on certain windows // differently from the normal use case. class COMPONENT_EXPORT(UI_WM) ShadowControllerDelegate { public: ShadowControllerDelegate() = default; virtual ~ShadowControllerDelegate() = default; // Invoked when the shadow on |window| is to be modified, either normally from // activation change or manually. virtual bool ShouldShowShadowForWindow(const aura::Window* window) = 0; }; } // namespace wm #endif // UI_WM_CORE_SHADOW_CONTROLLER_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/shadow_controller_delegate.h
C++
unknown
873
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/shadow_controller.h" #include <algorithm> #include <memory> #include <vector> #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/window_parenting_client.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/compositor/layer.h" #include "ui/compositor_extra/shadow.h" #include "ui/wm/core/shadow_controller_delegate.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/activation_client.h" namespace wm { class ShadowControllerTest : public aura::test::AuraTestBase { public: ShadowControllerTest() {} ShadowControllerTest(const ShadowControllerTest&) = delete; ShadowControllerTest& operator=(const ShadowControllerTest&) = delete; ~ShadowControllerTest() override {} void SetUp() override { AuraTestBase::SetUp(); InstallShadowController(nullptr); } void TearDown() override { shadow_controller_.reset(); AuraTestBase::TearDown(); } protected: ShadowController* shadow_controller() { return shadow_controller_.get(); } void ActivateWindow(aura::Window* window) { DCHECK(window); DCHECK(window->GetRootWindow()); GetActivationClient(window->GetRootWindow())->ActivateWindow(window); } void InstallShadowController( std::unique_ptr<ShadowControllerDelegate> delegate) { shadow_controller_ = std::make_unique<ShadowController>( GetActivationClient(root_window()), std::move(delegate)); } private: std::unique_ptr<ShadowController> shadow_controller_; }; // Tests that various methods in Window update the Shadow object as expected. TEST_F(ShadowControllerTest, Shadow) { std::unique_ptr<aura::Window> window(new aura::Window(NULL)); window->SetType(aura::client::WINDOW_TYPE_NORMAL); window->Init(ui::LAYER_TEXTURED); ParentWindow(window.get()); // The shadow is not created until the Window is shown (some Windows should // never get shadows, which is checked when the window first becomes visible). EXPECT_FALSE(ShadowController::GetShadowForWindow(window.get())); window->Show(); const ui::Shadow* shadow = ShadowController::GetShadowForWindow(window.get()); ASSERT_TRUE(shadow != NULL); EXPECT_TRUE(shadow->layer()->visible()); // The shadow should remain visible after window visibility changes. window->Hide(); EXPECT_TRUE(shadow->layer()->visible()); // If the shadow is disabled, it should be hidden. SetShadowElevation(window.get(), kShadowElevationNone); window->Show(); EXPECT_FALSE(shadow->layer()->visible()); SetShadowElevation(window.get(), kShadowElevationInactiveWindow); EXPECT_TRUE(shadow->layer()->visible()); // The shadow's layer should be a child of the window's layer. EXPECT_EQ(window->layer(), shadow->layer()->parent()); } // Tests that the window's shadow's bounds are updated correctly. TEST_F(ShadowControllerTest, ShadowBounds) { std::unique_ptr<aura::Window> window(new aura::Window(NULL)); window->SetType(aura::client::WINDOW_TYPE_NORMAL); window->Init(ui::LAYER_TEXTURED); ParentWindow(window.get()); window->Show(); const gfx::Rect kOldBounds(20, 30, 400, 300); window->SetBounds(kOldBounds); // When the shadow is first created, it should use the window's size (but // remain at the origin, since it's a child of the window's layer). SetShadowElevation(window.get(), kShadowElevationInactiveWindow); const ui::Shadow* shadow = ShadowController::GetShadowForWindow(window.get()); ASSERT_TRUE(shadow != NULL); EXPECT_EQ(gfx::Rect(kOldBounds.size()).ToString(), shadow->content_bounds().ToString()); // When we change the window's bounds, the shadow's should be updated too. gfx::Rect kNewBounds(50, 60, 500, 400); window->SetBounds(kNewBounds); EXPECT_EQ(gfx::Rect(kNewBounds.size()).ToString(), shadow->content_bounds().ToString()); } // Tests that the window's shadow's bounds are not updated if not following // the window bounds. TEST_F(ShadowControllerTest, ShadowBoundsDetached) { const gfx::Rect kInitialBounds(20, 30, 400, 300); std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithBounds(kInitialBounds, root_window())); window->Show(); const ui::Shadow* shadow = ShadowController::GetShadowForWindow(window.get()); ASSERT_TRUE(shadow); EXPECT_EQ(gfx::Rect(kInitialBounds.size()), shadow->content_bounds()); // When we change the window's bounds, the shadow's should be updated too. const gfx::Rect kBounds1(30, 40, 100, 200); window->SetBounds(kBounds1); EXPECT_EQ(gfx::Rect(kBounds1.size()), shadow->content_bounds()); // Once |kUseWindowBoundsForShadow| is false, the shadow's bounds should no // longer follow the window bounds. window->SetProperty(aura::client::kUseWindowBoundsForShadow, false); gfx::Rect kBounds2(50, 60, 500, 400); window->SetBounds(kBounds2); EXPECT_EQ(gfx::Rect(kBounds1.size()), shadow->content_bounds()); } // Tests that activating a window changes the shadow style. TEST_F(ShadowControllerTest, ShadowStyle) { std::unique_ptr<aura::Window> window1(new aura::Window(NULL)); window1->SetType(aura::client::WINDOW_TYPE_NORMAL); window1->Init(ui::LAYER_TEXTURED); ParentWindow(window1.get()); window1->SetBounds(gfx::Rect(10, 20, 300, 400)); window1->Show(); ActivateWindow(window1.get()); // window1 is active, so style should have active appearance. ui::Shadow* shadow1 = ShadowController::GetShadowForWindow(window1.get()); ASSERT_TRUE(shadow1 != NULL); EXPECT_EQ(kShadowElevationActiveWindow, shadow1->desired_elevation()); // Create another window and activate it. std::unique_ptr<aura::Window> window2(new aura::Window(NULL)); window2->SetType(aura::client::WINDOW_TYPE_NORMAL); window2->Init(ui::LAYER_TEXTURED); ParentWindow(window2.get()); window2->SetBounds(gfx::Rect(11, 21, 301, 401)); window2->Show(); ActivateWindow(window2.get()); // window1 is now inactive, so shadow should go inactive. ui::Shadow* shadow2 = ShadowController::GetShadowForWindow(window2.get()); ASSERT_TRUE(shadow2 != NULL); EXPECT_EQ(kShadowElevationInactiveWindow, shadow1->desired_elevation()); EXPECT_EQ(kShadowElevationActiveWindow, shadow2->desired_elevation()); } // Tests that shadow gets updated when the window show state changes. TEST_F(ShadowControllerTest, ShowState) { std::unique_ptr<aura::Window> window(new aura::Window(NULL)); window->SetType(aura::client::WINDOW_TYPE_NORMAL); window->Init(ui::LAYER_TEXTURED); ParentWindow(window.get()); window->Show(); ui::Shadow* shadow = ShadowController::GetShadowForWindow(window.get()); ASSERT_TRUE(shadow != NULL); EXPECT_EQ(kShadowElevationInactiveWindow, shadow->desired_elevation()); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_FALSE(shadow->layer()->visible()); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); EXPECT_TRUE(shadow->layer()->visible()); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); EXPECT_FALSE(shadow->layer()->visible()); } // Tests that we use smaller shadows for tooltips and menus. TEST_F(ShadowControllerTest, SmallShadowsForTooltipsAndMenus) { std::unique_ptr<aura::Window> tooltip_window(new aura::Window(NULL)); tooltip_window->SetType(aura::client::WINDOW_TYPE_TOOLTIP); tooltip_window->Init(ui::LAYER_TEXTURED); ParentWindow(tooltip_window.get()); tooltip_window->SetBounds(gfx::Rect(10, 20, 300, 400)); tooltip_window->Show(); ui::Shadow* tooltip_shadow = ShadowController::GetShadowForWindow(tooltip_window.get()); ASSERT_TRUE(tooltip_shadow != NULL); EXPECT_EQ(kShadowElevationMenuOrTooltip, tooltip_shadow->desired_elevation()); std::unique_ptr<aura::Window> menu_window(new aura::Window(NULL)); menu_window->SetType(aura::client::WINDOW_TYPE_MENU); menu_window->Init(ui::LAYER_TEXTURED); ParentWindow(menu_window.get()); menu_window->SetBounds(gfx::Rect(10, 20, 300, 400)); menu_window->Show(); ui::Shadow* menu_shadow = ShadowController::GetShadowForWindow(tooltip_window.get()); ASSERT_TRUE(menu_shadow != NULL); EXPECT_EQ(kShadowElevationMenuOrTooltip, menu_shadow->desired_elevation()); } // http://crbug.com/120210 - transient parents of certain types of transients // should not lose their shadow when they lose activation to the transient. TEST_F(ShadowControllerTest, TransientParentKeepsActiveShadow) { std::unique_ptr<aura::Window> window1(new aura::Window(NULL)); window1->SetType(aura::client::WINDOW_TYPE_NORMAL); window1->Init(ui::LAYER_TEXTURED); ParentWindow(window1.get()); window1->SetBounds(gfx::Rect(10, 20, 300, 400)); window1->Show(); ActivateWindow(window1.get()); // window1 is active, so style should have active appearance. ui::Shadow* shadow1 = ShadowController::GetShadowForWindow(window1.get()); ASSERT_TRUE(shadow1 != NULL); EXPECT_EQ(kShadowElevationActiveWindow, shadow1->desired_elevation()); // Create a window that is transient to window1, and that has the 'hide on // deactivate' property set. Upon activation, window1 should still have an // active shadow. std::unique_ptr<aura::Window> window2(new aura::Window(NULL)); window2->SetType(aura::client::WINDOW_TYPE_NORMAL); window2->Init(ui::LAYER_TEXTURED); ParentWindow(window2.get()); window2->SetBounds(gfx::Rect(11, 21, 301, 401)); AddTransientChild(window1.get(), window2.get()); SetHideOnDeactivate(window2.get(), true); window2->Show(); ActivateWindow(window2.get()); // window1 is now inactive, but its shadow should still appear active. EXPECT_EQ(kShadowElevationActiveWindow, shadow1->desired_elevation()); } namespace { class TestShadowControllerDelegate : public wm::ShadowControllerDelegate { public: TestShadowControllerDelegate() {} TestShadowControllerDelegate(const TestShadowControllerDelegate&) = delete; TestShadowControllerDelegate& operator=(const TestShadowControllerDelegate&) = delete; ~TestShadowControllerDelegate() override {} bool ShouldShowShadowForWindow(const aura::Window* window) override { return window->parent(); } }; } // namespace TEST_F(ShadowControllerTest, UpdateShadowWhenAddedToParent) { InstallShadowController(std::make_unique<TestShadowControllerDelegate>()); std::unique_ptr<aura::Window> window1(new aura::Window(NULL)); window1->SetType(aura::client::WINDOW_TYPE_NORMAL); window1->Init(ui::LAYER_TEXTURED); window1->SetBounds(gfx::Rect(10, 20, 300, 400)); window1->Show(); EXPECT_FALSE(ShadowController::GetShadowForWindow(window1.get())); ParentWindow(window1.get()); ASSERT_TRUE(ShadowController::GetShadowForWindow(window1.get())); EXPECT_TRUE( ShadowController::GetShadowForWindow(window1.get())->layer()->visible()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/shadow_controller_unittest.cc
C++
unknown
11,074
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/shadow_types.h" #include "ui/base/class_property.h" namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(int, kShadowElevationKey, kShadowElevationDefault) void SetShadowElevation(aura::Window* window, int elevation) { window->SetProperty(kShadowElevationKey, elevation); } int GetDefaultShadowElevationForWindow(const aura::Window* window) { switch (window->GetType()) { case aura::client::WINDOW_TYPE_NORMAL: return kShadowElevationInactiveWindow; case aura::client::WINDOW_TYPE_MENU: case aura::client::WINDOW_TYPE_TOOLTIP: return kShadowElevationMenuOrTooltip; default: return kShadowElevationNone; } } int GetShadowElevationConvertDefault(const aura::Window* window) { int elevation = window->GetProperty(kShadowElevationKey); return elevation == kShadowElevationDefault ? GetDefaultShadowElevationForWindow(window) : elevation; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/shadow_types.cc
C++
unknown
1,090
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_SHADOW_TYPES_H_ #define UI_WM_CORE_SHADOW_TYPES_H_ #include "base/component_export.h" #include "build/chromeos_buildflags.h" #include "ui/aura/window.h" namespace wm { // Indicates an elevation should be chosen based on the window. This is used // by wm::ShadowController, but is not a valid elevation to pass to wm::Shadow. constexpr int kShadowElevationDefault = -1; // Different types of drop shadows that can be drawn under a window by the // shell. Used as a value for the kShadowElevationKey property. constexpr int kShadowElevationNone = 0; // Standard shadow elevations used by the the aura window manager. The value is // used to initialize an instance of wm::Shadow and controls the offset and blur // of the shadow style created by gfx::ShadowValue::MakeMdShadowValues() or // gfx::ShadowValue::MakeChromeOSSystemUIShadowValues(). constexpr int kShadowElevationMenuOrTooltip = 6; #if BUILDFLAG(IS_CHROMEOS_ASH) constexpr int kShadowElevationInactiveWindow = 12; #else constexpr int kShadowElevationInactiveWindow = 8; #endif constexpr int kShadowElevationActiveWindow = 24; COMPONENT_EXPORT(UI_WM) void SetShadowElevation(aura::Window* window, int elevation); // Returns the default shadow elevaltion value for |window|. COMPONENT_EXPORT(UI_WM) int GetDefaultShadowElevationForWindow(const aura::Window* window); // Returns the shadow elevation property value for |window|, converting // |kShadowElevationDefault| to the appropriate value. COMPONENT_EXPORT(UI_WM) int GetShadowElevationConvertDefault(const aura::Window* window); // A property key describing the drop shadow that should be displayed under the // window. A null value is interpreted as using the default. COMPONENT_EXPORT(UI_WM) extern const aura::WindowProperty<int>* const kShadowElevationKey; } // namespace wm #endif // UI_WM_CORE_SHADOW_TYPES_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/shadow_types.h
C++
unknown
2,004
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/transient_window_controller.h" #include "base/observer_list.h" #include "ui/aura/client/transient_window_client_observer.h" #include "ui/wm/core/transient_window_manager.h" namespace wm { // static TransientWindowController* TransientWindowController::instance_ = nullptr; TransientWindowController::TransientWindowController() { DCHECK(!instance_); instance_ = this; } TransientWindowController::~TransientWindowController() { DCHECK_EQ(instance_, this); instance_ = nullptr; } void TransientWindowController::AddTransientChild(aura::Window* parent, aura::Window* child) { TransientWindowManager::GetOrCreate(parent)->AddTransientChild(child); } void TransientWindowController::RemoveTransientChild(aura::Window* parent, aura::Window* child) { TransientWindowManager::GetOrCreate(parent)->RemoveTransientChild(child); } aura::Window* TransientWindowController::GetTransientParent( aura::Window* window) { return const_cast<aura::Window*>(GetTransientParent( const_cast<const aura::Window*>(window))); } const aura::Window* TransientWindowController::GetTransientParent( const aura::Window* window) { const TransientWindowManager* window_manager = TransientWindowManager::GetIfExists(window); return window_manager ? window_manager->transient_parent() : nullptr; } std::vector<aura::Window*> TransientWindowController::GetTransientChildren( const aura::Window* parent) { const TransientWindowManager* window_manager = TransientWindowManager::GetIfExists(parent); if (!window_manager) return {}; return window_manager->transient_children(); } void TransientWindowController::AddObserver( aura::client::TransientWindowClientObserver* observer) { observers_.AddObserver(observer); } void TransientWindowController::RemoveObserver( aura::client::TransientWindowClientObserver* observer) { observers_.RemoveObserver(observer); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_controller.cc
C++
unknown
2,194
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_TRANSIENT_WINDOW_CONTROLLER_H_ #define UI_WM_CORE_TRANSIENT_WINDOW_CONTROLLER_H_ #include "base/component_export.h" #include "base/observer_list.h" #include "ui/aura/client/transient_window_client.h" namespace wm { class TransientWindowManager; // TransientWindowClient implementation. Uses TransientWindowManager to handle // tracking transient per window. class COMPONENT_EXPORT(UI_WM) TransientWindowController : public aura::client::TransientWindowClient { public: TransientWindowController(); TransientWindowController(const TransientWindowController&) = delete; TransientWindowController& operator=(const TransientWindowController&) = delete; ~TransientWindowController() override; // Returns the single TransientWindowController instance. static TransientWindowController* Get() { return instance_; } // TransientWindowClient: void AddTransientChild(aura::Window* parent, aura::Window* child) override; void RemoveTransientChild(aura::Window* parent, aura::Window* child) override; aura::Window* GetTransientParent(aura::Window* window) override; const aura::Window* GetTransientParent(const aura::Window* window) override; std::vector<aura::Window*> GetTransientChildren( const aura::Window* parent) override; void AddObserver( aura::client::TransientWindowClientObserver* observer) override; void RemoveObserver( aura::client::TransientWindowClientObserver* observer) override; private: friend class TransientWindowManager; static TransientWindowController* instance_; base::ObserverList<aura::client::TransientWindowClientObserver>::Unchecked observers_; }; } // namespace wm #endif // UI_WM_CORE_TRANSIENT_WINDOW_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_controller.h
C++
unknown
1,886
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/transient_window_manager.h" #include <functional> #include "base/auto_reset.h" #include "base/containers/adapters.h" #include "base/containers/contains.h" #include "base/memory/ptr_util.h" #include "base/observer_list.h" #include "base/ranges/algorithm.h" #include "ui/aura/client/transient_window_client.h" #include "ui/aura/client/transient_window_client_observer.h" #include "ui/aura/window.h" #include "ui/aura/window_tracker.h" #include "ui/base/class_property.h" #include "ui/wm/core/transient_window_controller.h" #include "ui/wm/core/transient_window_observer.h" #include "ui/wm/core/transient_window_stacking_client.h" #include "ui/wm/core/window_util.h" using aura::Window; DEFINE_UI_CLASS_PROPERTY_TYPE(::wm::TransientWindowManager*) namespace wm { namespace { DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(TransientWindowManager, kPropertyKey, nullptr) } // namespace TransientWindowManager::~TransientWindowManager() = default; // static TransientWindowManager* TransientWindowManager::GetOrCreate(Window* window) { if (auto* manager = window->GetProperty(kPropertyKey)) return manager; // Using WrapUnique due to private constructor. return window->SetProperty( kPropertyKey, base::WrapUnique(new TransientWindowManager(window))); } // static const TransientWindowManager* TransientWindowManager::GetIfExists( const Window* window) { return window->GetProperty(kPropertyKey); } void TransientWindowManager::AddObserver(TransientWindowObserver* observer) { observers_.AddObserver(observer); } void TransientWindowManager::RemoveObserver(TransientWindowObserver* observer) { observers_.RemoveObserver(observer); } void TransientWindowManager::AddTransientChild(Window* child) { // TransientWindowStackingClient does the stacking of transient windows. If it // isn't installed stacking is going to be wrong. DCHECK(TransientWindowStackingClient::instance_); // Self-owning windows break things, shouldn't happen. DCHECK_NE(this->window_, child); TransientWindowManager* child_manager = GetOrCreate(child); if (child_manager->transient_parent_) GetOrCreate(child_manager->transient_parent_)->RemoveTransientChild(child); DCHECK(!base::Contains(transient_children_, child)); transient_children_.push_back(child); child_manager->transient_parent_ = window_; for (aura::client::TransientWindowClientObserver& observer : TransientWindowController::Get()->observers_) { observer.OnTransientChildWindowAdded(window_, child); } // Restack |child| properly above its transient parent, if they share the same // parent. if (child->parent() == window_->parent()) RestackTransientDescendants(); for (auto& observer : observers_) observer.OnTransientChildAdded(window_, child); for (auto& observer : child_manager->observers_) observer.OnTransientParentChanged(window_); } void TransientWindowManager::RemoveTransientChild(Window* child) { auto i = base::ranges::find(transient_children_, child); DCHECK(i != transient_children_.end()); transient_children_.erase(i); TransientWindowManager* child_manager = GetOrCreate(child); DCHECK_EQ(window_, child_manager->transient_parent_); child_manager->transient_parent_ = nullptr; for (aura::client::TransientWindowClientObserver& observer : TransientWindowController::Get()->observers_) { observer.OnTransientChildWindowRemoved(window_, child); } // If |child| and its former transient parent share the same parent, |child| // should be restacked properly so it is not among transient children of its // former parent, anymore. if (window_->parent() == child->parent()) RestackTransientDescendants(); for (auto& observer : observers_) observer.OnTransientChildRemoved(window_, child); for (auto& observer : child_manager->observers_) observer.OnTransientParentChanged(nullptr); } bool TransientWindowManager::IsStackingTransient( const aura::Window* target) const { return stacking_target_ == target; } TransientWindowManager::TransientWindowManager(Window* window) : window_(window), transient_parent_(nullptr), stacking_target_(nullptr), parent_controls_visibility_(false), show_on_parent_visible_(false), ignore_visibility_changed_event_(false) { window_->AddObserver(this); } void TransientWindowManager::RestackTransientDescendants() { if (pause_transient_descendants_restacking_) return; Window* parent = window_->parent(); if (!parent) return; // Stack any transient children that share the same parent to be in front of // |window_|. The existing stacking order is preserved by iterating backwards // and always stacking on top. Window::Windows children(parent->children()); for (auto* child_window : base::Reversed(children)) { if (child_window != window_ && HasTransientAncestor(child_window, window_)) { TransientWindowManager* descendant_manager = GetOrCreate(child_window); base::AutoReset<Window*> resetter( &descendant_manager->stacking_target_, window_); parent->StackChildAbove(child_window, window_); } } } void TransientWindowManager::OnWindowHierarchyChanged( const HierarchyChangeParams& params) { if (params.target != window_) return; // [1] Move the direct transient children which used to be on the old parent // of |window_| to the new parent. bool should_restack = false; aura::Window* new_parent = params.new_parent; aura::Window* old_parent = params.old_parent; if (new_parent) { // Reparenting multiple sibling transient children will call back onto us // (the transient parent) in [2] below, to restack all our descendants. We // should pause restacking until we're done with all the reparenting. base::AutoReset<bool> reset(&pause_transient_descendants_restacking_, true); for (auto* transient_child : transient_children_) { if (transient_child->parent() == old_parent) { new_parent->AddChild(transient_child); should_restack = true; } } } if (should_restack) RestackTransientDescendants(); // [2] Stack |window_| properly if it is a transient child of a sibling. if (transient_parent_ && transient_parent_->parent() == new_parent) { TransientWindowManager* transient_parent_manager = GetOrCreate(transient_parent_); transient_parent_manager->RestackTransientDescendants(); } } void TransientWindowManager::UpdateTransientChildVisibility( bool parent_visible) { base::AutoReset<bool> reset(&ignore_visibility_changed_event_, true); if (!parent_visible) { show_on_parent_visible_ = window_->TargetVisibility(); window_->Hide(); } else { if (show_on_parent_visible_ && parent_controls_visibility_) window_->Show(); show_on_parent_visible_ = false; } } void TransientWindowManager::OnWindowVisibilityChanged(Window* window, bool visible) { if (window_ != window) return; // If the window has transient children, updates the transient children's // visiblity as well. // WindowTracker is used because child window // could be deleted inside UpdateTransientChildVisibility call. aura::WindowTracker tracker(transient_children_); while (!tracker.windows().empty()) GetOrCreate(tracker.Pop())->UpdateTransientChildVisibility(visible); // Remember the show request in |show_on_parent_visible_| and hide it again // if the following conditions are met // - |parent_controls_visibility| is set to true. // - the window is hidden while the transient parent is not visible. // - Show/Hide was NOT called from TransientWindowManager. if (ignore_visibility_changed_event_ || !transient_parent_ || !parent_controls_visibility_) { return; } if (!transient_parent_->TargetVisibility() && visible) { base::AutoReset<bool> reset(&ignore_visibility_changed_event_, true); show_on_parent_visible_ = true; window_->Hide(); } else if (!visible) { DCHECK(!show_on_parent_visible_); } } void TransientWindowManager::OnWindowStackingChanged(Window* window) { DCHECK_EQ(window_, window); // Do nothing if we initiated the stacking change. const TransientWindowManager* transient_manager = GetIfExists(window); if (transient_manager && transient_manager->stacking_target_) { auto window_i = base::ranges::find(window->parent()->children(), window); DCHECK(window_i != window->parent()->children().end()); if (window_i != window->parent()->children().begin() && (*(window_i - 1) == transient_manager->stacking_target_)) return; } RestackTransientDescendants(); } void TransientWindowManager::OnWindowDestroying(Window* window) { // Removes ourselves from our transient parent (if it hasn't been done by the // RootWindow). if (transient_parent_) { TransientWindowManager::GetOrCreate(transient_parent_) ->RemoveTransientChild(window_); } // Destroy transient children, only after we've removed ourselves from our // parent, as destroying an active transient child may otherwise attempt to // refocus us. Windows transient_children(transient_children_); for (auto* child : transient_children) delete child; DCHECK(transient_children_.empty()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_manager.cc
C++
unknown
9,569
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_TRANSIENT_WINDOW_MANAGER_H_ #define UI_WM_CORE_TRANSIENT_WINDOW_MANAGER_H_ #include <vector> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/observer_list.h" #include "ui/aura/window_observer.h" namespace wm { class TransientWindowObserver; // TransientWindowManager manages the set of transient children for a window // along with the transient parent. Transient children get the following // behavior: // . The transient parent destroys any transient children when it is // destroyed. This means a transient child is destroyed if either its parent // or transient parent is destroyed. // . If a transient child and its transient parent share the same parent, then // transient children are always ordered above the transient parent. // . If a transient parent is hidden, it hides all transient children. // For show operation, please refer to |set_parent_controls_visibility(bool)|. // Transient windows are typically used for popups and menus. class COMPONENT_EXPORT(UI_WM) TransientWindowManager : public aura::WindowObserver { public: using Windows = std::vector<aura::Window*>; TransientWindowManager(const TransientWindowManager&) = delete; TransientWindowManager& operator=(const TransientWindowManager&) = delete; ~TransientWindowManager() override; // Returns the TransientWindowManager for |window|, creating if necessary. // This never returns nullptr. static TransientWindowManager* GetOrCreate(aura::Window* window); // Returns the TransientWindowManager for |window| only if it already exists. // WARNING: this may return nullptr. static const TransientWindowManager* GetIfExists(const aura::Window* window); void AddObserver(TransientWindowObserver* observer); void RemoveObserver(TransientWindowObserver* observer); // Adds or removes a transient child. void AddTransientChild(aura::Window* child); void RemoveTransientChild(aura::Window* child); // Setting true lets the transient parent show this transient // child when the parent is shown. If this was shown when the // transient parent is hidden, it remains hidden and gets shown // when the transient parent is shown. This is false by default. void set_parent_controls_visibility(bool parent_controls_visibility) { parent_controls_visibility_ = parent_controls_visibility; } const Windows& transient_children() const { return transient_children_; } aura::Window* transient_parent() { return transient_parent_; } const aura::Window* transient_parent() const { return transient_parent_; } // Returns true if in the process of stacking |window_| on top of |target|. // That is, when the stacking order of a window changes // (OnWindowStackingChanged()) the transients may get restacked as well. This // function can be used to detect if TransientWindowManager is in the process // of stacking a transient as the result of window stacking changing. bool IsStackingTransient(const aura::Window* target) const; private: explicit TransientWindowManager(aura::Window* window); // Stacks transient descendants of this window that are its siblings just // above it. void RestackTransientDescendants(); // Update the window's visibility following the transient parent's // visibility. See |set_parent_controls_visibility(bool)| for more details. void UpdateTransientChildVisibility(bool visible); // WindowObserver: void OnWindowHierarchyChanged(const HierarchyChangeParams& params) override; void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; void OnWindowStackingChanged(aura::Window* window) override; void OnWindowDestroying(aura::Window* window) override; raw_ptr<aura::Window> window_; raw_ptr<aura::Window> transient_parent_; Windows transient_children_; // If non-null we're actively restacking transient as the result of a // transient ancestor changing. // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION aura::Window* stacking_target_; bool parent_controls_visibility_; bool show_on_parent_visible_; bool ignore_visibility_changed_event_; // Set to true to pause updating the stacking order of transient descandant // windows while we reparent those transient children which used to be on the // the same old parent as that of |window| to its new parent. // This avoid recursively restacking multiple times when we have to reparent // multiple transient children. bool pause_transient_descendants_restacking_ = false; base::ObserverList<TransientWindowObserver>::Unchecked observers_; }; } // namespace wm #endif // UI_WM_CORE_TRANSIENT_WINDOW_MANAGER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_manager.h
C++
unknown
4,918
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/transient_window_manager.h" #include "base/memory/raw_ptr.h" #include <utility> #include "ui/aura/client/window_parenting_client.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #include "ui/wm/core/transient_window_observer.h" #include "ui/wm/core/window_util.h" using aura::Window; using aura::test::ChildWindowIDsAsString; using aura::test::CreateTestWindowWithId; namespace wm { class TestTransientWindowObserver : public TransientWindowObserver { public: TestTransientWindowObserver() = default; TestTransientWindowObserver(const TestTransientWindowObserver&) = delete; TestTransientWindowObserver& operator=(const TestTransientWindowObserver&) = delete; ~TestTransientWindowObserver() override {} int add_count() const { return add_count_; } int remove_count() const { return remove_count_; } int parent_change_count() const { return parent_change_count_; } // TransientWindowObserver overrides: void OnTransientChildAdded(Window* window, Window* transient) override { add_count_++; } void OnTransientChildRemoved(Window* window, Window* transient) override { remove_count_++; } void OnTransientParentChanged(Window* window) override { parent_change_count_++; } private: int add_count_ = 0; int remove_count_ = 0; int parent_change_count_ = 0; }; class WindowVisibilityObserver : public aura::WindowObserver { public: WindowVisibilityObserver(Window* observed_window, std::unique_ptr<Window> owned_window) : observed_window_(observed_window), owned_window_(std::move(owned_window)) { observed_window_->AddObserver(this); } WindowVisibilityObserver(const WindowVisibilityObserver&) = delete; WindowVisibilityObserver& operator=(const WindowVisibilityObserver&) = delete; ~WindowVisibilityObserver() override { observed_window_->RemoveObserver(this); } void OnWindowVisibilityChanged(Window* window, bool visible) override { owned_window_.reset(); } private: raw_ptr<Window> observed_window_; std::unique_ptr<Window> owned_window_; }; class TransientWindowManagerTest : public aura::test::AuraTestBase { public: TransientWindowManagerTest() {} TransientWindowManagerTest(const TransientWindowManagerTest&) = delete; TransientWindowManagerTest& operator=(const TransientWindowManagerTest&) = delete; ~TransientWindowManagerTest() override {} protected: // Creates a transient window that is transient to |parent|. Window* CreateTransientChild(int id, Window* parent) { Window* window = new Window(NULL); window->SetId(id); window->SetType(aura::client::WINDOW_TYPE_NORMAL); window->Init(ui::LAYER_TEXTURED); AddTransientChild(parent, window); aura::client::ParentWindowWithContext(window, root_window(), gfx::Rect()); return window; } }; // Various assertions for transient children. TEST_F(TransientWindowManagerTest, TransientChildren) { std::unique_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); std::unique_ptr<Window> w3(CreateTestWindowWithId(3, parent.get())); Window* w2 = CreateTestWindowWithId(2, parent.get()); // w2 is now owned by w1. AddTransientChild(w1.get(), w2); // Stack w1 at the top (end), this should force w2 to be last (on top of w1). parent->StackChildAtTop(w1.get()); ASSERT_EQ(3u, parent->children().size()); EXPECT_EQ(w2, parent->children().back()); // Destroy w1, which should also destroy w3 (since it's a transient child). w1.reset(); w2 = NULL; ASSERT_EQ(1u, parent->children().size()); EXPECT_EQ(w3.get(), parent->children()[0]); w1.reset(CreateTestWindowWithId(4, parent.get())); w2 = CreateTestWindowWithId(5, w3.get()); AddTransientChild(w1.get(), w2); parent->StackChildAtTop(w3.get()); // Stack w1 at the top (end), this shouldn't affect w2 since it has a // different parent. parent->StackChildAtTop(w1.get()); ASSERT_EQ(2u, parent->children().size()); EXPECT_EQ(w3.get(), parent->children()[0]); EXPECT_EQ(w1.get(), parent->children()[1]); // Hiding parent should hide transient children. EXPECT_TRUE(w2->IsVisible()); w1->Hide(); EXPECT_FALSE(w2->IsVisible()); // And they should stay hidden even after the parent became visible. w1->Show(); EXPECT_FALSE(w2->IsVisible()); // Hidden transient child should stay hidden regardless of // parent's visibility. w2->Hide(); EXPECT_FALSE(w2->IsVisible()); w1->Hide(); EXPECT_FALSE(w2->IsVisible()); w1->Show(); EXPECT_FALSE(w2->IsVisible()); // Transient child can be shown even if the transient parent is hidden. w1->Hide(); EXPECT_FALSE(w2->IsVisible()); w2->Show(); EXPECT_TRUE(w2->IsVisible()); w1->Show(); EXPECT_TRUE(w2->IsVisible()); // When the parent_controls_visibility is true, TransientWindowManager // controls the children's visibility. It stays invisible even if // Window::Show() is called, and gets shown when the parent becomes visible. wm::TransientWindowManager::GetOrCreate(w2)->set_parent_controls_visibility( true); w1->Hide(); EXPECT_FALSE(w2->IsVisible()); w2->Show(); EXPECT_FALSE(w2->IsVisible()); w1->Show(); EXPECT_TRUE(w2->IsVisible()); // Hiding a transient child that is hidden by the transient parent // is not currently handled and will be shown anyway. w1->Hide(); EXPECT_FALSE(w2->IsVisible()); w2->Hide(); EXPECT_FALSE(w2->IsVisible()); w1->Show(); EXPECT_TRUE(w2->IsVisible()); } // Tests that transient children are stacked as a unit when using stack above. TEST_F(TransientWindowManagerTest, TransientChildrenGroupAbove) { std::unique_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); Window* w11 = CreateTestWindowWithId(11, parent.get()); std::unique_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); Window* w21 = CreateTestWindowWithId(21, parent.get()); Window* w211 = CreateTestWindowWithId(211, parent.get()); Window* w212 = CreateTestWindowWithId(212, parent.get()); Window* w213 = CreateTestWindowWithId(213, parent.get()); Window* w22 = CreateTestWindowWithId(22, parent.get()); ASSERT_EQ(8u, parent->children().size()); // w11 is now owned by w1. AddTransientChild(w1.get(), w11); // w21 is now owned by w2. AddTransientChild(w2.get(), w21); // w22 is now owned by w2. AddTransientChild(w2.get(), w22); // w211 is now owned by w21. AddTransientChild(w21, w211); // w212 is now owned by w21. AddTransientChild(w21, w212); // w213 is now owned by w21. AddTransientChild(w21, w213); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); // Stack w1 at the top (end), this should force w11 to be last (on top of w1). parent->StackChildAtTop(w1.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); // This tests that the order in children_ array rather than in // transient_children_ array is used when reinserting transient children. // If transient_children_ array was used '22' would be following '21'. parent->StackChildAtTop(w2.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w11, w2.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w21, w1.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w21, w22); EXPECT_EQ(w213, parent->children().back()); EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w11, w21); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w213, w21); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); // No change when stacking a transient parent above its transient child. parent->StackChildAbove(w21, w211); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); // This tests that the order in children_ array rather than in // transient_children_ array is used when reinserting transient children. // If transient_children_ array was used '22' would be following '21'. parent->StackChildAbove(w2.get(), w1.get()); EXPECT_EQ(w212, parent->children().back()); EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w11, w213); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); } // Tests that transient children are stacked as a unit when using stack below. TEST_F(TransientWindowManagerTest, TransientChildrenGroupBelow) { std::unique_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); Window* w11 = CreateTestWindowWithId(11, parent.get()); std::unique_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); Window* w21 = CreateTestWindowWithId(21, parent.get()); Window* w211 = CreateTestWindowWithId(211, parent.get()); Window* w212 = CreateTestWindowWithId(212, parent.get()); Window* w213 = CreateTestWindowWithId(213, parent.get()); Window* w22 = CreateTestWindowWithId(22, parent.get()); ASSERT_EQ(8u, parent->children().size()); // w11 is now owned by w1. AddTransientChild(w1.get(), w11); // w21 is now owned by w2. AddTransientChild(w2.get(), w21); // w22 is now owned by w2. AddTransientChild(w2.get(), w22); // w211 is now owned by w21. AddTransientChild(w21, w211); // w212 is now owned by w21. AddTransientChild(w21, w212); // w213 is now owned by w21. AddTransientChild(w21, w213); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); // Stack w2 at the bottom, this should force w11 to be last (on top of w1). // This also tests that the order in children_ array rather than in // transient_children_ array is used when reinserting transient children. // If transient_children_ array was used '22' would be following '21'. parent->StackChildAtBottom(w2.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildAtBottom(w1.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w21, w1.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w11, w2.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w22, w21); EXPECT_EQ(w213, parent->children().back()); EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w21, w11); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w213, w211); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); // No change when stacking a transient parent below its transient child. parent->StackChildBelow(w21, w211); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w1.get(), w2.get()); EXPECT_EQ(w212, parent->children().back()); EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w213, w11); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); } // Tests that transient windows are stacked properly when created. TEST_F(TransientWindowManagerTest, StackUponCreation) { std::unique_ptr<Window> window0(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); std::unique_ptr<Window> window2(CreateTransientChild(2, window0.get())); EXPECT_EQ("0 2 1", ChildWindowIDsAsString(root_window())); } // Tests for a crash when window destroyed inside // UpdateTransientChildVisibility loop. TEST_F(TransientWindowManagerTest, CrashOnVisibilityChange) { std::unique_ptr<Window> window1(CreateTransientChild(1, root_window())); std::unique_ptr<Window> window2(CreateTransientChild(2, root_window())); window1->Show(); window2->Show(); WindowVisibilityObserver visibility_observer(window1.get(), std::move(window2)); root_window()->Hide(); } // Tests that windows are restacked properly after a call to AddTransientChild() // or RemoveTransientChild(). TEST_F(TransientWindowManagerTest, RestackUponAddOrRemoveTransientChild) { std::unique_ptr<Window> windows[4]; for (int i = 0; i < 4; i++) windows[i].reset(CreateTestWindowWithId(i, root_window())); EXPECT_EQ("0 1 2 3", ChildWindowIDsAsString(root_window())); AddTransientChild(windows[0].get(), windows[2].get()); EXPECT_EQ("0 2 1 3", ChildWindowIDsAsString(root_window())); AddTransientChild(windows[0].get(), windows[3].get()); EXPECT_EQ("0 2 3 1", ChildWindowIDsAsString(root_window())); RemoveTransientChild(windows[0].get(), windows[2].get()); EXPECT_EQ("0 3 2 1", ChildWindowIDsAsString(root_window())); RemoveTransientChild(windows[0].get(), windows[3].get()); EXPECT_EQ("0 3 2 1", ChildWindowIDsAsString(root_window())); } namespace { // Used by NotifyDelegateAfterDeletingTransients. Adds a string to a vector when // OnWindowDestroyed() is invoked so that destruction order can be verified. class DestroyedTrackingDelegate : public aura::test::TestWindowDelegate { public: explicit DestroyedTrackingDelegate(const std::string& name, std::vector<std::string>* results) : name_(name), results_(results) {} DestroyedTrackingDelegate(const DestroyedTrackingDelegate&) = delete; DestroyedTrackingDelegate& operator=(const DestroyedTrackingDelegate&) = delete; void OnWindowDestroyed(aura::Window* window) override { results_->push_back(name_); } private: const std::string name_; raw_ptr<std::vector<std::string>> results_; }; } // namespace // Verifies the delegate is notified of destruction after transients are // destroyed. TEST_F(TransientWindowManagerTest, NotifyDelegateAfterDeletingTransients) { std::vector<std::string> destruction_order; DestroyedTrackingDelegate parent_delegate("parent", &destruction_order); std::unique_ptr<Window> parent(new Window(&parent_delegate)); parent->Init(ui::LAYER_NOT_DRAWN); DestroyedTrackingDelegate transient_delegate("transient", &destruction_order); Window* transient = new Window(&transient_delegate); // Owned by |parent|. transient->Init(ui::LAYER_NOT_DRAWN); AddTransientChild(parent.get(), transient); parent.reset(); ASSERT_EQ(2u, destruction_order.size()); EXPECT_EQ("transient", destruction_order[0]); EXPECT_EQ("parent", destruction_order[1]); } TEST_F(TransientWindowManagerTest, StackTransientsLayersRelativeToOtherTransients) { // Create a window with several transients, then a couple windows on top. std::unique_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); std::unique_ptr<Window> window11(CreateTransientChild(11, window1.get())); std::unique_ptr<Window> window12(CreateTransientChild(12, window1.get())); std::unique_ptr<Window> window13(CreateTransientChild(13, window1.get())); EXPECT_EQ("1 11 12 13", ChildWindowIDsAsString(root_window())); // Stack 11 above 12. root_window()->StackChildAbove(window11.get(), window12.get()); EXPECT_EQ("1 12 11 13", ChildWindowIDsAsString(root_window())); // Stack 13 below 12. root_window()->StackChildBelow(window13.get(), window12.get()); EXPECT_EQ("1 13 12 11", ChildWindowIDsAsString(root_window())); // Stack 11 above 1. root_window()->StackChildAbove(window11.get(), window1.get()); EXPECT_EQ("1 11 13 12", ChildWindowIDsAsString(root_window())); // Stack 12 below 13. root_window()->StackChildBelow(window12.get(), window13.get()); EXPECT_EQ("1 11 12 13", ChildWindowIDsAsString(root_window())); } // Verifies TransientWindowObserver is notified appropriately. TEST_F(TransientWindowManagerTest, TransientWindowObserverNotified) { std::unique_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); TestTransientWindowObserver test_parent_observer, test_child_observer; TransientWindowManager::GetOrCreate(parent.get()) ->AddObserver(&test_parent_observer); TransientWindowManager::GetOrCreate(w1.get())->AddObserver( &test_child_observer); AddTransientChild(parent.get(), w1.get()); EXPECT_EQ(1, test_parent_observer.add_count()); EXPECT_EQ(0, test_parent_observer.remove_count()); EXPECT_EQ(1, test_child_observer.parent_change_count()); RemoveTransientChild(parent.get(), w1.get()); EXPECT_EQ(1, test_parent_observer.add_count()); EXPECT_EQ(1, test_parent_observer.remove_count()); EXPECT_EQ(2, test_child_observer.parent_change_count()); TransientWindowManager::GetOrCreate(parent.get()) ->RemoveObserver(&test_parent_observer); TransientWindowManager::GetOrCreate(parent.get()) ->RemoveObserver(&test_child_observer); } TEST_F(TransientWindowManagerTest, ChangeParent) { std::unique_ptr<Window> container_1(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> container_2(CreateTestWindowWithId(1, root_window())); std::unique_ptr<Window> container_3(CreateTestWindowWithId(2, root_window())); std::unique_ptr<Window> parent(CreateTestWindowWithId(3, container_1.get())); std::unique_ptr<Window> child_1(CreateTestWindowWithId(4, container_1.get())); std::unique_ptr<Window> child_2(CreateTestWindowWithId(5, container_1.get())); std::unique_ptr<Window> child_3(CreateTestWindowWithId(6, container_1.get())); std::unique_ptr<Window> child_4(CreateTestWindowWithId(7, container_3.get())); std::unique_ptr<Window> child_5(CreateTestWindowWithId(8, container_1.get())); AddTransientChild(parent.get(), child_1.get()); AddTransientChild(child_1.get(), child_2.get()); AddTransientChild(parent.get(), child_4.get()); AddTransientChild(parent.get(), child_5.get()); container_2->AddChild(parent.get()); // Transient children on the old container should be reparented to the new // container. EXPECT_EQ(child_1->parent(), container_2.get()); EXPECT_EQ(child_2->parent(), container_2.get()); EXPECT_EQ(child_5->parent(), container_2.get()); // child_3 and child_4 should remain unaffected. EXPECT_EQ(child_3->parent(), container_1.get()); EXPECT_EQ(child_4->parent(), container_3.get()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_manager_unittest.cc
C++
unknown
19,660
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_TRANSIENT_WINDOW_OBSERVER_H_ #define UI_WM_CORE_TRANSIENT_WINDOW_OBSERVER_H_ #include "base/component_export.h" namespace aura { class Window; } namespace wm { class COMPONENT_EXPORT(UI_WM) TransientWindowObserver { public: // Called when a transient child is added to |window|. virtual void OnTransientChildAdded(aura::Window* window, aura::Window* transient) {} // Called when a transient child is removed from |window|. virtual void OnTransientChildRemoved(aura::Window* window, aura::Window* transient) {} virtual void OnTransientParentChanged(aura::Window* new_parent) {} protected: virtual ~TransientWindowObserver() {} }; } // namespace wm #endif // UI_WM_CORE_TRANSIENT_WINDOW_OBSERVER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_observer.h
C++
unknown
961
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/transient_window_stacking_client.h" #include <stddef.h> #include "base/ranges/algorithm.h" #include "ui/aura/client/transient_window_client.h" #include "ui/wm/core/transient_window_manager.h" #include "ui/wm/core/window_util.h" using aura::Window; namespace wm { namespace { // Populates |ancestors| with all transient ancestors of |window| that are // siblings of |window|. Returns true if any ancestors were found, false if not. bool GetAllTransientAncestors(Window* window, Window::Windows* ancestors) { Window* parent = window->parent(); for (; window; window = GetTransientParent(window)) { if (window->parent() == parent) ancestors->push_back(window); } return (!ancestors->empty()); } // Replaces |window1| and |window2| with their possible transient ancestors that // are still siblings (have a common transient parent). |window1| and |window2| // are not modified if such ancestors cannot be found. void FindCommonTransientAncestor(Window** window1, Window** window2) { DCHECK(window1); DCHECK(window2); DCHECK(*window1); DCHECK(*window2); // Assemble chains of ancestors of both windows. Window::Windows ancestors1; Window::Windows ancestors2; if (!GetAllTransientAncestors(*window1, &ancestors1) || !GetAllTransientAncestors(*window2, &ancestors2)) { return; } // Walk the two chains backwards and look for the first difference. auto it1 = ancestors1.rbegin(); auto it2 = ancestors2.rbegin(); for (; it1 != ancestors1.rend() && it2 != ancestors2.rend(); ++it1, ++it2) { if (*it1 != *it2) { *window1 = *it1; *window2 = *it2; break; } } } } // namespace // static TransientWindowStackingClient* TransientWindowStackingClient::instance_ = NULL; TransientWindowStackingClient::TransientWindowStackingClient() { instance_ = this; } TransientWindowStackingClient::~TransientWindowStackingClient() { if (instance_ == this) instance_ = NULL; } bool TransientWindowStackingClient::AdjustStacking( Window** child, Window** target, Window::StackDirection* direction) { const TransientWindowManager* transient_manager = TransientWindowManager::GetIfExists(*child); if (transient_manager && transient_manager->IsStackingTransient(*target)) return true; // For windows that have transient children stack the transient ancestors that // are siblings. This prevents one transient group from being inserted in the // middle of another. FindCommonTransientAncestor(child, target); // When stacking above skip to the topmost transient descendant of the target. if (*direction == Window::STACK_ABOVE && !HasTransientAncestor(*child, *target)) { const Window::Windows& siblings((*child)->parent()->children()); size_t target_i = base::ranges::find(siblings, *target) - siblings.begin(); while (target_i + 1 < siblings.size() && HasTransientAncestor(siblings[target_i + 1], *target)) { ++target_i; } *target = siblings[target_i]; } return *child != *target; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_stacking_client.cc
C++
unknown
3,228
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_TRANSIENT_WINDOW_STACKING_CLIENT_H_ #define UI_WM_CORE_TRANSIENT_WINDOW_STACKING_CLIENT_H_ #include "base/component_export.h" #include "ui/aura/client/window_stacking_client.h" namespace wm { class TransientWindowManager; class COMPONENT_EXPORT(UI_WM) TransientWindowStackingClient : public aura::client::WindowStackingClient { public: TransientWindowStackingClient(); TransientWindowStackingClient(const TransientWindowStackingClient&) = delete; TransientWindowStackingClient& operator=( const TransientWindowStackingClient&) = delete; ~TransientWindowStackingClient() override; // WindowStackingClient: bool AdjustStacking(aura::Window** child, aura::Window** target, aura::Window::StackDirection* direction) override; private: // Purely for DCHECKs. friend class TransientWindowManager; static TransientWindowStackingClient* instance_; }; } // namespace wm #endif // UI_WM_CORE_TRANSIENT_WINDOW_STACKING_CLIENT_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_stacking_client.h
C++
unknown
1,167
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/transient_window_stacking_client.h" #include <memory> #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_windows.h" #include "ui/compositor/layer.h" #include "ui/compositor/test/test_layers.h" #include "ui/wm/core/window_util.h" using aura::test::ChildWindowIDsAsString; using aura::test::CreateTestWindowWithId; using aura::Window; namespace wm { class TransientWindowStackingClientTest : public aura::test::AuraTestBase { public: TransientWindowStackingClientTest() {} TransientWindowStackingClientTest(const TransientWindowStackingClientTest&) = delete; TransientWindowStackingClientTest& operator=( const TransientWindowStackingClientTest&) = delete; ~TransientWindowStackingClientTest() override {} void SetUp() override { AuraTestBase::SetUp(); client_ = std::make_unique<TransientWindowStackingClient>(); aura::client::SetWindowStackingClient(client_.get()); } void TearDown() override { aura::client::SetWindowStackingClient(NULL); AuraTestBase::TearDown(); } private: std::unique_ptr<TransientWindowStackingClient> client_; }; // Tests that transient children are stacked as a unit when using stack above. TEST_F(TransientWindowStackingClientTest, TransientChildrenGroupAbove) { std::unique_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); Window* w11 = CreateTestWindowWithId(11, parent.get()); std::unique_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); Window* w21 = CreateTestWindowWithId(21, parent.get()); Window* w211 = CreateTestWindowWithId(211, parent.get()); Window* w212 = CreateTestWindowWithId(212, parent.get()); Window* w213 = CreateTestWindowWithId(213, parent.get()); Window* w22 = CreateTestWindowWithId(22, parent.get()); ASSERT_EQ(8u, parent->children().size()); AddTransientChild(w1.get(), w11); // w11 is now owned by w1. AddTransientChild(w2.get(), w21); // w21 is now owned by w2. AddTransientChild(w2.get(), w22); // w22 is now owned by w2. AddTransientChild(w21, w211); // w211 is now owned by w21. AddTransientChild(w21, w212); // w212 is now owned by w21. AddTransientChild(w21, w213); // w213 is now owned by w21. EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); // Stack w1 at the top (end), this should force w11 to be last (on top of w1). parent->StackChildAtTop(w1.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); // This tests that the order in children_ array rather than in // transient_children_ array is used when reinserting transient children. // If transient_children_ array was used '22' would be following '21'. parent->StackChildAtTop(w2.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w11, w2.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w21, w1.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w21, w22); EXPECT_EQ(w213, parent->children().back()); EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w11, w21); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w213, w21); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); // No change when stacking a transient parent above its transient child. parent->StackChildAbove(w21, w211); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); // This tests that the order in children_ array rather than in // transient_children_ array is used when reinserting transient children. // If transient_children_ array was used '22' would be following '21'. parent->StackChildAbove(w2.get(), w1.get()); EXPECT_EQ(w212, parent->children().back()); EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); parent->StackChildAbove(w11, w213); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); } // Tests that transient children are stacked as a unit when using stack below. TEST_F(TransientWindowStackingClientTest, TransientChildrenGroupBelow) { std::unique_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); Window* w11 = CreateTestWindowWithId(11, parent.get()); std::unique_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); Window* w21 = CreateTestWindowWithId(21, parent.get()); Window* w211 = CreateTestWindowWithId(211, parent.get()); Window* w212 = CreateTestWindowWithId(212, parent.get()); Window* w213 = CreateTestWindowWithId(213, parent.get()); Window* w22 = CreateTestWindowWithId(22, parent.get()); ASSERT_EQ(8u, parent->children().size()); AddTransientChild(w1.get(), w11); // w11 is now owned by w1. AddTransientChild(w2.get(), w21); // w21 is now owned by w2. AddTransientChild(w2.get(), w22); // w22 is now owned by w2. AddTransientChild(w21, w211); // w211 is now owned by w21. AddTransientChild(w21, w212); // w212 is now owned by w21. AddTransientChild(w21, w213); // w213 is now owned by w21. EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); // Stack w2 at the bottom, this should force w11 to be last (on top of w1). // This also tests that the order in children_ array rather than in // transient_children_ array is used when reinserting transient children. // If transient_children_ array was used '22' would be following '21'. parent->StackChildAtBottom(w2.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildAtBottom(w1.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w21, w1.get()); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w11, w2.get()); EXPECT_EQ(w22, parent->children().back()); EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w22, w21); EXPECT_EQ(w213, parent->children().back()); EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w21, w11); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w213, w211); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); // No change when stacking a transient parent below its transient child. parent->StackChildBelow(w21, w211); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w1.get(), w2.get()); EXPECT_EQ(w212, parent->children().back()); EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); parent->StackChildBelow(w213, w11); EXPECT_EQ(w11, parent->children().back()); EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); } // Tests that windows can be stacked above windows with a NULL layer delegate. // Windows have a NULL layer delegate when they are in the process of closing. // See crbug.com/443433 TEST_F(TransientWindowStackingClientTest, StackAboveWindowWithNULLLayerDelegate) { std::unique_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); std::unique_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); std::unique_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); w2->layer()->set_delegate(NULL); EXPECT_EQ(w2.get(), parent->children().back()); parent->StackChildAbove(w1.get(), w2.get()); EXPECT_EQ(w1.get(), parent->children().back()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/transient_window_stacking_client_unittest.cc
C++
unknown
8,688
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/visibility_controller.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" #include "ui/compositor/layer.h" #include "ui/wm/core/window_animations.h" namespace wm { namespace { // Property set on all windows whose child windows' visibility changes are // animated. DEFINE_UI_CLASS_PROPERTY_KEY(bool, kChildWindowVisibilityChangesAnimatedKey, false) // A window with this property set will animate upon its visibility changes. DEFINE_UI_CLASS_PROPERTY_KEY(bool, kWindowVisibilityChangesAnimatedKey, false) bool ShouldAnimateWindow(aura::Window* window) { return (window->parent() && window->parent()->GetProperty( kChildWindowVisibilityChangesAnimatedKey)) || window->GetProperty(kWindowVisibilityChangesAnimatedKey); } } // namespace VisibilityController::VisibilityController() { } VisibilityController::~VisibilityController() { } bool VisibilityController::CallAnimateOnChildWindowVisibilityChanged( aura::Window* window, bool visible) { return AnimateOnChildWindowVisibilityChanged(window, visible); } void VisibilityController::UpdateLayerVisibility(aura::Window* window, bool visible) { bool animated = window->GetType() != aura::client::WINDOW_TYPE_CONTROL && window->GetType() != aura::client::WINDOW_TYPE_UNKNOWN && ShouldAnimateWindow(window); animated = animated && CallAnimateOnChildWindowVisibilityChanged(window, visible); // If we're already in the process of hiding don't do anything. Otherwise we // may end up prematurely canceling the animation. // This does not check opacity as when fading out a visibility change should // also be scheduled (to do otherwise would mean the window can not be seen, // opacity is 0, yet the window is marked as visible) (see CL 132903003). // TODO(vollick): remove this. if (!visible && window->layer()->GetAnimator()->IsAnimatingProperty( ui::LayerAnimationElement::VISIBILITY) && !window->layer()->GetTargetVisibility()) { return; } // When a window is made visible, we always make its layer visible // immediately. When a window is hidden, the layer must be left visible and // only made not visible once the animation is complete. if (!animated || visible) window->layer()->SetVisible(visible); } SuspendChildWindowVisibilityAnimations::SuspendChildWindowVisibilityAnimations( aura::Window* window) : window_(window), original_enabled_(window->GetProperty( kChildWindowVisibilityChangesAnimatedKey)) { window_->ClearProperty(kChildWindowVisibilityChangesAnimatedKey); } SuspendChildWindowVisibilityAnimations:: ~SuspendChildWindowVisibilityAnimations() { if (original_enabled_) window_->SetProperty(kChildWindowVisibilityChangesAnimatedKey, true); else window_->ClearProperty(kChildWindowVisibilityChangesAnimatedKey); } void SetWindowVisibilityChangesAnimated(aura::Window* window) { window->SetProperty(kWindowVisibilityChangesAnimatedKey, true); } void SetChildWindowVisibilityChangesAnimated(aura::Window* window) { window->SetProperty(kChildWindowVisibilityChangesAnimatedKey, true); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/visibility_controller.cc
C++
unknown
3,463
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_VISIBILITY_CONTROLLER_H_ #define UI_WM_CORE_VISIBILITY_CONTROLLER_H_ #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "ui/aura/client/visibility_client.h" namespace wm { class COMPONENT_EXPORT(UI_WM) VisibilityController : public aura::client::VisibilityClient { public: VisibilityController(); VisibilityController(const VisibilityController&) = delete; VisibilityController& operator=(const VisibilityController&) = delete; ~VisibilityController() override; protected: // Subclasses override if they want to call a different implementation of // this function. // TODO(beng): potentially replace by an actual window animator class in // window_animations.h. virtual bool CallAnimateOnChildWindowVisibilityChanged(aura::Window* window, bool visible); private: // Overridden from aura::client::VisibilityClient: void UpdateLayerVisibility(aura::Window* window, bool visible) override; }; // Suspends the animations for visibility changes during the lifetime of an // instance of this class. // // Example: // // void ViewName::UnanimatedAction() { // SuspendChildWindowVisibilityAnimations suspend(parent); // // Perform unanimated action here. // // ... // // When the method finishes, visibility animations will return to their // // previous state. // } // class COMPONENT_EXPORT(UI_WM) SuspendChildWindowVisibilityAnimations { public: // Suspend visibility animations of child windows. explicit SuspendChildWindowVisibilityAnimations(aura::Window* window); SuspendChildWindowVisibilityAnimations( const SuspendChildWindowVisibilityAnimations&) = delete; SuspendChildWindowVisibilityAnimations& operator=( const SuspendChildWindowVisibilityAnimations&) = delete; // Restore visibility animations to their original state. ~SuspendChildWindowVisibilityAnimations(); private: // The window to manage. raw_ptr<aura::Window> window_; // Whether the visibility animations on child windows were originally enabled. const bool original_enabled_; }; // Enable visibility change animation for specific |window|. Use this if // you want to enable visibility change animation on a specific window without // affecting other windows in the same container. Calling this on a window // whose animation is already enabled either by this function, or // via SetChildWindowVisibilityChangesAnimatedbelow below is allowed and // the animation stays enabled. COMPONENT_EXPORT(UI_WM) void SetWindowVisibilityChangesAnimated(aura::Window* window); // Enable visibility change animation for all children of the |window|. // Typically applied to a container whose child windows should be animated // when their visibility changes. COMPONENT_EXPORT(UI_WM) void SetChildWindowVisibilityChangesAnimated(aura::Window* window); } // namespace wm #endif // UI_WM_CORE_VISIBILITY_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/visibility_controller.h
C++
unknown
3,117