accelerator_controller_unittest.cc 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108
  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. #include <utility>
  5. #include "ash/accelerators/accelerator_controller_impl.h"
  6. #include "ash/accelerators/accelerator_history_impl.h"
  7. #include "ash/accelerators/accelerator_notifications.h"
  8. #include "ash/accelerators/accelerator_table.h"
  9. #include "ash/accelerators/pre_target_accelerator_handler.h"
  10. #include "ash/accessibility/accessibility_controller_impl.h"
  11. #include "ash/accessibility/magnifier/docked_magnifier_controller.h"
  12. #include "ash/accessibility/magnifier/fullscreen_magnifier_controller.h"
  13. #include "ash/accessibility/test_accessibility_controller_client.h"
  14. #include "ash/accessibility/ui/accessibility_confirmation_dialog.h"
  15. #include "ash/app_list/app_list_metrics.h"
  16. #include "ash/app_list/test/app_list_test_helper.h"
  17. #include "ash/capture_mode/capture_mode_controller.h"
  18. #include "ash/capture_mode/capture_mode_types.h"
  19. #include "ash/constants/ash_features.h"
  20. #include "ash/constants/ash_pref_names.h"
  21. #include "ash/constants/ash_switches.h"
  22. #include "ash/display/screen_orientation_controller.h"
  23. #include "ash/display/screen_orientation_controller_test_api.h"
  24. #include "ash/ime/ime_controller_impl.h"
  25. #include "ash/ime/mode_indicator_observer.h"
  26. #include "ash/ime/test_ime_controller_client.h"
  27. #include "ash/media/media_controller_impl.h"
  28. #include "ash/public/cpp/capture_mode/capture_mode_test_api.h"
  29. #include "ash/public/cpp/ime_info.h"
  30. #include "ash/public/cpp/shell_window_ids.h"
  31. #include "ash/public/cpp/test/shell_test_api.h"
  32. #include "ash/public/cpp/test/test_new_window_delegate.h"
  33. #include "ash/session/session_controller_impl.h"
  34. #include "ash/session/test_session_controller_client.h"
  35. #include "ash/shell.h"
  36. #include "ash/system/brightness_control_delegate.h"
  37. #include "ash/system/keyboard_brightness_control_delegate.h"
  38. #include "ash/system/power/power_button_controller_test_api.h"
  39. #include "ash/system/status_area_widget_test_helper.h"
  40. #include "ash/system/unified/unified_system_tray.h"
  41. #include "ash/test/ash_test_base.h"
  42. #include "ash/test_media_client.h"
  43. #include "ash/wm/lock_state_controller.h"
  44. #include "ash/wm/overview/overview_controller.h"
  45. #include "ash/wm/overview/overview_item.h"
  46. #include "ash/wm/overview/overview_test_util.h"
  47. #include "ash/wm/splitview/split_view_metrics_controller.h"
  48. #include "ash/wm/tablet_mode/tablet_mode_controller.h"
  49. #include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h"
  50. #include "ash/wm/test_session_state_animator.h"
  51. #include "ash/wm/window_positioning_utils.h"
  52. #include "ash/wm/window_state.h"
  53. #include "ash/wm/window_util.h"
  54. #include "ash/wm/wm_event.h"
  55. #include "base/bind.h"
  56. #include "base/command_line.h"
  57. #include "base/files/file_util.h"
  58. #include "base/files/scoped_temp_dir.h"
  59. #include "base/json/json_writer.h"
  60. #include "base/run_loop.h"
  61. #include "base/strings/utf_string_conversions.h"
  62. #include "base/test/bind.h"
  63. #include "base/test/metrics/histogram_tester.h"
  64. #include "base/test/metrics/user_action_tester.h"
  65. #include "base/test/scoped_feature_list.h"
  66. #include "chromeos/ui/base/window_state_type.h"
  67. #include "components/prefs/pref_change_registrar.h"
  68. #include "components/prefs/pref_service.h"
  69. #include "media/base/media_switches.h"
  70. #include "services/media_session/public/cpp/test/test_media_controller.h"
  71. #include "services/media_session/public/mojom/media_session.mojom.h"
  72. #include "testing/gmock/include/gmock/gmock.h"
  73. #include "third_party/abseil-cpp/absl/types/optional.h"
  74. #include "ui/aura/client/aura_constants.h"
  75. #include "ui/aura/test/test_window_delegate.h"
  76. #include "ui/aura/test/test_windows.h"
  77. #include "ui/aura/window.h"
  78. #include "ui/base/accelerators/media_keys_util.h"
  79. #include "ui/base/accelerators/test_accelerator_target.h"
  80. #include "ui/base/ime/ash/fake_ime_keyboard.h"
  81. #include "ui/base/ime/ash/ime_keyboard.h"
  82. #include "ui/base/ime/ash/mock_input_method_manager.h"
  83. #include "ui/base/ime/init/input_method_factory.h"
  84. #include "ui/base/ime/mock_input_method.h"
  85. #include "ui/base/ui_base_features.h"
  86. #include "ui/display/manager/display_manager.h"
  87. #include "ui/display/screen.h"
  88. #include "ui/display/test/display_manager_test_api.h"
  89. #include "ui/events/devices/device_data_manager_test_api.h"
  90. #include "ui/events/event.h"
  91. #include "ui/events/event_sink.h"
  92. #include "ui/events/keycodes/dom/dom_code.h"
  93. #include "ui/events/test/event_generator.h"
  94. #include "ui/message_center/message_center.h"
  95. #include "ui/views/widget/widget.h"
  96. #include "ui/wm/core/accelerator_filter.h"
  97. namespace ash {
  98. namespace {
  99. using ::chromeos::WindowStateType;
  100. using ::media_session::mojom::MediaSessionAction;
  101. struct PrefToAcceleratorEntry {
  102. const char* pref_name;
  103. // If |notification_id| has been set to nullptr, then no notification is
  104. // expected.
  105. const char* notification_id;
  106. const char* histogram_id;
  107. const ui::Accelerator accelerator;
  108. };
  109. const PrefToAcceleratorEntry kAccessibilityAcceleratorMap[] = {
  110. {
  111. prefs::kAccessibilityHighContrastEnabled,
  112. kHighContrastToggleAccelNotificationId,
  113. kAccessibilityHighContrastShortcut,
  114. ui::Accelerator(ui::VKEY_H, ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN),
  115. },
  116. {prefs::kDockedMagnifierEnabled, kDockedMagnifierToggleAccelNotificationId,
  117. kAccessibilityDockedMagnifierShortcut,
  118. ui::Accelerator(ui::VKEY_D, ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN)},
  119. {
  120. prefs::kAccessibilitySpokenFeedbackEnabled,
  121. nullptr,
  122. kAccessibilitySpokenFeedbackShortcut,
  123. ui::Accelerator(ui::VKEY_Z, ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN),
  124. },
  125. {prefs::kAccessibilityScreenMagnifierEnabled,
  126. kFullscreenMagnifierToggleAccelNotificationId,
  127. kAccessibilityScreenMagnifierShortcut,
  128. ui::Accelerator(ui::VKEY_M, ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN)},
  129. };
  130. void AddTestImes() {
  131. ImeInfo ime1;
  132. ime1.id = "id1";
  133. ImeInfo ime2;
  134. ime2.id = "id2";
  135. std::vector<ImeInfo> visible_imes;
  136. visible_imes.push_back(std::move(ime1));
  137. visible_imes.push_back(std::move(ime2));
  138. Shell::Get()->ime_controller()->RefreshIme("id1", std::move(visible_imes),
  139. std::vector<ImeMenuItem>());
  140. }
  141. void AddNotVisibleTestIme() {
  142. ImeInfo dictation;
  143. dictation.id = "_ext_ime_egfdjlfmgnehecnclamagfafdccgfndpdictation";
  144. const std::vector<ImeInfo> visible_imes =
  145. Shell::Get()->ime_controller()->GetVisibleImes();
  146. std::vector<ImeInfo> available_imes;
  147. for (auto ime : visible_imes) {
  148. available_imes.push_back(ime);
  149. }
  150. available_imes.push_back(dictation);
  151. Shell::Get()->ime_controller()->RefreshIme(
  152. dictation.id, std::move(available_imes), std::vector<ImeMenuItem>());
  153. }
  154. ui::Accelerator CreateReleaseAccelerator(ui::KeyboardCode key_code,
  155. int modifiers) {
  156. ui::Accelerator accelerator(key_code, modifiers);
  157. accelerator.set_key_state(ui::Accelerator::KeyState::RELEASED);
  158. return accelerator;
  159. }
  160. class DummyBrightnessControlDelegate : public BrightnessControlDelegate {
  161. public:
  162. DummyBrightnessControlDelegate()
  163. : handle_brightness_down_count_(0), handle_brightness_up_count_(0) {}
  164. DummyBrightnessControlDelegate(const DummyBrightnessControlDelegate&) =
  165. delete;
  166. DummyBrightnessControlDelegate& operator=(
  167. const DummyBrightnessControlDelegate&) = delete;
  168. ~DummyBrightnessControlDelegate() override = default;
  169. void HandleBrightnessDown(const ui::Accelerator& accelerator) override {
  170. ++handle_brightness_down_count_;
  171. last_accelerator_ = accelerator;
  172. }
  173. void HandleBrightnessUp(const ui::Accelerator& accelerator) override {
  174. ++handle_brightness_up_count_;
  175. last_accelerator_ = accelerator;
  176. }
  177. void SetBrightnessPercent(double percent, bool gradual) override {}
  178. void GetBrightnessPercent(
  179. base::OnceCallback<void(absl::optional<double>)> callback) override {
  180. std::move(callback).Run(100.0);
  181. }
  182. int handle_brightness_down_count() const {
  183. return handle_brightness_down_count_;
  184. }
  185. int handle_brightness_up_count() const { return handle_brightness_up_count_; }
  186. const ui::Accelerator& last_accelerator() const { return last_accelerator_; }
  187. private:
  188. int handle_brightness_down_count_;
  189. int handle_brightness_up_count_;
  190. ui::Accelerator last_accelerator_;
  191. };
  192. class DummyKeyboardBrightnessControlDelegate
  193. : public KeyboardBrightnessControlDelegate {
  194. public:
  195. DummyKeyboardBrightnessControlDelegate()
  196. : handle_keyboard_brightness_down_count_(0),
  197. handle_keyboard_brightness_up_count_(0) {}
  198. DummyKeyboardBrightnessControlDelegate(
  199. const DummyKeyboardBrightnessControlDelegate&) = delete;
  200. DummyKeyboardBrightnessControlDelegate& operator=(
  201. const DummyKeyboardBrightnessControlDelegate&) = delete;
  202. ~DummyKeyboardBrightnessControlDelegate() override = default;
  203. void HandleKeyboardBrightnessDown(
  204. const ui::Accelerator& accelerator) override {
  205. ++handle_keyboard_brightness_down_count_;
  206. last_accelerator_ = accelerator;
  207. }
  208. void HandleKeyboardBrightnessUp(const ui::Accelerator& accelerator) override {
  209. ++handle_keyboard_brightness_up_count_;
  210. last_accelerator_ = accelerator;
  211. }
  212. void HandleToggleKeyboardBacklight() override {}
  213. int handle_keyboard_brightness_down_count() const {
  214. return handle_keyboard_brightness_down_count_;
  215. }
  216. int handle_keyboard_brightness_up_count() const {
  217. return handle_keyboard_brightness_up_count_;
  218. }
  219. const ui::Accelerator& last_accelerator() const { return last_accelerator_; }
  220. private:
  221. int handle_keyboard_brightness_down_count_;
  222. int handle_keyboard_brightness_up_count_;
  223. ui::Accelerator last_accelerator_;
  224. };
  225. class MockNewWindowDelegate : public testing::NiceMock<TestNewWindowDelegate> {
  226. public:
  227. // TestNewWindowDelegate:
  228. MOCK_METHOD(void, OpenCalculator, (), (override));
  229. MOCK_METHOD(void, ShowKeyboardShortcutViewer, (), (override));
  230. MOCK_METHOD(void,
  231. OpenUrl,
  232. (const GURL& url, OpenUrlFrom from, Disposition disposition),
  233. (override));
  234. };
  235. class MockAcceleratorObserver
  236. : public testing::NiceMock<AcceleratorController::Observer> {
  237. public:
  238. // AcceleratorController::Observer:
  239. MOCK_METHOD(void, OnActionPerformed, (AcceleratorAction action), (override));
  240. MOCK_METHOD(void,
  241. OnAcceleratorControllerWillBeDestroyed,
  242. (AcceleratorController * controller),
  243. (override));
  244. };
  245. } // namespace
  246. // Note AcceleratorControllerTest can't be in the anonymous namespace because
  247. // it is referenced as a friend by exit_warning_handler.h
  248. class AcceleratorControllerTest : public AshTestBase {
  249. public:
  250. AcceleratorControllerTest() {
  251. auto delegate = std::make_unique<MockNewWindowDelegate>();
  252. new_window_delegate_ = delegate.get();
  253. delegate_provider_ =
  254. std::make_unique<TestNewWindowDelegateProvider>(std::move(delegate));
  255. }
  256. AcceleratorControllerTest(const AcceleratorControllerTest&) = delete;
  257. AcceleratorControllerTest& operator=(const AcceleratorControllerTest&) =
  258. delete;
  259. ~AcceleratorControllerTest() override = default;
  260. void SetUp() override {
  261. AshTestBase::SetUp();
  262. controller_ = Shell::Get()->accelerator_controller();
  263. test_api_ =
  264. std::make_unique<AcceleratorControllerImpl::TestApi>(controller_);
  265. }
  266. protected:
  267. static bool ProcessInController(const ui::Accelerator& accelerator) {
  268. AcceleratorControllerImpl* controller =
  269. Shell::Get()->accelerator_controller();
  270. if (accelerator.key_state() == ui::Accelerator::KeyState::RELEASED) {
  271. // If the |accelerator| should trigger on release, then we store the
  272. // pressed version of it first in history then the released one to
  273. // simulate what happens in reality.
  274. ui::Accelerator pressed_accelerator = accelerator;
  275. pressed_accelerator.set_key_state(ui::Accelerator::KeyState::PRESSED);
  276. controller->GetAcceleratorHistory()->StoreCurrentAccelerator(
  277. pressed_accelerator);
  278. }
  279. controller->GetAcceleratorHistory()->StoreCurrentAccelerator(accelerator);
  280. return controller->Process(accelerator);
  281. }
  282. bool ContainsHighContrastNotification() const {
  283. return nullptr != message_center()->FindVisibleNotificationById(
  284. kHighContrastToggleAccelNotificationId);
  285. }
  286. bool ContainsDockedMagnifierNotification() const {
  287. return nullptr != message_center()->FindVisibleNotificationById(
  288. kDockedMagnifierToggleAccelNotificationId);
  289. }
  290. bool ContainsFullscreenMagnifierNotification() const {
  291. return nullptr != message_center()->FindVisibleNotificationById(
  292. kFullscreenMagnifierToggleAccelNotificationId);
  293. }
  294. bool IsConfirmationDialogOpen() {
  295. return !!(test_api_->GetConfirmationDialog());
  296. }
  297. void AcceptConfirmationDialog() {
  298. DCHECK(test_api_->GetConfirmationDialog());
  299. test_api_->GetConfirmationDialog()->AcceptDialog();
  300. }
  301. void CancelConfirmationDialog() {
  302. DCHECK(test_api_->GetConfirmationDialog());
  303. test_api_->GetConfirmationDialog()->CancelDialog();
  304. }
  305. void TriggerRotateScreenShortcut() {
  306. PressAndReleaseKey(ui::VKEY_BROWSER_REFRESH,
  307. ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
  308. if (IsConfirmationDialogOpen()) {
  309. AcceptConfirmationDialog();
  310. base::RunLoop().RunUntilIdle();
  311. }
  312. }
  313. void RemoveAllNotifications() const {
  314. message_center()->RemoveAllNotifications(
  315. false /* by_user */, message_center::MessageCenter::RemoveType::ALL);
  316. }
  317. static const ui::Accelerator& GetPreviousAccelerator() {
  318. return Shell::Get()
  319. ->accelerator_controller()
  320. ->GetAcceleratorHistory()
  321. ->previous_accelerator();
  322. }
  323. static const ui::Accelerator& GetCurrentAccelerator() {
  324. return Shell::Get()
  325. ->accelerator_controller()
  326. ->GetAcceleratorHistory()
  327. ->current_accelerator();
  328. }
  329. // Several functions to access ExitWarningHandler (as friend).
  330. static void StubForTest(ExitWarningHandler* ewh) {
  331. ewh->stub_timer_for_test_ = true;
  332. }
  333. static void Reset(ExitWarningHandler* ewh) {
  334. ewh->state_ = ExitWarningHandler::IDLE;
  335. }
  336. static void SimulateTimerExpired(ExitWarningHandler* ewh) {
  337. ewh->TimerAction();
  338. }
  339. static bool is_ui_shown(ExitWarningHandler* ewh) { return !!ewh->widget_; }
  340. static bool is_idle(ExitWarningHandler* ewh) {
  341. return ewh->state_ == ExitWarningHandler::IDLE;
  342. }
  343. static bool is_exiting(ExitWarningHandler* ewh) {
  344. return ewh->state_ == ExitWarningHandler::EXITING;
  345. }
  346. message_center::MessageCenter* message_center() const {
  347. return message_center::MessageCenter::Get();
  348. }
  349. void SetBrightnessControlDelegate(
  350. std::unique_ptr<BrightnessControlDelegate> delegate) {
  351. Shell::Get()->brightness_control_delegate_ = std::move(delegate);
  352. }
  353. void SetKeyboardBrightnessControlDelegate(
  354. std::unique_ptr<KeyboardBrightnessControlDelegate> delegate) {
  355. Shell::Get()->keyboard_brightness_control_delegate_ = std::move(delegate);
  356. }
  357. bool WriteJsonFile(const base::FilePath& file_path,
  358. const std::string& json_string) const {
  359. if (!base::DirectoryExists(file_path.DirName()))
  360. base::CreateDirectory(file_path.DirName());
  361. int data_size = static_cast<int>(json_string.size());
  362. int bytes_written =
  363. base::WriteFile(file_path, json_string.data(), data_size);
  364. if (bytes_written != data_size) {
  365. LOG(ERROR) << " Wrote " << bytes_written << " byte(s) instead of "
  366. << data_size << " to " << file_path.value();
  367. return false;
  368. }
  369. return true;
  370. }
  371. AcceleratorControllerImpl* controller_ = nullptr; // Not owned.
  372. std::unique_ptr<AcceleratorControllerImpl::TestApi> test_api_;
  373. MockNewWindowDelegate* new_window_delegate_;
  374. std::unique_ptr<TestNewWindowDelegateProvider> delegate_provider_;
  375. };
  376. namespace {
  377. // Double press of exit shortcut => exiting
  378. TEST_F(AcceleratorControllerTest, ExitWarningHandlerTestDoublePress) {
  379. ui::Accelerator press(ui::VKEY_Q, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN);
  380. ui::Accelerator release(press);
  381. release.set_key_state(ui::Accelerator::KeyState::RELEASED);
  382. ExitWarningHandler* ewh = test_api_->GetExitWarningHandler();
  383. ASSERT_TRUE(ewh);
  384. StubForTest(ewh);
  385. EXPECT_TRUE(is_idle(ewh));
  386. EXPECT_FALSE(is_ui_shown(ewh));
  387. EXPECT_TRUE(ProcessInController(press));
  388. EXPECT_FALSE(ProcessInController(release));
  389. EXPECT_FALSE(is_idle(ewh));
  390. EXPECT_TRUE(is_ui_shown(ewh));
  391. EXPECT_TRUE(ProcessInController(press)); // second press before timer.
  392. EXPECT_FALSE(ProcessInController(release));
  393. SimulateTimerExpired(ewh);
  394. EXPECT_TRUE(is_exiting(ewh));
  395. EXPECT_FALSE(is_ui_shown(ewh));
  396. Reset(ewh);
  397. }
  398. // Single press of exit shortcut before timer => idle
  399. TEST_F(AcceleratorControllerTest, ExitWarningHandlerTestSinglePress) {
  400. ui::Accelerator press(ui::VKEY_Q, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN);
  401. ui::Accelerator release(press);
  402. release.set_key_state(ui::Accelerator::KeyState::RELEASED);
  403. ExitWarningHandler* ewh = test_api_->GetExitWarningHandler();
  404. ASSERT_TRUE(ewh);
  405. StubForTest(ewh);
  406. EXPECT_TRUE(is_idle(ewh));
  407. EXPECT_FALSE(is_ui_shown(ewh));
  408. EXPECT_TRUE(ProcessInController(press));
  409. EXPECT_FALSE(ProcessInController(release));
  410. EXPECT_FALSE(is_idle(ewh));
  411. EXPECT_TRUE(is_ui_shown(ewh));
  412. SimulateTimerExpired(ewh);
  413. EXPECT_TRUE(is_idle(ewh));
  414. EXPECT_FALSE(is_ui_shown(ewh));
  415. Reset(ewh);
  416. }
  417. // Shutdown ash with exit warning bubble open should not crash.
  418. TEST_F(AcceleratorControllerTest, LingeringExitWarningBubble) {
  419. ExitWarningHandler* ewh = test_api_->GetExitWarningHandler();
  420. ASSERT_TRUE(ewh);
  421. StubForTest(ewh);
  422. // Trigger once to show the bubble.
  423. ewh->HandleAccelerator();
  424. EXPECT_FALSE(is_idle(ewh));
  425. EXPECT_TRUE(is_ui_shown(ewh));
  426. // Exit ash and there should be no crash
  427. }
  428. TEST_F(AcceleratorControllerTest, Register) {
  429. ui::TestAcceleratorTarget target;
  430. const ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_NONE);
  431. const ui::Accelerator accelerator_b(ui::VKEY_B, ui::EF_NONE);
  432. const ui::Accelerator accelerator_c(ui::VKEY_C, ui::EF_NONE);
  433. const ui::Accelerator accelerator_d(ui::VKEY_D, ui::EF_NONE);
  434. controller_->Register(
  435. {accelerator_a, accelerator_b, accelerator_c, accelerator_d}, &target);
  436. // The registered accelerators are processed.
  437. EXPECT_TRUE(ProcessInController(accelerator_a));
  438. EXPECT_TRUE(ProcessInController(accelerator_b));
  439. EXPECT_TRUE(ProcessInController(accelerator_c));
  440. EXPECT_TRUE(ProcessInController(accelerator_d));
  441. EXPECT_EQ(4, target.accelerator_count());
  442. }
  443. TEST_F(AcceleratorControllerTest, RegisterMultipleTarget) {
  444. const ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_NONE);
  445. ui::TestAcceleratorTarget target1;
  446. controller_->Register({accelerator_a}, &target1);
  447. ui::TestAcceleratorTarget target2;
  448. controller_->Register({accelerator_a}, &target2);
  449. // If multiple targets are registered with the same accelerator, the target
  450. // registered later processes the accelerator.
  451. EXPECT_TRUE(ProcessInController(accelerator_a));
  452. EXPECT_EQ(0, target1.accelerator_count());
  453. EXPECT_EQ(1, target2.accelerator_count());
  454. }
  455. TEST_F(AcceleratorControllerTest, Unregister) {
  456. const ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_NONE);
  457. const ui::Accelerator accelerator_b(ui::VKEY_B, ui::EF_NONE);
  458. ui::TestAcceleratorTarget target;
  459. controller_->Register({accelerator_a, accelerator_b}, &target);
  460. // Unregistering a different accelerator does not affect the other
  461. // accelerator.
  462. controller_->Unregister(accelerator_b, &target);
  463. EXPECT_TRUE(ProcessInController(accelerator_a));
  464. EXPECT_EQ(1, target.accelerator_count());
  465. // The unregistered accelerator is no longer processed.
  466. target.ResetCounts();
  467. controller_->Unregister(accelerator_a, &target);
  468. EXPECT_FALSE(ProcessInController(accelerator_a));
  469. EXPECT_EQ(0, target.accelerator_count());
  470. }
  471. TEST_F(AcceleratorControllerTest, UnregisterAll) {
  472. const ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_NONE);
  473. const ui::Accelerator accelerator_b(ui::VKEY_B, ui::EF_NONE);
  474. ui::TestAcceleratorTarget target1;
  475. controller_->Register({accelerator_a, accelerator_b}, &target1);
  476. const ui::Accelerator accelerator_c(ui::VKEY_C, ui::EF_NONE);
  477. ui::TestAcceleratorTarget target2;
  478. controller_->Register({accelerator_c}, &target2);
  479. controller_->UnregisterAll(&target1);
  480. // All the accelerators registered for |target1| are no longer processed.
  481. EXPECT_FALSE(ProcessInController(accelerator_a));
  482. EXPECT_FALSE(ProcessInController(accelerator_b));
  483. EXPECT_EQ(0, target1.accelerator_count());
  484. // UnregisterAll with a different target does not affect the other target.
  485. EXPECT_TRUE(ProcessInController(accelerator_c));
  486. EXPECT_EQ(1, target2.accelerator_count());
  487. }
  488. TEST_F(AcceleratorControllerTest, Process) {
  489. const ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_NONE);
  490. ui::TestAcceleratorTarget target1;
  491. controller_->Register({accelerator_a}, &target1);
  492. // The registered accelerator is processed.
  493. EXPECT_TRUE(ProcessInController(accelerator_a));
  494. EXPECT_EQ(1, target1.accelerator_count());
  495. // The non-registered accelerator is not processed.
  496. const ui::Accelerator accelerator_b(ui::VKEY_B, ui::EF_NONE);
  497. EXPECT_FALSE(ProcessInController(accelerator_b));
  498. }
  499. TEST_F(AcceleratorControllerTest, IsRegistered) {
  500. const ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_NONE);
  501. const ui::Accelerator accelerator_shift_a(ui::VKEY_A, ui::EF_SHIFT_DOWN);
  502. ui::TestAcceleratorTarget target;
  503. controller_->Register({accelerator_a}, &target);
  504. EXPECT_TRUE(controller_->IsRegistered(accelerator_a));
  505. EXPECT_FALSE(controller_->IsRegistered(accelerator_shift_a));
  506. controller_->UnregisterAll(&target);
  507. EXPECT_FALSE(controller_->IsRegistered(accelerator_a));
  508. }
  509. TEST_F(AcceleratorControllerTest, WindowSnap) {
  510. std::unique_ptr<aura::Window> window(
  511. CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  512. WindowState* window_state = WindowState::Get(window.get());
  513. window_state->Activate();
  514. {
  515. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_LEFT, {});
  516. gfx::Rect expected_bounds = GetDefaultSnappedWindowBoundsInParent(
  517. window.get(), SnapViewType::kPrimary);
  518. EXPECT_EQ(expected_bounds.ToString(), window->bounds().ToString());
  519. }
  520. {
  521. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_RIGHT, {});
  522. gfx::Rect expected_bounds = GetDefaultSnappedWindowBoundsInParent(
  523. window.get(), SnapViewType::kSecondary);
  524. EXPECT_EQ(expected_bounds.ToString(), window->bounds().ToString());
  525. }
  526. {
  527. gfx::Rect normal_bounds = window_state->GetRestoreBoundsInParent();
  528. controller_->PerformActionIfEnabled(TOGGLE_MAXIMIZED, {});
  529. EXPECT_TRUE(window_state->IsMaximized());
  530. EXPECT_NE(normal_bounds.ToString(), window->bounds().ToString());
  531. controller_->PerformActionIfEnabled(TOGGLE_MAXIMIZED, {});
  532. EXPECT_FALSE(window_state->IsMaximized());
  533. // Window gets restored to its right snapped window bounds and its window
  534. // state should also restore to the right snapped window state.
  535. gfx::Rect expected_bounds = GetDefaultSnappedWindowBoundsInParent(
  536. window.get(), SnapViewType::kSecondary);
  537. EXPECT_EQ(expected_bounds.ToString(), window->bounds().ToString());
  538. EXPECT_EQ(window_state->GetStateType(), WindowStateType::kSecondarySnapped);
  539. controller_->PerformActionIfEnabled(TOGGLE_MAXIMIZED, {});
  540. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_LEFT, {});
  541. EXPECT_FALSE(window_state->IsMaximized());
  542. controller_->PerformActionIfEnabled(TOGGLE_MAXIMIZED, {});
  543. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_RIGHT, {});
  544. EXPECT_FALSE(window_state->IsMaximized());
  545. controller_->PerformActionIfEnabled(TOGGLE_MAXIMIZED, {});
  546. EXPECT_TRUE(window_state->IsMaximized());
  547. controller_->PerformActionIfEnabled(WINDOW_MINIMIZE, {});
  548. EXPECT_FALSE(window_state->IsMaximized());
  549. EXPECT_TRUE(window_state->IsMinimized());
  550. window_state->Restore();
  551. window_state->Activate();
  552. controller_->PerformActionIfEnabled(TOGGLE_FULLSCREEN, {});
  553. EXPECT_TRUE(window_state->IsFullscreen());
  554. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_LEFT, {});
  555. EXPECT_TRUE(window_state->IsSnapped());
  556. EXPECT_FALSE(window_state->IsFullscreen());
  557. controller_->PerformActionIfEnabled(TOGGLE_FULLSCREEN, {});
  558. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_RIGHT, {});
  559. EXPECT_TRUE(window_state->IsSnapped());
  560. EXPECT_FALSE(window_state->IsFullscreen());
  561. }
  562. {
  563. controller_->PerformActionIfEnabled(WINDOW_MINIMIZE, {});
  564. EXPECT_TRUE(window_state->IsMinimized());
  565. }
  566. }
  567. // Tests that window snapping works.
  568. TEST_F(AcceleratorControllerTest, TestRepeatedSnap) {
  569. std::unique_ptr<aura::Window> window(
  570. CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  571. WindowState* window_state = WindowState::Get(window.get());
  572. window_state->Activate();
  573. // Snap right.
  574. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_RIGHT, {});
  575. gfx::Rect normal_bounds = window_state->GetRestoreBoundsInParent();
  576. gfx::Rect expected_bounds = GetDefaultSnappedWindowBoundsInParent(
  577. window.get(), SnapViewType::kSecondary);
  578. EXPECT_EQ(expected_bounds.ToString(), window->bounds().ToString());
  579. EXPECT_TRUE(window_state->IsSnapped());
  580. // Snap right again ->> becomes normal.
  581. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_RIGHT, {});
  582. EXPECT_TRUE(window_state->IsNormalStateType());
  583. EXPECT_EQ(normal_bounds.ToString(), window->bounds().ToString());
  584. // Snap right.
  585. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_RIGHT, {});
  586. EXPECT_TRUE(window_state->IsSnapped());
  587. // Snap left.
  588. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_LEFT, {});
  589. EXPECT_TRUE(window_state->IsSnapped());
  590. expected_bounds = GetDefaultSnappedWindowBoundsInParent(
  591. window.get(), SnapViewType::kPrimary);
  592. EXPECT_EQ(expected_bounds.ToString(), window->bounds().ToString());
  593. // Snap left again ->> becomes normal.
  594. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_LEFT, {});
  595. EXPECT_TRUE(window_state->IsNormalStateType());
  596. EXPECT_EQ(normal_bounds.ToString(), window->bounds().ToString());
  597. }
  598. class AcceleratorControllerTestWithClamshellSplitView
  599. : public AcceleratorControllerTest {
  600. public:
  601. AcceleratorControllerTestWithClamshellSplitView() = default;
  602. AcceleratorControllerTestWithClamshellSplitView(
  603. const AcceleratorControllerTestWithClamshellSplitView&) = delete;
  604. AcceleratorControllerTestWithClamshellSplitView& operator=(
  605. const AcceleratorControllerTestWithClamshellSplitView&) = delete;
  606. ~AcceleratorControllerTestWithClamshellSplitView() override = default;
  607. protected:
  608. // Note: These functions assume the default display resolution 800x600.
  609. void EnterOverviewAndDragToSnapLeft(aura::Window* window) {
  610. EnterOverviewAndDragTo(window, gfx::Point(0, 300));
  611. }
  612. void EnterOverviewAndDragToSnapRight(aura::Window* window) {
  613. EnterOverviewAndDragTo(window, gfx::Point(799, 300));
  614. }
  615. private:
  616. void EnterOverviewAndDragTo(aura::Window* window,
  617. const gfx::Point& destination) {
  618. DCHECK(!Shell::Get()->overview_controller()->InOverviewSession());
  619. ToggleOverview();
  620. ui::test::EventGenerator* generator = GetEventGenerator();
  621. generator->MoveMouseTo(gfx::ToRoundedPoint(
  622. GetOverviewItemForWindow(window)->target_bounds().CenterPoint()));
  623. generator->DragMouseTo(destination);
  624. }
  625. };
  626. TEST_F(AcceleratorControllerTestWithClamshellSplitView, WindowSnapUma) {
  627. base::UserActionTester user_action_tester;
  628. base::HistogramTester histogram_tester;
  629. std::unique_ptr<aura::Window> window1(
  630. CreateTestWindowInShellWithBounds(gfx::Rect(10, 10, 20, 20)));
  631. // Some test cases use clamshell split view, for which we need a second window
  632. // so overview will be nonempty. Otherwise split view will end when it starts.
  633. std::unique_ptr<aura::Window> window2(
  634. CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  635. base::HistogramBase::Count left_clamshell_no_overview = 0;
  636. base::HistogramBase::Count left_clamshell_overview = 0;
  637. base::HistogramBase::Count left_tablet = 0;
  638. base::HistogramBase::Count right_clamshell_no_overview = 0;
  639. base::HistogramBase::Count right_clamshell_overview = 0;
  640. base::HistogramBase::Count right_tablet = 0;
  641. // Performs |action|, checks that |window1| is in |target_window1_state_type|,
  642. // and verifies metrics. Output of failed expectations includes |description|.
  643. const auto test = [&](const char* description, AcceleratorAction action,
  644. WindowStateType target_window1_state_type) {
  645. SCOPED_TRACE(description);
  646. controller_->PerformActionIfEnabled(action, {});
  647. EXPECT_EQ(target_window1_state_type,
  648. WindowState::Get(window1.get())->GetStateType());
  649. EXPECT_EQ(
  650. left_clamshell_no_overview + left_clamshell_overview + left_tablet,
  651. user_action_tester.GetActionCount("Accel_Window_Snap_Left"));
  652. EXPECT_EQ(
  653. right_clamshell_no_overview + right_clamshell_overview + right_tablet,
  654. user_action_tester.GetActionCount("Accel_Window_Snap_Right"));
  655. histogram_tester.ExpectBucketCount(
  656. kAccelWindowSnap,
  657. WindowSnapAcceleratorAction::kCycleLeftSnapInClamshellNoOverview,
  658. left_clamshell_no_overview);
  659. histogram_tester.ExpectBucketCount(
  660. kAccelWindowSnap,
  661. WindowSnapAcceleratorAction::kCycleLeftSnapInClamshellOverview,
  662. left_clamshell_overview);
  663. histogram_tester.ExpectBucketCount(
  664. kAccelWindowSnap, WindowSnapAcceleratorAction::kCycleLeftSnapInTablet,
  665. left_tablet);
  666. histogram_tester.ExpectBucketCount(
  667. kAccelWindowSnap,
  668. WindowSnapAcceleratorAction::kCycleRightSnapInClamshellNoOverview,
  669. right_clamshell_no_overview);
  670. histogram_tester.ExpectBucketCount(
  671. kAccelWindowSnap,
  672. WindowSnapAcceleratorAction::kCycleRightSnapInClamshellOverview,
  673. right_clamshell_overview);
  674. histogram_tester.ExpectBucketCount(
  675. kAccelWindowSnap, WindowSnapAcceleratorAction::kCycleRightSnapInTablet,
  676. right_tablet);
  677. };
  678. // Alt+[, clamshell, no overview
  679. wm::ActivateWindow(window1.get());
  680. left_clamshell_no_overview = 1;
  681. test("Snap left, clamshell, no overview", WINDOW_CYCLE_SNAP_LEFT,
  682. WindowStateType::kPrimarySnapped);
  683. left_clamshell_no_overview = 2;
  684. test("Unsnap left, clamshell, no overview", WINDOW_CYCLE_SNAP_LEFT,
  685. WindowStateType::kNormal);
  686. // Alt+[, clamshell, overview
  687. EnterOverviewAndDragToSnapRight(window1.get());
  688. left_clamshell_overview = 1;
  689. test("Snap left, clamshell, overview", WINDOW_CYCLE_SNAP_LEFT,
  690. WindowStateType::kPrimarySnapped);
  691. left_clamshell_overview = 2;
  692. test("Unsnap left, clamshell, overview", WINDOW_CYCLE_SNAP_LEFT,
  693. WindowStateType::kNormal);
  694. // Alt+], clamshell, no overview
  695. right_clamshell_no_overview = 1;
  696. test("Snap right, clamshell, no overview", WINDOW_CYCLE_SNAP_RIGHT,
  697. WindowStateType::kSecondarySnapped);
  698. right_clamshell_no_overview = 2;
  699. test("Unsnap right, clamshell, no overview", WINDOW_CYCLE_SNAP_RIGHT,
  700. WindowStateType::kNormal);
  701. // Alt+], clamshell, overview
  702. EnterOverviewAndDragToSnapLeft(window1.get());
  703. right_clamshell_overview = 1;
  704. test("Snap right, clamshell, overview", WINDOW_CYCLE_SNAP_RIGHT,
  705. WindowStateType::kSecondarySnapped);
  706. right_clamshell_overview = 2;
  707. test("Unsnap right, clamshell, overview", WINDOW_CYCLE_SNAP_RIGHT,
  708. WindowStateType::kNormal);
  709. // Alt+[, tablet, no overview
  710. ShellTestApi().SetTabletModeEnabledForTest(true);
  711. left_tablet = 1;
  712. test("Snap left, tablet, no overview", WINDOW_CYCLE_SNAP_LEFT,
  713. WindowStateType::kPrimarySnapped);
  714. ToggleOverview();
  715. left_tablet = 2;
  716. test("Unsnap left, tablet, no overview", WINDOW_CYCLE_SNAP_LEFT,
  717. WindowStateType::kMaximized);
  718. // Alt+[, tablet, overview
  719. EnterOverviewAndDragToSnapRight(window1.get());
  720. left_tablet = 3;
  721. test("Snap left, tablet, overview", WINDOW_CYCLE_SNAP_LEFT,
  722. WindowStateType::kPrimarySnapped);
  723. left_tablet = 4;
  724. test("Unsnap left, tablet, overview", WINDOW_CYCLE_SNAP_LEFT,
  725. WindowStateType::kMaximized);
  726. // Alt+], tablet, no overview
  727. right_tablet = 1;
  728. test("Snap right, tablet, no overview", WINDOW_CYCLE_SNAP_RIGHT,
  729. WindowStateType::kSecondarySnapped);
  730. ToggleOverview();
  731. right_tablet = 2;
  732. test("Unsnap right, tablet, no overview", WINDOW_CYCLE_SNAP_RIGHT,
  733. WindowStateType::kMaximized);
  734. // Alt+], tablet, overview
  735. EnterOverviewAndDragToSnapLeft(window1.get());
  736. right_tablet = 3;
  737. test("Snap right, tablet, overview", WINDOW_CYCLE_SNAP_RIGHT,
  738. WindowStateType::kSecondarySnapped);
  739. right_tablet = 4;
  740. test("Unsnap right, tablet, overview", WINDOW_CYCLE_SNAP_RIGHT,
  741. WindowStateType::kMaximized);
  742. }
  743. TEST_F(AcceleratorControllerTestWithClamshellSplitView,
  744. WindowSnapOrientationUma) {
  745. UpdateDisplay("800x600");
  746. std::unique_ptr<aura::Window> window(
  747. CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  748. WindowState* window_state = WindowState::Get(window.get());
  749. std::unique_ptr<aura::Window> window2(
  750. CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  751. WindowState* window_state2 = WindowState::Get(window2.get());
  752. base::HistogramTester histogram_tester;
  753. constexpr char kSnapWindowDeviceOrientationHistogram[] =
  754. "Ash.Window.Snap.DeviceOrientation";
  755. histogram_tester.ExpectBucketCount(
  756. kSnapWindowDeviceOrientationHistogram,
  757. SplitViewMetricsController::DeviceOrientation::kLandscape, 0);
  758. window_state->Activate();
  759. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_LEFT, {});
  760. gfx::Rect expected_bounds = GetDefaultSnappedWindowBoundsInParent(
  761. window.get(), SnapViewType::kPrimary);
  762. EXPECT_EQ(expected_bounds.ToString(), window->bounds().ToString());
  763. histogram_tester.ExpectBucketCount(
  764. kSnapWindowDeviceOrientationHistogram,
  765. SplitViewMetricsController::DeviceOrientation::kLandscape, 1);
  766. histogram_tester.ExpectBucketCount(
  767. kSnapWindowDeviceOrientationHistogram,
  768. SplitViewMetricsController::DeviceOrientation::kPortrait, 0);
  769. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_RIGHT, {});
  770. histogram_tester.ExpectBucketCount(
  771. kSnapWindowDeviceOrientationHistogram,
  772. SplitViewMetricsController::DeviceOrientation::kLandscape, 2);
  773. histogram_tester.ExpectBucketCount(
  774. kSnapWindowDeviceOrientationHistogram,
  775. SplitViewMetricsController::DeviceOrientation::kPortrait, 0);
  776. window_state2->Activate();
  777. UpdateDisplay("800x600/l");
  778. controller_->PerformActionIfEnabled(WINDOW_CYCLE_SNAP_LEFT, {});
  779. histogram_tester.ExpectBucketCount(
  780. kSnapWindowDeviceOrientationHistogram,
  781. SplitViewMetricsController::DeviceOrientation::kPortrait, 1);
  782. }
  783. TEST_F(AcceleratorControllerTest, RotateScreen) {
  784. display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
  785. display::Display::Rotation initial_rotation =
  786. GetActiveDisplayRotation(display.id());
  787. AccessibilityControllerImpl* accessibility_controller =
  788. Shell::Get()->accessibility_controller();
  789. EXPECT_FALSE(accessibility_controller
  790. ->HasDisplayRotationAcceleratorDialogBeenAccepted());
  791. PressAndReleaseKey(ui::VKEY_BROWSER_REFRESH,
  792. ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
  793. // Dialog should be open.
  794. EXPECT_TRUE(IsConfirmationDialogOpen());
  795. // Cancel on the dialog should have no effect.
  796. CancelConfirmationDialog();
  797. base::RunLoop().RunUntilIdle();
  798. EXPECT_FALSE(accessibility_controller
  799. ->HasDisplayRotationAcceleratorDialogBeenAccepted());
  800. display::Display::Rotation rotation_after_cancel =
  801. GetActiveDisplayRotation(display.id());
  802. // Screen rotation should not have been triggered.
  803. EXPECT_EQ(initial_rotation, rotation_after_cancel);
  804. // Use short cut again.
  805. PressAndReleaseKey(ui::VKEY_BROWSER_REFRESH,
  806. ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
  807. EXPECT_TRUE(IsConfirmationDialogOpen());
  808. AcceptConfirmationDialog();
  809. base::RunLoop().RunUntilIdle();
  810. // Dialog should be closed.
  811. EXPECT_FALSE(IsConfirmationDialogOpen());
  812. EXPECT_TRUE(accessibility_controller
  813. ->HasDisplayRotationAcceleratorDialogBeenAccepted());
  814. display::Display::Rotation rotation_after_accept =
  815. GetActiveDisplayRotation(display.id());
  816. // |new_rotation| is determined by the AcceleratorController.
  817. EXPECT_NE(initial_rotation, rotation_after_accept);
  818. }
  819. // Tests that using the keyboard shortcut to rotate the display while the device
  820. // is in physical tablet state behaves like a request to lock the user
  821. // orientation to the next rotation of the internal display, and disables auto-
  822. // rotation.
  823. TEST_F(AcceleratorControllerTest, RotateScreenInPhysicalTabletState) {
  824. display::test::DisplayManagerTestApi(display_manager())
  825. .SetFirstDisplayAsInternalDisplay();
  826. ShellTestApi().SetTabletModeEnabledForTest(true);
  827. auto* tablet_mode_controller = Shell::Get()->tablet_mode_controller();
  828. auto* screen_orientation_controller =
  829. Shell::Get()->screen_orientation_controller();
  830. EXPECT_TRUE(tablet_mode_controller->is_in_tablet_physical_state());
  831. EXPECT_FALSE(screen_orientation_controller->user_rotation_locked());
  832. EXPECT_FALSE(screen_orientation_controller->rotation_locked());
  833. EXPECT_EQ(chromeos::OrientationType::kLandscapePrimary,
  834. screen_orientation_controller->GetCurrentOrientation());
  835. TriggerRotateScreenShortcut();
  836. EXPECT_TRUE(screen_orientation_controller->user_rotation_locked());
  837. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  838. EXPECT_EQ(chromeos::OrientationType::kPortraitSecondary,
  839. screen_orientation_controller->GetCurrentOrientation());
  840. // When the device is no longer used as a tablet, the original rotation will
  841. // be restored.
  842. ShellTestApi().SetTabletModeEnabledForTest(false);
  843. EXPECT_FALSE(tablet_mode_controller->is_in_tablet_physical_state());
  844. EXPECT_EQ(chromeos::OrientationType::kLandscapePrimary,
  845. screen_orientation_controller->GetCurrentOrientation());
  846. // User rotation lock remains in place to be restored again when the device
  847. // goes to physical tablet state again.
  848. EXPECT_TRUE(screen_orientation_controller->user_rotation_locked());
  849. EXPECT_FALSE(screen_orientation_controller->rotation_locked());
  850. }
  851. // Tests that using the keyboard shortcut to rotate the display while
  852. // kSupportsClamshellAutoRotation is set in the device behaves like a request to
  853. // lock the user orientation to the next rotation of the internal display, and
  854. // disables auto-rotation.
  855. TEST_F(AcceleratorControllerTest,
  856. RotateScreenWithClamshellAutoRotationSupported) {
  857. display::test::DisplayManagerTestApi(display_manager())
  858. .SetFirstDisplayAsInternalDisplay();
  859. base::CommandLine::ForCurrentProcess()->AppendSwitch(
  860. switches::kSupportsClamshellAutoRotation);
  861. auto* screen_orientation_controller =
  862. Shell::Get()->screen_orientation_controller();
  863. EXPECT_TRUE(screen_orientation_controller->IsAutoRotationAllowed());
  864. EXPECT_FALSE(screen_orientation_controller->user_rotation_locked());
  865. EXPECT_FALSE(screen_orientation_controller->rotation_locked());
  866. EXPECT_EQ(chromeos::OrientationType::kLandscapePrimary,
  867. screen_orientation_controller->GetCurrentOrientation());
  868. TriggerRotateScreenShortcut();
  869. EXPECT_TRUE(screen_orientation_controller->user_rotation_locked());
  870. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  871. EXPECT_EQ(chromeos::OrientationType::kPortraitSecondary,
  872. screen_orientation_controller->GetCurrentOrientation());
  873. }
  874. // Tests the behavior of the shortcut when the active window requests to lock
  875. // the rotation to a particular orientation.
  876. TEST_F(AcceleratorControllerTest, RotateScreenWithWindowLockingOrientation) {
  877. display::test::DisplayManagerTestApi(display_manager())
  878. .SetFirstDisplayAsInternalDisplay();
  879. ShellTestApi().SetTabletModeEnabledForTest(true);
  880. auto* tablet_mode_controller = Shell::Get()->tablet_mode_controller();
  881. auto* screen_orientation_controller =
  882. Shell::Get()->screen_orientation_controller();
  883. EXPECT_TRUE(tablet_mode_controller->is_in_tablet_physical_state());
  884. EXPECT_FALSE(screen_orientation_controller->user_rotation_locked());
  885. auto win0 = CreateAppWindow(gfx::Rect{100, 300});
  886. auto win1 = CreateAppWindow(gfx::Rect{200, 200});
  887. screen_orientation_controller->LockOrientationForWindow(
  888. win0.get(), chromeos::OrientationType::kPortraitPrimary);
  889. screen_orientation_controller->LockOrientationForWindow(
  890. win1.get(), chromeos::OrientationType::kLandscape);
  891. // `win0` requests to lock the orientation to only portrait-primary. The
  892. // shortcut therefore won't be able to change the current rotation at all.
  893. wm::ActivateWindow(win0.get());
  894. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  895. EXPECT_FALSE(screen_orientation_controller->user_rotation_locked());
  896. EXPECT_EQ(chromeos::OrientationType::kPortraitPrimary,
  897. screen_orientation_controller->GetCurrentOrientation());
  898. TriggerRotateScreenShortcut();
  899. // Nothing happens; user rotation is still not locked, but the rotation is
  900. // app-locked.
  901. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  902. EXPECT_FALSE(screen_orientation_controller->user_rotation_locked());
  903. EXPECT_EQ(chromeos::OrientationType::kPortraitPrimary,
  904. screen_orientation_controller->GetCurrentOrientation());
  905. // Activate `win1` which allows any landscape orientations (either primary or
  906. // secondary). The shortcut will switch between the two allowed orientations
  907. // only.
  908. wm::ActivateWindow(win1.get());
  909. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  910. EXPECT_FALSE(screen_orientation_controller->user_rotation_locked());
  911. EXPECT_EQ(chromeos::OrientationType::kLandscapePrimary,
  912. screen_orientation_controller->GetCurrentOrientation());
  913. TriggerRotateScreenShortcut();
  914. // User rotation will now be locked.
  915. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  916. EXPECT_TRUE(screen_orientation_controller->user_rotation_locked());
  917. EXPECT_EQ(chromeos::OrientationType::kLandscapeSecondary,
  918. screen_orientation_controller->GetCurrentOrientation());
  919. TriggerRotateScreenShortcut();
  920. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  921. EXPECT_TRUE(screen_orientation_controller->user_rotation_locked());
  922. EXPECT_EQ(chromeos::OrientationType::kLandscapePrimary,
  923. screen_orientation_controller->GetCurrentOrientation());
  924. // Hook a mouse device, exiting tablet mode to clamshell mode (but remaining
  925. // in a tablet physical state). Expect that the shortcut changes the user
  926. // rotation lock in all directions regardless of which window is active, even
  927. // those that requested window rotation locks.
  928. TabletModeControllerTestApi().AttachExternalMouse();
  929. EXPECT_TRUE(tablet_mode_controller->is_in_tablet_physical_state());
  930. EXPECT_FALSE(tablet_mode_controller->InTabletMode());
  931. wm::ActivateWindow(win0.get());
  932. EXPECT_TRUE(screen_orientation_controller->rotation_locked());
  933. EXPECT_TRUE(screen_orientation_controller->user_rotation_locked());
  934. EXPECT_EQ(chromeos::OrientationType::kLandscapePrimary,
  935. screen_orientation_controller->GetCurrentOrientation());
  936. TriggerRotateScreenShortcut();
  937. EXPECT_EQ(chromeos::OrientationType::kPortraitSecondary,
  938. screen_orientation_controller->GetCurrentOrientation());
  939. TriggerRotateScreenShortcut();
  940. EXPECT_EQ(chromeos::OrientationType::kLandscapeSecondary,
  941. screen_orientation_controller->GetCurrentOrientation());
  942. wm::ActivateWindow(win1.get());
  943. TriggerRotateScreenShortcut();
  944. EXPECT_EQ(chromeos::OrientationType::kPortraitPrimary,
  945. screen_orientation_controller->GetCurrentOrientation());
  946. TriggerRotateScreenShortcut();
  947. EXPECT_EQ(chromeos::OrientationType::kLandscapePrimary,
  948. screen_orientation_controller->GetCurrentOrientation());
  949. }
  950. TEST_F(AcceleratorControllerTest, AutoRepeat) {
  951. ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  952. ui::TestAcceleratorTarget target_a;
  953. controller_->Register({accelerator_a}, &target_a);
  954. ui::Accelerator accelerator_b(ui::VKEY_B, ui::EF_CONTROL_DOWN);
  955. ui::TestAcceleratorTarget target_b;
  956. controller_->Register({accelerator_b}, &target_b);
  957. ui::test::EventGenerator* generator = GetEventGenerator();
  958. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  959. generator->ReleaseKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  960. EXPECT_EQ(1, target_a.accelerator_count());
  961. EXPECT_EQ(0, target_a.accelerator_repeat_count());
  962. // Long press should generate one
  963. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  964. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN | ui::EF_IS_REPEAT);
  965. EXPECT_EQ(2, target_a.accelerator_non_repeat_count());
  966. EXPECT_EQ(1, target_a.accelerator_repeat_count());
  967. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN | ui::EF_IS_REPEAT);
  968. EXPECT_EQ(2, target_a.accelerator_non_repeat_count());
  969. EXPECT_EQ(2, target_a.accelerator_repeat_count());
  970. generator->ReleaseKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  971. EXPECT_EQ(2, target_a.accelerator_non_repeat_count());
  972. EXPECT_EQ(2, target_a.accelerator_repeat_count());
  973. // Long press was intercepted by another key press.
  974. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  975. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN | ui::EF_IS_REPEAT);
  976. generator->PressKey(ui::VKEY_B, ui::EF_CONTROL_DOWN);
  977. generator->ReleaseKey(ui::VKEY_B, ui::EF_CONTROL_DOWN);
  978. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  979. generator->PressKey(ui::VKEY_A, ui::EF_CONTROL_DOWN | ui::EF_IS_REPEAT);
  980. generator->ReleaseKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  981. EXPECT_EQ(1, target_b.accelerator_non_repeat_count());
  982. EXPECT_EQ(0, target_b.accelerator_repeat_count());
  983. EXPECT_EQ(4, target_a.accelerator_non_repeat_count());
  984. EXPECT_EQ(4, target_a.accelerator_repeat_count());
  985. }
  986. TEST_F(AcceleratorControllerTest, Previous) {
  987. PressAndReleaseKey(ui::VKEY_VOLUME_MUTE, ui::EF_NONE);
  988. EXPECT_EQ(ui::VKEY_VOLUME_MUTE, GetPreviousAccelerator().key_code());
  989. EXPECT_EQ(ui::EF_NONE, GetPreviousAccelerator().modifiers());
  990. PressAndReleaseKey(ui::VKEY_TAB, ui::EF_CONTROL_DOWN);
  991. EXPECT_EQ(ui::VKEY_TAB, GetPreviousAccelerator().key_code());
  992. EXPECT_EQ(ui::EF_CONTROL_DOWN, GetPreviousAccelerator().modifiers());
  993. }
  994. TEST_F(AcceleratorControllerTest, DontRepeatToggleFullscreen) {
  995. const AcceleratorData accelerators[] = {
  996. {true, ui::VKEY_J, ui::EF_ALT_DOWN, TOGGLE_FULLSCREEN},
  997. {true, ui::VKEY_K, ui::EF_ALT_DOWN, TOGGLE_FULLSCREEN},
  998. };
  999. test_api_->RegisterAccelerators(accelerators, std::size(accelerators));
  1000. views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);
  1001. params.bounds = gfx::Rect(5, 5, 20, 20);
  1002. views::Widget* widget = new views::Widget;
  1003. params.context = GetContext();
  1004. widget->Init(std::move(params));
  1005. widget->Show();
  1006. widget->Activate();
  1007. widget->GetNativeView()->SetProperty(
  1008. aura::client::kResizeBehaviorKey,
  1009. aura::client::kResizeBehaviorCanMaximize);
  1010. ui::test::EventGenerator* generator = GetEventGenerator();
  1011. WindowState* window_state = WindowState::Get(widget->GetNativeView());
  1012. // Toggling not suppressed.
  1013. generator->PressKey(ui::VKEY_J, ui::EF_ALT_DOWN);
  1014. EXPECT_TRUE(window_state->IsFullscreen());
  1015. // The same accelerator - toggling suppressed.
  1016. generator->PressKey(ui::VKEY_J, ui::EF_ALT_DOWN | ui::EF_IS_REPEAT);
  1017. EXPECT_TRUE(window_state->IsFullscreen());
  1018. // Different accelerator.
  1019. generator->PressKey(ui::VKEY_K, ui::EF_ALT_DOWN);
  1020. EXPECT_FALSE(window_state->IsFullscreen());
  1021. }
  1022. TEST_F(AcceleratorControllerTest, DontToggleFullscreenWhenOverviewStarts) {
  1023. std::unique_ptr<views::Widget> widget(CreateTestWidget(
  1024. nullptr, desks_util::GetActiveDeskContainerId(), gfx::Rect(400, 400)));
  1025. ui::test::EventGenerator* generator = GetEventGenerator();
  1026. // Toggle overview and fullscreen immediately after.
  1027. generator->PressKey(ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_NONE);
  1028. generator->PressKey(ui::VKEY_ZOOM, ui::EF_NONE);
  1029. EXPECT_FALSE(WindowState::Get(widget->GetNativeWindow())->IsFullscreen());
  1030. EXPECT_TRUE(Shell::Get()->overview_controller()->InOverviewSession());
  1031. EXPECT_TRUE(Shell::Get()
  1032. ->overview_controller()
  1033. ->overview_session()
  1034. ->IsWindowInOverview(widget->GetNativeWindow()));
  1035. }
  1036. // TODO(oshima): Fix this test to use EventGenerator.
  1037. TEST_F(AcceleratorControllerTest, ProcessOnce) {
  1038. // The IME event filter interferes with the basic key event propagation we
  1039. // attempt to do here, so we disable it.
  1040. DisableIME();
  1041. ui::Accelerator accelerator_a(ui::VKEY_A, ui::EF_NONE);
  1042. ui::TestAcceleratorTarget target;
  1043. controller_->Register({accelerator_a}, &target);
  1044. // The accelerator is processed only once.
  1045. ui::EventSink* sink =
  1046. Shell::GetPrimaryRootWindow()->GetHost()->GetEventSink();
  1047. ui::KeyEvent key_event1(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE);
  1048. ui::EventDispatchDetails details = sink->OnEventFromSource(&key_event1);
  1049. EXPECT_TRUE(key_event1.handled() || details.dispatcher_destroyed);
  1050. ui::KeyEvent key_event2('A', ui::VKEY_A, ui::DomCode::NONE, ui::EF_NONE);
  1051. details = sink->OnEventFromSource(&key_event2);
  1052. EXPECT_FALSE(key_event2.handled() || details.dispatcher_destroyed);
  1053. ui::KeyEvent key_event3(ui::ET_KEY_RELEASED, ui::VKEY_A, ui::EF_NONE);
  1054. details = sink->OnEventFromSource(&key_event3);
  1055. EXPECT_FALSE(key_event3.handled() || details.dispatcher_destroyed);
  1056. EXPECT_EQ(1, target.accelerator_count());
  1057. }
  1058. TEST_F(AcceleratorControllerTest, GlobalAccelerators) {
  1059. // CycleBackward
  1060. EXPECT_TRUE(ProcessInController(
  1061. ui::Accelerator(ui::VKEY_TAB, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN)));
  1062. // CycleForward
  1063. EXPECT_TRUE(
  1064. ProcessInController(ui::Accelerator(ui::VKEY_TAB, ui::EF_ALT_DOWN)));
  1065. // CycleLinear
  1066. EXPECT_TRUE(ProcessInController(
  1067. ui::Accelerator(ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_NONE)));
  1068. const ui::Accelerator volume_mute(ui::VKEY_VOLUME_MUTE, ui::EF_NONE);
  1069. const ui::Accelerator volume_down(ui::VKEY_VOLUME_DOWN, ui::EF_NONE);
  1070. const ui::Accelerator volume_up(ui::VKEY_VOLUME_UP, ui::EF_NONE);
  1071. {
  1072. base::UserActionTester user_action_tester;
  1073. auto* history = controller_->GetAcceleratorHistory();
  1074. EXPECT_EQ(0, user_action_tester.GetActionCount("Accel_VolumeMute_F8"));
  1075. EXPECT_TRUE(ProcessInController(volume_mute));
  1076. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeMute_F8"));
  1077. EXPECT_EQ(volume_mute, history->current_accelerator());
  1078. EXPECT_EQ(0, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1079. EXPECT_TRUE(ProcessInController(volume_down));
  1080. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1081. EXPECT_EQ(volume_down, history->current_accelerator());
  1082. EXPECT_EQ(0, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1083. EXPECT_TRUE(ProcessInController(volume_up));
  1084. EXPECT_EQ(volume_up, history->current_accelerator());
  1085. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1086. }
  1087. // Brightness
  1088. // ui::VKEY_BRIGHTNESS_DOWN/UP are not defined on Windows.
  1089. const ui::Accelerator brightness_down(ui::VKEY_BRIGHTNESS_DOWN, ui::EF_NONE);
  1090. const ui::Accelerator brightness_up(ui::VKEY_BRIGHTNESS_UP, ui::EF_NONE);
  1091. {
  1092. DummyBrightnessControlDelegate* delegate =
  1093. new DummyBrightnessControlDelegate;
  1094. SetBrightnessControlDelegate(
  1095. std::unique_ptr<BrightnessControlDelegate>(delegate));
  1096. EXPECT_EQ(0, delegate->handle_brightness_down_count());
  1097. EXPECT_TRUE(ProcessInController(brightness_down));
  1098. EXPECT_EQ(1, delegate->handle_brightness_down_count());
  1099. EXPECT_EQ(brightness_down, delegate->last_accelerator());
  1100. EXPECT_EQ(0, delegate->handle_brightness_up_count());
  1101. EXPECT_TRUE(ProcessInController(brightness_up));
  1102. EXPECT_EQ(1, delegate->handle_brightness_up_count());
  1103. EXPECT_EQ(brightness_up, delegate->last_accelerator());
  1104. }
  1105. // Keyboard brightness
  1106. const ui::Accelerator alt_brightness_down(ui::VKEY_BRIGHTNESS_DOWN,
  1107. ui::EF_ALT_DOWN);
  1108. const ui::Accelerator alt_brightness_up(ui::VKEY_BRIGHTNESS_UP,
  1109. ui::EF_ALT_DOWN);
  1110. {
  1111. EXPECT_TRUE(ProcessInController(alt_brightness_down));
  1112. EXPECT_TRUE(ProcessInController(alt_brightness_up));
  1113. DummyKeyboardBrightnessControlDelegate* delegate =
  1114. new DummyKeyboardBrightnessControlDelegate;
  1115. SetKeyboardBrightnessControlDelegate(
  1116. std::unique_ptr<KeyboardBrightnessControlDelegate>(delegate));
  1117. EXPECT_EQ(0, delegate->handle_keyboard_brightness_down_count());
  1118. EXPECT_TRUE(ProcessInController(alt_brightness_down));
  1119. EXPECT_EQ(1, delegate->handle_keyboard_brightness_down_count());
  1120. EXPECT_EQ(alt_brightness_down, delegate->last_accelerator());
  1121. EXPECT_EQ(0, delegate->handle_keyboard_brightness_up_count());
  1122. EXPECT_TRUE(ProcessInController(alt_brightness_up));
  1123. EXPECT_EQ(1, delegate->handle_keyboard_brightness_up_count());
  1124. EXPECT_EQ(alt_brightness_up, delegate->last_accelerator());
  1125. }
  1126. // Exit
  1127. ExitWarningHandler* ewh = test_api_->GetExitWarningHandler();
  1128. ASSERT_TRUE(ewh);
  1129. StubForTest(ewh);
  1130. EXPECT_TRUE(is_idle(ewh));
  1131. EXPECT_FALSE(is_ui_shown(ewh));
  1132. EXPECT_TRUE(ProcessInController(
  1133. ui::Accelerator(ui::VKEY_Q, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN)));
  1134. EXPECT_FALSE(is_idle(ewh));
  1135. EXPECT_TRUE(is_ui_shown(ewh));
  1136. SimulateTimerExpired(ewh);
  1137. EXPECT_TRUE(is_idle(ewh));
  1138. EXPECT_FALSE(is_ui_shown(ewh));
  1139. Reset(ewh);
  1140. // New tab
  1141. EXPECT_TRUE(
  1142. ProcessInController(ui::Accelerator(ui::VKEY_T, ui::EF_CONTROL_DOWN)));
  1143. // New incognito window
  1144. EXPECT_TRUE(ProcessInController(
  1145. ui::Accelerator(ui::VKEY_N, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN)));
  1146. // New window
  1147. EXPECT_TRUE(
  1148. ProcessInController(ui::Accelerator(ui::VKEY_N, ui::EF_CONTROL_DOWN)));
  1149. // Restore tab
  1150. EXPECT_TRUE(ProcessInController(
  1151. ui::Accelerator(ui::VKEY_T, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN)));
  1152. // Show task manager
  1153. EXPECT_TRUE(ProcessInController(
  1154. ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_COMMAND_DOWN)));
  1155. // Open file manager
  1156. EXPECT_TRUE(ProcessInController(
  1157. ui::Accelerator(ui::VKEY_M, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN)));
  1158. // Lock screen
  1159. // NOTE: Accelerators that do not work on the lock screen need to be
  1160. // tested before the sequence below is invoked because it causes a side
  1161. // effect of locking the screen.
  1162. EXPECT_TRUE(
  1163. ProcessInController(ui::Accelerator(ui::VKEY_L, ui::EF_COMMAND_DOWN)));
  1164. message_center::MessageCenter::Get()->RemoveAllNotifications(
  1165. false /* by_user */, message_center::MessageCenter::RemoveType::ALL);
  1166. }
  1167. TEST_F(AcceleratorControllerTest, GlobalAcceleratorsToggleAppList) {
  1168. AccessibilityControllerImpl* accessibility_controller =
  1169. Shell::Get()->accessibility_controller();
  1170. // The press event should not toggle the AppList, the release should instead.
  1171. EXPECT_FALSE(
  1172. ProcessInController(ui::Accelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1173. base::RunLoop().RunUntilIdle();
  1174. EXPECT_EQ(ui::VKEY_LWIN, GetCurrentAccelerator().key_code());
  1175. GetAppListTestHelper()->CheckVisibility(false);
  1176. EXPECT_TRUE(ProcessInController(
  1177. CreateReleaseAccelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1178. base::RunLoop().RunUntilIdle();
  1179. GetAppListTestHelper()->CheckVisibility(true);
  1180. EXPECT_EQ(ui::VKEY_LWIN, GetPreviousAccelerator().key_code());
  1181. // When spoken feedback is on, the AppList should not toggle.
  1182. accessibility_controller->SetSpokenFeedbackEnabled(true,
  1183. A11Y_NOTIFICATION_NONE);
  1184. EXPECT_TRUE(accessibility_controller->spoken_feedback().enabled());
  1185. EXPECT_FALSE(
  1186. ProcessInController(ui::Accelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1187. EXPECT_FALSE(ProcessInController(
  1188. CreateReleaseAccelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1189. accessibility_controller->SetSpokenFeedbackEnabled(false,
  1190. A11Y_NOTIFICATION_NONE);
  1191. EXPECT_FALSE(accessibility_controller->spoken_feedback().enabled());
  1192. base::RunLoop().RunUntilIdle();
  1193. GetAppListTestHelper()->CheckVisibility(true);
  1194. // Turning off spoken feedback should allow the AppList to toggle again.
  1195. EXPECT_FALSE(
  1196. ProcessInController(ui::Accelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1197. EXPECT_TRUE(ProcessInController(
  1198. CreateReleaseAccelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1199. base::RunLoop().RunUntilIdle();
  1200. GetAppListTestHelper()->CheckVisibility(false);
  1201. // The press of VKEY_BROWSER_SEARCH should toggle the AppList
  1202. EXPECT_TRUE(ProcessInController(
  1203. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_NONE)));
  1204. base::RunLoop().RunUntilIdle();
  1205. GetAppListTestHelper()->CheckVisibility(true);
  1206. EXPECT_FALSE(ProcessInController(
  1207. CreateReleaseAccelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_NONE)));
  1208. base::RunLoop().RunUntilIdle();
  1209. GetAppListTestHelper()->CheckVisibility(true);
  1210. // When pressed key is interrupted by mouse, the AppList should not toggle.
  1211. EXPECT_FALSE(
  1212. ProcessInController(ui::Accelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1213. controller_->GetAcceleratorHistory()->InterruptCurrentAccelerator();
  1214. EXPECT_FALSE(ProcessInController(
  1215. CreateReleaseAccelerator(ui::VKEY_LWIN, ui::EF_NONE)));
  1216. base::RunLoop().RunUntilIdle();
  1217. GetAppListTestHelper()->CheckVisibility(true);
  1218. }
  1219. TEST_F(AcceleratorControllerTest, GlobalAcceleratorsToggleQuickSettings) {
  1220. UnifiedSystemTray* tray =
  1221. StatusAreaWidgetTestHelper::GetStatusAreaWidget()->unified_system_tray();
  1222. auto* generator = GetEventGenerator();
  1223. // Pressing accelerator once should show the quick settings bubble.
  1224. generator->PressKey(ui::VKEY_S, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN);
  1225. base::RunLoop().RunUntilIdle();
  1226. EXPECT_TRUE(tray->IsBubbleShown());
  1227. // Pressing accelerator a second time should dismiss the bubble.
  1228. generator->PressKey(ui::VKEY_S, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN);
  1229. base::RunLoop().RunUntilIdle();
  1230. EXPECT_FALSE(tray->IsBubbleShown());
  1231. }
  1232. class GlobalAcceleratorsToggleProductivityLauncher
  1233. : public AcceleratorControllerTest,
  1234. public testing::WithParamInterface<
  1235. std::pair<ui::KeyboardCode, ui::Accelerator::KeyState>> {
  1236. public:
  1237. GlobalAcceleratorsToggleProductivityLauncher() {
  1238. std::tie(key_, key_state_) = GetParam();
  1239. }
  1240. protected:
  1241. ui::KeyboardCode key_;
  1242. ui::Accelerator::KeyState key_state_;
  1243. };
  1244. INSTANTIATE_TEST_SUITE_P(
  1245. All,
  1246. GlobalAcceleratorsToggleProductivityLauncher,
  1247. testing::Values(std::make_pair(ui::VKEY_LWIN,
  1248. ui::Accelerator::KeyState::RELEASED),
  1249. std::make_pair(ui::VKEY_BROWSER_SEARCH,
  1250. ui::Accelerator::KeyState::PRESSED),
  1251. std::make_pair(ui::VKEY_ALL_APPLICATIONS,
  1252. ui::Accelerator::KeyState::PRESSED)));
  1253. TEST_P(GlobalAcceleratorsToggleProductivityLauncher, ToggleLauncher) {
  1254. base::test::ScopedFeatureList feature_list;
  1255. feature_list.InitAndEnableFeature(features::kProductivityLauncher);
  1256. EXPECT_TRUE(
  1257. ProcessInController(ui::Accelerator(key_, ui::EF_NONE, key_state_)));
  1258. base::RunLoop().RunUntilIdle();
  1259. GetAppListTestHelper()->CheckVisibility(true);
  1260. EXPECT_TRUE(
  1261. ProcessInController(ui::Accelerator(key_, ui::EF_NONE, key_state_)));
  1262. base::RunLoop().RunUntilIdle();
  1263. GetAppListTestHelper()->CheckVisibility(false);
  1264. }
  1265. TEST_F(AcceleratorControllerTest, GlobalAcceleratorsToggleAppListFullscreen) {
  1266. base::test::ScopedFeatureList feature_list;
  1267. feature_list.InitAndDisableFeature(features::kProductivityLauncher);
  1268. base::HistogramTester histogram_tester;
  1269. int toggle_count_total = 0;
  1270. int toggle_count_regular = 0;
  1271. int toggle_count_fullscreen = 0;
  1272. // Shift+VKEY_BROWSER_SEARCH should toggle the AppList in fullscreen mode.
  1273. EXPECT_TRUE(ProcessInController(
  1274. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_SHIFT_DOWN)));
  1275. base::RunLoop().RunUntilIdle();
  1276. GetAppListTestHelper()->CheckVisibility(true);
  1277. GetAppListTestHelper()->CheckState(AppListViewState::kFullscreenAllApps);
  1278. histogram_tester.ExpectTotalCount("Apps.AppListShowSource",
  1279. ++toggle_count_total);
  1280. histogram_tester.ExpectBucketCount("Apps.AppListShowSource",
  1281. kSearchKeyFullscreen,
  1282. ++toggle_count_fullscreen);
  1283. EXPECT_TRUE(ProcessInController(
  1284. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_SHIFT_DOWN)));
  1285. base::RunLoop().RunUntilIdle();
  1286. GetAppListTestHelper()->CheckVisibility(false);
  1287. // Shift+VKEY_BROWSER_SEARCH should transition from peeking to fullscreen
  1288. // mode.
  1289. EXPECT_TRUE(ProcessInController(
  1290. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_NONE)));
  1291. base::RunLoop().RunUntilIdle();
  1292. GetAppListTestHelper()->CheckVisibility(true);
  1293. GetAppListTestHelper()->CheckState(AppListViewState::kPeeking);
  1294. histogram_tester.ExpectTotalCount("Apps.AppListShowSource",
  1295. ++toggle_count_total);
  1296. histogram_tester.ExpectBucketCount("Apps.AppListShowSource", kSearchKey,
  1297. ++toggle_count_regular);
  1298. EXPECT_TRUE(ProcessInController(
  1299. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_SHIFT_DOWN)));
  1300. base::RunLoop().RunUntilIdle();
  1301. GetAppListTestHelper()->CheckVisibility(true);
  1302. GetAppListTestHelper()->CheckState(AppListViewState::kFullscreenAllApps);
  1303. histogram_tester.ExpectTotalCount("Apps.AppListShowSource",
  1304. ++toggle_count_total);
  1305. histogram_tester.ExpectBucketCount("Apps.AppListShowSource",
  1306. kSearchKeyFullscreen,
  1307. ++toggle_count_fullscreen);
  1308. // VKEY_BROWSER_SEARCH (no shift) should not return to peeking, but close the
  1309. // AppList.
  1310. EXPECT_TRUE(ProcessInController(
  1311. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_NONE)));
  1312. base::RunLoop().RunUntilIdle();
  1313. GetAppListTestHelper()->CheckVisibility(false);
  1314. // Open AppList in peeking mode and type in the search box.
  1315. EXPECT_TRUE(ProcessInController(
  1316. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_NONE)));
  1317. base::RunLoop().RunUntilIdle();
  1318. GetAppListTestHelper()->CheckVisibility(true);
  1319. GetAppListTestHelper()->CheckState(AppListViewState::kPeeking);
  1320. histogram_tester.ExpectTotalCount("Apps.AppListShowSource",
  1321. ++toggle_count_total);
  1322. histogram_tester.ExpectBucketCount("Apps.AppListShowSource", kSearchKey,
  1323. ++toggle_count_regular);
  1324. PressAndReleaseKey(ui::VKEY_0);
  1325. base::RunLoop().RunUntilIdle();
  1326. GetAppListTestHelper()->CheckVisibility(true);
  1327. GetAppListTestHelper()->CheckState(AppListViewState::kHalf);
  1328. // Shift+VKEY_BROWSER_SEARCH transitions to FULLSCREEN_SEARCH.
  1329. EXPECT_TRUE(ProcessInController(
  1330. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_SHIFT_DOWN)));
  1331. base::RunLoop().RunUntilIdle();
  1332. GetAppListTestHelper()->CheckVisibility(true);
  1333. GetAppListTestHelper()->CheckState(AppListViewState::kFullscreenSearch);
  1334. histogram_tester.ExpectTotalCount("Apps.AppListShowSource",
  1335. ++toggle_count_total);
  1336. histogram_tester.ExpectBucketCount("Apps.AppListShowSource",
  1337. kSearchKeyFullscreen,
  1338. ++toggle_count_fullscreen);
  1339. // Shift+VKEY_BROWSER_SEARCH closes the AppList.
  1340. EXPECT_TRUE(ProcessInController(
  1341. ui::Accelerator(ui::VKEY_BROWSER_SEARCH, ui::EF_SHIFT_DOWN)));
  1342. base::RunLoop().RunUntilIdle();
  1343. GetAppListTestHelper()->CheckVisibility(false);
  1344. }
  1345. TEST_F(AcceleratorControllerTest, ImeGlobalAccelerators) {
  1346. ASSERT_EQ(0u, Shell::Get()->ime_controller()->GetVisibleImes().size());
  1347. // Cycling IME is blocked because there is nothing to switch to.
  1348. ui::Accelerator control_space_down(ui::VKEY_SPACE, ui::EF_CONTROL_DOWN);
  1349. ui::Accelerator control_space_up(ui::VKEY_SPACE, ui::EF_CONTROL_DOWN);
  1350. control_space_up.set_key_state(ui::Accelerator::KeyState::RELEASED);
  1351. ui::Accelerator control_shift_space(ui::VKEY_SPACE,
  1352. ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
  1353. EXPECT_FALSE(ProcessInController(control_space_down));
  1354. EXPECT_FALSE(ProcessInController(control_space_up));
  1355. EXPECT_FALSE(ProcessInController(control_shift_space));
  1356. // Adding only a not visible IME doesn't make IME accelerators available.
  1357. AddNotVisibleTestIme();
  1358. ASSERT_EQ(0u, Shell::Get()->ime_controller()->GetVisibleImes().size());
  1359. EXPECT_FALSE(ProcessInController(control_space_down));
  1360. EXPECT_FALSE(ProcessInController(control_space_up));
  1361. EXPECT_FALSE(ProcessInController(control_shift_space));
  1362. // Cycling IME works when there are IMEs available.
  1363. AddTestImes();
  1364. EXPECT_TRUE(ProcessInController(control_space_down));
  1365. EXPECT_TRUE(ProcessInController(control_space_up));
  1366. EXPECT_TRUE(ProcessInController(control_shift_space));
  1367. // Adding the not visible IME back doesn't block cycling.
  1368. AddNotVisibleTestIme();
  1369. EXPECT_TRUE(ProcessInController(control_space_down));
  1370. EXPECT_TRUE(ProcessInController(control_space_up));
  1371. EXPECT_TRUE(ProcessInController(control_shift_space));
  1372. }
  1373. // TODO(nona|mazda): Remove this when crbug.com/139556 in a better way.
  1374. TEST_F(AcceleratorControllerTest, ImeGlobalAcceleratorsWorkaround139556) {
  1375. // The workaround for crbug.com/139556 depends on the fact that we don't
  1376. // use Shift+Alt+Enter/Space with ET_KEY_PRESSED as an accelerator. Test it.
  1377. const ui::Accelerator shift_alt_return_press(
  1378. ui::VKEY_RETURN, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN);
  1379. EXPECT_FALSE(ProcessInController(shift_alt_return_press));
  1380. const ui::Accelerator shift_alt_space_press(
  1381. ui::VKEY_SPACE, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN);
  1382. EXPECT_FALSE(ProcessInController(shift_alt_space_press));
  1383. }
  1384. TEST_F(AcceleratorControllerTest, PreferredReservedAccelerators) {
  1385. // Power key is reserved on chromeos.
  1386. EXPECT_TRUE(
  1387. controller_->IsReserved(ui::Accelerator(ui::VKEY_POWER, ui::EF_NONE)));
  1388. EXPECT_FALSE(
  1389. controller_->IsPreferred(ui::Accelerator(ui::VKEY_POWER, ui::EF_NONE)));
  1390. // ALT+Tab are not reserved but preferred.
  1391. EXPECT_FALSE(
  1392. controller_->IsReserved(ui::Accelerator(ui::VKEY_TAB, ui::EF_ALT_DOWN)));
  1393. EXPECT_FALSE(controller_->IsReserved(
  1394. ui::Accelerator(ui::VKEY_TAB, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN)));
  1395. EXPECT_TRUE(
  1396. controller_->IsPreferred(ui::Accelerator(ui::VKEY_TAB, ui::EF_ALT_DOWN)));
  1397. EXPECT_TRUE(controller_->IsPreferred(
  1398. ui::Accelerator(ui::VKEY_TAB, ui::EF_SHIFT_DOWN | ui::EF_ALT_DOWN)));
  1399. // Others are not reserved nor preferred
  1400. EXPECT_FALSE(
  1401. controller_->IsReserved(ui::Accelerator(ui::VKEY_SNAPSHOT, ui::EF_NONE)));
  1402. EXPECT_FALSE(controller_->IsPreferred(
  1403. ui::Accelerator(ui::VKEY_SNAPSHOT, ui::EF_NONE)));
  1404. EXPECT_FALSE(
  1405. controller_->IsReserved(ui::Accelerator(ui::VKEY_TAB, ui::EF_NONE)));
  1406. EXPECT_FALSE(
  1407. controller_->IsPreferred(ui::Accelerator(ui::VKEY_TAB, ui::EF_NONE)));
  1408. EXPECT_FALSE(
  1409. controller_->IsReserved(ui::Accelerator(ui::VKEY_A, ui::EF_NONE)));
  1410. EXPECT_FALSE(
  1411. controller_->IsPreferred(ui::Accelerator(ui::VKEY_A, ui::EF_NONE)));
  1412. }
  1413. TEST_F(AcceleratorControllerTest, SideVolumeButtonLocation) {
  1414. // |side_volume_button_location_| should be empty when location info file
  1415. // doesn't exist.
  1416. EXPECT_TRUE(test_api_->side_volume_button_location().region.empty());
  1417. EXPECT_TRUE(test_api_->side_volume_button_location().side.empty());
  1418. // Tests that |side_volume_button_location_| is read correctly if the location
  1419. // file exists.
  1420. base::DictionaryValue location;
  1421. location.SetStringKey(AcceleratorControllerImpl::kVolumeButtonRegion,
  1422. AcceleratorControllerImpl::kVolumeButtonRegionScreen);
  1423. location.SetStringKey(AcceleratorControllerImpl::kVolumeButtonSide,
  1424. AcceleratorControllerImpl::kVolumeButtonSideLeft);
  1425. std::string json_location;
  1426. base::JSONWriter::Write(location, &json_location);
  1427. base::ScopedTempDir file_tmp_dir;
  1428. ASSERT_TRUE(file_tmp_dir.CreateUniqueTempDir());
  1429. base::FilePath file_path = file_tmp_dir.GetPath().Append("location.json");
  1430. ASSERT_TRUE(WriteJsonFile(file_path, json_location));
  1431. EXPECT_TRUE(base::PathExists(file_path));
  1432. test_api_->SetSideVolumeButtonFilePath(file_path);
  1433. EXPECT_EQ(AcceleratorControllerImpl::kVolumeButtonRegionScreen,
  1434. test_api_->side_volume_button_location().region);
  1435. EXPECT_EQ(AcceleratorControllerImpl::kVolumeButtonSideLeft,
  1436. test_api_->side_volume_button_location().side);
  1437. base::DeleteFile(file_path);
  1438. }
  1439. // Tests the histogram of volume adjustment in tablet mode.
  1440. TEST_F(AcceleratorControllerTest, TabletModeVolumeAdjustHistogram) {
  1441. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true);
  1442. base::HistogramTester histogram_tester;
  1443. const ui::Accelerator kVolumeDown(ui::VKEY_VOLUME_DOWN, ui::EF_NONE);
  1444. const ui::Accelerator kVolumeUp(ui::VKEY_VOLUME_UP, ui::EF_NONE);
  1445. // Starts with volume up but ends with an overall-decreased volume.
  1446. ProcessInController(kVolumeUp);
  1447. ProcessInController(kVolumeDown);
  1448. ProcessInController(kVolumeDown);
  1449. EXPECT_TRUE(test_api_->TriggerTabletModeVolumeAdjustTimer());
  1450. histogram_tester.ExpectBucketCount(
  1451. kTabletCountOfVolumeAdjustType,
  1452. TabletModeVolumeAdjustType::kAccidentalAdjustWithSwapEnabled, 1);
  1453. // Starts with volume up and ends with an overall-increased volume.
  1454. ProcessInController(kVolumeUp);
  1455. ProcessInController(kVolumeUp);
  1456. ProcessInController(kVolumeUp);
  1457. EXPECT_TRUE(test_api_->TriggerTabletModeVolumeAdjustTimer());
  1458. histogram_tester.ExpectBucketCount(
  1459. kTabletCountOfVolumeAdjustType,
  1460. TabletModeVolumeAdjustType::kNormalAdjustWithSwapEnabled, 1);
  1461. }
  1462. class SideVolumeButtonAcceleratorTest
  1463. : public AcceleratorControllerTest,
  1464. public testing::WithParamInterface<std::pair<std::string, std::string>> {
  1465. public:
  1466. // Input device id of the side volume button.
  1467. static constexpr int kSideVolumeButtonId = 7;
  1468. SideVolumeButtonAcceleratorTest()
  1469. : region_(GetParam().first), side_(GetParam().second) {}
  1470. SideVolumeButtonAcceleratorTest(const SideVolumeButtonAcceleratorTest&) =
  1471. delete;
  1472. SideVolumeButtonAcceleratorTest& operator=(
  1473. const SideVolumeButtonAcceleratorTest&) = delete;
  1474. ~SideVolumeButtonAcceleratorTest() override = default;
  1475. void SetUp() override {
  1476. AcceleratorControllerTest::SetUp();
  1477. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true);
  1478. test_api_->SetSideVolumeButtonLocation(region_, side_);
  1479. ui::DeviceDataManagerTestApi().SetUncategorizedDevices({ui::InputDevice(
  1480. kSideVolumeButtonId, ui::InputDeviceType::INPUT_DEVICE_INTERNAL,
  1481. "cros_ec_buttons")});
  1482. }
  1483. bool IsLeftOrRightSide() const {
  1484. return side_ == AcceleratorControllerImpl::kVolumeButtonSideLeft ||
  1485. side_ == AcceleratorControllerImpl::kVolumeButtonSideRight;
  1486. }
  1487. bool IsOnKeyboard() const {
  1488. return region_ == AcceleratorControllerImpl::kVolumeButtonRegionKeyboard;
  1489. }
  1490. private:
  1491. std::string region_, side_;
  1492. };
  1493. // Tests the the action of side volume button will get flipped in corresponding
  1494. // screen orientation.
  1495. TEST_P(SideVolumeButtonAcceleratorTest, FlipSideVolumeButtonAction) {
  1496. display::test::ScopedSetInternalDisplayId set_internal(
  1497. display_manager(), GetPrimaryDisplay().id());
  1498. ScreenOrientationControllerTestApi test_api(
  1499. Shell::Get()->screen_orientation_controller());
  1500. // Set the screen orientation to LANDSCAPE_PRIMARY.
  1501. test_api.SetDisplayRotation(display::Display::ROTATE_0,
  1502. display::Display::RotationSource::ACTIVE);
  1503. EXPECT_EQ(test_api.GetCurrentOrientation(),
  1504. chromeos::OrientationType::kLandscapePrimary);
  1505. base::UserActionTester user_action_tester;
  1506. const ui::Accelerator volume_down(ui::VKEY_VOLUME_DOWN, ui::EF_NONE);
  1507. ASSERT_EQ(ui::ED_UNKNOWN_DEVICE, volume_down.source_device_id());
  1508. ProcessInController(volume_down);
  1509. // Tests that the VOLUME_DOWN accelerator always goes to decrease the volume
  1510. // if it is not from the side volume button.
  1511. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1512. user_action_tester.ResetCounts();
  1513. ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_VOLUME_DOWN,
  1514. ui::DomCode::VOLUME_DOWN, /*flags=*/0, /*dom_key=*/2099727,
  1515. base::TimeTicks::Now());
  1516. event.set_source_device_id(kSideVolumeButtonId);
  1517. const ui::Accelerator volume_down_from_side_volume_button(event);
  1518. ProcessInController(volume_down_from_side_volume_button);
  1519. // Tests that the action of side volume button will get flipped in landscape
  1520. // primary if the the button is at the left or right of keyboard.
  1521. if (IsOnKeyboard() && IsLeftOrRightSide())
  1522. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1523. else
  1524. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1525. user_action_tester.ResetCounts();
  1526. // Rotate the screen by 270 degree.
  1527. test_api.SetDisplayRotation(display::Display::ROTATE_270,
  1528. display::Display::RotationSource::ACTIVE);
  1529. EXPECT_EQ(test_api.GetCurrentOrientation(),
  1530. chromeos::OrientationType::kPortraitPrimary);
  1531. ProcessInController(volume_down_from_side_volume_button);
  1532. // Tests that the action of side volume button will not be flipped in portrait
  1533. // primary if the button is at the left or right of screen. Otherwise, the
  1534. // action will be flipped.
  1535. if (!IsOnKeyboard() && IsLeftOrRightSide())
  1536. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1537. else
  1538. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1539. user_action_tester.ResetCounts();
  1540. // Rotate the screen by 180 degree.
  1541. test_api.SetDisplayRotation(display::Display::ROTATE_180,
  1542. display::Display::RotationSource::ACTIVE);
  1543. EXPECT_EQ(test_api.GetCurrentOrientation(),
  1544. chromeos::OrientationType::kLandscapeSecondary);
  1545. ProcessInController(volume_down_from_side_volume_button);
  1546. // Tests that the action of side volume button will not be flipped in
  1547. // landscape secondary if the button is at the left or right of keyboard.
  1548. // Otherwise, the action will be flipped.
  1549. if (IsOnKeyboard() && IsLeftOrRightSide())
  1550. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1551. else
  1552. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1553. user_action_tester.ResetCounts();
  1554. // Rotate the screen by 90 degree.
  1555. test_api.SetDisplayRotation(display::Display::ROTATE_90,
  1556. display::Display::RotationSource::ACTIVE);
  1557. EXPECT_EQ(test_api.GetCurrentOrientation(),
  1558. chromeos::OrientationType::kPortraitSecondary);
  1559. ProcessInController(volume_down_from_side_volume_button);
  1560. // Tests that the action of side volume button will be flipped in portrait
  1561. // secondary if the buttonis at the left or right of screen.
  1562. if (!IsOnKeyboard() && IsLeftOrRightSide())
  1563. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1564. else
  1565. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1566. }
  1567. INSTANTIATE_TEST_SUITE_P(
  1568. AshSideVolumeButton,
  1569. SideVolumeButtonAcceleratorTest,
  1570. testing::ValuesIn(
  1571. {std::make_pair<std::string, std::string>(
  1572. AcceleratorControllerImpl::kVolumeButtonRegionKeyboard,
  1573. AcceleratorControllerImpl::kVolumeButtonSideLeft),
  1574. std::make_pair<std::string, std::string>(
  1575. AcceleratorControllerImpl::kVolumeButtonRegionKeyboard,
  1576. AcceleratorControllerImpl::kVolumeButtonSideRight),
  1577. std::make_pair<std::string, std::string>(
  1578. AcceleratorControllerImpl::kVolumeButtonRegionKeyboard,
  1579. AcceleratorControllerImpl::kVolumeButtonSideBottom),
  1580. std::make_pair<std::string, std::string>(
  1581. AcceleratorControllerImpl::kVolumeButtonRegionScreen,
  1582. AcceleratorControllerImpl::kVolumeButtonSideLeft),
  1583. std::make_pair<std::string, std::string>(
  1584. AcceleratorControllerImpl::kVolumeButtonRegionScreen,
  1585. AcceleratorControllerImpl::kVolumeButtonSideRight),
  1586. std::make_pair<std::string, std::string>(
  1587. AcceleratorControllerImpl::kVolumeButtonRegionScreen,
  1588. AcceleratorControllerImpl::kVolumeButtonSideTop),
  1589. std::make_pair<std::string, std::string>(
  1590. AcceleratorControllerImpl::kVolumeButtonRegionScreen,
  1591. AcceleratorControllerImpl::kVolumeButtonSideBottom)}));
  1592. // Tests the TOGGLE_CAPS_LOCK accelerator.
  1593. TEST_F(AcceleratorControllerTest, ToggleCapsLockAccelerators) {
  1594. ImeControllerImpl* controller = Shell::Get()->ime_controller();
  1595. TestImeControllerClient client;
  1596. controller->SetClient(&client);
  1597. EXPECT_EQ(0, client.set_caps_lock_count_);
  1598. // 1. Press Alt, Press Search, Release Search, Release Alt.
  1599. // Note when you press Alt then press search, the key_code at this point is
  1600. // VKEY_LWIN (for search) and Alt is the modifier.
  1601. const ui::Accelerator press_alt_then_search(ui::VKEY_LWIN, ui::EF_ALT_DOWN);
  1602. EXPECT_FALSE(ProcessInController(press_alt_then_search));
  1603. // When you release Search before Alt, the key_code is still VKEY_LWIN and
  1604. // Alt is still the modifier.
  1605. const ui::Accelerator release_search_before_alt(
  1606. CreateReleaseAccelerator(ui::VKEY_LWIN, ui::EF_ALT_DOWN));
  1607. EXPECT_TRUE(ProcessInController(release_search_before_alt));
  1608. EXPECT_EQ(1, client.set_caps_lock_count_);
  1609. EXPECT_TRUE(controller->IsCapsLockEnabled());
  1610. controller->UpdateCapsLockState(false);
  1611. // 2. Press Search, Press Alt, Release Search, Release Alt.
  1612. const ui::Accelerator press_search_then_alt(ui::VKEY_MENU,
  1613. ui::EF_COMMAND_DOWN);
  1614. EXPECT_FALSE(ProcessInController(press_search_then_alt));
  1615. EXPECT_TRUE(ProcessInController(release_search_before_alt));
  1616. EXPECT_EQ(2, client.set_caps_lock_count_);
  1617. EXPECT_TRUE(controller->IsCapsLockEnabled());
  1618. controller->UpdateCapsLockState(false);
  1619. // 3. Press Alt, Press Search, Release Alt, Release Search.
  1620. EXPECT_FALSE(ProcessInController(press_alt_then_search));
  1621. const ui::Accelerator release_alt_before_search(
  1622. CreateReleaseAccelerator(ui::VKEY_MENU, ui::EF_COMMAND_DOWN));
  1623. EXPECT_TRUE(ProcessInController(release_alt_before_search));
  1624. EXPECT_EQ(3, client.set_caps_lock_count_);
  1625. EXPECT_TRUE(controller->IsCapsLockEnabled());
  1626. controller->UpdateCapsLockState(false);
  1627. // 4. Press Search, Press Alt, Release Alt, Release Search.
  1628. EXPECT_FALSE(ProcessInController(press_search_then_alt));
  1629. EXPECT_TRUE(ProcessInController(release_alt_before_search));
  1630. EXPECT_EQ(4, client.set_caps_lock_count_);
  1631. EXPECT_TRUE(controller->IsCapsLockEnabled());
  1632. controller->UpdateCapsLockState(false);
  1633. // 5. Press M, Press Alt, Press Search, Release Alt. After that CapsLock
  1634. // should not be triggered. https://crbug.com/789283
  1635. ui::test::EventGenerator* generator = GetEventGenerator();
  1636. generator->PressKey(ui::VKEY_M, ui::EF_NONE);
  1637. generator->PressKey(ui::VKEY_MENU, ui::EF_NONE);
  1638. generator->PressKey(ui::VKEY_LWIN, ui::EF_ALT_DOWN);
  1639. generator->ReleaseKey(ui::VKEY_MENU, ui::EF_COMMAND_DOWN);
  1640. EXPECT_FALSE(controller->IsCapsLockEnabled());
  1641. controller->UpdateCapsLockState(false);
  1642. generator->ReleaseKey(ui::VKEY_M, ui::EF_NONE);
  1643. generator->ReleaseKey(ui::VKEY_LWIN, ui::EF_ALT_DOWN);
  1644. // 6. Toggle CapsLock shortcut should still work after the partial screenshot
  1645. // shortcut is used. (https://crbug.com/920030)
  1646. {
  1647. // Press Ctrl+Shift+F5 then release to enter the partial screenshot session.
  1648. const ui::Accelerator press_partial_screenshot_shortcut(
  1649. ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN);
  1650. EXPECT_TRUE(ProcessInController(press_partial_screenshot_shortcut));
  1651. const ui::Accelerator release_partial_screenshot_shortcut =
  1652. CreateReleaseAccelerator(ui::VKEY_MEDIA_LAUNCH_APP1,
  1653. ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN);
  1654. EXPECT_FALSE(ProcessInController(release_partial_screenshot_shortcut));
  1655. // Press mouse left button, move mouse and release mouse button. Then
  1656. // the partial screenshot is taken.
  1657. generator->MoveMouseTo(0, 0);
  1658. generator->PressLeftButton();
  1659. generator->MoveMouseTo(10, 10);
  1660. generator->ReleaseLeftButton();
  1661. auto* capture_mode_controller = CaptureModeController::Get();
  1662. EXPECT_TRUE(capture_mode_controller->IsActive());
  1663. EXPECT_EQ(CaptureModeSource::kRegion, capture_mode_controller->source());
  1664. // Press Search, Press Alt, Release Search, Release Alt. CapsLock should be
  1665. // triggered.
  1666. EXPECT_FALSE(ProcessInController(press_search_then_alt));
  1667. EXPECT_TRUE(ProcessInController(release_search_before_alt));
  1668. EXPECT_EQ(5, client.set_caps_lock_count_);
  1669. EXPECT_TRUE(controller->IsCapsLockEnabled());
  1670. controller->UpdateCapsLockState(false);
  1671. }
  1672. // 7. Toggle CapsLock shortcut should still work after fake events generated.
  1673. // (https://crbug.com/918317).
  1674. generator->PressKey(ui::VKEY_PROCESSKEY, ui::EF_IME_FABRICATED_KEY);
  1675. generator->ReleaseKey(ui::VKEY_UNKNOWN, ui::EF_IME_FABRICATED_KEY);
  1676. // Press Search, Press Alt, Release Search, Release Alt. CapsLock should be
  1677. // triggered.
  1678. EXPECT_FALSE(ProcessInController(press_search_then_alt));
  1679. EXPECT_TRUE(ProcessInController(release_search_before_alt));
  1680. EXPECT_EQ(6, client.set_caps_lock_count_);
  1681. EXPECT_TRUE(controller->IsCapsLockEnabled());
  1682. controller->UpdateCapsLockState(false);
  1683. }
  1684. class PreferredReservedAcceleratorsTest : public AshTestBase {
  1685. public:
  1686. PreferredReservedAcceleratorsTest() = default;
  1687. PreferredReservedAcceleratorsTest(const PreferredReservedAcceleratorsTest&) =
  1688. delete;
  1689. PreferredReservedAcceleratorsTest& operator=(
  1690. const PreferredReservedAcceleratorsTest&) = delete;
  1691. ~PreferredReservedAcceleratorsTest() override = default;
  1692. // AshTestBase:
  1693. void SetUp() override {
  1694. AshTestBase::SetUp();
  1695. Shell::Get()->lock_state_controller()->set_animator_for_test(
  1696. new TestSessionStateAnimator);
  1697. Shell::Get()->power_button_controller()->OnGetSwitchStates(
  1698. chromeos::PowerManagerClient::SwitchStates{
  1699. chromeos::PowerManagerClient::LidState::OPEN,
  1700. chromeos::PowerManagerClient::TabletMode::ON});
  1701. }
  1702. };
  1703. TEST_F(PreferredReservedAcceleratorsTest, AcceleratorsWithFullscreen) {
  1704. aura::Window* w1 = CreateTestWindowInShellWithId(0);
  1705. aura::Window* w2 = CreateTestWindowInShellWithId(1);
  1706. wm::ActivateWindow(w1);
  1707. WMEvent fullscreen(WM_EVENT_FULLSCREEN);
  1708. WindowState* w1_state = WindowState::Get(w1);
  1709. w1_state->OnWMEvent(&fullscreen);
  1710. ASSERT_TRUE(w1_state->IsFullscreen());
  1711. ui::test::EventGenerator* generator = GetEventGenerator();
  1712. // Power key (reserved) should always be handled.
  1713. Shell::Get()->power_button_controller()->OnTabletModeStarted();
  1714. PowerButtonControllerTestApi test_api(
  1715. Shell::Get()->power_button_controller());
  1716. EXPECT_FALSE(test_api.PowerButtonMenuTimerIsRunning());
  1717. generator->PressKey(ui::VKEY_POWER, ui::EF_NONE);
  1718. EXPECT_TRUE(test_api.PowerButtonMenuTimerIsRunning());
  1719. auto press_and_release_alt_tab = [&generator]() {
  1720. generator->PressKey(ui::VKEY_TAB, ui::EF_ALT_DOWN);
  1721. // Release the alt key to trigger the window activation.
  1722. generator->ReleaseKey(ui::VKEY_MENU, ui::EF_NONE);
  1723. };
  1724. // A fullscreen window can consume ALT-TAB (preferred).
  1725. ASSERT_EQ(w1, window_util::GetActiveWindow());
  1726. press_and_release_alt_tab();
  1727. ASSERT_EQ(w1, window_util::GetActiveWindow());
  1728. ASSERT_NE(w2, window_util::GetActiveWindow());
  1729. // ALT-TAB is non repeatable. Press A to cancel the
  1730. // repeat record.
  1731. generator->PressKey(ui::VKEY_A, ui::EF_NONE);
  1732. generator->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
  1733. // A normal window shouldn't consume preferred accelerator.
  1734. WMEvent normal(WM_EVENT_NORMAL);
  1735. w1_state->OnWMEvent(&normal);
  1736. ASSERT_FALSE(w1_state->IsFullscreen());
  1737. EXPECT_EQ(w1, window_util::GetActiveWindow());
  1738. press_and_release_alt_tab();
  1739. ASSERT_NE(w1, window_util::GetActiveWindow());
  1740. ASSERT_EQ(w2, window_util::GetActiveWindow());
  1741. }
  1742. TEST_F(PreferredReservedAcceleratorsTest, AcceleratorsWithPinned) {
  1743. aura::Window* w1 = CreateTestWindowInShellWithId(0);
  1744. aura::Window* w2 = CreateTestWindowInShellWithId(1);
  1745. wm::ActivateWindow(w1);
  1746. {
  1747. WMEvent pin_event(WM_EVENT_PIN);
  1748. WindowState* w1_state = WindowState::Get(w1);
  1749. w1_state->OnWMEvent(&pin_event);
  1750. ASSERT_TRUE(w1_state->IsPinned());
  1751. }
  1752. ui::test::EventGenerator* generator = GetEventGenerator();
  1753. // Power key (reserved) should always be handled.
  1754. Shell::Get()->power_button_controller()->OnTabletModeStarted();
  1755. PowerButtonControllerTestApi test_api(
  1756. Shell::Get()->power_button_controller());
  1757. EXPECT_FALSE(test_api.PowerButtonMenuTimerIsRunning());
  1758. generator->PressKey(ui::VKEY_POWER, ui::EF_NONE);
  1759. EXPECT_TRUE(test_api.PowerButtonMenuTimerIsRunning());
  1760. // A pinned window can consume ALT-TAB (preferred), but no side effect.
  1761. ASSERT_EQ(w1, window_util::GetActiveWindow());
  1762. generator->PressKey(ui::VKEY_TAB, ui::EF_ALT_DOWN);
  1763. generator->ReleaseKey(ui::VKEY_TAB, ui::EF_ALT_DOWN);
  1764. ASSERT_EQ(w1, window_util::GetActiveWindow());
  1765. ASSERT_NE(w2, window_util::GetActiveWindow());
  1766. }
  1767. TEST_F(AcceleratorControllerTest, DisallowedAtModalWindow) {
  1768. std::set<AcceleratorAction> all_actions;
  1769. for (size_t i = 0; i < kAcceleratorDataLength; ++i)
  1770. all_actions.insert(kAcceleratorData[i].action);
  1771. std::set<AcceleratorAction> all_debug_actions;
  1772. for (size_t i = 0; i < kDebugAcceleratorDataLength; ++i)
  1773. all_debug_actions.insert(kDebugAcceleratorData[i].action);
  1774. std::set<AcceleratorAction> all_dev_actions;
  1775. for (size_t i = 0; i < kDeveloperAcceleratorDataLength; ++i)
  1776. all_dev_actions.insert(kDeveloperAcceleratorData[i].action);
  1777. std::set<AcceleratorAction> actionsAllowedAtModalWindow;
  1778. for (size_t k = 0; k < kActionsAllowedAtModalWindowLength; ++k)
  1779. actionsAllowedAtModalWindow.insert(kActionsAllowedAtModalWindow[k]);
  1780. for (const auto& action : actionsAllowedAtModalWindow) {
  1781. EXPECT_TRUE(all_actions.find(action) != all_actions.end() ||
  1782. all_debug_actions.find(action) != all_debug_actions.end() ||
  1783. all_dev_actions.find(action) != all_dev_actions.end())
  1784. << " action from kActionsAllowedAtModalWindow"
  1785. << " not found in kAcceleratorData, kDebugAcceleratorData or"
  1786. << " kDeveloperAcceleratorData action: " << action;
  1787. }
  1788. std::unique_ptr<aura::Window> window(
  1789. CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  1790. wm::ActivateWindow(window.get());
  1791. ShellTestApi().SimulateModalWindowOpenForTest(true);
  1792. for (const auto& action : all_actions) {
  1793. if (actionsAllowedAtModalWindow.find(action) ==
  1794. actionsAllowedAtModalWindow.end()) {
  1795. EXPECT_TRUE(controller_->PerformActionIfEnabled(action, {}))
  1796. << " for action (disallowed at modal window): " << action;
  1797. }
  1798. }
  1799. // Testing of top row (F5-F10) accelerators that should still work
  1800. // when a modal window is open
  1801. //
  1802. // Screenshot
  1803. auto* controller = CaptureModeController::Get();
  1804. // Control + shift + F5 opens capture mode to take a region screenshot.
  1805. EXPECT_TRUE(ProcessInController(ui::Accelerator(
  1806. ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN)));
  1807. EXPECT_TRUE(controller->IsActive());
  1808. EXPECT_EQ(CaptureModeSource::kRegion, controller->source());
  1809. controller->Stop();
  1810. // Control + alt + F5 opens capture mode to take a window screenshot.
  1811. EXPECT_TRUE(ProcessInController(ui::Accelerator(
  1812. ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_ALT_DOWN | ui::EF_CONTROL_DOWN)));
  1813. EXPECT_TRUE(controller->IsActive());
  1814. EXPECT_EQ(CaptureModeSource::kWindow, controller->source());
  1815. controller->Stop();
  1816. // Snapshot key opens capture mode with the last type, and closes it if it
  1817. // is already open.
  1818. EXPECT_TRUE(
  1819. ProcessInController(ui::Accelerator(ui::VKEY_SNAPSHOT, ui::EF_NONE)));
  1820. EXPECT_TRUE(controller->IsActive());
  1821. EXPECT_EQ(CaptureModeSource::kWindow, controller->source());
  1822. EXPECT_TRUE(
  1823. ProcessInController(ui::Accelerator(ui::VKEY_SNAPSHOT, ui::EF_NONE)));
  1824. ASSERT_FALSE(controller->IsActive());
  1825. // Control + F5 takes a screenshot of all displays without opening capture
  1826. // mode. The loop will timeout if a screenshot was not successfully taken
  1827. // and saved.
  1828. EXPECT_TRUE(ProcessInController(
  1829. ui::Accelerator(ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_CONTROL_DOWN)));
  1830. EXPECT_FALSE(controller->IsActive());
  1831. base::RunLoop run_loop;
  1832. CaptureModeTestApi().SetOnCaptureFileSavedCallback(base::BindLambdaForTesting(
  1833. [&run_loop](const base::FilePath& path) { run_loop.Quit(); }));
  1834. run_loop.Run();
  1835. // Brightness
  1836. const ui::Accelerator brightness_down(ui::VKEY_BRIGHTNESS_DOWN, ui::EF_NONE);
  1837. const ui::Accelerator brightness_up(ui::VKEY_BRIGHTNESS_UP, ui::EF_NONE);
  1838. {
  1839. DummyBrightnessControlDelegate* delegate =
  1840. new DummyBrightnessControlDelegate;
  1841. SetBrightnessControlDelegate(
  1842. std::unique_ptr<BrightnessControlDelegate>(delegate));
  1843. EXPECT_EQ(0, delegate->handle_brightness_down_count());
  1844. EXPECT_TRUE(ProcessInController(brightness_down));
  1845. EXPECT_EQ(1, delegate->handle_brightness_down_count());
  1846. EXPECT_EQ(brightness_down, delegate->last_accelerator());
  1847. EXPECT_EQ(0, delegate->handle_brightness_up_count());
  1848. EXPECT_TRUE(ProcessInController(brightness_up));
  1849. EXPECT_EQ(1, delegate->handle_brightness_up_count());
  1850. EXPECT_EQ(brightness_up, delegate->last_accelerator());
  1851. }
  1852. // Volume
  1853. const ui::Accelerator volume_mute(ui::VKEY_VOLUME_MUTE, ui::EF_NONE);
  1854. const ui::Accelerator volume_down(ui::VKEY_VOLUME_DOWN, ui::EF_NONE);
  1855. const ui::Accelerator volume_up(ui::VKEY_VOLUME_UP, ui::EF_NONE);
  1856. {
  1857. base::UserActionTester user_action_tester;
  1858. auto* history = controller_->GetAcceleratorHistory();
  1859. EXPECT_EQ(0, user_action_tester.GetActionCount("Accel_VolumeMute_F8"));
  1860. EXPECT_TRUE(ProcessInController(volume_mute));
  1861. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeMute_F8"));
  1862. EXPECT_EQ(volume_mute, history->current_accelerator());
  1863. EXPECT_EQ(0, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1864. EXPECT_TRUE(ProcessInController(volume_down));
  1865. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeDown_F9"));
  1866. EXPECT_EQ(volume_down, history->current_accelerator());
  1867. EXPECT_EQ(0, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1868. EXPECT_TRUE(ProcessInController(volume_up));
  1869. EXPECT_EQ(volume_up, history->current_accelerator());
  1870. EXPECT_EQ(1, user_action_tester.GetActionCount("Accel_VolumeUp_F10"));
  1871. }
  1872. }
  1873. TEST_F(AcceleratorControllerTest, DisallowedWithNoWindow) {
  1874. AccessibilityControllerImpl* accessibility_controller =
  1875. Shell::Get()->accessibility_controller();
  1876. TestAccessibilityControllerClient client;
  1877. // Extract the accelerators of actions that need windows to be able to provide
  1878. // them to PerformActionIfEnabled(), otherwise we could hit some NOTREACHED()
  1879. // if we don't provide the correct keybindings.
  1880. std::set<AcceleratorAction> actions_needing_window;
  1881. for (size_t i = 0; i < kActionsNeedingWindowLength; ++i)
  1882. actions_needing_window.insert(kActionsNeedingWindow[i]);
  1883. std::map<AcceleratorAction, ui::Accelerator> accelerators_needing_window;
  1884. for (size_t i = 0; i < kAcceleratorDataLength; ++i) {
  1885. const auto& accelerator_data = kAcceleratorData[i];
  1886. auto iter = actions_needing_window.find(accelerator_data.action);
  1887. if (iter == actions_needing_window.end())
  1888. continue;
  1889. ui::Accelerator accelerator{accelerator_data.keycode,
  1890. accelerator_data.modifiers};
  1891. if (!accelerator_data.trigger_on_press)
  1892. accelerator.set_key_state(ui::Accelerator::KeyState::RELEASED);
  1893. accelerators_needing_window[*iter] = accelerator;
  1894. }
  1895. for (const auto& iter : accelerators_needing_window) {
  1896. accessibility_controller->TriggerAccessibilityAlert(
  1897. AccessibilityAlert::NONE);
  1898. EXPECT_TRUE(controller_->PerformActionIfEnabled(iter.first, iter.second));
  1899. EXPECT_EQ(AccessibilityAlert::WINDOW_NEEDED, client.last_a11y_alert());
  1900. }
  1901. // Make sure we don't alert if we do have a window.
  1902. std::unique_ptr<aura::Window> window;
  1903. for (const auto& iter : accelerators_needing_window) {
  1904. window.reset(CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  1905. wm::ActivateWindow(window.get());
  1906. accessibility_controller->TriggerAccessibilityAlert(
  1907. AccessibilityAlert::NONE);
  1908. controller_->PerformActionIfEnabled(iter.first, iter.second);
  1909. EXPECT_NE(AccessibilityAlert::WINDOW_NEEDED, client.last_a11y_alert());
  1910. }
  1911. // Don't alert if we have a minimized window either.
  1912. for (const auto& iter : accelerators_needing_window) {
  1913. window.reset(CreateTestWindowInShellWithBounds(gfx::Rect(5, 5, 20, 20)));
  1914. wm::ActivateWindow(window.get());
  1915. controller_->PerformActionIfEnabled(WINDOW_MINIMIZE, {});
  1916. accessibility_controller->TriggerAccessibilityAlert(
  1917. AccessibilityAlert::NONE);
  1918. controller_->PerformActionIfEnabled(iter.first, iter.second);
  1919. EXPECT_NE(AccessibilityAlert::WINDOW_NEEDED, client.last_a11y_alert());
  1920. }
  1921. }
  1922. TEST_F(AcceleratorControllerTest, TestDialogCancel) {
  1923. ui::Accelerator accelerator(ui::VKEY_H,
  1924. ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN);
  1925. AccessibilityControllerImpl* accessibility_controller =
  1926. Shell::Get()->accessibility_controller();
  1927. // Pressing cancel on the dialog should have no effect.
  1928. EXPECT_FALSE(accessibility_controller->high_contrast().WasDialogAccepted());
  1929. EXPECT_FALSE(IsConfirmationDialogOpen());
  1930. EXPECT_TRUE(ProcessInController(accelerator));
  1931. EXPECT_TRUE(IsConfirmationDialogOpen());
  1932. CancelConfirmationDialog();
  1933. base::RunLoop().RunUntilIdle();
  1934. EXPECT_FALSE(accessibility_controller->high_contrast().WasDialogAccepted());
  1935. EXPECT_FALSE(IsConfirmationDialogOpen());
  1936. }
  1937. TEST_F(AcceleratorControllerTest, TestToggleHighContrast) {
  1938. ui::Accelerator accelerator(ui::VKEY_H,
  1939. ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN);
  1940. // High Contrast Mode Enabled dialog and notification should be shown.
  1941. EXPECT_FALSE(IsConfirmationDialogOpen());
  1942. AccessibilityControllerImpl* accessibility_controller =
  1943. Shell::Get()->accessibility_controller();
  1944. EXPECT_FALSE(accessibility_controller->high_contrast().WasDialogAccepted());
  1945. EXPECT_TRUE(ProcessInController(accelerator));
  1946. EXPECT_TRUE(IsConfirmationDialogOpen());
  1947. AcceptConfirmationDialog();
  1948. base::RunLoop().RunUntilIdle();
  1949. EXPECT_TRUE(ContainsHighContrastNotification());
  1950. EXPECT_TRUE(accessibility_controller->high_contrast().WasDialogAccepted());
  1951. EXPECT_FALSE(IsConfirmationDialogOpen());
  1952. // High Contrast Mode Enabled dialog and notification should be hidden as the
  1953. // feature is disabled.
  1954. EXPECT_TRUE(ProcessInController(accelerator));
  1955. EXPECT_FALSE(ContainsHighContrastNotification());
  1956. EXPECT_TRUE(accessibility_controller->high_contrast().WasDialogAccepted());
  1957. // Notification should be shown again when toggled, but dialog will not be
  1958. // shown.
  1959. EXPECT_TRUE(ProcessInController(accelerator));
  1960. EXPECT_FALSE(IsConfirmationDialogOpen());
  1961. EXPECT_TRUE(ContainsHighContrastNotification());
  1962. RemoveAllNotifications();
  1963. }
  1964. TEST_F(AcceleratorControllerTest, CalculatorKey) {
  1965. auto observer = std::make_unique<MockAcceleratorObserver>();
  1966. auto* accelerator_controller = ash::AcceleratorController::Get();
  1967. accelerator_controller->AddObserver(observer.get());
  1968. // Verify that the launch calculator key (VKEY_MEDIA_LAUNCH_APP2) is
  1969. // registered.
  1970. ui::Accelerator accelerator(ui::VKEY_MEDIA_LAUNCH_APP2, ui::EF_NONE);
  1971. EXPECT_TRUE(controller_->IsRegistered(accelerator));
  1972. // Verify that the delegate to open the app is called.
  1973. EXPECT_CALL(*new_window_delegate_, OpenCalculator)
  1974. .WillOnce(testing::Return());
  1975. EXPECT_CALL(*observer, OnActionPerformed)
  1976. .WillOnce(
  1977. [](AcceleratorAction action) { EXPECT_EQ(OPEN_CALCULATOR, action); });
  1978. EXPECT_TRUE(ProcessInController(accelerator));
  1979. accelerator_controller->RemoveObserver(observer.get());
  1980. }
  1981. // Tests the IME mode change key.
  1982. TEST_F(AcceleratorControllerTest, ChangeIMEMode_SwitchesInputMethod) {
  1983. AddTestImes();
  1984. ImeController* controller = Shell::Get()->ime_controller();
  1985. TestImeControllerClient client;
  1986. controller->SetClient(&client);
  1987. EXPECT_EQ(0, client.next_ime_count_);
  1988. ProcessInController(ui::Accelerator(ui::VKEY_MODECHANGE, ui::EF_NONE));
  1989. EXPECT_EQ(1, client.next_ime_count_);
  1990. }
  1991. class AcceleratorControllerInputMethodTest : public AcceleratorControllerTest {
  1992. public:
  1993. AcceleratorControllerInputMethodTest() = default;
  1994. ~AcceleratorControllerInputMethodTest() override = default;
  1995. class AcceleratorMockInputMethod : public ui::MockInputMethod {
  1996. public:
  1997. AcceleratorMockInputMethod() : ui::MockInputMethod(nullptr) {}
  1998. void CancelComposition(const ui::TextInputClient* client) override {
  1999. cancel_composition_call_count++;
  2000. }
  2001. uint32_t cancel_composition_call_count = 0;
  2002. };
  2003. void SetUp() override {
  2004. scoped_feature_list_.InitAndEnableFeature(
  2005. ::features::kImprovedKeyboardShortcuts);
  2006. // Setup the mock input method to capture the calls to
  2007. // |CancelCompositionAfterAccelerator|. Ownersship is passed to
  2008. // ui::SetUpInputMethodForTesting().
  2009. mock_input_ = new AcceleratorMockInputMethod();
  2010. ui::SetUpInputMethodForTesting(mock_input_);
  2011. AcceleratorControllerTest::SetUp();
  2012. }
  2013. protected:
  2014. AcceleratorMockInputMethod* mock_input_ = nullptr; // Not owned.
  2015. private:
  2016. base::test::ScopedFeatureList scoped_feature_list_;
  2017. };
  2018. // In some layouts positional accelerators can be on dead/compose keys. To
  2019. // ensure that the input method is not left in a partially composed state
  2020. // the composition state is reset when an accelerator is matched.
  2021. TEST_F(AcceleratorControllerInputMethodTest, AcceleratorClearsComposition) {
  2022. EXPECT_EQ(0u, mock_input_->cancel_composition_call_count);
  2023. // An acclerator that isn't recognized will not cause composition to be
  2024. // cancelled.
  2025. ui::Accelerator unknown_accelerator(ui::VKEY_OEM_MINUS, ui::EF_NONE);
  2026. EXPECT_FALSE(controller_->IsRegistered(unknown_accelerator));
  2027. EXPECT_FALSE(ProcessInController(unknown_accelerator));
  2028. EXPECT_EQ(0u, mock_input_->cancel_composition_call_count);
  2029. // A matching accelerator should cause CancelCompositionAfterAccelerator() to
  2030. // be called.
  2031. ui::Accelerator accelerator(ui::VKEY_OEM_MINUS,
  2032. ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
  2033. EXPECT_TRUE(controller_->IsRegistered(accelerator));
  2034. EXPECT_TRUE(ProcessInController(accelerator));
  2035. EXPECT_EQ(1u, mock_input_->cancel_composition_call_count);
  2036. }
  2037. // TODO(crbug.com/1179893): Remove once the feature is enabled permanently.
  2038. class AcceleratorControllerDeprecatedTest : public AcceleratorControllerTest {
  2039. public:
  2040. AcceleratorControllerDeprecatedTest() = default;
  2041. ~AcceleratorControllerDeprecatedTest() override = default;
  2042. void SetUp() override {
  2043. scoped_feature_list_.InitAndDisableFeature(
  2044. ::features::kImprovedKeyboardShortcuts);
  2045. AcceleratorControllerTest::SetUp();
  2046. }
  2047. private:
  2048. base::test::ScopedFeatureList scoped_feature_list_;
  2049. };
  2050. // TODO(crbug.com/1179893): Remove once the feature is enabled permanently.
  2051. TEST_F(AcceleratorControllerDeprecatedTest, DeskShortcuts_Old) {
  2052. // The shortcuts are Search+Shift+[MINUS|PLUS], but due to event
  2053. // rewriting they became Shift+[F11|F12]. So only the rewritten shortcut
  2054. // works but the "real" shortcut doesn't.
  2055. EXPECT_TRUE(controller_->IsRegistered(
  2056. ui::Accelerator(ui::VKEY_F12, ui::EF_SHIFT_DOWN)));
  2057. EXPECT_TRUE(controller_->IsRegistered(
  2058. ui::Accelerator(ui::VKEY_F11, ui::EF_SHIFT_DOWN)));
  2059. EXPECT_FALSE(controller_->IsRegistered(ui::Accelerator(
  2060. ui::VKEY_OEM_PLUS, ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN)));
  2061. EXPECT_FALSE(controller_->IsRegistered(ui::Accelerator(
  2062. ui::VKEY_OEM_MINUS, ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN)));
  2063. }
  2064. // defines a class to test the behavior of deprecated accelerators.
  2065. class DeprecatedAcceleratorTester : public AcceleratorControllerTest {
  2066. public:
  2067. DeprecatedAcceleratorTester() = default;
  2068. DeprecatedAcceleratorTester(const DeprecatedAcceleratorTester&) = delete;
  2069. DeprecatedAcceleratorTester& operator=(const DeprecatedAcceleratorTester&) =
  2070. delete;
  2071. ~DeprecatedAcceleratorTester() override = default;
  2072. ui::Accelerator CreateAccelerator(const AcceleratorData& data) const {
  2073. ui::Accelerator result(data.keycode, data.modifiers);
  2074. result.set_key_state(data.trigger_on_press
  2075. ? ui::Accelerator::KeyState::PRESSED
  2076. : ui::Accelerator::KeyState::RELEASED);
  2077. return result;
  2078. }
  2079. void ResetStateIfNeeded() {
  2080. if (Shell::Get()->session_controller()->IsScreenLocked() ||
  2081. Shell::Get()->session_controller()->IsUserSessionBlocked()) {
  2082. UnblockUserSession();
  2083. }
  2084. }
  2085. bool ContainsDeprecatedAcceleratorNotification(const char* const id) const {
  2086. return nullptr != message_center()->FindVisibleNotificationById(id);
  2087. }
  2088. bool IsMessageCenterEmpty() const {
  2089. return message_center()->GetVisibleNotifications().empty();
  2090. }
  2091. };
  2092. TEST_F(DeprecatedAcceleratorTester, TestDeprecatedAcceleratorsBehavior) {
  2093. for (size_t i = 0; i < kDeprecatedAcceleratorsLength; ++i) {
  2094. const AcceleratorData& entry = kDeprecatedAccelerators[i];
  2095. const DeprecatedAcceleratorData* data =
  2096. test_api_->GetDeprecatedAcceleratorData(entry.action);
  2097. DCHECK(data);
  2098. EXPECT_TRUE(IsMessageCenterEmpty());
  2099. ui::Accelerator deprecated_accelerator = CreateAccelerator(entry);
  2100. if (data->deprecated_enabled)
  2101. EXPECT_TRUE(ProcessInController(deprecated_accelerator));
  2102. else
  2103. EXPECT_FALSE(ProcessInController(deprecated_accelerator));
  2104. // We expect to see a notification in the message center.
  2105. EXPECT_TRUE(
  2106. ContainsDeprecatedAcceleratorNotification(data->uma_histogram_name));
  2107. RemoveAllNotifications();
  2108. // If the action is LOCK_SCREEN, we must reset the state by unlocking the
  2109. // screen before we proceed testing the rest of accelerators.
  2110. ResetStateIfNeeded();
  2111. }
  2112. }
  2113. TEST_F(DeprecatedAcceleratorTester, TestNewAccelerators) {
  2114. // Add below the new accelerators that replaced the deprecated ones (if any).
  2115. const AcceleratorData kNewAccelerators[] = {
  2116. {true, ui::VKEY_L, ui::EF_COMMAND_DOWN, LOCK_SCREEN},
  2117. {true, ui::VKEY_SPACE, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN,
  2118. SWITCH_TO_NEXT_IME},
  2119. {true, ui::VKEY_ESCAPE, ui::EF_COMMAND_DOWN, SHOW_TASK_MANAGER},
  2120. {true, ui::VKEY_K, ui::EF_SHIFT_DOWN | ui::EF_COMMAND_DOWN,
  2121. TOGGLE_IME_MENU_BUBBLE},
  2122. {true, ui::VKEY_H, ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN,
  2123. TOGGLE_HIGH_CONTRAST},
  2124. };
  2125. // The SWITCH_TO_NEXT_IME accelerator requires multiple IMEs to be available.
  2126. AddTestImes();
  2127. EXPECT_TRUE(IsMessageCenterEmpty());
  2128. for (auto data : kNewAccelerators) {
  2129. EXPECT_TRUE(ProcessInController(CreateAccelerator(data)));
  2130. // Expect no notifications from the new accelerators.
  2131. if (data.action != TOGGLE_HIGH_CONTRAST) {
  2132. // The toggle high contrast accelerator displays a notification specific
  2133. // to the high contrast mode.
  2134. EXPECT_TRUE(IsMessageCenterEmpty());
  2135. }
  2136. // If the action is LOCK_SCREEN, we must reset the state by unlocking the
  2137. // screen before we proceed testing the rest of accelerators.
  2138. ResetStateIfNeeded();
  2139. }
  2140. RemoveAllNotifications();
  2141. }
  2142. using AcceleratorControllerGuestModeTest = NoSessionAshTestBase;
  2143. TEST_F(AcceleratorControllerGuestModeTest, IncognitoWindowDisabled) {
  2144. SimulateGuestLogin();
  2145. // New incognito window is disabled.
  2146. EXPECT_FALSE(Shell::Get()->accelerator_controller()->PerformActionIfEnabled(
  2147. NEW_INCOGNITO_WINDOW, {}));
  2148. }
  2149. constexpr char kUserEmail[] = "user@magnifier";
  2150. class MagnifiersAcceleratorsTester : public AcceleratorControllerTest {
  2151. public:
  2152. MagnifiersAcceleratorsTester() = default;
  2153. MagnifiersAcceleratorsTester(const MagnifiersAcceleratorsTester&) = delete;
  2154. MagnifiersAcceleratorsTester& operator=(const MagnifiersAcceleratorsTester&) =
  2155. delete;
  2156. ~MagnifiersAcceleratorsTester() override = default;
  2157. DockedMagnifierController* docked_magnifier_controller() const {
  2158. return Shell::Get()->docked_magnifier_controller();
  2159. }
  2160. FullscreenMagnifierController* fullscreen_magnifier_controller() const {
  2161. return Shell::Get()->fullscreen_magnifier_controller();
  2162. }
  2163. PrefService* user_pref_service() {
  2164. return Shell::Get()->session_controller()->GetUserPrefServiceForUser(
  2165. AccountId::FromUserEmail(kUserEmail));
  2166. }
  2167. void SetUp() override {
  2168. AcceleratorControllerTest::SetUp();
  2169. // Create user session and simulate its login.
  2170. SimulateUserLogin(kUserEmail);
  2171. }
  2172. };
  2173. // TODO (afakhry): Remove this class after refactoring MagnificationManager.
  2174. // Mocked chrome/browser/ash/accessibility/magnification_manager.cc
  2175. class FakeMagnificationManager {
  2176. public:
  2177. FakeMagnificationManager() = default;
  2178. FakeMagnificationManager(const FakeMagnificationManager&) = delete;
  2179. FakeMagnificationManager& operator=(const FakeMagnificationManager&) = delete;
  2180. void SetPrefs(PrefService* prefs) {
  2181. pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
  2182. pref_change_registrar_->Init(prefs);
  2183. pref_change_registrar_->Add(
  2184. prefs::kAccessibilityScreenMagnifierEnabled,
  2185. base::BindRepeating(&FakeMagnificationManager::UpdateMagnifierFromPrefs,
  2186. base::Unretained(this)));
  2187. prefs_ = prefs;
  2188. }
  2189. void UpdateMagnifierFromPrefs() {
  2190. Shell::Get()->fullscreen_magnifier_controller()->SetEnabled(
  2191. prefs_->GetBoolean(prefs::kAccessibilityScreenMagnifierEnabled));
  2192. }
  2193. private:
  2194. std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_;
  2195. PrefService* prefs_;
  2196. };
  2197. TEST_F(MagnifiersAcceleratorsTester, TestToggleFullscreenMagnifier) {
  2198. FakeMagnificationManager manager;
  2199. manager.SetPrefs(user_pref_service());
  2200. EXPECT_FALSE(docked_magnifier_controller()->GetEnabled());
  2201. EXPECT_FALSE(fullscreen_magnifier_controller()->IsEnabled());
  2202. EXPECT_FALSE(IsConfirmationDialogOpen());
  2203. AccessibilityControllerImpl* accessibility_controller =
  2204. Shell::Get()->accessibility_controller();
  2205. // Toggle the fullscreen magnifier on/off, dialog should be shown on first use
  2206. // of accelerator.
  2207. const ui::Accelerator fullscreen_magnifier_accelerator(
  2208. ui::VKEY_M, ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN);
  2209. EXPECT_FALSE(
  2210. accessibility_controller->fullscreen_magnifier().WasDialogAccepted());
  2211. EXPECT_TRUE(ProcessInController(fullscreen_magnifier_accelerator));
  2212. EXPECT_TRUE(IsConfirmationDialogOpen());
  2213. AcceptConfirmationDialog();
  2214. base::RunLoop().RunUntilIdle();
  2215. EXPECT_FALSE(IsConfirmationDialogOpen());
  2216. EXPECT_FALSE(docked_magnifier_controller()->GetEnabled());
  2217. EXPECT_TRUE(fullscreen_magnifier_controller()->IsEnabled());
  2218. EXPECT_TRUE(ContainsFullscreenMagnifierNotification());
  2219. EXPECT_TRUE(ProcessInController(fullscreen_magnifier_accelerator));
  2220. EXPECT_FALSE(docked_magnifier_controller()->GetEnabled());
  2221. EXPECT_FALSE(fullscreen_magnifier_controller()->IsEnabled());
  2222. EXPECT_TRUE(
  2223. accessibility_controller->fullscreen_magnifier().WasDialogAccepted());
  2224. EXPECT_FALSE(IsConfirmationDialogOpen());
  2225. EXPECT_FALSE(ContainsFullscreenMagnifierNotification());
  2226. // Dialog will not be shown the second time the accelerator is used.
  2227. EXPECT_TRUE(ProcessInController(fullscreen_magnifier_accelerator));
  2228. EXPECT_FALSE(IsConfirmationDialogOpen());
  2229. EXPECT_TRUE(
  2230. accessibility_controller->fullscreen_magnifier().WasDialogAccepted());
  2231. EXPECT_FALSE(docked_magnifier_controller()->GetEnabled());
  2232. EXPECT_TRUE(fullscreen_magnifier_controller()->IsEnabled());
  2233. EXPECT_TRUE(ContainsFullscreenMagnifierNotification());
  2234. RemoveAllNotifications();
  2235. }
  2236. TEST_F(MagnifiersAcceleratorsTester, TestToggleDockedMagnifier) {
  2237. EXPECT_FALSE(docked_magnifier_controller()->GetEnabled());
  2238. EXPECT_FALSE(fullscreen_magnifier_controller()->IsEnabled());
  2239. EXPECT_FALSE(IsConfirmationDialogOpen());
  2240. AccessibilityControllerImpl* accessibility_controller =
  2241. Shell::Get()->accessibility_controller();
  2242. // Toggle the docked magnifier on/off, dialog should be shown on first use of
  2243. // accelerator.
  2244. const ui::Accelerator docked_magnifier_accelerator(
  2245. ui::VKEY_D, ui::EF_COMMAND_DOWN | ui::EF_CONTROL_DOWN);
  2246. EXPECT_TRUE(ProcessInController(docked_magnifier_accelerator));
  2247. EXPECT_TRUE(IsConfirmationDialogOpen());
  2248. AcceptConfirmationDialog();
  2249. base::RunLoop().RunUntilIdle();
  2250. EXPECT_FALSE(IsConfirmationDialogOpen());
  2251. EXPECT_TRUE(docked_magnifier_controller()->GetEnabled());
  2252. EXPECT_FALSE(fullscreen_magnifier_controller()->IsEnabled());
  2253. EXPECT_TRUE(ContainsDockedMagnifierNotification());
  2254. EXPECT_TRUE(ProcessInController(docked_magnifier_accelerator));
  2255. EXPECT_FALSE(docked_magnifier_controller()->GetEnabled());
  2256. EXPECT_FALSE(fullscreen_magnifier_controller()->IsEnabled());
  2257. EXPECT_TRUE(accessibility_controller->docked_magnifier().WasDialogAccepted());
  2258. EXPECT_FALSE(IsConfirmationDialogOpen());
  2259. EXPECT_FALSE(ContainsDockedMagnifierNotification());
  2260. // Dialog will not be shown the second time accelerator is used.
  2261. EXPECT_TRUE(ProcessInController(docked_magnifier_accelerator));
  2262. EXPECT_FALSE(IsConfirmationDialogOpen());
  2263. EXPECT_TRUE(docked_magnifier_controller()->GetEnabled());
  2264. EXPECT_FALSE(fullscreen_magnifier_controller()->IsEnabled());
  2265. EXPECT_TRUE(ContainsDockedMagnifierNotification());
  2266. RemoveAllNotifications();
  2267. }
  2268. class AccessibilityAcceleratorTester : public MagnifiersAcceleratorsTester {
  2269. public:
  2270. AccessibilityAcceleratorTester() = default;
  2271. ~AccessibilityAcceleratorTester() override = default;
  2272. AccessibilityAcceleratorTester(const AccessibilityAcceleratorTester&) =
  2273. delete;
  2274. AccessibilityAcceleratorTester& operator=(
  2275. const AccessibilityAcceleratorTester&) = delete;
  2276. bool ContainsAccessibilityNotification(
  2277. const std::string& notification_id) const {
  2278. return nullptr !=
  2279. message_center()->FindVisibleNotificationById(notification_id);
  2280. }
  2281. void TestAccessibilityAcceleratorControlledByPref(
  2282. const std::string& pref_name,
  2283. const char* notification_id,
  2284. const std::string& accessibility_histogram_id,
  2285. const ui::Accelerator& accelerator) {
  2286. // Verify that the initial state for the accessibility feature will be
  2287. // disabled, and for accessibility accelerators controller pref
  2288. // |kAccessibilityShortcutsEnabled| is enabled. And neither of that
  2289. // accessibility feature notification id, nor its confirmation dialog have
  2290. // appeared.
  2291. base::HistogramTester histogram_tester_;
  2292. EXPECT_FALSE(user_pref_service()->GetBoolean(pref_name));
  2293. EXPECT_TRUE(
  2294. user_pref_service()->GetBoolean(prefs::kAccessibilityShortcutsEnabled));
  2295. EXPECT_FALSE(IsConfirmationDialogOpen());
  2296. if (notification_id)
  2297. EXPECT_FALSE(ContainsAccessibilityNotification(notification_id));
  2298. // Verify that after disabling the accessibility accelerators, the
  2299. // confirmation dialog won't appear for that accessibility feature. And its
  2300. // corresponding pref won't be enabled. But a notification should appear,
  2301. // which shows that the shortcut for that feature has been disabled. And
  2302. // verify that the accessibility shortcut state is being recorded
  2303. // accordingly.
  2304. user_pref_service()->SetBoolean(prefs::kAccessibilityShortcutsEnabled,
  2305. false);
  2306. EXPECT_TRUE(ProcessInController(accelerator));
  2307. EXPECT_FALSE(IsConfirmationDialogOpen());
  2308. if (notification_id)
  2309. EXPECT_TRUE(ContainsAccessibilityNotification(notification_id));
  2310. EXPECT_FALSE(user_pref_service()->GetBoolean(pref_name));
  2311. histogram_tester_.ExpectBucketCount(accessibility_histogram_id, 0, 1);
  2312. // Verify that if the accessibility accelerators are enabled, then
  2313. // it will show the confirmation dialog for the first time only when
  2314. // toggling its value. And the coressponding pref will be chanaged
  2315. // accordingly. And verify that the accessibility shortcut state is being
  2316. // recorded accordingly.
  2317. user_pref_service()->SetBoolean(prefs::kAccessibilityShortcutsEnabled,
  2318. true);
  2319. EXPECT_TRUE(ProcessInController(accelerator));
  2320. if (notification_id)
  2321. AcceptConfirmationDialog();
  2322. base::RunLoop().RunUntilIdle();
  2323. message_center::NotificationList::Notifications notifications =
  2324. message_center()->GetVisibleNotifications();
  2325. ASSERT_EQ(1u, notifications.size());
  2326. EXPECT_TRUE(user_pref_service()->GetBoolean(pref_name));
  2327. if (notification_id)
  2328. EXPECT_TRUE(ContainsAccessibilityNotification(notification_id));
  2329. histogram_tester_.ExpectBucketCount(accessibility_histogram_id, 1, 1);
  2330. // Verify that the notification id, won't be shown if the accessibility
  2331. // feature is going to be disabled. And verify that the accessibility
  2332. // shortcut state is being recorded accordingly.
  2333. EXPECT_TRUE(ProcessInController(accelerator));
  2334. if (notification_id)
  2335. EXPECT_FALSE(ContainsAccessibilityNotification(notification_id));
  2336. EXPECT_FALSE(user_pref_service()->GetBoolean(pref_name));
  2337. histogram_tester_.ExpectBucketCount(accessibility_histogram_id, 1, 2);
  2338. histogram_tester_.ExpectTotalCount(accessibility_histogram_id, 3);
  2339. // Remove all the current notifications, to get the initial state again.
  2340. RemoveAllNotifications();
  2341. }
  2342. };
  2343. TEST_F(AccessibilityAcceleratorTester, DisableAccessibilityAccelerators) {
  2344. FakeMagnificationManager manager;
  2345. manager.SetPrefs(user_pref_service());
  2346. for (const auto& test_data : kAccessibilityAcceleratorMap) {
  2347. TestAccessibilityAcceleratorControlledByPref(
  2348. test_data.pref_name, test_data.notification_id, test_data.histogram_id,
  2349. test_data.accelerator);
  2350. }
  2351. }
  2352. // Tests that the shortcuts for starting another screen capture session will be
  2353. // treated as no-op if a capture session is already running.
  2354. TEST_F(AccessibilityAcceleratorTester,
  2355. DisableScreenCaptureAcceleratorsIfSessionIsActive) {
  2356. auto* controller = CaptureModeController::Get();
  2357. EXPECT_FALSE(controller->IsActive());
  2358. // Start a window capture session.
  2359. EXPECT_TRUE(ProcessInController(ui::Accelerator(
  2360. ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_ALT_DOWN | ui::EF_CONTROL_DOWN)));
  2361. EXPECT_TRUE(controller->IsActive());
  2362. EXPECT_EQ(CaptureModeSource::kWindow, controller->source());
  2363. // Accelerators for partial screenshot will be a no-op if a
  2364. // session is already running.
  2365. EXPECT_TRUE(ProcessInController(ui::Accelerator(
  2366. ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN)));
  2367. EXPECT_EQ(CaptureModeSource::kWindow, controller->source());
  2368. controller->Stop();
  2369. // Start a partial screenshot capture session.
  2370. EXPECT_TRUE(ProcessInController(ui::Accelerator(
  2371. ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN)));
  2372. EXPECT_TRUE(controller->IsActive());
  2373. EXPECT_EQ(CaptureModeSource::kRegion, controller->source());
  2374. // Accelerators for window screenshot will be a no-op if a
  2375. // session is already running.
  2376. EXPECT_TRUE(ProcessInController(ui::Accelerator(
  2377. ui::VKEY_MEDIA_LAUNCH_APP1, ui::EF_ALT_DOWN | ui::EF_CONTROL_DOWN)));
  2378. EXPECT_EQ(CaptureModeSource::kRegion, controller->source());
  2379. }
  2380. struct MediaSessionAcceleratorTestConfig {
  2381. // Runs the test with the media session service enabled.
  2382. bool service_enabled;
  2383. // Runs the test with the supplied action enabled and will also send the media
  2384. // session info to the controller.
  2385. absl::optional<MediaSessionAction> with_action_enabled;
  2386. // If true then we should expect the action will handle the media keys.
  2387. bool eligible_action = false;
  2388. // If true then we should force forwarding the action to the client.
  2389. bool force_key_handling = false;
  2390. };
  2391. } // namespace
  2392. // MediaSessionAcceleratorTest tests media key handling with media session
  2393. // service integration. The parameter is a struct that configures different
  2394. // settings to run the test under.
  2395. // Note this class can't be in the anonymous namespace because it is referenced
  2396. // as a friend by ash/media/media_controller_impl.h.
  2397. class MediaSessionAcceleratorTest
  2398. : public AcceleratorControllerTest,
  2399. public testing::WithParamInterface<MediaSessionAcceleratorTestConfig> {
  2400. public:
  2401. MediaSessionAcceleratorTest() = default;
  2402. MediaSessionAcceleratorTest(const MediaSessionAcceleratorTest&) = delete;
  2403. MediaSessionAcceleratorTest& operator=(const MediaSessionAcceleratorTest&) =
  2404. delete;
  2405. ~MediaSessionAcceleratorTest() override = default;
  2406. // AcceleratorControllerTest:
  2407. void SetUp() override {
  2408. if (service_enabled()) {
  2409. scoped_feature_list_.InitAndEnableFeature(
  2410. media::kHardwareMediaKeyHandling);
  2411. } else {
  2412. scoped_feature_list_.InitAndDisableFeature(
  2413. media::kHardwareMediaKeyHandling);
  2414. }
  2415. AcceleratorControllerTest::SetUp();
  2416. client_ = std::make_unique<TestMediaClient>();
  2417. controller_ = std::make_unique<media_session::test::TestMediaController>();
  2418. MediaControllerImpl* media_controller = Shell::Get()->media_controller();
  2419. media_controller->SetClient(client_.get());
  2420. media_controller->SetMediaSessionControllerForTest(
  2421. controller_->CreateMediaControllerRemote());
  2422. media_controller->SetForceMediaClientKeyHandling(
  2423. GetParam().force_key_handling);
  2424. media_controller->FlushForTesting();
  2425. }
  2426. void MaybeEnableMediaSession(
  2427. media_session::mojom::MediaPlaybackState playback_state) {
  2428. if (!GetParam().with_action_enabled)
  2429. return;
  2430. SimulateActionsChanged(GetParam().with_action_enabled);
  2431. SimulatePlaybackState(playback_state);
  2432. }
  2433. void SimulateActionsChanged(absl::optional<MediaSessionAction> action) {
  2434. std::vector<MediaSessionAction> actions;
  2435. if (action)
  2436. actions.push_back(*action);
  2437. controller()->SimulateMediaSessionActionsChanged(actions);
  2438. controller()->Flush();
  2439. }
  2440. TestMediaClient* client() const { return client_.get(); }
  2441. media_session::test::TestMediaController* controller() const {
  2442. return controller_.get();
  2443. }
  2444. bool service_enabled() const { return GetParam().service_enabled; }
  2445. bool eligible_action() const { return GetParam().eligible_action; }
  2446. bool force_key_handling() const { return GetParam().force_key_handling; }
  2447. void ExpectActionRecorded(ui::MediaHardwareKeyAction action) {
  2448. histogram_tester_.ExpectBucketCount(
  2449. ui::kMediaHardwareKeyActionHistogramName,
  2450. static_cast<base::HistogramBase::Sample>(action), 1);
  2451. }
  2452. private:
  2453. void SimulatePlaybackState(
  2454. media_session::mojom::MediaPlaybackState playback_state) {
  2455. media_session::mojom::MediaSessionInfoPtr session_info(
  2456. media_session::mojom::MediaSessionInfo::New());
  2457. session_info->state =
  2458. media_session::mojom::MediaSessionInfo::SessionState::kActive;
  2459. session_info->playback_state = playback_state;
  2460. controller()->SimulateMediaSessionInfoChanged(std::move(session_info));
  2461. controller()->Flush();
  2462. }
  2463. std::unique_ptr<TestMediaClient> client_;
  2464. std::unique_ptr<media_session::test::TestMediaController> controller_;
  2465. base::HistogramTester histogram_tester_;
  2466. base::test::ScopedFeatureList scoped_feature_list_;
  2467. };
  2468. INSTANTIATE_TEST_SUITE_P(
  2469. All,
  2470. MediaSessionAcceleratorTest,
  2471. testing::Values(
  2472. MediaSessionAcceleratorTestConfig{true, MediaSessionAction::kPlay,
  2473. true},
  2474. MediaSessionAcceleratorTestConfig{true, MediaSessionAction::kPause,
  2475. true},
  2476. MediaSessionAcceleratorTestConfig{
  2477. true, MediaSessionAction::kPreviousTrack, true},
  2478. MediaSessionAcceleratorTestConfig{true, MediaSessionAction::kNextTrack,
  2479. true},
  2480. MediaSessionAcceleratorTestConfig{true,
  2481. MediaSessionAction::kSeekBackward},
  2482. MediaSessionAcceleratorTestConfig{true,
  2483. MediaSessionAction::kSeekForward},
  2484. MediaSessionAcceleratorTestConfig{true, MediaSessionAction::kStop},
  2485. MediaSessionAcceleratorTestConfig{false, MediaSessionAction::kPlay},
  2486. MediaSessionAcceleratorTestConfig{false, MediaSessionAction::kPause},
  2487. MediaSessionAcceleratorTestConfig{false,
  2488. MediaSessionAction::kPreviousTrack},
  2489. MediaSessionAcceleratorTestConfig{false,
  2490. MediaSessionAction::kNextTrack},
  2491. MediaSessionAcceleratorTestConfig{false,
  2492. MediaSessionAction::kSeekBackward},
  2493. MediaSessionAcceleratorTestConfig{false,
  2494. MediaSessionAction::kSeekForward},
  2495. MediaSessionAcceleratorTestConfig{false, MediaSessionAction::kStop},
  2496. MediaSessionAcceleratorTestConfig{true, MediaSessionAction::kPlay,
  2497. false, true},
  2498. MediaSessionAcceleratorTestConfig{true, MediaSessionAction::kPause,
  2499. false, true},
  2500. MediaSessionAcceleratorTestConfig{true, MediaSessionAction::kNextTrack,
  2501. false, true},
  2502. MediaSessionAcceleratorTestConfig{
  2503. true, MediaSessionAction::kPreviousTrack, false, true}));
  2504. TEST_P(MediaSessionAcceleratorTest, MediaPlaybackAcceleratorsBehavior) {
  2505. const ui::KeyboardCode media_keys[] = {ui::VKEY_MEDIA_NEXT_TRACK,
  2506. ui::VKEY_MEDIA_PLAY_PAUSE,
  2507. ui::VKEY_MEDIA_PREV_TRACK};
  2508. ::wm::AcceleratorFilter filter(
  2509. std::make_unique<PreTargetAcceleratorHandler>());
  2510. for (ui::KeyboardCode key : media_keys) {
  2511. // If the media session service integration is enabled then media keys will
  2512. // be handled in ash.
  2513. std::unique_ptr<aura::Window> window(CreateTestWindowInShellWithId(1));
  2514. {
  2515. ui::KeyEvent press_key(ui::ET_KEY_PRESSED, key, ui::EF_NONE);
  2516. ui::Event::DispatcherApi dispatch_helper(&press_key);
  2517. dispatch_helper.set_target(window.get());
  2518. filter.OnKeyEvent(&press_key);
  2519. EXPECT_EQ(service_enabled(), press_key.stopped_propagation());
  2520. }
  2521. // Setting a window property on the target allows media keys to pass
  2522. // through.
  2523. WindowState::Get(window.get())->SetCanConsumeSystemKeys(true);
  2524. {
  2525. ui::KeyEvent press_key(ui::ET_KEY_PRESSED, key, ui::EF_NONE);
  2526. ui::Event::DispatcherApi dispatch_helper(&press_key);
  2527. dispatch_helper.set_target(window.get());
  2528. filter.OnKeyEvent(&press_key);
  2529. EXPECT_FALSE(press_key.stopped_propagation());
  2530. }
  2531. }
  2532. }
  2533. TEST_P(MediaSessionAcceleratorTest, MediaGlobalAccelerators_NextTrack) {
  2534. MaybeEnableMediaSession(media_session::mojom::MediaPlaybackState::kPaused);
  2535. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2536. EXPECT_EQ(0, controller()->next_track_count());
  2537. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_NEXT_TRACK, ui::EF_NONE));
  2538. Shell::Get()->media_controller()->FlushForTesting();
  2539. if (service_enabled() && eligible_action() && !force_key_handling()) {
  2540. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2541. EXPECT_EQ(1, controller()->next_track_count());
  2542. } else {
  2543. EXPECT_EQ(1, client()->handle_media_next_track_count());
  2544. EXPECT_EQ(0, controller()->next_track_count());
  2545. }
  2546. ExpectActionRecorded(ui::MediaHardwareKeyAction::kNextTrack);
  2547. }
  2548. TEST_P(MediaSessionAcceleratorTest, MediaGlobalAccelerators_Play) {
  2549. MaybeEnableMediaSession(media_session::mojom::MediaPlaybackState::kPaused);
  2550. EXPECT_EQ(0, client()->handle_media_play_pause_count());
  2551. EXPECT_EQ(0, controller()->resume_count());
  2552. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_PLAY_PAUSE, ui::EF_NONE));
  2553. Shell::Get()->media_controller()->FlushForTesting();
  2554. if (service_enabled() && eligible_action()) {
  2555. EXPECT_EQ(0, client()->handle_media_play_pause_count());
  2556. EXPECT_EQ(1, controller()->resume_count());
  2557. // If media session handles the key then we should always know the playback
  2558. // state so we can record a more granular action.
  2559. ExpectActionRecorded(ui::MediaHardwareKeyAction::kPlay);
  2560. } else {
  2561. EXPECT_EQ(1, client()->handle_media_play_pause_count());
  2562. EXPECT_EQ(0, controller()->resume_count());
  2563. // If we pass through to the client we don't know whether the action will
  2564. // play or pause so we should record a generic "play/pause" action.
  2565. ExpectActionRecorded(ui::MediaHardwareKeyAction::kPlayPause);
  2566. }
  2567. }
  2568. TEST_P(MediaSessionAcceleratorTest, MediaGlobalAccelerators_Pause) {
  2569. MaybeEnableMediaSession(media_session::mojom::MediaPlaybackState::kPlaying);
  2570. EXPECT_EQ(0, client()->handle_media_play_pause_count());
  2571. EXPECT_EQ(0, controller()->suspend_count());
  2572. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_PLAY_PAUSE, ui::EF_NONE));
  2573. Shell::Get()->media_controller()->FlushForTesting();
  2574. if (service_enabled() && eligible_action() && !force_key_handling()) {
  2575. EXPECT_EQ(0, client()->handle_media_play_pause_count());
  2576. EXPECT_EQ(1, controller()->suspend_count());
  2577. // If media session handles the key then we should always know the playback
  2578. // state so we can record a more granular action.
  2579. ExpectActionRecorded(ui::MediaHardwareKeyAction::kPause);
  2580. } else {
  2581. EXPECT_EQ(1, client()->handle_media_play_pause_count());
  2582. EXPECT_EQ(0, controller()->suspend_count());
  2583. // If we pass through to the client we don't know whether the action will
  2584. // play or pause so we should record a generic "play/pause" action.
  2585. ExpectActionRecorded(ui::MediaHardwareKeyAction::kPlayPause);
  2586. }
  2587. }
  2588. TEST_P(MediaSessionAcceleratorTest, MediaGlobalAccelerators_PrevTrack) {
  2589. MaybeEnableMediaSession(media_session::mojom::MediaPlaybackState::kPaused);
  2590. EXPECT_EQ(0, client()->handle_media_prev_track_count());
  2591. EXPECT_EQ(0, controller()->previous_track_count());
  2592. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_PREV_TRACK, ui::EF_NONE));
  2593. Shell::Get()->media_controller()->FlushForTesting();
  2594. if (service_enabled() && eligible_action() && !force_key_handling()) {
  2595. EXPECT_EQ(0, client()->handle_media_prev_track_count());
  2596. EXPECT_EQ(1, controller()->previous_track_count());
  2597. } else {
  2598. EXPECT_EQ(1, client()->handle_media_prev_track_count());
  2599. EXPECT_EQ(0, controller()->previous_track_count());
  2600. }
  2601. ExpectActionRecorded(ui::MediaHardwareKeyAction::kPreviousTrack);
  2602. }
  2603. TEST_P(MediaSessionAcceleratorTest,
  2604. MediaGlobalAccelerators_UpdateAction_Disable) {
  2605. MaybeEnableMediaSession(media_session::mojom::MediaPlaybackState::kPaused);
  2606. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2607. EXPECT_EQ(0, controller()->next_track_count());
  2608. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_NEXT_TRACK, ui::EF_NONE));
  2609. Shell::Get()->media_controller()->FlushForTesting();
  2610. if (service_enabled() && eligible_action() && !force_key_handling()) {
  2611. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2612. EXPECT_EQ(1, controller()->next_track_count());
  2613. } else {
  2614. EXPECT_EQ(1, client()->handle_media_next_track_count());
  2615. EXPECT_EQ(0, controller()->next_track_count());
  2616. }
  2617. SimulateActionsChanged(absl::nullopt);
  2618. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_NEXT_TRACK, ui::EF_NONE));
  2619. Shell::Get()->media_controller()->FlushForTesting();
  2620. if (service_enabled() && eligible_action() && !force_key_handling()) {
  2621. EXPECT_EQ(1, client()->handle_media_next_track_count());
  2622. EXPECT_EQ(1, controller()->next_track_count());
  2623. } else {
  2624. EXPECT_EQ(2, client()->handle_media_next_track_count());
  2625. EXPECT_EQ(0, controller()->next_track_count());
  2626. }
  2627. }
  2628. TEST_P(MediaSessionAcceleratorTest,
  2629. MediaGlobalAccelerators_UpdateAction_Enable) {
  2630. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2631. EXPECT_EQ(0, controller()->next_track_count());
  2632. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_NEXT_TRACK, ui::EF_NONE));
  2633. Shell::Get()->media_controller()->FlushForTesting();
  2634. EXPECT_EQ(1, client()->handle_media_next_track_count());
  2635. EXPECT_EQ(0, controller()->next_track_count());
  2636. MaybeEnableMediaSession(media_session::mojom::MediaPlaybackState::kPaused);
  2637. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_NEXT_TRACK, ui::EF_NONE));
  2638. Shell::Get()->media_controller()->FlushForTesting();
  2639. if (service_enabled() && eligible_action() && !force_key_handling()) {
  2640. EXPECT_EQ(1, client()->handle_media_next_track_count());
  2641. EXPECT_EQ(1, controller()->next_track_count());
  2642. } else {
  2643. EXPECT_EQ(2, client()->handle_media_next_track_count());
  2644. EXPECT_EQ(0, controller()->next_track_count());
  2645. }
  2646. }
  2647. TEST_P(MediaSessionAcceleratorTest,
  2648. MediaGlobalAccelerators_UpdateForceKeyHandling) {
  2649. MaybeEnableMediaSession(media_session::mojom::MediaPlaybackState::kPaused);
  2650. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2651. EXPECT_EQ(0, controller()->next_track_count());
  2652. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_NEXT_TRACK, ui::EF_NONE));
  2653. Shell::Get()->media_controller()->FlushForTesting();
  2654. if (service_enabled() && eligible_action() && !force_key_handling()) {
  2655. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2656. EXPECT_EQ(1, controller()->next_track_count());
  2657. } else {
  2658. EXPECT_EQ(1, client()->handle_media_next_track_count());
  2659. EXPECT_EQ(0, controller()->next_track_count());
  2660. }
  2661. // Update the force media client key handling setting. It may have been
  2662. // previously set if |force_key_handling| is true.
  2663. Shell::Get()->media_controller()->SetForceMediaClientKeyHandling(false);
  2664. ProcessInController(ui::Accelerator(ui::VKEY_MEDIA_NEXT_TRACK, ui::EF_NONE));
  2665. Shell::Get()->media_controller()->FlushForTesting();
  2666. if (service_enabled() && force_key_handling()) {
  2667. // If we had |force_key_handling| true the first time we pressed the play
  2668. // pause key then we should see the previous action that was forward to the
  2669. // client. Since the service is enabled, the second action will be handled
  2670. // by the controller.
  2671. EXPECT_EQ(1, client()->handle_media_next_track_count());
  2672. EXPECT_EQ(1, controller()->next_track_count());
  2673. } else if (service_enabled() && eligible_action()) {
  2674. // If we had |force_key_handling| disabled the whole time and the service
  2675. // enabled then both actions should be handled in the controller.
  2676. EXPECT_EQ(0, client()->handle_media_next_track_count());
  2677. EXPECT_EQ(2, controller()->next_track_count());
  2678. } else {
  2679. // If we had |force_key_handling| disabled the whole time and the service
  2680. // disabled then both actions should fallback to the client because there is
  2681. // nothing in Ash to handle them.
  2682. EXPECT_EQ(2, client()->handle_media_next_track_count());
  2683. EXPECT_EQ(0, controller()->next_track_count());
  2684. }
  2685. }
  2686. } // namespace ash