view.h 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef UI_VIEWS_VIEW_H_
  5. #define UI_VIEWS_VIEW_H_
  6. #include <stddef.h>
  7. #include <algorithm>
  8. #include <memory>
  9. #include <set>
  10. #include <string>
  11. #include <utility>
  12. #include <vector>
  13. #include "base/as_const.h"
  14. #include "base/callback.h"
  15. #include "base/callback_list.h"
  16. #include "base/gtest_prod_util.h"
  17. #include "base/memory/ptr_util.h"
  18. #include "base/memory/raw_ptr.h"
  19. #include "base/observer_list.h"
  20. #include "base/strings/string_piece.h"
  21. #include "build/build_config.h"
  22. #include "third_party/abseil-cpp/absl/types/optional.h"
  23. #include "third_party/skia/include/core/SkPath.h"
  24. #include "ui/accessibility/ax_enums.mojom-forward.h"
  25. #include "ui/base/accelerators/accelerator.h"
  26. #include "ui/base/class_property.h"
  27. #include "ui/base/clipboard/clipboard_format_type.h"
  28. #include "ui/base/cursor/cursor.h"
  29. #include "ui/base/dragdrop/drop_target_event.h"
  30. #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
  31. #include "ui/base/dragdrop/os_exchange_data.h"
  32. #include "ui/base/metadata/metadata_header_macros.h"
  33. #include "ui/base/metadata/metadata_types.h"
  34. #include "ui/base/ui_base_types.h"
  35. #include "ui/compositor/layer_delegate.h"
  36. #include "ui/compositor/layer_observer.h"
  37. #include "ui/compositor/layer_owner.h"
  38. #include "ui/compositor/layer_type.h"
  39. #include "ui/compositor/paint_cache.h"
  40. #include "ui/events/event.h"
  41. #include "ui/events/event_target.h"
  42. #include "ui/gfx/geometry/insets.h"
  43. #include "ui/gfx/geometry/point.h"
  44. #include "ui/gfx/geometry/rect.h"
  45. #include "ui/gfx/geometry/transform.h"
  46. #include "ui/gfx/geometry/vector2d.h"
  47. #include "ui/gfx/geometry/vector2d_conversions.h"
  48. #include "ui/gfx/native_widget_types.h"
  49. #include "ui/views/layout/layout_manager.h"
  50. #include "ui/views/layout/layout_types.h"
  51. #include "ui/views/metadata/view_factory.h"
  52. #include "ui/views/paint_info.h"
  53. #include "ui/views/view_targeter.h"
  54. #include "ui/views/views_export.h"
  55. using ui::OSExchangeData;
  56. namespace gfx {
  57. class Canvas;
  58. class Insets;
  59. } // namespace gfx
  60. namespace ui {
  61. struct AXActionData;
  62. struct AXNodeData;
  63. class ColorProvider;
  64. class Compositor;
  65. class InputMethod;
  66. class Layer;
  67. class NativeTheme;
  68. class PaintContext;
  69. class ThemeProvider;
  70. class TransformRecorder;
  71. } // namespace ui
  72. namespace views {
  73. class Background;
  74. class Border;
  75. class ContextMenuController;
  76. class DragController;
  77. class FocusManager;
  78. class FocusTraversable;
  79. class LayoutProvider;
  80. class ScrollView;
  81. class SizeBounds;
  82. class ViewAccessibility;
  83. class ViewMaskLayer;
  84. class ViewObserver;
  85. class Widget;
  86. class WordLookupClient;
  87. namespace internal {
  88. class PreEventDispatchHandler;
  89. class PostEventDispatchHandler;
  90. class RootView;
  91. class ScopedChildrenLock;
  92. } // namespace internal
  93. // Struct used to describe how a View hierarchy has changed. See
  94. // View::ViewHierarchyChanged.
  95. // TODO(pbos): Move to a separate view_hierarchy_changed_details.h header.
  96. struct VIEWS_EXPORT ViewHierarchyChangedDetails {
  97. ViewHierarchyChangedDetails() = default;
  98. ViewHierarchyChangedDetails(bool is_add,
  99. View* parent,
  100. View* child,
  101. View* move_view)
  102. : is_add(is_add), parent(parent), child(child), move_view(move_view) {}
  103. bool is_add = false;
  104. // New parent if |is_add| is true, old parent if |is_add| is false.
  105. raw_ptr<View> parent = nullptr;
  106. // The view being added or removed.
  107. raw_ptr<View> child = nullptr;
  108. // If this is a move (reparent), meaning AddChildViewAt() is invoked with an
  109. // existing parent, then a notification for the remove is sent first,
  110. // followed by one for the add. This case can be distinguished by a
  111. // non-null |move_view|.
  112. // For the remove part of move, |move_view| is the new parent of the View
  113. // being removed.
  114. // For the add part of move, |move_view| is the old parent of the View being
  115. // added.
  116. raw_ptr<View> move_view = nullptr;
  117. };
  118. using PropertyChangedCallback = ui::metadata::PropertyChangedCallback;
  119. // The elements in PropertyEffects represent bits which define what effect(s) a
  120. // changed Property has on the containing class. Additional elements should
  121. // use the next most significant bit.
  122. enum PropertyEffects {
  123. kPropertyEffectsNone = 0,
  124. // Any changes to the property should cause the container to invalidate the
  125. // current layout state.
  126. kPropertyEffectsLayout = 0x00000001,
  127. // Changes to the property should cause the container to schedule a painting
  128. // update.
  129. kPropertyEffectsPaint = 0x00000002,
  130. // Changes to the property should cause the preferred size to change. This
  131. // implies kPropertyEffectsLayout.
  132. kPropertyEffectsPreferredSizeChanged = 0x00000004,
  133. };
  134. /////////////////////////////////////////////////////////////////////////////
  135. //
  136. // View class
  137. //
  138. // A View is a rectangle within the views View hierarchy. It is the base
  139. // class for all Views.
  140. //
  141. // A View is a container of other Views (there is no such thing as a Leaf
  142. // View - makes code simpler, reduces type conversion headaches, design
  143. // mistakes etc)
  144. //
  145. // The View contains basic properties for sizing (bounds), layout (flex,
  146. // orientation, etc), painting of children and event dispatch.
  147. //
  148. // The View also uses a simple Box Layout Manager similar to XUL's
  149. // SprocketLayout system. Alternative Layout Managers implementing the
  150. // LayoutManager interface can be used to lay out children if required.
  151. //
  152. // It is up to the subclass to implement Painting and storage of subclass -
  153. // specific properties and functionality.
  154. //
  155. // Unless otherwise documented, views is not thread safe and should only be
  156. // accessed from the main thread.
  157. //
  158. // Properties ------------------
  159. //
  160. // Properties which are intended to be dynamically visible through metadata to
  161. // other subsystems, such as dev-tools must adhere to a naming convention,
  162. // usage and implementation patterns.
  163. //
  164. // Properties start with their base name, such as "Frobble" (note the
  165. // capitalization). The method to set the property must be called SetXXXX and
  166. // the method to retrieve the value is called GetXXXX. For the aforementioned
  167. // Frobble property, this would be SetFrobble and GetFrobble.
  168. //
  169. // void SetFrobble(bool is_frobble);
  170. // bool GetFrobble() const;
  171. //
  172. // In the SetXXXX method, after the value storage location has been updated,
  173. // OnPropertyChanged() must be called using the address of the storage
  174. // location as a key. Additionally, any combination of PropertyEffects are
  175. // also passed in. This will ensure that any desired side effects are properly
  176. // invoked.
  177. //
  178. // void View::SetFrobble(bool is_frobble) {
  179. // if (is_frobble == frobble_)
  180. // return;
  181. // frobble_ = is_frobble;
  182. // OnPropertyChanged(&frobble_, kPropertyEffectsPaint);
  183. // }
  184. //
  185. // Each property should also have a way to "listen" to changes by registering
  186. // a callback.
  187. //
  188. // base::CallbackListSubscription AddFrobbleChangedCallback(
  189. // PropertyChangedCallback callback);
  190. //
  191. // Each callback uses the the existing base::Bind mechanisms which allow for
  192. // various kinds of callbacks; object methods, normal functions and lambdas.
  193. //
  194. // Example:
  195. //
  196. // class FrobbleView : public View {
  197. // ...
  198. // private:
  199. // void OnFrobbleChanged();
  200. // base::CallbackListSubscription frobble_changed_subscription_;
  201. // }
  202. //
  203. // ...
  204. // frobble_changed_subscription_ = AddFrobbleChangedCallback(
  205. // base::BindRepeating(&FrobbleView::OnFrobbleChanged,
  206. // base::Unretained(this)));
  207. //
  208. // Example:
  209. //
  210. // void MyView::ValidateFrobbleChanged() {
  211. // bool frobble_changed = false;
  212. // base::CallbackListSubscription subscription =
  213. // frobble_view_->AddFrobbleChangedCallback(
  214. // base::BindRepeating([](bool* frobble_changed_ptr) {
  215. // *frobble_changed_ptr = true;
  216. // }, &frobble_changed));
  217. // frobble_view_->SetFrobble(!frobble_view_->GetFrobble());
  218. // LOG() << frobble_changed ? "Frobble changed" : "Frobble NOT changed!";
  219. // }
  220. //
  221. // Property metadata -----------
  222. //
  223. // For Views that expose properties which are intended to be dynamically
  224. // discoverable by other subsystems, each View and its descendants must
  225. // include metadata. These other subsystems, such as dev tools or a delarative
  226. // layout system, can then enumerate the properties on any given instance or
  227. // class. Using the enumerated information, the actual values of the
  228. // properties can be read or written. This will be done by getting and setting
  229. // the values using string representations. The metadata can also be used to
  230. // instantiate and initialize a View (or descendant) class from a declarative
  231. // "script".
  232. //
  233. // For each View class in their respective header declaration, place the macro
  234. // METADATA_HEADER(<classname>) in the public section.
  235. //
  236. // In the implementing .cc file, add the following macros to the same
  237. // namespace in which the class resides.
  238. //
  239. // BEGIN_METADATA(View, ParentView)
  240. // ADD_PROPERTY_METADATA(bool, Frobble)
  241. // END_METADATA
  242. //
  243. // For each property, add a definition using ADD_PROPERTY_METADATA() between
  244. // the begin and end macros.
  245. //
  246. // Descendant classes must specify the parent class as a macro parameter.
  247. //
  248. // BEGIN_METADATA(MyView, views::View)
  249. // ADD_PROPERTY_METADATA(int, Bobble)
  250. // END_METADATA
  251. /////////////////////////////////////////////////////////////////////////////
  252. class VIEWS_EXPORT View : public ui::LayerDelegate,
  253. public ui::LayerObserver,
  254. public ui::LayerOwner,
  255. public ui::AcceleratorTarget,
  256. public ui::EventTarget,
  257. public ui::EventHandler,
  258. public ui::PropertyHandler,
  259. public ui::metadata::MetaDataProvider {
  260. public:
  261. using Views = std::vector<View*>;
  262. // TODO(crbug.com/1289902): The |event| parameter is being removed. Do not add
  263. // new callers.
  264. using DropCallback =
  265. base::OnceCallback<void(const ui::DropTargetEvent& event,
  266. ui::mojom::DragOperation& output_drag_op)>;
  267. METADATA_HEADER_BASE(View);
  268. enum class FocusBehavior {
  269. // Use when the View is never focusable. Default.
  270. NEVER,
  271. // Use when the View is to be focusable both in regular and accessibility
  272. // mode.
  273. ALWAYS,
  274. // Use when the View is focusable only during accessibility mode.
  275. ACCESSIBLE_ONLY,
  276. };
  277. // During paint, the origin of each view in physical pixel is calculated by
  278. // view_origin_pixel = ROUND(view.origin() * device_scale_factor)
  279. //
  280. // Thus in a view hierarchy, the offset between two views, view_i and view_j,
  281. // is calculated by:
  282. // view_offset_ij_pixel = SUM [view_origin_pixel.OffsetFromOrigin()]
  283. // {For all views along the path from view_i to view_j}
  284. //
  285. // But the offset between the two layers, the layer in view_i and the layer in
  286. // view_j, is computed by
  287. // view_offset_ij_dip = SUM [view.origin().OffsetFromOrigin()]
  288. // {For all views along the path from view_i to view_j}
  289. //
  290. // layer_offset_ij_pixel = ROUND (view_offset_ij_dip * device_scale_factor)
  291. //
  292. // Due to this difference in the logic for computation of offset, the values
  293. // view_offset_ij_pixel and layer_offset_ij_pixel may not always be equal.
  294. // They will differ by some subpixel_offset. This leads to bugs like
  295. // crbug.com/734787.
  296. // The subpixel offset needs to be applied to the layer to get the correct
  297. // output during paint.
  298. //
  299. // This class manages the computation of subpixel offset internally when
  300. // working with offsets.
  301. class LayerOffsetData {
  302. public:
  303. explicit LayerOffsetData(float device_scale_factor = 1.f,
  304. const gfx::Vector2d& offset = gfx::Vector2d())
  305. : device_scale_factor_(device_scale_factor) {
  306. AddOffset(offset);
  307. }
  308. const gfx::Vector2d& offset() const { return offset_; }
  309. const gfx::Vector2dF GetSubpixelOffset() const {
  310. // |rounded_pixel_offset_| is stored in physical pixel space. Convert it
  311. // into DIP space before returning.
  312. gfx::Vector2dF subpixel_offset(rounded_pixel_offset_);
  313. subpixel_offset.Scale(1.f / device_scale_factor_);
  314. return subpixel_offset;
  315. }
  316. LayerOffsetData& operator+=(const gfx::Vector2d& offset) {
  317. AddOffset(offset);
  318. return *this;
  319. }
  320. LayerOffsetData operator+(const gfx::Vector2d& offset) const {
  321. LayerOffsetData offset_data(*this);
  322. offset_data.AddOffset(offset);
  323. return offset_data;
  324. }
  325. private:
  326. // Adds the |offset_to_parent| to the total |offset_| and updates the
  327. // |rounded_pixel_offset_| value.
  328. void AddOffset(const gfx::Vector2d& offset_to_parent) {
  329. // Add the DIP |offset_to_parent| amount to the total offset.
  330. offset_ += offset_to_parent;
  331. // Convert |offset_to_parent| to physical pixel coordinates.
  332. gfx::Vector2dF fractional_pixel_offset(
  333. offset_to_parent.x() * device_scale_factor_,
  334. offset_to_parent.y() * device_scale_factor_);
  335. // Since pixels cannot be fractional, we need to round the offset to get
  336. // the correct physical pixel coordinate.
  337. gfx::Vector2d integral_pixel_offset =
  338. gfx::ToRoundedVector2d(fractional_pixel_offset);
  339. // |integral_pixel_offset - fractional_pixel_offset| gives the subpixel
  340. // offset amount for |offset_to_parent|. This is added to
  341. // |rounded_pixel_offset_| to update the total subpixel offset.
  342. rounded_pixel_offset_ += integral_pixel_offset - fractional_pixel_offset;
  343. }
  344. // Total offset so far. This stores the offset between two nodes in the view
  345. // hierarchy.
  346. gfx::Vector2d offset_;
  347. // This stores the value such that if added to
  348. // |offset_ * device_scale_factor| will give the correct aligned offset in
  349. // physical pixels.
  350. gfx::Vector2dF rounded_pixel_offset_;
  351. // The device scale factor at which the subpixel offset is being computed.
  352. float device_scale_factor_;
  353. };
  354. // Creation and lifetime -----------------------------------------------------
  355. View();
  356. View(const View&) = delete;
  357. View& operator=(const View&) = delete;
  358. ~View() override;
  359. // By default a View is owned by its parent unless specified otherwise here.
  360. void set_owned_by_client() { owned_by_client_ = true; }
  361. bool owned_by_client() const { return owned_by_client_; }
  362. // Tree operations -----------------------------------------------------------
  363. // Get the Widget that hosts this View, if any.
  364. virtual const Widget* GetWidget() const;
  365. virtual Widget* GetWidget();
  366. // Adds |view| as a child of this view, optionally at |index|.
  367. // Returns the raw pointer for callers which want to hold a pointer to the
  368. // added view. This requires declaring the function as a template in order to
  369. // return the actual passed-in type.
  370. template <typename T>
  371. T* AddChildView(std::unique_ptr<T> view) {
  372. DCHECK(!view->owned_by_client())
  373. << "This should only be called if the client is passing ownership of "
  374. "|view| to the parent View.";
  375. return AddChildView<T>(view.release());
  376. }
  377. template <typename T>
  378. T* AddChildViewAt(std::unique_ptr<T> view, size_t index) {
  379. DCHECK(!view->owned_by_client())
  380. << "This should only be called if the client is passing ownership of "
  381. "|view| to the parent View.";
  382. return AddChildViewAt<T>(view.release(), index);
  383. }
  384. // Prefer using the AddChildView(std::unique_ptr) overloads over raw pointers
  385. // for new code.
  386. template <typename T>
  387. T* AddChildView(T* view) {
  388. AddChildViewAtImpl(view, children_.size());
  389. return view;
  390. }
  391. template <typename T>
  392. T* AddChildViewAt(T* view, size_t index) {
  393. AddChildViewAtImpl(view, index);
  394. return view;
  395. }
  396. // Moves |view| to the specified |index|. An |index| at least as large as that
  397. // of the last child moves the view to the end.
  398. void ReorderChildView(View* view, size_t index);
  399. // Removes |view| from this view. The view's parent will change to null.
  400. void RemoveChildView(View* view);
  401. // Removes |view| from this view and transfers ownership back to the caller in
  402. // the form of a std::unique_ptr<T>.
  403. // TODO(kylixrd): Rename back to RemoveChildView() once the code is refactored
  404. // to eliminate the uses of the old RemoveChildView().
  405. template <typename T>
  406. std::unique_ptr<T> RemoveChildViewT(T* view) {
  407. DCHECK(!view->owned_by_client())
  408. << "This should only be called if the client doesn't already have "
  409. "ownership of |view|.";
  410. DCHECK(std::find(children_.cbegin(), children_.cend(), view) !=
  411. children_.cend());
  412. RemoveChildView(view);
  413. return base::WrapUnique(view);
  414. }
  415. // Partially specialized version to directly take a raw_ptr<T>.
  416. template <typename T>
  417. std::unique_ptr<T> RemoveChildViewT(raw_ptr<T> view) {
  418. return RemoveChildViewT(view.get());
  419. }
  420. // Removes all the children from this view. This deletes all children that are
  421. // not set_owned_by_client(), which is deprecated.
  422. void RemoveAllChildViews();
  423. // TODO(pbos): Remove this method, deleting children when removing them should
  424. // not be optional. If ownership needs to be preserved, use RemoveChildViewT()
  425. // to retain ownership of the removed children.
  426. void RemoveAllChildViewsWithoutDeleting();
  427. const Views& children() const { return children_; }
  428. // Returns the parent view.
  429. const View* parent() const { return parent_; }
  430. View* parent() { return parent_; }
  431. // Returns true if |view| is contained within this View's hierarchy, even as
  432. // an indirect descendant. Will return true if child is also this view.
  433. bool Contains(const View* view) const;
  434. // Returns an iterator pointing to |view|, or children_.cend() if |view| is
  435. // not a child of this view.
  436. Views::const_iterator FindChild(const View* view) const;
  437. // Returns the index of |view|, or nullopt if |view| is not a child of this
  438. // view.
  439. absl::optional<size_t> GetIndexOf(const View* view) const;
  440. // Size and disposition ------------------------------------------------------
  441. // Methods for obtaining and modifying the position and size of the view.
  442. // Position is in the coordinate system of the view's parent.
  443. // Position is NOT flipped for RTL. See "RTL positioning" for RTL-sensitive
  444. // position accessors.
  445. // Transformations are not applied on the size/position. For example, if
  446. // bounds is (0, 0, 100, 100) and it is scaled by 0.5 along the X axis, the
  447. // width will still be 100 (although when painted, it will be 50x100, painted
  448. // at location (0, 0)).
  449. void SetBounds(int x, int y, int width, int height);
  450. void SetBoundsRect(const gfx::Rect& bounds);
  451. void SetSize(const gfx::Size& size);
  452. void SetPosition(const gfx::Point& position);
  453. void SetX(int x);
  454. void SetY(int y);
  455. // No transformation is applied on the size or the locations.
  456. const gfx::Rect& bounds() const { return bounds_; }
  457. int x() const { return bounds_.x(); }
  458. int y() const { return bounds_.y(); }
  459. int width() const { return bounds_.width(); }
  460. int height() const { return bounds_.height(); }
  461. const gfx::Point& origin() const { return bounds_.origin(); }
  462. const gfx::Size& size() const { return bounds_.size(); }
  463. // Returns the bounds of the content area of the view, i.e. the rectangle
  464. // enclosed by the view's border.
  465. gfx::Rect GetContentsBounds() const;
  466. // Returns the bounds of the view in its own coordinates (i.e. position is
  467. // 0, 0).
  468. gfx::Rect GetLocalBounds() const;
  469. // Returns the insets of the current border. If there is no border an empty
  470. // insets is returned.
  471. virtual gfx::Insets GetInsets() const;
  472. // Returns the visible bounds of the receiver in the receivers coordinate
  473. // system.
  474. //
  475. // When traversing the View hierarchy in order to compute the bounds, the
  476. // function takes into account the mirroring setting and transformation for
  477. // each View and therefore it will return the mirrored and transformed version
  478. // of the visible bounds if need be.
  479. gfx::Rect GetVisibleBounds() const;
  480. // Return the bounds of the View in screen coordinate system.
  481. gfx::Rect GetBoundsInScreen() const;
  482. // Return the bounds that an anchored widget should anchor to. These can be
  483. // different from |GetBoundsInScreen()| when a view is larger than its visible
  484. // size, for instance to provide a larger hittable area.
  485. virtual gfx::Rect GetAnchorBoundsInScreen() const;
  486. // Returns the baseline of this view, or -1 if this view has no baseline. The
  487. // return value is relative to the preferred height.
  488. virtual int GetBaseline() const;
  489. // Get the size the View would like to be under the current bounds.
  490. // If the View is never laid out before, assume it to be laid out in an
  491. // unbounded space.
  492. // TODO(crbug.com/1346889): Don't use this. Use the size-constrained
  493. // GetPreferredSize(const SizeBounds&) instead.
  494. gfx::Size GetPreferredSize() const;
  495. // Get the size the View would like to be given `available_size`, ignoring the
  496. // current bounds.
  497. gfx::Size GetPreferredSize(const SizeBounds& available_size) const;
  498. // Sets or unsets the size that this View will request during layout. The
  499. // actual size may differ. It should rarely be necessary to set this; usually
  500. // the right approach is controlling the parent's layout via a LayoutManager.
  501. void SetPreferredSize(absl::optional<gfx::Size> size);
  502. // Convenience method that sizes this view to its preferred size.
  503. void SizeToPreferredSize();
  504. // Gets the minimum size of the view. View's implementation invokes
  505. // GetPreferredSize.
  506. virtual gfx::Size GetMinimumSize() const;
  507. // Gets the maximum size of the view. Currently only used for sizing shell
  508. // windows.
  509. virtual gfx::Size GetMaximumSize() const;
  510. // Return the preferred height for a specific width. Override if the
  511. // preferred height depends upon the width (such as a multi-line label). If
  512. // a LayoutManger has been installed this returns the value of
  513. // LayoutManager::GetPreferredHeightForWidth(), otherwise this returns
  514. // GetPreferredSize().height().
  515. virtual int GetHeightForWidth(int w) const;
  516. // Returns a bound on the available space for a child view, for example, in
  517. // case the child view wants to play an animation that would cause it to
  518. // become larger. Default is not to bound the available size; it is the
  519. // responsibility of specific view/layout manager implementations to determine
  520. // if and when a bound applies.
  521. virtual SizeBounds GetAvailableSize(const View* child) const;
  522. // The |Visible| property. See comment above for instructions on declaring and
  523. // implementing a property.
  524. //
  525. // Sets whether this view is visible. Painting is scheduled as needed. Also,
  526. // clears focus if the focused view or one of its ancestors is set to be
  527. // hidden.
  528. virtual void SetVisible(bool visible);
  529. // Return whether a view is visible.
  530. bool GetVisible() const;
  531. // Adds a callback associated with the above Visible property. The callback
  532. // will be invoked whenever the Visible property changes.
  533. [[nodiscard]] base::CallbackListSubscription AddVisibleChangedCallback(
  534. PropertyChangedCallback callback);
  535. // Returns true if this view is drawn on screen.
  536. virtual bool IsDrawn() const;
  537. // The |Enabled| property. See comment above for instructions on declaring and
  538. // implementing a property.
  539. //
  540. // Set whether this view is enabled. A disabled view does not receive keyboard
  541. // or mouse inputs. If |enabled| differs from the current value, SchedulePaint
  542. // is invoked. Also, clears focus if the focused view is disabled.
  543. void SetEnabled(bool enabled);
  544. // Returns whether the view is enabled.
  545. bool GetEnabled() const;
  546. // Adds a callback associated with the above |Enabled| property. The callback
  547. // will be invoked whenever the property changes.
  548. [[nodiscard]] base::CallbackListSubscription AddEnabledChangedCallback(
  549. PropertyChangedCallback callback);
  550. // Returns the child views ordered in reverse z-order. That is, views later in
  551. // the returned vector have a higher z-order (are painted later) than those
  552. // early in the vector. The returned vector has exactly the same number of
  553. // Views as |children_|. The default implementation returns |children_|,
  554. // subclass if the paint order should differ from that of |children_|.
  555. // This order is taken into account by painting and targeting implementations.
  556. // NOTE: see SetPaintToLayer() for details on painting and views with layers.
  557. virtual Views GetChildrenInZOrder();
  558. // Transformations -----------------------------------------------------------
  559. // Methods for setting transformations for a view (e.g. rotation, scaling).
  560. // Care should be taken not to transform a view in such a way that its bounds
  561. // lie outside those of its parent, or else the default ViewTargeterDelegate
  562. // implementation will not pass mouse events to the view.
  563. gfx::Transform GetTransform() const;
  564. // Clipping is done relative to the view's local bounds.
  565. void SetClipPath(const SkPath& path);
  566. const SkPath& clip_path() const { return clip_path_; }
  567. // Sets the transform to the supplied transform.
  568. void SetTransform(const gfx::Transform& transform);
  569. // Accelerated painting ------------------------------------------------------
  570. // Sets whether this view paints to a layer. A view paints to a layer if
  571. // either of the following are true:
  572. // . the view has a non-identity transform.
  573. // . SetPaintToLayer(ui::LayerType) has been invoked.
  574. // View creates the Layer only when it exists in a Widget with a non-NULL
  575. // Compositor.
  576. // Enabling a view to have a layer impacts painting of sibling views.
  577. // Specifically views with layers effectively paint in a z-order that is
  578. // always above any sibling views that do not have layers. This happens
  579. // regardless of the ordering returned by GetChildrenInZOrder().
  580. void SetPaintToLayer(ui::LayerType layer_type = ui::LAYER_TEXTURED);
  581. // Cancels layer painting triggered by a call to |SetPaintToLayer()|. Note
  582. // that this will not actually destroy the layer if the view paints to a layer
  583. // for another reason.
  584. void DestroyLayer();
  585. // Add or remove layers below this view. This view does not take ownership of
  586. // the layers. It is the caller's responsibility to keep track of this View's
  587. // size and update their layer accordingly.
  588. //
  589. // In very rare cases, it may be necessary to override these. If any of this
  590. // view's contents must be painted to the same layer as its parent, or can't
  591. // handle being painted with transparency, overriding might be appropriate.
  592. // One example is LabelButton, where the label must paint below any added
  593. // layers for subpixel rendering reasons. Overrides should be made
  594. // judiciously, and generally they should just forward the calls to a child
  595. // view. They must be overridden together for correctness.
  596. virtual void AddLayerBeneathView(ui::Layer* new_layer);
  597. virtual void RemoveLayerBeneathView(ui::Layer* old_layer);
  598. // This is like RemoveLayerBeneathView() but doesn't remove |old_layer| from
  599. // its parent. This is useful for when a layer beneth this view is owned by a
  600. // ui::LayerOwner which just recreated it (by calling RecreateLayer()). In
  601. // this case, this function can be called to remove it from |layers_beneath_|,
  602. // and to stop observing it, but it remains in the layer tree since the
  603. // expectation of ui::LayerOwner::RecreateLayer() is that the old layer
  604. // remains under the same parent, and stacked above the newly cloned layer.
  605. void RemoveLayerBeneathViewKeepInLayerTree(ui::Layer* old_layer);
  606. // Gets the layers associated with this view that should be immediate children
  607. // of the parent layer. They are returned in bottom-to-top order. This
  608. // includes |this->layer()| and any layers added with |AddLayerBeneathView()|.
  609. // Returns an empty vector if this view doesn't paint to a layer.
  610. std::vector<ui::Layer*> GetLayersInOrder();
  611. // ui::LayerObserver:
  612. void LayerDestroyed(ui::Layer* layer) override;
  613. // Overridden from ui::LayerOwner:
  614. std::unique_ptr<ui::Layer> RecreateLayer() override;
  615. // RTL positioning -----------------------------------------------------------
  616. // Methods for accessing the bounds and position of the view, relative to its
  617. // parent. The position returned is mirrored if the parent view is using a RTL
  618. // layout.
  619. //
  620. // NOTE: in the vast majority of the cases, the mirroring implementation is
  621. // transparent to the View subclasses and therefore you should use the
  622. // bounds() accessor instead.
  623. gfx::Rect GetMirroredBounds() const;
  624. gfx::Rect GetMirroredContentsBounds() const;
  625. gfx::Point GetMirroredPosition() const;
  626. int GetMirroredX() const;
  627. // Given a rectangle specified in this View's coordinate system, the function
  628. // computes the 'left' value for the mirrored rectangle within this View. If
  629. // the View's UI layout is not right-to-left, then bounds.x() is returned.
  630. //
  631. // UI mirroring is transparent to most View subclasses and therefore there is
  632. // no need to call this routine from anywhere within your subclass
  633. // implementation.
  634. int GetMirroredXForRect(const gfx::Rect& rect) const;
  635. // Given a rectangle specified in this View's coordinate system, the function
  636. // computes the mirrored rectangle.
  637. gfx::Rect GetMirroredRect(const gfx::Rect& rect) const;
  638. // Given the X coordinate of a point inside the View, this function returns
  639. // the mirrored X coordinate of the point if the View's UI layout is
  640. // right-to-left. If the layout is left-to-right, the same X coordinate is
  641. // returned.
  642. //
  643. // Following are a few examples of the values returned by this function for
  644. // a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
  645. //
  646. // GetMirroredXCoordinateInView(0) -> 100
  647. // GetMirroredXCoordinateInView(20) -> 80
  648. // GetMirroredXCoordinateInView(99) -> 1
  649. int GetMirroredXInView(int x) const;
  650. // Given a X coordinate and a width inside the View, this function returns
  651. // the mirrored X coordinate if the View's UI layout is right-to-left. If the
  652. // layout is left-to-right, the same X coordinate is returned.
  653. //
  654. // Following are a few examples of the values returned by this function for
  655. // a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
  656. //
  657. // GetMirroredXCoordinateInView(0, 10) -> 90
  658. // GetMirroredXCoordinateInView(20, 20) -> 60
  659. int GetMirroredXWithWidthInView(int x, int w) const;
  660. // Layout --------------------------------------------------------------------
  661. // Lay out the child Views (set their bounds based on sizing heuristics
  662. // specific to the current Layout Manager)
  663. virtual void Layout();
  664. // Mark this view and all parents to require a relayout. This ensures the
  665. // next call to Layout() will propagate to this view, even if the bounds of
  666. // parent views do not change.
  667. void InvalidateLayout();
  668. // TODO(kylixrd): Update comment once UseDefaultFillLayout is true by default.
  669. // UseDefaultFillLayout will be set to true by default once the codebase is
  670. // audited and refactored.
  671. //
  672. // Gets/Sets the Layout Manager used by this view to size and place its
  673. // children. NOTE: This will force UseDefaultFillLayout to false if it had
  674. // been set to true.
  675. //
  676. // The LayoutManager is owned by the View and is deleted when the view is
  677. // deleted, or when a new LayoutManager is installed. Call
  678. // SetLayoutManager(nullptr) to clear it.
  679. //
  680. // SetLayoutManager returns a bare pointer version of the input parameter
  681. // (now owned by the view). If code needs to use the layout manager after
  682. // being assigned, use this pattern:
  683. //
  684. // views::BoxLayout* box_layout = SetLayoutManager(
  685. // std::make_unique<views::BoxLayout>(...));
  686. // box_layout->Foo();
  687. LayoutManager* GetLayoutManager() const;
  688. template <typename LayoutManager>
  689. LayoutManager* SetLayoutManager(
  690. std::unique_ptr<LayoutManager> layout_manager) {
  691. LayoutManager* lm = layout_manager.get();
  692. SetLayoutManagerImpl(std::move(layout_manager));
  693. return lm;
  694. }
  695. void SetLayoutManager(std::nullptr_t);
  696. // Sets whether or not the default layout manager should be used for this
  697. // view. NOTE: this can only be set if |layout_manager_| isn't assigned.
  698. bool GetUseDefaultFillLayout() const;
  699. void SetUseDefaultFillLayout(bool value);
  700. // Attributes ----------------------------------------------------------------
  701. // Recursively descends the view tree starting at this view, and returns
  702. // the first child that it encounters that has the given ID.
  703. // Returns NULL if no matching child view is found.
  704. const View* GetViewByID(int id) const;
  705. View* GetViewByID(int id);
  706. // Gets and sets the ID for this view. ID should be unique within the subtree
  707. // that you intend to search for it. 0 is the default ID for views.
  708. int GetID() const { return id_; }
  709. void SetID(int id);
  710. // Adds a callback associated with the above |ID| property. The callback will
  711. // be invoked whenever the property changes.
  712. [[nodiscard]] base::CallbackListSubscription AddIDChangedCallback(
  713. PropertyChangedCallback callback);
  714. // A group id is used to tag views which are part of the same logical group.
  715. // Focus can be moved between views with the same group using the arrow keys.
  716. // Groups are currently used to implement radio button mutual exclusion.
  717. // The group id is immutable once it's set.
  718. void SetGroup(int gid);
  719. // Returns the group id of the view, or -1 if the id is not set yet.
  720. int GetGroup() const;
  721. // Adds a callback associated with the above |Group| property. The callback
  722. // will be invoked whenever the property changes.
  723. [[nodiscard]] base::CallbackListSubscription AddGroupChangedCallback(
  724. PropertyChangedCallback callback);
  725. // If this returns true, the views from the same group can each be focused
  726. // when moving focus with the Tab/Shift-Tab key. If this returns false,
  727. // only the selected view from the group (obtained with
  728. // GetSelectedViewForGroup()) is focused.
  729. virtual bool IsGroupFocusTraversable() const;
  730. // Fills |views| with all the available views which belong to the provided
  731. // |group|.
  732. void GetViewsInGroup(int group, Views* views);
  733. // Returns the View that is currently selected in |group|.
  734. // The default implementation simply returns the first View found for that
  735. // group.
  736. virtual View* GetSelectedViewForGroup(int group);
  737. // Coordinate conversion -----------------------------------------------------
  738. // Note that the utility coordinate conversions functions always operate on
  739. // the mirrored position of the child Views if the parent View uses a
  740. // right-to-left UI layout.
  741. // Convert a point from the coordinate system of one View to another.
  742. //
  743. // |source| and |target| must be in the same widget, but doesn't need to be in
  744. // the same view hierarchy.
  745. // Neither |source| nor |target| can be NULL.
  746. static void ConvertPointToTarget(const View* source,
  747. const View* target,
  748. gfx::Point* point);
  749. // Convert |rect| from the coordinate system of |source| to the coordinate
  750. // system of |target|.
  751. //
  752. // |source| and |target| must be in the same widget, but doesn't need to be in
  753. // the same view hierarchy.
  754. // Neither |source| nor |target| can be NULL.
  755. static void ConvertRectToTarget(const View* source,
  756. const View* target,
  757. gfx::RectF* rect);
  758. // Convert a point from a View's coordinate system to that of its Widget.
  759. static void ConvertPointToWidget(const View* src, gfx::Point* point);
  760. // Convert a point from the coordinate system of a View's Widget to that
  761. // View's coordinate system.
  762. static void ConvertPointFromWidget(const View* dest, gfx::Point* p);
  763. // Convert a point from a View's coordinate system to that of the screen.
  764. static void ConvertPointToScreen(const View* src, gfx::Point* point);
  765. // Convert a point from the screen coordinate system to that View's coordinate
  766. // system.
  767. static void ConvertPointFromScreen(const View* dst, gfx::Point* point);
  768. // Convert a rect from a View's coordinate system to that of the screen.
  769. static void ConvertRectToScreen(const View* src, gfx::Rect* rect);
  770. // Applies transformation on the rectangle, which is in the view's coordinate
  771. // system, to convert it into the parent's coordinate system.
  772. gfx::Rect ConvertRectToParent(const gfx::Rect& rect) const;
  773. // Converts a rectangle from this views coordinate system to its widget
  774. // coordinate system.
  775. gfx::Rect ConvertRectToWidget(const gfx::Rect& rect) const;
  776. // Painting ------------------------------------------------------------------
  777. // Mark all or part of the View's bounds as dirty (needing repaint).
  778. // |r| is in the View's coordinates.
  779. // TODO(beng): Make protected.
  780. void SchedulePaint();
  781. void SchedulePaintInRect(const gfx::Rect& r);
  782. // Called by the framework to paint a View. Performs translation and clipping
  783. // for View coordinates and language direction as required, allows the View
  784. // to paint itself via the various OnPaint*() event handlers and then paints
  785. // the hierarchy beneath it.
  786. void Paint(const PaintInfo& parent_paint_info);
  787. // The background object may be null.
  788. void SetBackground(std::unique_ptr<Background> b);
  789. Background* GetBackground() const;
  790. const Background* background() const { return background_.get(); }
  791. Background* background() { return background_.get(); }
  792. // The border object may be null.
  793. virtual void SetBorder(std::unique_ptr<Border> b);
  794. Border* GetBorder() const;
  795. // Get the theme provider from the parent widget.
  796. const ui::ThemeProvider* GetThemeProvider() const;
  797. // Get the layout provider for the View.
  798. const LayoutProvider* GetLayoutProvider() const;
  799. // Returns the ColorProvider from the ColorProviderManager.
  800. ui::ColorProvider* GetColorProvider() {
  801. return const_cast<ui::ColorProvider*>(
  802. base::as_const(*this).GetColorProvider());
  803. }
  804. const ui::ColorProvider* GetColorProvider() const;
  805. // Returns the NativeTheme to use for this View. This calls through to
  806. // GetNativeTheme() on the Widget this View is in, or provides a default
  807. // theme if there's no widget, or returns |native_theme_| if that's
  808. // set. Warning: the default theme might not be correct; you should probably
  809. // override OnThemeChanged().
  810. ui::NativeTheme* GetNativeTheme() {
  811. return const_cast<ui::NativeTheme*>(base::as_const(*this).GetNativeTheme());
  812. }
  813. const ui::NativeTheme* GetNativeTheme() const;
  814. // Sets the native theme and informs descendants.
  815. void SetNativeThemeForTesting(ui::NativeTheme* theme);
  816. // RTL painting --------------------------------------------------------------
  817. // Returns whether the gfx::Canvas object passed to Paint() needs to be
  818. // transformed such that anything drawn on the canvas object during Paint()
  819. // is flipped horizontally.
  820. bool GetFlipCanvasOnPaintForRTLUI() const;
  821. // Enables or disables flipping of the gfx::Canvas during Paint(). Note that
  822. // if canvas flipping is enabled, the canvas will be flipped only if the UI
  823. // layout is right-to-left; that is, the canvas will be flipped only if
  824. // GetMirrored() is true.
  825. //
  826. // Enabling canvas flipping is useful for leaf views that draw an image that
  827. // needs to be flipped horizontally when the UI layout is right-to-left
  828. // (views::Button, for example). This method is helpful for such classes
  829. // because their drawing logic stays the same and they can become agnostic to
  830. // the UI directionality.
  831. void SetFlipCanvasOnPaintForRTLUI(bool enable);
  832. // Adds a callback associated with the above FlipCanvasOnPaintForRTLUI
  833. // property. The callback will be invoked whenever the
  834. // FlipCanvasOnPaintForRTLUI property changes.
  835. [[nodiscard]] base::CallbackListSubscription
  836. AddFlipCanvasOnPaintForRTLUIChangedCallback(PropertyChangedCallback callback);
  837. // When set, this view will ignore base::l18n::IsRTL() and instead be drawn
  838. // according to |is_mirrored|.
  839. //
  840. // This is useful for views that should be displayed the same regardless of UI
  841. // direction. Unlike SetFlipCanvasOnPaintForRTLUI this setting has an effect
  842. // on the visual order of child views.
  843. //
  844. // This setting does not propagate to child views. So while the visual order
  845. // of this view's children may change, the visual order of this view's
  846. // grandchildren in relation to their parents are unchanged.
  847. void SetMirrored(bool is_mirrored);
  848. bool GetMirrored() const;
  849. // Input ---------------------------------------------------------------------
  850. // The points, rects, mouse locations, and touch locations in the following
  851. // functions are in the view's coordinates, except for a RootView.
  852. // A convenience function which calls into GetEventHandlerForRect() with
  853. // a 1x1 rect centered at |point|. |point| is in the local coordinate
  854. // space of |this|.
  855. View* GetEventHandlerForPoint(const gfx::Point& point);
  856. // Returns the View that should be the target of an event having |rect| as
  857. // its location, or NULL if no such target exists. |rect| is in the local
  858. // coordinate space of |this|.
  859. View* GetEventHandlerForRect(const gfx::Rect& rect);
  860. // Returns the deepest visible descendant that contains the specified point
  861. // and supports tooltips. If the view does not contain the point, returns
  862. // NULL.
  863. virtual View* GetTooltipHandlerForPoint(const gfx::Point& point);
  864. // Return the cursor that should be used for this view or the default cursor.
  865. // The event location is in the receiver's coordinate system. The caller is
  866. // responsible for managing the lifetime of the returned object, though that
  867. // lifetime may vary from platform to platform. On Windows and Aura,
  868. // the cursor is a shared resource.
  869. virtual ui::Cursor GetCursor(const ui::MouseEvent& event);
  870. // A convenience function which calls HitTestRect() with a rect of size
  871. // 1x1 and an origin of |point|. |point| is in the local coordinate space
  872. // of |this|.
  873. bool HitTestPoint(const gfx::Point& point) const;
  874. // Returns true if |rect| intersects this view's bounds. |rect| is in the
  875. // local coordinate space of |this|.
  876. bool HitTestRect(const gfx::Rect& rect) const;
  877. // Returns true if this view or any of its descendants are permitted to
  878. // be the target of an event.
  879. virtual bool GetCanProcessEventsWithinSubtree() const;
  880. // Sets whether this view or any of its descendants are permitted to be the
  881. // target of an event.
  882. void SetCanProcessEventsWithinSubtree(bool can_process);
  883. // Returns true if the mouse cursor is over |view| and mouse events are
  884. // enabled.
  885. bool IsMouseHovered() const;
  886. // This method is invoked when the user clicks on this view.
  887. // The provided event is in the receiver's coordinate system.
  888. //
  889. // Return true if you processed the event and want to receive subsequent
  890. // MouseDragged and MouseReleased events. This also stops the event from
  891. // bubbling. If you return false, the event will bubble through parent
  892. // views.
  893. //
  894. // If you remove yourself from the tree while processing this, event bubbling
  895. // stops as if you returned true, but you will not receive future events.
  896. // The return value is ignored in this case.
  897. //
  898. // Default implementation returns true if a ContextMenuController has been
  899. // set, false otherwise. Override as needed.
  900. //
  901. virtual bool OnMousePressed(const ui::MouseEvent& event);
  902. // This method is invoked when the user clicked on this control.
  903. // and is still moving the mouse with a button pressed.
  904. // The provided event is in the receiver's coordinate system.
  905. //
  906. // Return true if you processed the event and want to receive
  907. // subsequent MouseDragged and MouseReleased events.
  908. //
  909. // Default implementation returns true if a ContextMenuController has been
  910. // set, false otherwise. Override as needed.
  911. //
  912. virtual bool OnMouseDragged(const ui::MouseEvent& event);
  913. // This method is invoked when the user releases the mouse
  914. // button. The event is in the receiver's coordinate system.
  915. //
  916. // Default implementation notifies the ContextMenuController is appropriate.
  917. // Subclasses that wish to honor the ContextMenuController should invoke
  918. // super.
  919. virtual void OnMouseReleased(const ui::MouseEvent& event);
  920. // This method is invoked when the mouse press/drag was canceled by a
  921. // system/user gesture.
  922. virtual void OnMouseCaptureLost();
  923. // This method is invoked when the mouse is above this control
  924. // The event is in the receiver's coordinate system.
  925. //
  926. // Default implementation does nothing. Override as needed.
  927. virtual void OnMouseMoved(const ui::MouseEvent& event);
  928. // This method is invoked when the mouse enters this control.
  929. //
  930. // Default implementation does nothing. Override as needed.
  931. virtual void OnMouseEntered(const ui::MouseEvent& event);
  932. // This method is invoked when the mouse exits this control
  933. // The provided event location is always (0, 0)
  934. // Default implementation does nothing. Override as needed.
  935. virtual void OnMouseExited(const ui::MouseEvent& event);
  936. // Set both the MouseHandler and the GestureHandler for a drag session.
  937. //
  938. // A drag session is a stream of mouse events starting
  939. // with a MousePressed event, followed by several MouseDragged
  940. // events and finishing with a MouseReleased event.
  941. //
  942. // This method should be only invoked while processing a
  943. // MouseDragged or MousePressed event.
  944. //
  945. // All further mouse dragged and mouse up events will be sent
  946. // the MouseHandler, even if it is reparented to another window.
  947. //
  948. // The MouseHandler is automatically cleared when the control
  949. // comes back from processing the MouseReleased event.
  950. //
  951. // Note: if the mouse handler is no longer connected to a
  952. // view hierarchy, events won't be sent.
  953. virtual void SetMouseAndGestureHandler(View* new_handler);
  954. // Sets a new mouse handler.
  955. virtual void SetMouseHandler(View* new_handler);
  956. // Invoked when a key is pressed or released.
  957. // Subclasses should return true if the event has been processed and false
  958. // otherwise. If the event has not been processed, the parent will be given a
  959. // chance.
  960. virtual bool OnKeyPressed(const ui::KeyEvent& event);
  961. virtual bool OnKeyReleased(const ui::KeyEvent& event);
  962. // Invoked when the user uses the mousewheel. Implementors should return true
  963. // if the event has been processed and false otherwise. This message is sent
  964. // if the view is focused. If the event has not been processed, the parent
  965. // will be given a chance.
  966. virtual bool OnMouseWheel(const ui::MouseWheelEvent& event);
  967. // See field for description.
  968. void SetNotifyEnterExitOnChild(bool notify);
  969. bool GetNotifyEnterExitOnChild() const;
  970. // Convenience method to retrieve the InputMethod associated with the
  971. // Widget that contains this view.
  972. ui::InputMethod* GetInputMethod() {
  973. return const_cast<ui::InputMethod*>(base::as_const(*this).GetInputMethod());
  974. }
  975. const ui::InputMethod* GetInputMethod() const;
  976. // Sets a new ViewTargeter for the view, and returns the previous
  977. // ViewTargeter.
  978. std::unique_ptr<ViewTargeter> SetEventTargeter(
  979. std::unique_ptr<ViewTargeter> targeter);
  980. // Returns the ViewTargeter installed on |this| if one exists,
  981. // otherwise returns the ViewTargeter installed on our root view.
  982. // The return value is guaranteed to be non-null.
  983. ViewTargeter* GetEffectiveViewTargeter() const;
  984. ViewTargeter* targeter() const { return targeter_.get(); }
  985. // Returns the WordLookupClient associated with this view.
  986. virtual WordLookupClient* GetWordLookupClient();
  987. // Overridden from ui::EventTarget:
  988. bool CanAcceptEvent(const ui::Event& event) override;
  989. ui::EventTarget* GetParentTarget() override;
  990. std::unique_ptr<ui::EventTargetIterator> GetChildIterator() const override;
  991. ui::EventTargeter* GetEventTargeter() override;
  992. void ConvertEventToTarget(const ui::EventTarget* target,
  993. ui::LocatedEvent* event) const override;
  994. gfx::PointF GetScreenLocationF(const ui::LocatedEvent& event) const override;
  995. // Overridden from ui::EventHandler:
  996. void OnKeyEvent(ui::KeyEvent* event) override;
  997. void OnMouseEvent(ui::MouseEvent* event) override;
  998. void OnScrollEvent(ui::ScrollEvent* event) override;
  999. void OnTouchEvent(ui::TouchEvent* event) final;
  1000. void OnGestureEvent(ui::GestureEvent* event) override;
  1001. base::StringPiece GetLogContext() const override;
  1002. // Accelerators --------------------------------------------------------------
  1003. // Sets a keyboard accelerator for that view. When the user presses the
  1004. // accelerator key combination, the AcceleratorPressed method is invoked.
  1005. // Note that you can set multiple accelerators for a view by invoking this
  1006. // method several times. Note also that AcceleratorPressed is invoked only
  1007. // when CanHandleAccelerators() is true.
  1008. void AddAccelerator(const ui::Accelerator& accelerator);
  1009. // Removes the specified accelerator for this view.
  1010. void RemoveAccelerator(const ui::Accelerator& accelerator);
  1011. // Removes all the keyboard accelerators for this view.
  1012. void ResetAccelerators();
  1013. // Overridden from AcceleratorTarget:
  1014. bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
  1015. // Returns whether accelerators are enabled for this view. Accelerators are
  1016. // enabled if the containing widget is visible and the view is enabled() and
  1017. // IsDrawn()
  1018. bool CanHandleAccelerators() const override;
  1019. // Focus ---------------------------------------------------------------------
  1020. // Returns whether this view currently has the focus.
  1021. virtual bool HasFocus() const;
  1022. // Returns the view that is a candidate to be focused next when pressing Tab.
  1023. //
  1024. // The returned view might not be `IsFocusable`, but it's children can be
  1025. // traversed to evaluate if one of them `IsFocusable`.
  1026. //
  1027. // If this returns `nullptr` then it is the last focusable candidate view in
  1028. // the list including its siblings.
  1029. View* GetNextFocusableView();
  1030. const View* GetNextFocusableView() const;
  1031. // Returns the view that is a candidate to be focused next when pressing
  1032. // Shift-Tab.
  1033. //
  1034. // The returned view might not be `IsFocusable`, but it's children can be
  1035. // traversed to evaluate if one of them `IsFocusable`.
  1036. //
  1037. // If this returns `nullptr` then it is the first focusable candidate view in
  1038. // the list including its siblings.
  1039. View* GetPreviousFocusableView();
  1040. // Removes |this| from its focus list, updating the previous and next
  1041. // views' points accordingly.
  1042. void RemoveFromFocusList();
  1043. // Insert |this| before or after |view| in the focus list.
  1044. void InsertBeforeInFocusList(View* view);
  1045. void InsertAfterInFocusList(View* view);
  1046. // Returns the list of children in the order of their focus. Each child might
  1047. // not be `IsFocusable`. Children that are not `IsFocusable` might still have
  1048. // children of its own that are `IsFocusable`.
  1049. Views GetChildrenFocusList();
  1050. // Gets/sets |FocusBehavior|. SetFocusBehavior() advances focus if necessary.
  1051. virtual FocusBehavior GetFocusBehavior() const;
  1052. void SetFocusBehavior(FocusBehavior focus_behavior);
  1053. // Set this to suppress default handling of focus for this View. By default
  1054. // native focus will be cleared and a11y events announced based on the new
  1055. // View focus.
  1056. // TODO(pbos): This is here to make removing focus behavior from the base
  1057. // implementation of OnFocus a no-op. Try to avoid new uses of this. Also
  1058. // investigate if this can be configured with more granularity (which event
  1059. // to fire on focus etc.).
  1060. void set_suppress_default_focus_handling() {
  1061. suppress_default_focus_handling_ = true;
  1062. }
  1063. // Returns true if this view is focusable, |enabled_| and drawn.
  1064. bool IsFocusable() const;
  1065. // Return whether this view is focusable when the user requires full keyboard
  1066. // access, even though it may not be normally focusable.
  1067. bool IsAccessibilityFocusable() const;
  1068. // Convenience method to retrieve the FocusManager associated with the
  1069. // Widget that contains this view. This can return NULL if this view is not
  1070. // part of a view hierarchy with a Widget.
  1071. FocusManager* GetFocusManager();
  1072. const FocusManager* GetFocusManager() const;
  1073. // Request keyboard focus. The receiving view will become the focused view.
  1074. virtual void RequestFocus();
  1075. // Invoked when a view is about to be requested for focus due to the focus
  1076. // traversal. Reverse is this request was generated going backward
  1077. // (Shift-Tab).
  1078. virtual void AboutToRequestFocusFromTabTraversal(bool reverse) {}
  1079. // Invoked when a key is pressed before the key event is processed (and
  1080. // potentially eaten) by the focus manager for tab traversal, accelerators and
  1081. // other focus related actions.
  1082. // The default implementation returns false, ensuring that tab traversal and
  1083. // accelerators processing is performed.
  1084. // Subclasses should return true if they want to process the key event and not
  1085. // have it processed as an accelerator (if any) or as a tab traversal (if the
  1086. // key event is for the TAB key). In that case, OnKeyPressed will
  1087. // subsequently be invoked for that event.
  1088. virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event);
  1089. // Subclasses that contain traversable children that are not directly
  1090. // accessible through the children hierarchy should return the associated
  1091. // FocusTraversable for the focus traversal to work properly.
  1092. virtual FocusTraversable* GetFocusTraversable();
  1093. // Subclasses that can act as a "pane" must implement their own
  1094. // FocusTraversable to keep the focus trapped within the pane.
  1095. // If this method returns an object, any view that's a direct or
  1096. // indirect child of this view will always use this FocusTraversable
  1097. // rather than the one from the widget.
  1098. virtual FocusTraversable* GetPaneFocusTraversable();
  1099. // Tooltips ------------------------------------------------------------------
  1100. // Gets the tooltip for this View. If the View does not have a tooltip,
  1101. // the returned value should be empty.
  1102. // Any time the tooltip text that a View is displaying changes, it must
  1103. // invoke TooltipTextChanged.
  1104. // |p| provides the coordinates of the mouse (relative to this view).
  1105. virtual std::u16string GetTooltipText(const gfx::Point& p) const;
  1106. // Context menus -------------------------------------------------------------
  1107. // Sets the ContextMenuController. Setting this to non-null makes the View
  1108. // process mouse events.
  1109. ContextMenuController* context_menu_controller() {
  1110. return context_menu_controller_;
  1111. }
  1112. void set_context_menu_controller(ContextMenuController* menu_controller) {
  1113. context_menu_controller_ = menu_controller;
  1114. }
  1115. // Provides default implementation for context menu handling. The default
  1116. // implementation calls the ShowContextMenu of the current
  1117. // ContextMenuController (if it is not NULL). Overridden in subclassed views
  1118. // to provide right-click menu display triggered by the keyboard (i.e. for the
  1119. // Chrome toolbar Back and Forward buttons). No source needs to be specified,
  1120. // as it is always equal to the current View.
  1121. // Note that this call is asynchronous for views menu and synchronous for
  1122. // mac's native menu.
  1123. virtual void ShowContextMenu(const gfx::Point& p,
  1124. ui::MenuSourceType source_type);
  1125. // Returns the location, in screen coordinates, to show the context menu at
  1126. // when the context menu is shown from the keyboard. This implementation
  1127. // returns the middle of the visible region of this view.
  1128. //
  1129. // This method is invoked when the context menu is shown by way of the
  1130. // keyboard.
  1131. virtual gfx::Point GetKeyboardContextMenuLocation();
  1132. // Drag and drop -------------------------------------------------------------
  1133. DragController* drag_controller() { return drag_controller_; }
  1134. void set_drag_controller(DragController* drag_controller) {
  1135. drag_controller_ = drag_controller;
  1136. }
  1137. // During a drag and drop session when the mouse moves the view under the
  1138. // mouse is queried for the drop types it supports by way of the
  1139. // GetDropFormats methods. If the view returns true and the drag site can
  1140. // provide data in one of the formats, the view is asked if the drop data
  1141. // is required before any other drop events are sent. Once the
  1142. // data is available the view is asked if it supports the drop (by way of
  1143. // the CanDrop method). If a view returns true from CanDrop,
  1144. // OnDragEntered is sent to the view when the mouse first enters the view,
  1145. // as the mouse moves around within the view OnDragUpdated is invoked.
  1146. // If the user releases the mouse over the view and OnDragUpdated returns a
  1147. // valid drop, then GetDropCallback is invoked. If the mouse moves outside the
  1148. // view or over another view that wants the drag, OnDragExited is invoked.
  1149. //
  1150. // Similar to mouse events, the deepest view under the mouse is first checked
  1151. // if it supports the drop (Drop). If the deepest view under
  1152. // the mouse does not support the drop, the ancestors are walked until one
  1153. // is found that supports the drop.
  1154. // Override and return the set of formats that can be dropped on this view.
  1155. // |formats| is a bitmask of the formats defined bye OSExchangeData::Format.
  1156. // The default implementation returns false, which means the view doesn't
  1157. // support dropping.
  1158. virtual bool GetDropFormats(int* formats,
  1159. std::set<ui::ClipboardFormatType>* format_types);
  1160. // Override and return true if the data must be available before any drop
  1161. // methods should be invoked. The default is false.
  1162. virtual bool AreDropTypesRequired();
  1163. // A view that supports drag and drop must override this and return true if
  1164. // data contains a type that may be dropped on this view.
  1165. virtual bool CanDrop(const OSExchangeData& data);
  1166. // OnDragEntered is invoked when the mouse enters this view during a drag and
  1167. // drop session and CanDrop returns true. This is immediately
  1168. // followed by an invocation of OnDragUpdated, and eventually one of
  1169. // OnDragExited or GetDropCallback.
  1170. virtual void OnDragEntered(const ui::DropTargetEvent& event);
  1171. // Invoked during a drag and drop session while the mouse is over the view.
  1172. // This should return a bitmask of the DragDropTypes::DragOperation supported
  1173. // based on the location of the event. Return 0 to indicate the drop should
  1174. // not be accepted.
  1175. virtual int OnDragUpdated(const ui::DropTargetEvent& event);
  1176. // Invoked during a drag and drop session when the mouse exits the views, or
  1177. // when the drag session was canceled and the mouse was over the view.
  1178. virtual void OnDragExited();
  1179. // Invoked from DoDrag after the drag completes. This implementation does
  1180. // nothing, and is intended for subclasses to do cleanup.
  1181. virtual void OnDragDone();
  1182. // Invoked during a drag and drop session when OnDragUpdated returns a valid
  1183. // operation and the user release the mouse but the drop is held because of
  1184. // DataTransferPolicyController. When calling, ensure that the |event|
  1185. // uses View local coordinates.
  1186. virtual DropCallback GetDropCallback(const ui::DropTargetEvent& event);
  1187. // Returns true if the mouse was dragged enough to start a drag operation.
  1188. // delta_x and y are the distance the mouse was dragged.
  1189. static bool ExceededDragThreshold(const gfx::Vector2d& delta);
  1190. // Accessibility -------------------------------------------------------------
  1191. // Get the object managing the accessibility interface for this View.
  1192. ViewAccessibility& GetViewAccessibility() const;
  1193. // Modifies |node_data| to reflect the current accessible state of this
  1194. // view.
  1195. virtual void GetAccessibleNodeData(ui::AXNodeData* node_data) {}
  1196. // Handle a request from assistive technology to perform an action on this
  1197. // view. Returns true on success, but note that the success/failure is
  1198. // not propagated to the client that requested the action, since the
  1199. // request is sometimes asynchronous. The right way to send a response is
  1200. // via NotifyAccessibilityEvent(), below.
  1201. virtual bool HandleAccessibleAction(const ui::AXActionData& action_data);
  1202. // Returns an instance of the native accessibility interface for this view.
  1203. virtual gfx::NativeViewAccessible GetNativeViewAccessible();
  1204. // Notifies assistive technology that an accessibility event has
  1205. // occurred on this view, such as when the view is focused or when its
  1206. // value changes. Pass true for |send_native_event| except for rare
  1207. // cases where the view is a native control that's already sending a
  1208. // native accessibility event and the duplicate event would cause
  1209. // problems.
  1210. void NotifyAccessibilityEvent(ax::mojom::Event event_type,
  1211. bool send_native_event);
  1212. // Views may override this function to know when an accessibility
  1213. // event is fired. This will be called by NotifyAccessibilityEvent.
  1214. virtual void OnAccessibilityEvent(ax::mojom::Event event_type);
  1215. // Scrolling -----------------------------------------------------------------
  1216. // TODO(beng): Figure out if this can live somewhere other than View, i.e.
  1217. // closer to ScrollView.
  1218. // Scrolls the specified region, in this View's coordinate system, to be
  1219. // visible. View's implementation passes the call onto the parent View (after
  1220. // adjusting the coordinates). It is up to views that only show a portion of
  1221. // the child view, such as Viewport, to override appropriately.
  1222. virtual void ScrollRectToVisible(const gfx::Rect& rect);
  1223. // Scrolls the view's bounds or some subset thereof to be visible. By default
  1224. // this function calls ScrollRectToVisible(GetLocalBounds()).
  1225. void ScrollViewToVisible();
  1226. void AddObserver(ViewObserver* observer);
  1227. void RemoveObserver(ViewObserver* observer);
  1228. bool HasObserver(const ViewObserver* observer) const;
  1229. protected:
  1230. // Used to track a drag. RootView passes this into
  1231. // ProcessMousePressed/Dragged.
  1232. struct DragInfo {
  1233. // Sets possible_drag to false and start_x/y to 0. This is invoked by
  1234. // RootView prior to invoke ProcessMousePressed.
  1235. void Reset();
  1236. // Sets possible_drag to true and start_pt to the specified point.
  1237. // This is invoked by the target view if it detects the press may generate
  1238. // a drag.
  1239. void PossibleDrag(const gfx::Point& p);
  1240. // Whether the press may generate a drag.
  1241. bool possible_drag = false;
  1242. // Coordinates of the mouse press.
  1243. gfx::Point start_pt;
  1244. };
  1245. // Size and disposition ------------------------------------------------------
  1246. // Calculates the natural size for the View, to be taken into consideration
  1247. // when the parent is performing layout.
  1248. // `preferred_size_` will take precedence over CalculatePreferredSize() if
  1249. // it exists.
  1250. virtual gfx::Size CalculatePreferredSize() const;
  1251. // Calculates the preferred size for the View given `available_size`.
  1252. // `preferred_size_` will take precedence over CalculatePreferredSize() if
  1253. // it exists.
  1254. virtual gfx::Size CalculatePreferredSize(
  1255. const SizeBounds& available_size) const;
  1256. // Override to be notified when the bounds of the view have changed.
  1257. virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) {}
  1258. // Called when the preferred size of a child view changed. This gives the
  1259. // parent an opportunity to do a fresh layout if that makes sense.
  1260. virtual void ChildPreferredSizeChanged(View* child) {}
  1261. // Called when the visibility of a child view changed. This gives the parent
  1262. // an opportunity to do a fresh layout if that makes sense.
  1263. virtual void ChildVisibilityChanged(View* child) {}
  1264. // Invalidates the layout and calls ChildPreferredSizeChanged() on the parent
  1265. // if there is one. Be sure to call PreferredSizeChanged() when overriding
  1266. // such that the layout is properly invalidated.
  1267. virtual void PreferredSizeChanged();
  1268. // Override returning true when the view needs to be notified when its visible
  1269. // bounds relative to the root view may have changed. Only used by
  1270. // NativeViewHost.
  1271. virtual bool GetNeedsNotificationWhenVisibleBoundsChange() const;
  1272. // Notification that this View's visible bounds relative to the root view may
  1273. // have changed. The visible bounds are the region of the View not clipped by
  1274. // its ancestors. This is used for clipping NativeViewHost.
  1275. virtual void OnVisibleBoundsChanged();
  1276. bool needs_layout() const { return needs_layout_; }
  1277. // Tree operations -----------------------------------------------------------
  1278. // This method is invoked when the tree changes.
  1279. //
  1280. // When a view is removed, it is invoked for all children and grand
  1281. // children. For each of these views, a notification is sent to the
  1282. // view and all parents.
  1283. //
  1284. // When a view is added, a notification is sent to the view, all its
  1285. // parents, and all its children (and grand children)
  1286. //
  1287. // Default implementation does nothing. Override to perform operations
  1288. // required when a view is added or removed from a view hierarchy
  1289. //
  1290. // Refer to comments in struct |ViewHierarchyChangedDetails| for |details|.
  1291. //
  1292. // See also AddedToWidget() and RemovedFromWidget() for detecting when the
  1293. // view is added to/removed from a widget.
  1294. virtual void ViewHierarchyChanged(const ViewHierarchyChangedDetails& details);
  1295. // When SetVisible() changes the visibility of a view, this method is
  1296. // invoked for that view as well as all the children recursively.
  1297. virtual void VisibilityChanged(View* starting_from, bool is_visible);
  1298. // This method is invoked when the parent NativeView of the widget that the
  1299. // view is attached to has changed and the view hierarchy has not changed.
  1300. // ViewHierarchyChanged() is called when the parent NativeView of the widget
  1301. // that the view is attached to is changed as a result of changing the view
  1302. // hierarchy. Overriding this method is useful for tracking which
  1303. // FocusManager manages this view.
  1304. virtual void NativeViewHierarchyChanged();
  1305. // This method is invoked for a view when it is attached to a hierarchy with
  1306. // a widget, i.e. GetWidget() starts returning a non-null result.
  1307. // It is also called when the view is moved to a different widget.
  1308. virtual void AddedToWidget();
  1309. // This method is invoked for a view when it is removed from a hierarchy with
  1310. // a widget or moved to a different widget.
  1311. virtual void RemovedFromWidget();
  1312. // Painting ------------------------------------------------------------------
  1313. // Override to control paint redirection or to provide a different Rectangle
  1314. // |r| to be repainted. This is a function with an empty implementation in
  1315. // view.cc and is purely intended for subclasses to override.
  1316. virtual void OnDidSchedulePaint(const gfx::Rect& r);
  1317. // Responsible for calling Paint() on child Views. Override to control the
  1318. // order child Views are painted.
  1319. virtual void PaintChildren(const PaintInfo& info);
  1320. // Override to provide rendering in any part of the View's bounds. Typically
  1321. // this is the "contents" of the view. If you override this method you will
  1322. // have to call the subsequent OnPaint*() methods manually.
  1323. virtual void OnPaint(gfx::Canvas* canvas);
  1324. // Override to paint a background before any content is drawn. Typically this
  1325. // is done if you are satisfied with a default OnPaint handler but wish to
  1326. // supply a different background.
  1327. virtual void OnPaintBackground(gfx::Canvas* canvas);
  1328. // Override to paint a border not specified by SetBorder().
  1329. virtual void OnPaintBorder(gfx::Canvas* canvas);
  1330. // Returns the type of scaling to be done for this View. Override this to
  1331. // change the default scaling type from |kScaleToFit|. You would want to
  1332. // override this for a view and return |kScaleToScaleFactor| in cases where
  1333. // scaling should cause no distortion. Such as in the case of an image or
  1334. // an icon.
  1335. virtual PaintInfo::ScaleType GetPaintScaleType() const;
  1336. // Accelerated painting ------------------------------------------------------
  1337. // Returns the offset from this view to the nearest ancestor with a layer. If
  1338. // |layer_parent| is non-NULL it is set to the nearest ancestor with a layer.
  1339. virtual LayerOffsetData CalculateOffsetToAncestorWithLayer(
  1340. ui::Layer** layer_parent);
  1341. // Updates the view's layer's parent. Called when a view is added to a view
  1342. // hierarchy, responsible for parenting the view's layer to the enclosing
  1343. // layer in the hierarchy.
  1344. virtual void UpdateParentLayer();
  1345. // If this view has a layer, the layer is reparented to |parent_layer| and its
  1346. // bounds is set based on |point|. If this view does not have a layer, then
  1347. // recurses through all children. This is used when adding a layer to an
  1348. // existing view to make sure all descendants that have layers are parented to
  1349. // the right layer.
  1350. void MoveLayerToParent(ui::Layer* parent_layer,
  1351. const LayerOffsetData& offset_data);
  1352. // Called to update the bounds of any child layers within this View's
  1353. // hierarchy when something happens to the hierarchy.
  1354. void UpdateChildLayerBounds(const LayerOffsetData& offset_data);
  1355. // Overridden from ui::LayerDelegate:
  1356. void OnPaintLayer(const ui::PaintContext& context) override;
  1357. void OnLayerTransformed(const gfx::Transform& old_transform,
  1358. ui::PropertyChangeReason reason) final;
  1359. void OnLayerClipRectChanged(const gfx::Rect& old_rect,
  1360. ui::PropertyChangeReason reason) override;
  1361. void OnDeviceScaleFactorChanged(float old_device_scale_factor,
  1362. float new_device_scale_factor) override;
  1363. // Finds the layer that this view paints to (it may belong to an ancestor
  1364. // view), then reorders the immediate children of that layer to match the
  1365. // order of the view tree.
  1366. void ReorderLayers();
  1367. // This reorders the immediate children of |*parent_layer| to match the
  1368. // order of the view tree. Child layers which are owned by a view are
  1369. // reordered so that they are below any child layers not owned by a view.
  1370. // Widget::ReorderNativeViews() should be called to reorder any child layers
  1371. // with an associated view. Widget::ReorderNativeViews() may reorder layers
  1372. // below layers owned by a view.
  1373. virtual void ReorderChildLayers(ui::Layer* parent_layer);
  1374. // Notifies parents about a layer being created or destroyed in a child. An
  1375. // example where a subclass may override this method is when it wants to clip
  1376. // the child by adding its own layer.
  1377. virtual void OnChildLayerChanged(View* child);
  1378. // Input ---------------------------------------------------------------------
  1379. virtual DragInfo* GetDragInfo();
  1380. // Focus ---------------------------------------------------------------------
  1381. // Override to be notified when focus has changed either to or from this View.
  1382. virtual void OnFocus();
  1383. virtual void OnBlur();
  1384. // Handle view focus/blur events for this view.
  1385. void Focus();
  1386. void Blur();
  1387. // System events -------------------------------------------------------------
  1388. // Called when either the UI theme or the NativeTheme associated with this
  1389. // View changes. This is also called when the NativeTheme first becomes
  1390. // available (after the view is added to a widget hierarchy). Overriding
  1391. // allows individual Views to do special cleanup and processing (such as
  1392. // dropping resource caches). To dispatch a theme changed notification, call
  1393. // Widget::ThemeChanged().
  1394. virtual void OnThemeChanged();
  1395. // Tooltips ------------------------------------------------------------------
  1396. // Views must invoke this when the tooltip text they are to display changes.
  1397. void TooltipTextChanged();
  1398. // Drag and drop -------------------------------------------------------------
  1399. // These are cover methods that invoke the method of the same name on
  1400. // the DragController. Subclasses may wish to override rather than install
  1401. // a DragController.
  1402. // See DragController for a description of these methods.
  1403. virtual int GetDragOperations(const gfx::Point& press_pt);
  1404. virtual void WriteDragData(const gfx::Point& press_pt, OSExchangeData* data);
  1405. // Returns whether we're in the middle of a drag session that was initiated
  1406. // by us.
  1407. bool InDrag() const;
  1408. // Returns how much the mouse needs to move in one direction to start a
  1409. // drag. These methods cache in a platform-appropriate way. These values are
  1410. // used by the public static method ExceededDragThreshold().
  1411. static int GetHorizontalDragThreshold();
  1412. static int GetVerticalDragThreshold();
  1413. // PropertyHandler -----------------------------------------------------------
  1414. // Note: you MUST call this base method from derived classes that override it
  1415. // or else your class will not properly register for ElementTrackerViews and
  1416. // won't be available for interactive tests or in-product help/tutorials which
  1417. // use that system.
  1418. void AfterPropertyChange(const void* key, int64_t old_value) override;
  1419. // Property Support ----------------------------------------------------------
  1420. void OnPropertyChanged(ui::metadata::PropertyKey property,
  1421. PropertyEffects property_effects);
  1422. private:
  1423. friend class internal::PreEventDispatchHandler;
  1424. friend class internal::PostEventDispatchHandler;
  1425. friend class internal::RootView;
  1426. friend class internal::ScopedChildrenLock;
  1427. friend class FocusManager;
  1428. friend class ViewDebugWrapperImpl;
  1429. friend class ViewLayerTest;
  1430. friend class ViewLayerPixelCanvasTest;
  1431. friend class ViewTestApi;
  1432. friend class Widget;
  1433. FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithMovedViewUsesCache);
  1434. FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithMovedViewUsesCacheInRTL);
  1435. FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithUnknownInvalidation);
  1436. // http://crbug.com/1162949 : Instrumentation that indicates if this is alive.
  1437. enum class LifeCycleState : uint32_t {
  1438. kAlive = 0x600D600D,
  1439. kDestroyed = 0xBAADBAAD,
  1440. };
  1441. // This is the default view layout. It is a very simple version of FillLayout,
  1442. // which merely sets the bounds of the children to the content bounds. The
  1443. // actual FillLayout isn't used here because it supports a couple of features
  1444. // not used in the vast majority of instances. It also descends from
  1445. // LayoutManagerBase which adds some extra overhead not needed here.
  1446. class DefaultFillLayout : public LayoutManager {
  1447. public:
  1448. DefaultFillLayout();
  1449. ~DefaultFillLayout() override;
  1450. void Layout(View* host) override;
  1451. gfx::Size GetPreferredSize(const View* host) const override;
  1452. int GetPreferredHeightForWidth(const View* host, int width) const override;
  1453. };
  1454. // Painting -----------------------------------------------------------------
  1455. // Responsible for propagating SchedulePaint() to the view's layer. If there
  1456. // is no associated layer, the requested paint rect is propagated up the
  1457. // view hierarchy by calling this function on the parent view. Rectangle |r|
  1458. // is in the view's coordinate system. The transformations are applied to it
  1459. // to convert it into the parent coordinate system before propagating
  1460. // SchedulePaint() up the view hierarchy. This function should NOT be directly
  1461. // called. Instead call SchedulePaint() or SchedulePaintInRect(), which will
  1462. // call into this as necessary.
  1463. void SchedulePaintInRectImpl(const gfx::Rect& r);
  1464. // Invoked before and after the bounds change to schedule painting the old and
  1465. // new bounds.
  1466. void SchedulePaintBoundsChanged(bool size_changed);
  1467. // Schedules a paint on the parent View if it exists.
  1468. void SchedulePaintOnParent();
  1469. // Returns whether this view is eligible for painting, i.e. is visible and
  1470. // nonempty. Note that this does not behave like IsDrawn(), since it doesn't
  1471. // check ancestors recursively; rather, it's used to prune subtrees of views
  1472. // during painting.
  1473. bool ShouldPaint() const;
  1474. // Adjusts the transform of |recorder| in advance of painting.
  1475. void SetUpTransformRecorderForPainting(
  1476. const gfx::Vector2d& offset_from_parent,
  1477. ui::TransformRecorder* recorder) const;
  1478. // Recursively calls the painting method |func| on all non-layered children,
  1479. // in Z order.
  1480. void RecursivePaintHelper(void (View::*func)(const PaintInfo&),
  1481. const PaintInfo& info);
  1482. // Invokes Paint() and, if necessary, PaintDebugRects(). Should be called
  1483. // only on the root of a widget/layer. PaintDebugRects() is invoked as a
  1484. // separate pass, instead of being rolled into Paint(), so that siblings will
  1485. // not obscure debug rects.
  1486. void PaintFromPaintRoot(const ui::PaintContext& parent_context);
  1487. // Draws a semitransparent rect to indicate the bounds of this view.
  1488. // Recursively does the same for all children. Invoked only with
  1489. // --draw-view-bounds-rects.
  1490. void PaintDebugRects(const PaintInfo& paint_info);
  1491. // Tree operations -----------------------------------------------------------
  1492. // Adds |view| as a child of this view at |index|.
  1493. void AddChildViewAtImpl(View* view, size_t index);
  1494. // Removes |view| from the hierarchy tree. If |update_tool_tip| is
  1495. // true, the tooltip is updated. If |delete_removed_view| is true, the
  1496. // view is also deleted (if it is parent owned). If |new_parent| is
  1497. // not null, the remove is the result of AddChildView() to a new
  1498. // parent. For this case, |new_parent| is the View that |view| is
  1499. // going to be added to after the remove completes.
  1500. void DoRemoveChildView(View* view,
  1501. bool update_tool_tip,
  1502. bool delete_removed_view,
  1503. View* new_parent);
  1504. // Call ViewHierarchyChanged() for all child views and all parents.
  1505. // |old_parent| is the original parent of the View that was removed.
  1506. // If |new_parent| is not null, the View that was removed will be reparented
  1507. // to |new_parent| after the remove operation.
  1508. // If is_removed_from_widget is true, calls RemovedFromWidget for all
  1509. // children.
  1510. void PropagateRemoveNotifications(View* old_parent,
  1511. View* new_parent,
  1512. bool is_removed_from_widget);
  1513. // Call ViewHierarchyChanged() for all children.
  1514. // If is_added_to_widget is true, calls AddedToWidget for all children.
  1515. void PropagateAddNotifications(const ViewHierarchyChangedDetails& details,
  1516. bool is_added_to_widget);
  1517. // Propagates NativeViewHierarchyChanged() notification through all the
  1518. // children.
  1519. void PropagateNativeViewHierarchyChanged();
  1520. // Calls ViewHierarchyChanged() and notifies observers.
  1521. void ViewHierarchyChangedImpl(const ViewHierarchyChangedDetails& details);
  1522. // Size and disposition ------------------------------------------------------
  1523. // Call VisibilityChanged() recursively for all children.
  1524. void PropagateVisibilityNotifications(View* from, bool is_visible);
  1525. // Registers/unregisters accelerators as necessary and calls
  1526. // VisibilityChanged().
  1527. void VisibilityChangedImpl(View* starting_from, bool is_visible);
  1528. // Visible bounds notification registration.
  1529. // When a view is added to a hierarchy, it and all its children are asked if
  1530. // they need to be registered for "visible bounds within root" notifications
  1531. // (see comment on OnVisibleBoundsChanged()). If they do, they are registered
  1532. // with every ancestor between them and the root of the hierarchy.
  1533. static void RegisterChildrenForVisibleBoundsNotification(View* view);
  1534. static void UnregisterChildrenForVisibleBoundsNotification(View* view);
  1535. void RegisterForVisibleBoundsNotification();
  1536. void UnregisterForVisibleBoundsNotification();
  1537. // Adds/removes view to the list of descendants that are notified any time
  1538. // this views location and possibly size are changed.
  1539. void AddDescendantToNotify(View* view);
  1540. void RemoveDescendantToNotify(View* view);
  1541. // Non-templatized backend for SetLayoutManager().
  1542. void SetLayoutManagerImpl(std::unique_ptr<LayoutManager> layout);
  1543. // Transformations -----------------------------------------------------------
  1544. // Returns in |transform| the transform to get from coordinates of |ancestor|
  1545. // to this. Returns true if |ancestor| is found. If |ancestor| is not found,
  1546. // or NULL, |transform| is set to convert from root view coordinates to this.
  1547. bool GetTransformRelativeTo(const View* ancestor,
  1548. gfx::Transform* transform) const;
  1549. // Coordinate conversion -----------------------------------------------------
  1550. // Convert a point in the view's coordinate to an ancestor view's coordinate
  1551. // system using necessary transformations. Returns whether the point was
  1552. // successfully converted to the ancestor's coordinate system.
  1553. bool ConvertPointForAncestor(const View* ancestor, gfx::Point* point) const;
  1554. // Convert a point in the ancestor's coordinate system to the view's
  1555. // coordinate system using necessary transformations. Returns whether the
  1556. // point was successfully converted from the ancestor's coordinate system
  1557. // to the view's coordinate system.
  1558. bool ConvertPointFromAncestor(const View* ancestor, gfx::Point* point) const;
  1559. // Convert a rect in the view's coordinate to an ancestor view's coordinate
  1560. // system using necessary transformations. Returns whether the rect was
  1561. // successfully converted to the ancestor's coordinate system.
  1562. bool ConvertRectForAncestor(const View* ancestor, gfx::RectF* rect) const;
  1563. // Convert a rect in the ancestor's coordinate system to the view's
  1564. // coordinate system using necessary transformations. Returns whether the
  1565. // rect was successfully converted from the ancestor's coordinate system
  1566. // to the view's coordinate system.
  1567. bool ConvertRectFromAncestor(const View* ancestor, gfx::RectF* rect) const;
  1568. // Accelerated painting ------------------------------------------------------
  1569. // Creates the layer and related fields for this view.
  1570. void CreateLayer(ui::LayerType layer_type);
  1571. // Recursively calls UpdateParentLayers() on all descendants, stopping at any
  1572. // Views that have layers. Calls UpdateParentLayer() for any Views that have
  1573. // a layer with no parent. If at least one descendant had an unparented layer
  1574. // true is returned.
  1575. bool UpdateParentLayers();
  1576. // Parents this view's layer to |parent_layer|, and sets its bounds and other
  1577. // properties in accordance to the layer hierarchy.
  1578. void ReparentLayer(ui::Layer* parent_layer);
  1579. // Called to update the layer visibility. The layer will be visible if the
  1580. // View itself, and all its parent Views are visible. This also updates
  1581. // visibility of the child layers.
  1582. void UpdateLayerVisibility();
  1583. void UpdateChildLayerVisibility(bool visible);
  1584. enum class LayerChangeNotifyBehavior {
  1585. // Notify the parent chain about the layer change.
  1586. NOTIFY,
  1587. // Don't notify the parent chain about the layer change.
  1588. DONT_NOTIFY
  1589. };
  1590. // Destroys the layer associated with this view, and reparents any descendants
  1591. // to the destroyed layer's parent. If the view does not currently have a
  1592. // layer, this has no effect.
  1593. // The |notify_parents| enum controls whether a notification about the layer
  1594. // change is sent to the parents.
  1595. void DestroyLayerImpl(LayerChangeNotifyBehavior notify_parents);
  1596. // Determines whether we need to be painting to a layer, checks whether we
  1597. // currently have a layer, and creates or destroys the layer if necessary.
  1598. void CreateOrDestroyLayer();
  1599. // Notifies parents about layering changes in the view. This includes layer
  1600. // creation and destruction.
  1601. void NotifyParentsOfLayerChange();
  1602. // Orphans the layers in this subtree that are parented to layers outside of
  1603. // this subtree.
  1604. void OrphanLayers();
  1605. // Adjust the layer's offset so that it snaps to the physical pixel boundary.
  1606. // This has no effect if the view does not have an associated layer.
  1607. void SnapLayerToPixelBoundary(const LayerOffsetData& offset_data);
  1608. // Sets the layer's bounds given in DIP coordinates.
  1609. void SetLayerBounds(const gfx::Size& size_in_dip,
  1610. const LayerOffsetData& layer_offset_data);
  1611. // Creates a mask layer for the current view using |clip_path_|.
  1612. void CreateMaskLayer();
  1613. // Layout --------------------------------------------------------------------
  1614. // Returns whether a layout is deferred to a layout manager, either the
  1615. // default fill layout or the assigned layout manager.
  1616. bool HasLayoutManager() const;
  1617. // Input ---------------------------------------------------------------------
  1618. bool ProcessMousePressed(const ui::MouseEvent& event);
  1619. void ProcessMouseDragged(ui::MouseEvent* event);
  1620. void ProcessMouseReleased(const ui::MouseEvent& event);
  1621. // Accelerators --------------------------------------------------------------
  1622. // Registers this view's keyboard accelerators that are not registered to
  1623. // FocusManager yet, if possible.
  1624. void RegisterPendingAccelerators();
  1625. // Unregisters all the keyboard accelerators associated with this view.
  1626. // |leave_data_intact| if true does not remove data from accelerators_ array,
  1627. // so it could be re-registered with other focus manager
  1628. void UnregisterAccelerators(bool leave_data_intact);
  1629. // Focus ---------------------------------------------------------------------
  1630. // Sets previous/next focusable views for both |view| and other children
  1631. // assuming we've just inserted |view| at |pos|.
  1632. void SetFocusSiblings(View* view, Views::const_iterator pos);
  1633. // Helper function to advance focus, in case the currently focused view has
  1634. // become unfocusable.
  1635. void AdvanceFocusIfNecessary();
  1636. // System events -------------------------------------------------------------
  1637. // Used to propagate UI theme changed or NativeTheme changed notifications
  1638. // from the root view to all views in the hierarchy.
  1639. void PropagateThemeChanged();
  1640. // Used to propagate device scale factor changed notifications from the root
  1641. // view to all views in the hierarchy.
  1642. void PropagateDeviceScaleFactorChanged(float old_device_scale_factor,
  1643. float new_device_scale_factor);
  1644. // Tooltips ------------------------------------------------------------------
  1645. // Propagates UpdateTooltip() to the TooltipManager for the Widget.
  1646. // This must be invoked any time the View hierarchy changes in such a way
  1647. // the view under the mouse differs. For example, if the bounds of a View is
  1648. // changed, this is invoked. Similarly, as Views are added/removed, this
  1649. // is invoked.
  1650. void UpdateTooltip();
  1651. // Drag and drop -------------------------------------------------------------
  1652. // Starts a drag and drop operation originating from this view. This invokes
  1653. // WriteDragData to write the data and GetDragOperations to determine the
  1654. // supported drag operations. When done, OnDragDone is invoked. |press_pt| is
  1655. // in the view's coordinate system.
  1656. // Returns true if a drag was started.
  1657. bool DoDrag(const ui::LocatedEvent& event,
  1658. const gfx::Point& press_pt,
  1659. ui::mojom::DragEventSource source);
  1660. // Property support ----------------------------------------------------------
  1661. // Called from OnPropertyChanged with the given set of property effects. This
  1662. // function is NOT called if effects == kPropertyEffectsNone.
  1663. void HandlePropertyChangeEffects(PropertyEffects effects);
  1664. // The following methods are used by the property access system described in
  1665. // the comments above. They follow the required naming convention in order to
  1666. // allow them to be visible via the metadata.
  1667. int GetX() const;
  1668. int GetY() const;
  1669. int GetWidth() const;
  1670. int GetHeight() const;
  1671. void SetWidth(int width);
  1672. void SetHeight(int height);
  1673. bool GetIsDrawn() const;
  1674. // Special property accessor used by metadata to get the ToolTip text.
  1675. std::u16string GetTooltip() const;
  1676. //////////////////////////////////////////////////////////////////////////////
  1677. // Creation and lifetime -----------------------------------------------------
  1678. // False if this View is owned by its parent - i.e. it will be deleted by its
  1679. // parent during its parents destruction. False is the default.
  1680. bool owned_by_client_ = false;
  1681. // Attributes ----------------------------------------------------------------
  1682. // The id of this View. Used to find this View.
  1683. int id_ = 0;
  1684. // The group of this view. Some view subclasses use this id to find other
  1685. // views of the same group. For example radio button uses this information
  1686. // to find other radio buttons.
  1687. int group_ = -1;
  1688. // Tree operations -----------------------------------------------------------
  1689. // This view's parent.
  1690. raw_ptr<View> parent_ = nullptr;
  1691. // This view's children.
  1692. Views children_;
  1693. #if DCHECK_IS_ON()
  1694. // True while iterating over |children_|. Used to detect and DCHECK when
  1695. // |children_| is mutated during iteration.
  1696. mutable bool iterating_ = false;
  1697. #endif
  1698. bool can_process_events_within_subtree_ = true;
  1699. // Size and disposition ------------------------------------------------------
  1700. absl::optional<gfx::Size> preferred_size_;
  1701. // This View's bounds in the parent coordinate system.
  1702. gfx::Rect bounds_;
  1703. // Whether this view is visible.
  1704. bool visible_ = true;
  1705. // Whether this view is enabled.
  1706. bool enabled_ = true;
  1707. // When this flag is on, a View receives a mouse-enter and mouse-leave event
  1708. // even if a descendant View is the event-recipient for the real mouse
  1709. // events. When this flag is turned on, and mouse moves from outside of the
  1710. // view into a child view, both the child view and this view receives
  1711. // mouse-enter event. Similarly, if the mouse moves from inside a child view
  1712. // and out of this view, then both views receive a mouse-leave event.
  1713. // When this flag is turned off, if the mouse moves from inside this view into
  1714. // a child view, then this view receives a mouse-leave event. When this flag
  1715. // is turned on, it does not receive the mouse-leave event in this case.
  1716. // When the mouse moves from inside the child view out of the child view but
  1717. // still into this view, this view receives a mouse-enter event if this flag
  1718. // is turned off, but doesn't if this flag is turned on.
  1719. // This flag is initialized to false.
  1720. bool notify_enter_exit_on_child_ = false;
  1721. // Whether or not RegisterViewForVisibleBoundsNotification on the RootView
  1722. // has been invoked.
  1723. bool registered_for_visible_bounds_notification_ = false;
  1724. // List of descendants wanting notification when their visible bounds change.
  1725. std::unique_ptr<Views> descendants_to_notify_;
  1726. // Transformations -----------------------------------------------------------
  1727. // Painting will be clipped to this path.
  1728. SkPath clip_path_;
  1729. // Layout --------------------------------------------------------------------
  1730. // Whether the view needs to be laid out.
  1731. bool needs_layout_ = true;
  1732. // The View's LayoutManager defines the sizing heuristics applied to child
  1733. // Views. The default is absolute positioning according to bounds_.
  1734. std::unique_ptr<LayoutManager> layout_manager_;
  1735. // The default "fill" layout manager. This is set only if |layout_manager_|
  1736. // isn't set and SetUseDefaultFillLayout(true) is called or
  1737. // |kUseDefaultFillLayout| is true.
  1738. absl::optional<DefaultFillLayout> default_fill_layout_;
  1739. // Whether this View's layer should be snapped to the pixel boundary.
  1740. bool snap_layer_to_pixel_boundary_ = false;
  1741. // Painting ------------------------------------------------------------------
  1742. // Border.
  1743. std::unique_ptr<Border> border_;
  1744. // Background may rely on Border, so it must be declared last and destroyed
  1745. // first.
  1746. std::unique_ptr<Background> background_;
  1747. // Cached output of painting to be reused in future frames until invalidated.
  1748. ui::PaintCache paint_cache_;
  1749. // Whether SchedulePaintInRect() was invoked on this View.
  1750. bool needs_paint_ = false;
  1751. // Native theme --------------------------------------------------------------
  1752. // A native theme for this view and its descendants. Typically null, in which
  1753. // case the native theme is drawn from the parent view (eventually the
  1754. // widget).
  1755. raw_ptr<ui::NativeTheme> native_theme_ = nullptr;
  1756. // RTL painting --------------------------------------------------------------
  1757. // Indicates whether or not the gfx::Canvas object passed to Paint() is going
  1758. // to be flipped horizontally (using the appropriate transform) on
  1759. // right-to-left locales for this View.
  1760. bool flip_canvas_on_paint_for_rtl_ui_ = false;
  1761. // Controls whether GetTransform(), the mirroring functions, and the like
  1762. // horizontally mirror. This controls how child views are physically
  1763. // positioned onscreen. The default behavior should be correct in most cases,
  1764. // but can be overridden if a particular view must always be laid out in some
  1765. // direction regardless of the application's default UI direction.
  1766. absl::optional<bool> is_mirrored_;
  1767. // Accelerated painting ------------------------------------------------------
  1768. // Whether layer painting was explicitly set by a call to |SetPaintToLayer()|.
  1769. bool paint_to_layer_explicitly_set_ = false;
  1770. // Whether we are painting to a layer because of a non-identity transform.
  1771. bool paint_to_layer_for_transform_ = false;
  1772. // Set of layers that should be painted beneath this View's layer. These
  1773. // layers are maintained as siblings of this View's layer and are stacked
  1774. // beneath.
  1775. std::vector<ui::Layer*> layers_beneath_;
  1776. // If painting to a layer |mask_layer_| will mask the current layer and all
  1777. // child layers to within the |clip_path_|.
  1778. std::unique_ptr<views::ViewMaskLayer> mask_layer_;
  1779. // Accelerators --------------------------------------------------------------
  1780. // Focus manager accelerators registered on.
  1781. raw_ptr<FocusManager> accelerator_focus_manager_ = nullptr;
  1782. // The list of accelerators. List elements in the range
  1783. // [0, registered_accelerator_count_) are already registered to FocusManager,
  1784. // and the rest are not yet.
  1785. std::unique_ptr<std::vector<ui::Accelerator>> accelerators_;
  1786. size_t registered_accelerator_count_ = 0;
  1787. // Focus ---------------------------------------------------------------------
  1788. // Next view to be focused when the Tab key is pressed.
  1789. raw_ptr<View> next_focusable_view_ = nullptr;
  1790. // Next view to be focused when the Shift-Tab key combination is pressed.
  1791. raw_ptr<View> previous_focusable_view_ = nullptr;
  1792. // The focus behavior of the view in regular and accessibility mode.
  1793. FocusBehavior focus_behavior_ = FocusBehavior::NEVER;
  1794. // This is set when focus events should be skipped after focus reaches this
  1795. // View.
  1796. bool suppress_default_focus_handling_ = false;
  1797. // Context menus -------------------------------------------------------------
  1798. // The menu controller.
  1799. raw_ptr<ContextMenuController> context_menu_controller_ = nullptr;
  1800. // Drag and drop -------------------------------------------------------------
  1801. raw_ptr<DragController> drag_controller_ = nullptr;
  1802. // Input --------------------------------------------------------------------
  1803. std::unique_ptr<ViewTargeter> targeter_;
  1804. // System events -------------------------------------------------------------
  1805. #if DCHECK_IS_ON()
  1806. bool on_theme_changed_called_ = false;
  1807. #endif
  1808. // Accessibility -------------------------------------------------------------
  1809. // Manages the accessibility interface for this View.
  1810. mutable std::unique_ptr<ViewAccessibility> view_accessibility_;
  1811. // Keeps track of whether accessibility checks for this View have run yet.
  1812. // They run once inside ::OnPaint() to keep overhead low. The idea is that if
  1813. // a View is ready to paint it should also be set up to be accessible.
  1814. bool has_run_accessibility_paint_checks_ = false;
  1815. // Observers -----------------------------------------------------------------
  1816. base::ObserverList<ViewObserver>::Unchecked observers_;
  1817. // http://crbug.com/1162949 : Instrumentation that indicates if this is alive.
  1818. LifeCycleState life_cycle_state_ = LifeCycleState::kAlive;
  1819. };
  1820. BEGIN_VIEW_BUILDER(VIEWS_EXPORT, View, BaseView)
  1821. template <typename LayoutManager>
  1822. BuilderT& SetLayoutManager(std::unique_ptr<LayoutManager> layout_manager) & {
  1823. auto setter = std::make_unique<::views::internal::PropertySetter<
  1824. ViewClass_, std::unique_ptr<LayoutManager>,
  1825. decltype((static_cast<LayoutManager* (
  1826. ViewClass_::*)(std::unique_ptr<LayoutManager>)>(
  1827. &ViewClass_::SetLayoutManager))),
  1828. &ViewClass_::SetLayoutManager>>(std::move(layout_manager));
  1829. ::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter));
  1830. return *static_cast<BuilderT*>(this);
  1831. }
  1832. template <typename LayoutManager>
  1833. BuilderT&& SetLayoutManager(std::unique_ptr<LayoutManager> layout_manager) && {
  1834. return std::move(this->SetLayoutManager(std::move(layout_manager)));
  1835. }
  1836. VIEW_BUILDER_PROPERTY(std::unique_ptr<Background>, Background)
  1837. VIEW_BUILDER_PROPERTY(std::unique_ptr<Border>, Border)
  1838. VIEW_BUILDER_PROPERTY(gfx::Rect, BoundsRect)
  1839. VIEW_BUILDER_PROPERTY(gfx::Size, Size)
  1840. VIEW_BUILDER_PROPERTY(gfx::Point, Position)
  1841. VIEW_BUILDER_PROPERTY(int, X)
  1842. VIEW_BUILDER_PROPERTY(int, Y)
  1843. VIEW_BUILDER_PROPERTY(gfx::Size, PreferredSize)
  1844. VIEW_BUILDER_PROPERTY(SkPath, ClipPath)
  1845. VIEW_BUILDER_PROPERTY_DEFAULT(ui::LayerType, PaintToLayer, ui::LAYER_TEXTURED)
  1846. VIEW_BUILDER_PROPERTY(bool, Enabled)
  1847. VIEW_BUILDER_PROPERTY(bool, FlipCanvasOnPaintForRTLUI)
  1848. VIEW_BUILDER_PROPERTY(views::View::FocusBehavior, FocusBehavior)
  1849. VIEW_BUILDER_PROPERTY(int, Group)
  1850. VIEW_BUILDER_PROPERTY(int, ID)
  1851. VIEW_BUILDER_PROPERTY(bool, Mirrored)
  1852. VIEW_BUILDER_PROPERTY(bool, NotifyEnterExitOnChild)
  1853. VIEW_BUILDER_PROPERTY(gfx::Transform, Transform)
  1854. VIEW_BUILDER_PROPERTY(bool, Visible)
  1855. VIEW_BUILDER_PROPERTY(bool, CanProcessEventsWithinSubtree)
  1856. VIEW_BUILDER_PROPERTY(bool, UseDefaultFillLayout)
  1857. END_VIEW_BUILDER
  1858. } // namespace views
  1859. DEFINE_VIEW_BUILDER(VIEWS_EXPORT, View)
  1860. #endif // UI_VIEWS_VIEW_H_