InputDispatcher.cpp 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558
  1. /*
  2. * Copyright (C) 2010 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #define LOG_TAG "InputDispatcher"
  17. #define ATRACE_TAG ATRACE_TAG_INPUT
  18. //#define LOG_NDEBUG 0
  19. // Log detailed debug messages about each inbound event notification to the dispatcher.
  20. #define DEBUG_INBOUND_EVENT_DETAILS 0
  21. // Log detailed debug messages about each outbound event processed by the dispatcher.
  22. #define DEBUG_OUTBOUND_EVENT_DETAILS 0
  23. // Log debug messages about the dispatch cycle.
  24. #define DEBUG_DISPATCH_CYCLE 0
  25. // Log debug messages about registrations.
  26. #define DEBUG_REGISTRATION 0
  27. // Log debug messages about input event injection.
  28. #define DEBUG_INJECTION 0
  29. // Log debug messages about input focus tracking.
  30. #define DEBUG_FOCUS 0
  31. // Log debug messages about the app switch latency optimization.
  32. #define DEBUG_APP_SWITCH 0
  33. // Log debug messages about hover events.
  34. #define DEBUG_HOVER 0
  35. #include "InputDispatcher.h"
  36. #include <utils/Trace.h>
  37. #include <cutils/log.h>
  38. #include <powermanager/PowerManager.h>
  39. #include <ui/Region.h>
  40. #include <stddef.h>
  41. #include <unistd.h>
  42. #include <errno.h>
  43. #include <limits.h>
  44. #include <time.h>
  45. #define INDENT " "
  46. #define INDENT2 " "
  47. #define INDENT3 " "
  48. #define INDENT4 " "
  49. namespace android {
  50. // Default input dispatching timeout if there is no focused application or paused window
  51. // from which to determine an appropriate dispatching timeout.
  52. const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
  53. // Amount of time to allow for all pending events to be processed when an app switch
  54. // key is on the way. This is used to preempt input dispatch and drop input events
  55. // when an application takes too long to respond and the user has pressed an app switch key.
  56. const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
  57. // Amount of time to allow for an event to be dispatched (measured since its eventTime)
  58. // before considering it stale and dropping it.
  59. const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
  60. // Amount of time to allow touch events to be streamed out to a connection before requiring
  61. // that the first event be finished. This value extends the ANR timeout by the specified
  62. // amount. For example, if streaming is allowed to get ahead by one second relative to the
  63. // queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
  64. const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
  65. // Log a warning when an event takes longer than this to process, even if an ANR does not occur.
  66. const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
  67. // Number of recent events to keep for debugging purposes.
  68. const size_t RECENT_QUEUE_MAX_SIZE = 10;
  69. static inline nsecs_t now() {
  70. return systemTime(SYSTEM_TIME_MONOTONIC);
  71. }
  72. static inline const char* toString(bool value) {
  73. return value ? "true" : "false";
  74. }
  75. static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
  76. return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
  77. >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  78. }
  79. static bool isValidKeyAction(int32_t action) {
  80. switch (action) {
  81. case AKEY_EVENT_ACTION_DOWN:
  82. case AKEY_EVENT_ACTION_UP:
  83. return true;
  84. default:
  85. return false;
  86. }
  87. }
  88. static bool validateKeyEvent(int32_t action) {
  89. if (! isValidKeyAction(action)) {
  90. ALOGE("Key event has invalid action code 0x%x", action);
  91. return false;
  92. }
  93. return true;
  94. }
  95. static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
  96. switch (action & AMOTION_EVENT_ACTION_MASK) {
  97. case AMOTION_EVENT_ACTION_DOWN:
  98. case AMOTION_EVENT_ACTION_UP:
  99. case AMOTION_EVENT_ACTION_CANCEL:
  100. case AMOTION_EVENT_ACTION_MOVE:
  101. case AMOTION_EVENT_ACTION_OUTSIDE:
  102. case AMOTION_EVENT_ACTION_HOVER_ENTER:
  103. case AMOTION_EVENT_ACTION_HOVER_MOVE:
  104. case AMOTION_EVENT_ACTION_HOVER_EXIT:
  105. case AMOTION_EVENT_ACTION_SCROLL:
  106. return true;
  107. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  108. case AMOTION_EVENT_ACTION_POINTER_UP: {
  109. int32_t index = getMotionEventActionPointerIndex(action);
  110. return index >= 0 && size_t(index) < pointerCount;
  111. }
  112. case AMOTION_EVENT_ACTION_BUTTON_PRESS:
  113. case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
  114. return actionButton != 0;
  115. default:
  116. return false;
  117. }
  118. }
  119. static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
  120. const PointerProperties* pointerProperties) {
  121. if (! isValidMotionAction(action, actionButton, pointerCount)) {
  122. ALOGE("Motion event has invalid action code 0x%x", action);
  123. return false;
  124. }
  125. if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
  126. ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
  127. pointerCount, MAX_POINTERS);
  128. return false;
  129. }
  130. BitSet32 pointerIdBits;
  131. for (size_t i = 0; i < pointerCount; i++) {
  132. int32_t id = pointerProperties[i].id;
  133. if (id < 0 || id > MAX_POINTER_ID) {
  134. ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
  135. id, MAX_POINTER_ID);
  136. return false;
  137. }
  138. if (pointerIdBits.hasBit(id)) {
  139. ALOGE("Motion event has duplicate pointer id %d", id);
  140. return false;
  141. }
  142. pointerIdBits.markBit(id);
  143. }
  144. return true;
  145. }
  146. static bool isMainDisplay(int32_t displayId) {
  147. return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
  148. }
  149. static void dumpRegion(String8& dump, const Region& region) {
  150. if (region.isEmpty()) {
  151. dump.append("<empty>");
  152. return;
  153. }
  154. bool first = true;
  155. Region::const_iterator cur = region.begin();
  156. Region::const_iterator const tail = region.end();
  157. while (cur != tail) {
  158. if (first) {
  159. first = false;
  160. } else {
  161. dump.append("|");
  162. }
  163. dump.appendFormat("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
  164. cur++;
  165. }
  166. }
  167. // --- InputDispatcher ---
  168. InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
  169. mPolicy(policy),
  170. mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED),
  171. mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
  172. mNextUnblockedEvent(NULL),
  173. mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
  174. mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
  175. mLooper = new Looper(false);
  176. mKeyRepeatState.lastKeyEntry = NULL;
  177. policy->getDispatcherConfiguration(&mConfig);
  178. }
  179. InputDispatcher::~InputDispatcher() {
  180. { // acquire lock
  181. AutoMutex _l(mLock);
  182. resetKeyRepeatLocked();
  183. releasePendingEventLocked();
  184. drainInboundQueueLocked();
  185. }
  186. while (mConnectionsByFd.size() != 0) {
  187. unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
  188. }
  189. }
  190. void InputDispatcher::dispatchOnce() {
  191. nsecs_t nextWakeupTime = LONG_LONG_MAX;
  192. { // acquire lock
  193. AutoMutex _l(mLock);
  194. mDispatcherIsAliveCondition.broadcast();
  195. // Run a dispatch loop if there are no pending commands.
  196. // The dispatch loop might enqueue commands to run afterwards.
  197. if (!haveCommandsLocked()) {
  198. dispatchOnceInnerLocked(&nextWakeupTime);
  199. }
  200. // Run all pending commands if there are any.
  201. // If any commands were run then force the next poll to wake up immediately.
  202. if (runCommandsLockedInterruptible()) {
  203. nextWakeupTime = LONG_LONG_MIN;
  204. }
  205. } // release lock
  206. // Wait for callback or timeout or wake. (make sure we round up, not down)
  207. nsecs_t currentTime = now();
  208. int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
  209. mLooper->pollOnce(timeoutMillis);
  210. }
  211. void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
  212. nsecs_t currentTime = now();
  213. // Reset the key repeat timer whenever normal dispatch is suspended while the
  214. // device is in a non-interactive state. This is to ensure that we abort a key
  215. // repeat if the device is just coming out of sleep.
  216. if (!mDispatchEnabled) {
  217. resetKeyRepeatLocked();
  218. }
  219. // If dispatching is frozen, do not process timeouts or try to deliver any new events.
  220. if (mDispatchFrozen) {
  221. #if DEBUG_FOCUS
  222. ALOGD("Dispatch frozen. Waiting some more.");
  223. #endif
  224. return;
  225. }
  226. // Optimize latency of app switches.
  227. // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
  228. // been pressed. When it expires, we preempt dispatch and drop all other pending events.
  229. bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
  230. if (mAppSwitchDueTime < *nextWakeupTime) {
  231. *nextWakeupTime = mAppSwitchDueTime;
  232. }
  233. // Ready to start a new event.
  234. // If we don't already have a pending event, go grab one.
  235. if (! mPendingEvent) {
  236. if (mInboundQueue.isEmpty()) {
  237. if (isAppSwitchDue) {
  238. // The inbound queue is empty so the app switch key we were waiting
  239. // for will never arrive. Stop waiting for it.
  240. resetPendingAppSwitchLocked(false);
  241. isAppSwitchDue = false;
  242. }
  243. // Synthesize a key repeat if appropriate.
  244. if (mKeyRepeatState.lastKeyEntry) {
  245. if (currentTime >= mKeyRepeatState.nextRepeatTime) {
  246. mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
  247. } else {
  248. if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
  249. *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
  250. }
  251. }
  252. }
  253. // Nothing to do if there is no pending event.
  254. if (!mPendingEvent) {
  255. return;
  256. }
  257. } else {
  258. // Inbound queue has at least one entry.
  259. mPendingEvent = mInboundQueue.dequeueAtHead();
  260. traceInboundQueueLengthLocked();
  261. }
  262. // Poke user activity for this event.
  263. if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
  264. pokeUserActivityLocked(mPendingEvent);
  265. }
  266. // Get ready to dispatch the event.
  267. resetANRTimeoutsLocked();
  268. }
  269. // Now we have an event to dispatch.
  270. // All events are eventually dequeued and processed this way, even if we intend to drop them.
  271. ALOG_ASSERT(mPendingEvent != NULL);
  272. bool done = false;
  273. DropReason dropReason = DROP_REASON_NOT_DROPPED;
  274. if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
  275. dropReason = DROP_REASON_POLICY;
  276. } else if (!mDispatchEnabled) {
  277. dropReason = DROP_REASON_DISABLED;
  278. }
  279. if (mNextUnblockedEvent == mPendingEvent) {
  280. mNextUnblockedEvent = NULL;
  281. }
  282. switch (mPendingEvent->type) {
  283. case EventEntry::TYPE_CONFIGURATION_CHANGED: {
  284. ConfigurationChangedEntry* typedEntry =
  285. static_cast<ConfigurationChangedEntry*>(mPendingEvent);
  286. done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
  287. dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
  288. break;
  289. }
  290. case EventEntry::TYPE_DEVICE_RESET: {
  291. DeviceResetEntry* typedEntry =
  292. static_cast<DeviceResetEntry*>(mPendingEvent);
  293. done = dispatchDeviceResetLocked(currentTime, typedEntry);
  294. dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
  295. break;
  296. }
  297. case EventEntry::TYPE_KEY: {
  298. KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
  299. if (isAppSwitchDue) {
  300. if (isAppSwitchKeyEventLocked(typedEntry)) {
  301. resetPendingAppSwitchLocked(true);
  302. isAppSwitchDue = false;
  303. } else if (dropReason == DROP_REASON_NOT_DROPPED) {
  304. dropReason = DROP_REASON_APP_SWITCH;
  305. }
  306. }
  307. if (dropReason == DROP_REASON_NOT_DROPPED
  308. && isStaleEventLocked(currentTime, typedEntry)) {
  309. dropReason = DROP_REASON_STALE;
  310. }
  311. if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
  312. dropReason = DROP_REASON_BLOCKED;
  313. }
  314. done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
  315. break;
  316. }
  317. case EventEntry::TYPE_MOTION: {
  318. MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
  319. if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
  320. dropReason = DROP_REASON_APP_SWITCH;
  321. }
  322. if (dropReason == DROP_REASON_NOT_DROPPED
  323. && isStaleEventLocked(currentTime, typedEntry)) {
  324. dropReason = DROP_REASON_STALE;
  325. }
  326. if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
  327. dropReason = DROP_REASON_BLOCKED;
  328. }
  329. done = dispatchMotionLocked(currentTime, typedEntry,
  330. &dropReason, nextWakeupTime);
  331. break;
  332. }
  333. default:
  334. ALOG_ASSERT(false);
  335. break;
  336. }
  337. if (done) {
  338. if (dropReason != DROP_REASON_NOT_DROPPED) {
  339. dropInboundEventLocked(mPendingEvent, dropReason);
  340. }
  341. mLastDropReason = dropReason;
  342. releasePendingEventLocked();
  343. *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
  344. }
  345. }
  346. bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
  347. bool needWake = mInboundQueue.isEmpty();
  348. mInboundQueue.enqueueAtTail(entry);
  349. traceInboundQueueLengthLocked();
  350. switch (entry->type) {
  351. case EventEntry::TYPE_KEY: {
  352. // Optimize app switch latency.
  353. // If the application takes too long to catch up then we drop all events preceding
  354. // the app switch key.
  355. KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
  356. if (isAppSwitchKeyEventLocked(keyEntry)) {
  357. if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
  358. mAppSwitchSawKeyDown = true;
  359. } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
  360. if (mAppSwitchSawKeyDown) {
  361. #if DEBUG_APP_SWITCH
  362. ALOGD("App switch is pending!");
  363. #endif
  364. mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
  365. mAppSwitchSawKeyDown = false;
  366. needWake = true;
  367. }
  368. }
  369. }
  370. break;
  371. }
  372. case EventEntry::TYPE_MOTION: {
  373. // Optimize case where the current application is unresponsive and the user
  374. // decides to touch a window in a different application.
  375. // If the application takes too long to catch up then we drop all events preceding
  376. // the touch into the other window.
  377. MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
  378. if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
  379. && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
  380. && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
  381. && mInputTargetWaitApplicationHandle != NULL) {
  382. int32_t displayId = motionEntry->displayId;
  383. int32_t x = int32_t(motionEntry->pointerCoords[0].
  384. getAxisValue(AMOTION_EVENT_AXIS_X));
  385. int32_t y = int32_t(motionEntry->pointerCoords[0].
  386. getAxisValue(AMOTION_EVENT_AXIS_Y));
  387. sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
  388. if (touchedWindowHandle != NULL
  389. && touchedWindowHandle->inputApplicationHandle
  390. != mInputTargetWaitApplicationHandle) {
  391. // User touched a different application than the one we are waiting on.
  392. // Flag the event, and start pruning the input queue.
  393. mNextUnblockedEvent = motionEntry;
  394. needWake = true;
  395. }
  396. }
  397. break;
  398. }
  399. }
  400. return needWake;
  401. }
  402. void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
  403. entry->refCount += 1;
  404. mRecentQueue.enqueueAtTail(entry);
  405. if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
  406. mRecentQueue.dequeueAtHead()->release();
  407. }
  408. }
  409. sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
  410. int32_t x, int32_t y) {
  411. // Traverse windows from front to back to find touched window.
  412. size_t numWindows = mWindowHandles.size();
  413. for (size_t i = 0; i < numWindows; i++) {
  414. sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
  415. const InputWindowInfo* windowInfo = windowHandle->getInfo();
  416. if (windowInfo->displayId == displayId) {
  417. int32_t flags = windowInfo->layoutParamsFlags;
  418. if (windowInfo->visible) {
  419. if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
  420. bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
  421. | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
  422. if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
  423. // Found window.
  424. return windowHandle;
  425. }
  426. }
  427. }
  428. }
  429. }
  430. return NULL;
  431. }
  432. void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
  433. const char* reason;
  434. switch (dropReason) {
  435. case DROP_REASON_POLICY:
  436. #if DEBUG_INBOUND_EVENT_DETAILS
  437. ALOGD("Dropped event because policy consumed it.");
  438. #endif
  439. reason = "inbound event was dropped because the policy consumed it";
  440. break;
  441. case DROP_REASON_DISABLED:
  442. if (mLastDropReason != DROP_REASON_DISABLED) {
  443. ALOGI("Dropped event because input dispatch is disabled.");
  444. }
  445. reason = "inbound event was dropped because input dispatch is disabled";
  446. break;
  447. case DROP_REASON_APP_SWITCH:
  448. ALOGI("Dropped event because of pending overdue app switch.");
  449. reason = "inbound event was dropped because of pending overdue app switch";
  450. break;
  451. case DROP_REASON_BLOCKED:
  452. ALOGI("Dropped event because the current application is not responding and the user "
  453. "has started interacting with a different application.");
  454. reason = "inbound event was dropped because the current application is not responding "
  455. "and the user has started interacting with a different application";
  456. break;
  457. case DROP_REASON_STALE:
  458. ALOGI("Dropped event because it is stale.");
  459. reason = "inbound event was dropped because it is stale";
  460. break;
  461. default:
  462. ALOG_ASSERT(false);
  463. return;
  464. }
  465. switch (entry->type) {
  466. case EventEntry::TYPE_KEY: {
  467. CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
  468. synthesizeCancelationEventsForAllConnectionsLocked(options);
  469. break;
  470. }
  471. case EventEntry::TYPE_MOTION: {
  472. MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
  473. if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
  474. CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
  475. synthesizeCancelationEventsForAllConnectionsLocked(options);
  476. } else {
  477. CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
  478. synthesizeCancelationEventsForAllConnectionsLocked(options);
  479. }
  480. break;
  481. }
  482. }
  483. }
  484. bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
  485. return keyCode == AKEYCODE_HOME
  486. || keyCode == AKEYCODE_ENDCALL
  487. || keyCode == AKEYCODE_APP_SWITCH;
  488. }
  489. bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
  490. return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
  491. && isAppSwitchKeyCode(keyEntry->keyCode)
  492. && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
  493. && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
  494. }
  495. bool InputDispatcher::isAppSwitchPendingLocked() {
  496. return mAppSwitchDueTime != LONG_LONG_MAX;
  497. }
  498. void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
  499. mAppSwitchDueTime = LONG_LONG_MAX;
  500. #if DEBUG_APP_SWITCH
  501. if (handled) {
  502. ALOGD("App switch has arrived.");
  503. } else {
  504. ALOGD("App switch was abandoned.");
  505. }
  506. #endif
  507. }
  508. bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
  509. return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
  510. }
  511. bool InputDispatcher::haveCommandsLocked() const {
  512. return !mCommandQueue.isEmpty();
  513. }
  514. bool InputDispatcher::runCommandsLockedInterruptible() {
  515. if (mCommandQueue.isEmpty()) {
  516. return false;
  517. }
  518. do {
  519. CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
  520. Command command = commandEntry->command;
  521. (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
  522. commandEntry->connection.clear();
  523. delete commandEntry;
  524. } while (! mCommandQueue.isEmpty());
  525. return true;
  526. }
  527. InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
  528. CommandEntry* commandEntry = new CommandEntry(command);
  529. mCommandQueue.enqueueAtTail(commandEntry);
  530. return commandEntry;
  531. }
  532. void InputDispatcher::drainInboundQueueLocked() {
  533. while (! mInboundQueue.isEmpty()) {
  534. EventEntry* entry = mInboundQueue.dequeueAtHead();
  535. releaseInboundEventLocked(entry);
  536. }
  537. traceInboundQueueLengthLocked();
  538. }
  539. void InputDispatcher::releasePendingEventLocked() {
  540. if (mPendingEvent) {
  541. resetANRTimeoutsLocked();
  542. releaseInboundEventLocked(mPendingEvent);
  543. mPendingEvent = NULL;
  544. }
  545. }
  546. void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
  547. InjectionState* injectionState = entry->injectionState;
  548. if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
  549. #if DEBUG_DISPATCH_CYCLE
  550. ALOGD("Injected inbound event was dropped.");
  551. #endif
  552. setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
  553. }
  554. if (entry == mNextUnblockedEvent) {
  555. mNextUnblockedEvent = NULL;
  556. }
  557. addRecentEventLocked(entry);
  558. entry->release();
  559. }
  560. void InputDispatcher::resetKeyRepeatLocked() {
  561. if (mKeyRepeatState.lastKeyEntry) {
  562. mKeyRepeatState.lastKeyEntry->release();
  563. mKeyRepeatState.lastKeyEntry = NULL;
  564. }
  565. }
  566. InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
  567. KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
  568. // Reuse the repeated key entry if it is otherwise unreferenced.
  569. uint32_t policyFlags = entry->policyFlags &
  570. (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
  571. if (entry->refCount == 1) {
  572. entry->recycle();
  573. entry->eventTime = currentTime;
  574. entry->policyFlags = policyFlags;
  575. entry->repeatCount += 1;
  576. } else {
  577. KeyEntry* newEntry = new KeyEntry(currentTime,
  578. entry->deviceId, entry->source, policyFlags,
  579. entry->action, entry->flags, entry->keyCode, entry->scanCode,
  580. entry->metaState, entry->repeatCount + 1, entry->downTime);
  581. mKeyRepeatState.lastKeyEntry = newEntry;
  582. entry->release();
  583. entry = newEntry;
  584. }
  585. entry->syntheticRepeat = true;
  586. // Increment reference count since we keep a reference to the event in
  587. // mKeyRepeatState.lastKeyEntry in addition to the one we return.
  588. entry->refCount += 1;
  589. mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
  590. return entry;
  591. }
  592. bool InputDispatcher::dispatchConfigurationChangedLocked(
  593. nsecs_t currentTime, ConfigurationChangedEntry* entry) {
  594. #if DEBUG_OUTBOUND_EVENT_DETAILS
  595. ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
  596. #endif
  597. // Reset key repeating in case a keyboard device was added or removed or something.
  598. resetKeyRepeatLocked();
  599. // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
  600. CommandEntry* commandEntry = postCommandLocked(
  601. & InputDispatcher::doNotifyConfigurationChangedInterruptible);
  602. commandEntry->eventTime = entry->eventTime;
  603. return true;
  604. }
  605. bool InputDispatcher::dispatchDeviceResetLocked(
  606. nsecs_t currentTime, DeviceResetEntry* entry) {
  607. #if DEBUG_OUTBOUND_EVENT_DETAILS
  608. ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
  609. #endif
  610. CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
  611. "device was reset");
  612. options.deviceId = entry->deviceId;
  613. synthesizeCancelationEventsForAllConnectionsLocked(options);
  614. return true;
  615. }
  616. bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
  617. DropReason* dropReason, nsecs_t* nextWakeupTime) {
  618. // Preprocessing.
  619. if (! entry->dispatchInProgress) {
  620. if (entry->repeatCount == 0
  621. && entry->action == AKEY_EVENT_ACTION_DOWN
  622. && (entry->policyFlags & POLICY_FLAG_TRUSTED)
  623. && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
  624. if (mKeyRepeatState.lastKeyEntry
  625. && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
  626. // We have seen two identical key downs in a row which indicates that the device
  627. // driver is automatically generating key repeats itself. We take note of the
  628. // repeat here, but we disable our own next key repeat timer since it is clear that
  629. // we will not need to synthesize key repeats ourselves.
  630. entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
  631. resetKeyRepeatLocked();
  632. mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
  633. } else {
  634. // Not a repeat. Save key down state in case we do see a repeat later.
  635. resetKeyRepeatLocked();
  636. mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
  637. }
  638. mKeyRepeatState.lastKeyEntry = entry;
  639. entry->refCount += 1;
  640. } else if (! entry->syntheticRepeat) {
  641. resetKeyRepeatLocked();
  642. }
  643. if (entry->repeatCount == 1) {
  644. entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
  645. } else {
  646. entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
  647. }
  648. entry->dispatchInProgress = true;
  649. logOutboundKeyDetailsLocked("dispatchKey - ", entry);
  650. }
  651. // Handle case where the policy asked us to try again later last time.
  652. if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
  653. if (currentTime < entry->interceptKeyWakeupTime) {
  654. if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
  655. *nextWakeupTime = entry->interceptKeyWakeupTime;
  656. }
  657. return false; // wait until next wakeup
  658. }
  659. entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
  660. entry->interceptKeyWakeupTime = 0;
  661. }
  662. // Give the policy a chance to intercept the key.
  663. if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
  664. if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
  665. CommandEntry* commandEntry = postCommandLocked(
  666. & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
  667. if (mFocusedWindowHandle != NULL) {
  668. commandEntry->inputWindowHandle = mFocusedWindowHandle;
  669. }
  670. commandEntry->keyEntry = entry;
  671. entry->refCount += 1;
  672. return false; // wait for the command to run
  673. } else {
  674. entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
  675. }
  676. } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
  677. if (*dropReason == DROP_REASON_NOT_DROPPED) {
  678. *dropReason = DROP_REASON_POLICY;
  679. }
  680. }
  681. // Clean up if dropping the event.
  682. if (*dropReason != DROP_REASON_NOT_DROPPED) {
  683. setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
  684. ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
  685. return true;
  686. }
  687. // Identify targets.
  688. Vector<InputTarget> inputTargets;
  689. int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
  690. entry, inputTargets, nextWakeupTime);
  691. if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
  692. return false;
  693. }
  694. setInjectionResultLocked(entry, injectionResult);
  695. if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
  696. return true;
  697. }
  698. addMonitoringTargetsLocked(inputTargets);
  699. // Dispatch the key.
  700. dispatchEventLocked(currentTime, entry, inputTargets);
  701. return true;
  702. }
  703. void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
  704. #if DEBUG_OUTBOUND_EVENT_DETAILS
  705. ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
  706. "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
  707. "repeatCount=%d, downTime=%lld",
  708. prefix,
  709. entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
  710. entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
  711. entry->repeatCount, entry->downTime);
  712. #endif
  713. }
  714. bool InputDispatcher::dispatchMotionLocked(
  715. nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
  716. // Preprocessing.
  717. if (! entry->dispatchInProgress) {
  718. entry->dispatchInProgress = true;
  719. logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
  720. }
  721. // Clean up if dropping the event.
  722. if (*dropReason != DROP_REASON_NOT_DROPPED) {
  723. setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
  724. ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
  725. return true;
  726. }
  727. bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
  728. // Identify targets.
  729. Vector<InputTarget> inputTargets;
  730. bool conflictingPointerActions = false;
  731. int32_t injectionResult;
  732. if (isPointerEvent) {
  733. // Pointer event. (eg. touchscreen)
  734. injectionResult = findTouchedWindowTargetsLocked(currentTime,
  735. entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
  736. } else {
  737. // Non touch event. (eg. trackball)
  738. injectionResult = findFocusedWindowTargetsLocked(currentTime,
  739. entry, inputTargets, nextWakeupTime);
  740. }
  741. if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
  742. return false;
  743. }
  744. setInjectionResultLocked(entry, injectionResult);
  745. if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
  746. if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
  747. CancelationOptions::Mode mode(isPointerEvent ?
  748. CancelationOptions::CANCEL_POINTER_EVENTS :
  749. CancelationOptions::CANCEL_NON_POINTER_EVENTS);
  750. CancelationOptions options(mode, "input event injection failed");
  751. synthesizeCancelationEventsForMonitorsLocked(options);
  752. }
  753. return true;
  754. }
  755. // TODO: support sending secondary display events to input monitors
  756. if (isMainDisplay(entry->displayId)) {
  757. addMonitoringTargetsLocked(inputTargets);
  758. }
  759. // Dispatch the motion.
  760. if (conflictingPointerActions) {
  761. CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
  762. "conflicting pointer actions");
  763. synthesizeCancelationEventsForAllConnectionsLocked(options);
  764. }
  765. dispatchEventLocked(currentTime, entry, inputTargets);
  766. return true;
  767. }
  768. void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
  769. #if DEBUG_OUTBOUND_EVENT_DETAILS
  770. ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
  771. "action=0x%x, actionButton=0x%x, flags=0x%x, "
  772. "metaState=0x%x, buttonState=0x%x,"
  773. "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
  774. prefix,
  775. entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
  776. entry->action, entry->actionButton, entry->flags,
  777. entry->metaState, entry->buttonState,
  778. entry->edgeFlags, entry->xPrecision, entry->yPrecision,
  779. entry->downTime);
  780. for (uint32_t i = 0; i < entry->pointerCount; i++) {
  781. ALOGD(" Pointer %d: id=%d, toolType=%d, "
  782. "x=%f, y=%f, pressure=%f, size=%f, "
  783. "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
  784. "orientation=%f",
  785. i, entry->pointerProperties[i].id,
  786. entry->pointerProperties[i].toolType,
  787. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
  788. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
  789. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
  790. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
  791. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
  792. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
  793. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
  794. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
  795. entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
  796. }
  797. #endif
  798. }
  799. void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
  800. EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
  801. #if DEBUG_DISPATCH_CYCLE
  802. ALOGD("dispatchEventToCurrentInputTargets");
  803. #endif
  804. ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
  805. pokeUserActivityLocked(eventEntry);
  806. for (size_t i = 0; i < inputTargets.size(); i++) {
  807. const InputTarget& inputTarget = inputTargets.itemAt(i);
  808. ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
  809. if (connectionIndex >= 0) {
  810. sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
  811. prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
  812. } else {
  813. #if DEBUG_FOCUS
  814. ALOGD("Dropping event delivery to target with channel '%s' because it "
  815. "is no longer registered with the input dispatcher.",
  816. inputTarget.inputChannel->getName().string());
  817. #endif
  818. }
  819. }
  820. }
  821. int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
  822. const EventEntry* entry,
  823. const sp<InputApplicationHandle>& applicationHandle,
  824. const sp<InputWindowHandle>& windowHandle,
  825. nsecs_t* nextWakeupTime, const char* reason) {
  826. if (applicationHandle == NULL && windowHandle == NULL) {
  827. if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
  828. #if DEBUG_FOCUS
  829. ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
  830. #endif
  831. mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
  832. mInputTargetWaitStartTime = currentTime;
  833. mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
  834. mInputTargetWaitTimeoutExpired = false;
  835. mInputTargetWaitApplicationHandle.clear();
  836. }
  837. } else {
  838. if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
  839. #if DEBUG_FOCUS
  840. ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
  841. getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
  842. reason);
  843. #endif
  844. nsecs_t timeout;
  845. if (windowHandle != NULL) {
  846. timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
  847. } else if (applicationHandle != NULL) {
  848. timeout = applicationHandle->getDispatchingTimeout(
  849. DEFAULT_INPUT_DISPATCHING_TIMEOUT);
  850. } else {
  851. timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
  852. }
  853. mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
  854. mInputTargetWaitStartTime = currentTime;
  855. mInputTargetWaitTimeoutTime = currentTime + timeout;
  856. mInputTargetWaitTimeoutExpired = false;
  857. mInputTargetWaitApplicationHandle.clear();
  858. if (windowHandle != NULL) {
  859. mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
  860. }
  861. if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
  862. mInputTargetWaitApplicationHandle = applicationHandle;
  863. }
  864. }
  865. }
  866. if (mInputTargetWaitTimeoutExpired) {
  867. return INPUT_EVENT_INJECTION_TIMED_OUT;
  868. }
  869. if (currentTime >= mInputTargetWaitTimeoutTime) {
  870. onANRLocked(currentTime, applicationHandle, windowHandle,
  871. entry->eventTime, mInputTargetWaitStartTime, reason);
  872. // Force poll loop to wake up immediately on next iteration once we get the
  873. // ANR response back from the policy.
  874. *nextWakeupTime = LONG_LONG_MIN;
  875. return INPUT_EVENT_INJECTION_PENDING;
  876. } else {
  877. // Force poll loop to wake up when timeout is due.
  878. if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
  879. *nextWakeupTime = mInputTargetWaitTimeoutTime;
  880. }
  881. return INPUT_EVENT_INJECTION_PENDING;
  882. }
  883. }
  884. void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
  885. const sp<InputChannel>& inputChannel) {
  886. if (newTimeout > 0) {
  887. // Extend the timeout.
  888. mInputTargetWaitTimeoutTime = now() + newTimeout;
  889. } else {
  890. // Give up.
  891. mInputTargetWaitTimeoutExpired = true;
  892. // Input state will not be realistic. Mark it out of sync.
  893. if (inputChannel.get()) {
  894. ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
  895. if (connectionIndex >= 0) {
  896. sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
  897. sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
  898. if (windowHandle != NULL) {
  899. const InputWindowInfo* info = windowHandle->getInfo();
  900. if (info) {
  901. ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
  902. if (stateIndex >= 0) {
  903. mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
  904. windowHandle);
  905. }
  906. }
  907. }
  908. if (connection->status == Connection::STATUS_NORMAL) {
  909. CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
  910. "application not responding");
  911. synthesizeCancelationEventsForConnectionLocked(connection, options);
  912. }
  913. }
  914. }
  915. }
  916. }
  917. nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
  918. nsecs_t currentTime) {
  919. if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
  920. return currentTime - mInputTargetWaitStartTime;
  921. }
  922. return 0;
  923. }
  924. void InputDispatcher::resetANRTimeoutsLocked() {
  925. #if DEBUG_FOCUS
  926. ALOGD("Resetting ANR timeouts.");
  927. #endif
  928. // Reset input target wait timeout.
  929. mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
  930. mInputTargetWaitApplicationHandle.clear();
  931. }
  932. int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
  933. const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
  934. int32_t injectionResult;
  935. String8 reason;
  936. // If there is no currently focused window and no focused application
  937. // then drop the event.
  938. if (mFocusedWindowHandle == NULL) {
  939. if (mFocusedApplicationHandle != NULL) {
  940. injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
  941. mFocusedApplicationHandle, NULL, nextWakeupTime,
  942. "Waiting because no window has focus but there is a "
  943. "focused application that may eventually add a window "
  944. "when it finishes starting up.");
  945. goto Unresponsive;
  946. }
  947. ALOGI("Dropping event because there is no focused window or focused application.");
  948. injectionResult = INPUT_EVENT_INJECTION_FAILED;
  949. goto Failed;
  950. }
  951. // Check permissions.
  952. if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
  953. injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
  954. goto Failed;
  955. }
  956. // Check whether the window is ready for more input.
  957. reason = checkWindowReadyForMoreInputLocked(currentTime,
  958. mFocusedWindowHandle, entry, "focused");
  959. if (!reason.isEmpty()) {
  960. injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
  961. mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.string());
  962. goto Unresponsive;
  963. }
  964. // Success! Output targets.
  965. injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
  966. addWindowTargetLocked(mFocusedWindowHandle,
  967. InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
  968. inputTargets);
  969. // Done.
  970. Failed:
  971. Unresponsive:
  972. nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
  973. updateDispatchStatisticsLocked(currentTime, entry,
  974. injectionResult, timeSpentWaitingForApplication);
  975. #if DEBUG_FOCUS
  976. ALOGD("findFocusedWindow finished: injectionResult=%d, "
  977. "timeSpentWaitingForApplication=%0.1fms",
  978. injectionResult, timeSpentWaitingForApplication / 1000000.0);
  979. #endif
  980. return injectionResult;
  981. }
  982. int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
  983. const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
  984. bool* outConflictingPointerActions) {
  985. enum InjectionPermission {
  986. INJECTION_PERMISSION_UNKNOWN,
  987. INJECTION_PERMISSION_GRANTED,
  988. INJECTION_PERMISSION_DENIED
  989. };
  990. nsecs_t startTime = now();
  991. // For security reasons, we defer updating the touch state until we are sure that
  992. // event injection will be allowed.
  993. int32_t displayId = entry->displayId;
  994. int32_t action = entry->action;
  995. int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
  996. // Update the touch state as needed based on the properties of the touch event.
  997. int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
  998. InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
  999. sp<InputWindowHandle> newHoverWindowHandle;
  1000. // Copy current touch state into mTempTouchState.
  1001. // This state is always reset at the end of this function, so if we don't find state
  1002. // for the specified display then our initial state will be empty.
  1003. const TouchState* oldState = NULL;
  1004. ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
  1005. if (oldStateIndex >= 0) {
  1006. oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
  1007. mTempTouchState.copyFrom(*oldState);
  1008. }
  1009. bool isSplit = mTempTouchState.split;
  1010. bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
  1011. && (mTempTouchState.deviceId != entry->deviceId
  1012. || mTempTouchState.source != entry->source
  1013. || mTempTouchState.displayId != displayId);
  1014. bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
  1015. || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
  1016. || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
  1017. bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
  1018. || maskedAction == AMOTION_EVENT_ACTION_SCROLL
  1019. || isHoverAction);
  1020. bool wrongDevice = false;
  1021. if (newGesture) {
  1022. bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
  1023. if (switchedDevice && mTempTouchState.down && !down) {
  1024. #if DEBUG_FOCUS
  1025. ALOGD("Dropping event because a pointer for a different device is already down.");
  1026. #endif
  1027. injectionResult = INPUT_EVENT_INJECTION_FAILED;
  1028. switchedDevice = false;
  1029. wrongDevice = true;
  1030. goto Failed;
  1031. }
  1032. mTempTouchState.reset();
  1033. mTempTouchState.down = down;
  1034. mTempTouchState.deviceId = entry->deviceId;
  1035. mTempTouchState.source = entry->source;
  1036. mTempTouchState.displayId = displayId;
  1037. isSplit = false;
  1038. }
  1039. if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
  1040. /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
  1041. int32_t pointerIndex = getMotionEventActionPointerIndex(action);
  1042. int32_t x = int32_t(entry->pointerCoords[pointerIndex].
  1043. getAxisValue(AMOTION_EVENT_AXIS_X));
  1044. int32_t y = int32_t(entry->pointerCoords[pointerIndex].
  1045. getAxisValue(AMOTION_EVENT_AXIS_Y));
  1046. sp<InputWindowHandle> newTouchedWindowHandle;
  1047. bool isTouchModal = false;
  1048. // Traverse windows from front to back to find touched window and outside targets.
  1049. size_t numWindows = mWindowHandles.size();
  1050. for (size_t i = 0; i < numWindows; i++) {
  1051. sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
  1052. const InputWindowInfo* windowInfo = windowHandle->getInfo();
  1053. if (windowInfo->displayId != displayId) {
  1054. continue; // wrong display
  1055. }
  1056. int32_t flags = windowInfo->layoutParamsFlags;
  1057. if (windowInfo->visible) {
  1058. if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
  1059. isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
  1060. | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
  1061. if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
  1062. newTouchedWindowHandle = windowHandle;
  1063. break; // found touched window, exit window loop
  1064. }
  1065. }
  1066. if (maskedAction == AMOTION_EVENT_ACTION_DOWN
  1067. && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
  1068. mTempTouchState.addOrUpdateWindow(
  1069. windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
  1070. }
  1071. }
  1072. }
  1073. // Figure out whether splitting will be allowed for this window.
  1074. if (newTouchedWindowHandle != NULL
  1075. && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
  1076. // New window supports splitting.
  1077. isSplit = true;
  1078. } else if (isSplit) {
  1079. // New window does not support splitting but we have already split events.
  1080. // Ignore the new window.
  1081. newTouchedWindowHandle = NULL;
  1082. }
  1083. // Handle the case where we did not find a window.
  1084. if (newTouchedWindowHandle == NULL) {
  1085. // Try to assign the pointer to the first foreground window we find, if there is one.
  1086. newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
  1087. if (newTouchedWindowHandle == NULL) {
  1088. ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
  1089. injectionResult = INPUT_EVENT_INJECTION_FAILED;
  1090. goto Failed;
  1091. }
  1092. }
  1093. // Set target flags.
  1094. int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
  1095. if (isSplit) {
  1096. targetFlags |= InputTarget::FLAG_SPLIT;
  1097. }
  1098. if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
  1099. targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
  1100. } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
  1101. targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
  1102. }
  1103. // Update hover state.
  1104. if (isHoverAction) {
  1105. newHoverWindowHandle = newTouchedWindowHandle;
  1106. } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
  1107. newHoverWindowHandle = mLastHoverWindowHandle;
  1108. }
  1109. // Update the temporary touch state.
  1110. BitSet32 pointerIds;
  1111. if (isSplit) {
  1112. uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
  1113. pointerIds.markBit(pointerId);
  1114. }
  1115. mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
  1116. } else {
  1117. /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
  1118. // If the pointer is not currently down, then ignore the event.
  1119. if (! mTempTouchState.down) {
  1120. #if DEBUG_FOCUS
  1121. ALOGD("Dropping event because the pointer is not down or we previously "
  1122. "dropped the pointer down event.");
  1123. #endif
  1124. injectionResult = INPUT_EVENT_INJECTION_FAILED;
  1125. goto Failed;
  1126. }
  1127. // Check whether touches should slip outside of the current foreground window.
  1128. if (maskedAction == AMOTION_EVENT_ACTION_MOVE
  1129. && entry->pointerCount == 1
  1130. && mTempTouchState.isSlippery()) {
  1131. int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
  1132. int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
  1133. sp<InputWindowHandle> oldTouchedWindowHandle =
  1134. mTempTouchState.getFirstForegroundWindowHandle();
  1135. sp<InputWindowHandle> newTouchedWindowHandle =
  1136. findTouchedWindowAtLocked(displayId, x, y);
  1137. if (oldTouchedWindowHandle != newTouchedWindowHandle
  1138. && newTouchedWindowHandle != NULL) {
  1139. #if DEBUG_FOCUS
  1140. ALOGD("Touch is slipping out of window %s into window %s.",
  1141. oldTouchedWindowHandle->getName().string(),
  1142. newTouchedWindowHandle->getName().string());
  1143. #endif
  1144. // Make a slippery exit from the old window.
  1145. mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
  1146. InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
  1147. // Make a slippery entrance into the new window.
  1148. if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
  1149. isSplit = true;
  1150. }
  1151. int32_t targetFlags = InputTarget::FLAG_FOREGROUND
  1152. | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
  1153. if (isSplit) {
  1154. targetFlags |= InputTarget::FLAG_SPLIT;
  1155. }
  1156. if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
  1157. targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
  1158. }
  1159. BitSet32 pointerIds;
  1160. if (isSplit) {
  1161. pointerIds.markBit(entry->pointerProperties[0].id);
  1162. }
  1163. mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
  1164. }
  1165. }
  1166. }
  1167. if (newHoverWindowHandle != mLastHoverWindowHandle) {
  1168. // Let the previous window know that the hover sequence is over.
  1169. if (mLastHoverWindowHandle != NULL) {
  1170. #if DEBUG_HOVER
  1171. ALOGD("Sending hover exit event to window %s.",
  1172. mLastHoverWindowHandle->getName().string());
  1173. #endif
  1174. mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
  1175. InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
  1176. }
  1177. // Let the new window know that the hover sequence is starting.
  1178. if (newHoverWindowHandle != NULL) {
  1179. #if DEBUG_HOVER
  1180. ALOGD("Sending hover enter event to window %s.",
  1181. newHoverWindowHandle->getName().string());
  1182. #endif
  1183. mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
  1184. InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
  1185. }
  1186. }
  1187. // Check permission to inject into all touched foreground windows and ensure there
  1188. // is at least one touched foreground window.
  1189. {
  1190. bool haveForegroundWindow = false;
  1191. for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
  1192. const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
  1193. if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
  1194. haveForegroundWindow = true;
  1195. if (! checkInjectionPermission(touchedWindow.windowHandle,
  1196. entry->injectionState)) {
  1197. injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
  1198. injectionPermission = INJECTION_PERMISSION_DENIED;
  1199. goto Failed;
  1200. }
  1201. }
  1202. }
  1203. if (! haveForegroundWindow) {
  1204. #if DEBUG_FOCUS
  1205. ALOGD("Dropping event because there is no touched foreground window to receive it.");
  1206. #endif
  1207. injectionResult = INPUT_EVENT_INJECTION_FAILED;
  1208. goto Failed;
  1209. }
  1210. // Permission granted to injection into all touched foreground windows.
  1211. injectionPermission = INJECTION_PERMISSION_GRANTED;
  1212. }
  1213. // Check whether windows listening for outside touches are owned by the same UID. If it is
  1214. // set the policy flag that we will not reveal coordinate information to this window.
  1215. if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
  1216. sp<InputWindowHandle> foregroundWindowHandle =
  1217. mTempTouchState.getFirstForegroundWindowHandle();
  1218. const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
  1219. for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
  1220. const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
  1221. if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
  1222. sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
  1223. if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
  1224. mTempTouchState.addOrUpdateWindow(inputWindowHandle,
  1225. InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
  1226. }
  1227. }
  1228. }
  1229. }
  1230. // Ensure all touched foreground windows are ready for new input.
  1231. for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
  1232. const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
  1233. if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
  1234. // Check whether the window is ready for more input.
  1235. String8 reason = checkWindowReadyForMoreInputLocked(currentTime,
  1236. touchedWindow.windowHandle, entry, "touched");
  1237. if (!reason.isEmpty()) {
  1238. injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
  1239. NULL, touchedWindow.windowHandle, nextWakeupTime, reason.string());
  1240. goto Unresponsive;
  1241. }
  1242. }
  1243. }
  1244. // If this is the first pointer going down and the touched window has a wallpaper
  1245. // then also add the touched wallpaper windows so they are locked in for the duration
  1246. // of the touch gesture.
  1247. // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
  1248. // engine only supports touch events. We would need to add a mechanism similar
  1249. // to View.onGenericMotionEvent to enable wallpapers to handle these events.
  1250. if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
  1251. sp<InputWindowHandle> foregroundWindowHandle =
  1252. mTempTouchState.getFirstForegroundWindowHandle();
  1253. if (foregroundWindowHandle->getInfo()->hasWallpaper) {
  1254. for (size_t i = 0; i < mWindowHandles.size(); i++) {
  1255. sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
  1256. const InputWindowInfo* info = windowHandle->getInfo();
  1257. if (info->displayId == displayId
  1258. && windowHandle->getInfo()->layoutParamsType
  1259. == InputWindowInfo::TYPE_WALLPAPER) {
  1260. mTempTouchState.addOrUpdateWindow(windowHandle,
  1261. InputTarget::FLAG_WINDOW_IS_OBSCURED
  1262. | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
  1263. | InputTarget::FLAG_DISPATCH_AS_IS,
  1264. BitSet32(0));
  1265. }
  1266. }
  1267. }
  1268. }
  1269. // Success! Output targets.
  1270. injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
  1271. for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
  1272. const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
  1273. addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
  1274. touchedWindow.pointerIds, inputTargets);
  1275. }
  1276. // Drop the outside or hover touch windows since we will not care about them
  1277. // in the next iteration.
  1278. mTempTouchState.filterNonAsIsTouchWindows();
  1279. Failed:
  1280. // Check injection permission once and for all.
  1281. if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
  1282. if (checkInjectionPermission(NULL, entry->injectionState)) {
  1283. injectionPermission = INJECTION_PERMISSION_GRANTED;
  1284. } else {
  1285. injectionPermission = INJECTION_PERMISSION_DENIED;
  1286. }
  1287. }
  1288. // Update final pieces of touch state if the injector had permission.
  1289. if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
  1290. if (!wrongDevice) {
  1291. if (switchedDevice) {
  1292. #if DEBUG_FOCUS
  1293. ALOGD("Conflicting pointer actions: Switched to a different device.");
  1294. #endif
  1295. *outConflictingPointerActions = true;
  1296. }
  1297. if (isHoverAction) {
  1298. // Started hovering, therefore no longer down.
  1299. if (oldState && oldState->down) {
  1300. #if DEBUG_FOCUS
  1301. ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
  1302. #endif
  1303. *outConflictingPointerActions = true;
  1304. }
  1305. mTempTouchState.reset();
  1306. if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
  1307. || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
  1308. mTempTouchState.deviceId = entry->deviceId;
  1309. mTempTouchState.source = entry->source;
  1310. mTempTouchState.displayId = displayId;
  1311. }
  1312. } else if (maskedAction == AMOTION_EVENT_ACTION_UP
  1313. || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
  1314. // All pointers up or canceled.
  1315. mTempTouchState.reset();
  1316. } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
  1317. // First pointer went down.
  1318. if (oldState && oldState->down) {
  1319. #if DEBUG_FOCUS
  1320. ALOGD("Conflicting pointer actions: Down received while already down.");
  1321. #endif
  1322. *outConflictingPointerActions = true;
  1323. }
  1324. } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
  1325. // One pointer went up.
  1326. if (isSplit) {
  1327. int32_t pointerIndex = getMotionEventActionPointerIndex(action);
  1328. uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
  1329. for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
  1330. TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
  1331. if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
  1332. touchedWindow.pointerIds.clearBit(pointerId);
  1333. if (touchedWindow.pointerIds.isEmpty()) {
  1334. mTempTouchState.windows.removeAt(i);
  1335. continue;
  1336. }
  1337. }
  1338. i += 1;
  1339. }
  1340. }
  1341. }
  1342. // Save changes unless the action was scroll in which case the temporary touch
  1343. // state was only valid for this one action.
  1344. if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
  1345. if (mTempTouchState.displayId >= 0) {
  1346. if (oldStateIndex >= 0) {
  1347. mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
  1348. } else {
  1349. mTouchStatesByDisplay.add(displayId, mTempTouchState);
  1350. }
  1351. } else if (oldStateIndex >= 0) {
  1352. mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
  1353. }
  1354. }
  1355. // Update hover state.
  1356. mLastHoverWindowHandle = newHoverWindowHandle;
  1357. }
  1358. } else {
  1359. #if DEBUG_FOCUS
  1360. ALOGD("Not updating touch focus because injection was denied.");
  1361. #endif
  1362. }
  1363. Unresponsive:
  1364. // Reset temporary touch state to ensure we release unnecessary references to input channels.
  1365. mTempTouchState.reset();
  1366. nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
  1367. updateDispatchStatisticsLocked(currentTime, entry,
  1368. injectionResult, timeSpentWaitingForApplication);
  1369. #if DEBUG_FOCUS
  1370. ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
  1371. "timeSpentWaitingForApplication=%0.1fms",
  1372. injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
  1373. #endif
  1374. return injectionResult;
  1375. }
  1376. void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
  1377. int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
  1378. inputTargets.push();
  1379. const InputWindowInfo* windowInfo = windowHandle->getInfo();
  1380. InputTarget& target = inputTargets.editTop();
  1381. target.inputChannel = windowInfo->inputChannel;
  1382. target.flags = targetFlags;
  1383. target.xOffset = - windowInfo->frameLeft;
  1384. target.yOffset = - windowInfo->frameTop;
  1385. target.scaleFactor = windowInfo->scaleFactor;
  1386. target.pointerIds = pointerIds;
  1387. }
  1388. void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
  1389. for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
  1390. inputTargets.push();
  1391. InputTarget& target = inputTargets.editTop();
  1392. target.inputChannel = mMonitoringChannels[i];
  1393. target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
  1394. target.xOffset = 0;
  1395. target.yOffset = 0;
  1396. target.pointerIds.clear();
  1397. target.scaleFactor = 1.0f;
  1398. }
  1399. }
  1400. bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
  1401. const InjectionState* injectionState) {
  1402. if (injectionState
  1403. && (windowHandle == NULL
  1404. || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
  1405. && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
  1406. if (windowHandle != NULL) {
  1407. ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
  1408. "owned by uid %d",
  1409. injectionState->injectorPid, injectionState->injectorUid,
  1410. windowHandle->getName().string(),
  1411. windowHandle->getInfo()->ownerUid);
  1412. } else {
  1413. ALOGW("Permission denied: injecting event from pid %d uid %d",
  1414. injectionState->injectorPid, injectionState->injectorUid);
  1415. }
  1416. return false;
  1417. }
  1418. return true;
  1419. }
  1420. bool InputDispatcher::isWindowObscuredAtPointLocked(
  1421. const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
  1422. int32_t displayId = windowHandle->getInfo()->displayId;
  1423. size_t numWindows = mWindowHandles.size();
  1424. for (size_t i = 0; i < numWindows; i++) {
  1425. sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
  1426. if (otherHandle == windowHandle) {
  1427. break;
  1428. }
  1429. const InputWindowInfo* otherInfo = otherHandle->getInfo();
  1430. if (otherInfo->displayId == displayId
  1431. && otherInfo->visible && !otherInfo->isTrustedOverlay()
  1432. && otherInfo->frameContainsPoint(x, y)) {
  1433. return true;
  1434. }
  1435. }
  1436. return false;
  1437. }
  1438. bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
  1439. int32_t displayId = windowHandle->getInfo()->displayId;
  1440. const InputWindowInfo* windowInfo = windowHandle->getInfo();
  1441. size_t numWindows = mWindowHandles.size();
  1442. for (size_t i = 0; i < numWindows; i++) {
  1443. sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
  1444. if (otherHandle == windowHandle) {
  1445. break;
  1446. }
  1447. const InputWindowInfo* otherInfo = otherHandle->getInfo();
  1448. if (otherInfo->displayId == displayId
  1449. && otherInfo->visible && !otherInfo->isTrustedOverlay()
  1450. && otherInfo->overlaps(windowInfo)) {
  1451. return true;
  1452. }
  1453. }
  1454. return false;
  1455. }
  1456. String8 InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
  1457. const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
  1458. const char* targetType) {
  1459. // If the window is paused then keep waiting.
  1460. if (windowHandle->getInfo()->paused) {
  1461. return String8::format("Waiting because the %s window is paused.", targetType);
  1462. }
  1463. // If the window's connection is not registered then keep waiting.
  1464. ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
  1465. if (connectionIndex < 0) {
  1466. return String8::format("Waiting because the %s window's input channel is not "
  1467. "registered with the input dispatcher. The window may be in the process "
  1468. "of being removed.", targetType);
  1469. }
  1470. // If the connection is dead then keep waiting.
  1471. sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
  1472. if (connection->status != Connection::STATUS_NORMAL) {
  1473. return String8::format("Waiting because the %s window's input connection is %s."
  1474. "The window may be in the process of being removed.", targetType,
  1475. connection->getStatusLabel());
  1476. }
  1477. // If the connection is backed up then keep waiting.
  1478. if (connection->inputPublisherBlocked) {
  1479. return String8::format("Waiting because the %s window's input channel is full. "
  1480. "Outbound queue length: %d. Wait queue length: %d.",
  1481. targetType, connection->outboundQueue.count(), connection->waitQueue.count());
  1482. }
  1483. // Ensure that the dispatch queues aren't too far backed up for this event.
  1484. if (eventEntry->type == EventEntry::TYPE_KEY) {
  1485. // If the event is a key event, then we must wait for all previous events to
  1486. // complete before delivering it because previous events may have the
  1487. // side-effect of transferring focus to a different window and we want to
  1488. // ensure that the following keys are sent to the new window.
  1489. //
  1490. // Suppose the user touches a button in a window then immediately presses "A".
  1491. // If the button causes a pop-up window to appear then we want to ensure that
  1492. // the "A" key is delivered to the new pop-up window. This is because users
  1493. // often anticipate pending UI changes when typing on a keyboard.
  1494. // To obtain this behavior, we must serialize key events with respect to all
  1495. // prior input events.
  1496. if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
  1497. return String8::format("Waiting to send key event because the %s window has not "
  1498. "finished processing all of the input events that were previously "
  1499. "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
  1500. targetType, connection->outboundQueue.count(), connection->waitQueue.count());
  1501. }
  1502. } else {
  1503. // Touch events can always be sent to a window immediately because the user intended
  1504. // to touch whatever was visible at the time. Even if focus changes or a new
  1505. // window appears moments later, the touch event was meant to be delivered to
  1506. // whatever window happened to be on screen at the time.
  1507. //
  1508. // Generic motion events, such as trackball or joystick events are a little trickier.
  1509. // Like key events, generic motion events are delivered to the focused window.
  1510. // Unlike key events, generic motion events don't tend to transfer focus to other
  1511. // windows and it is not important for them to be serialized. So we prefer to deliver
  1512. // generic motion events as soon as possible to improve efficiency and reduce lag
  1513. // through batching.
  1514. //
  1515. // The one case where we pause input event delivery is when the wait queue is piling
  1516. // up with lots of events because the application is not responding.
  1517. // This condition ensures that ANRs are detected reliably.
  1518. if (!connection->waitQueue.isEmpty()
  1519. && currentTime >= connection->waitQueue.head->deliveryTime
  1520. + STREAM_AHEAD_EVENT_TIMEOUT) {
  1521. return String8::format("Waiting to send non-key event because the %s window has not "
  1522. "finished processing certain input events that were delivered to it over "
  1523. "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
  1524. targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
  1525. connection->waitQueue.count(),
  1526. (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
  1527. }
  1528. }
  1529. return String8::empty();
  1530. }
  1531. String8 InputDispatcher::getApplicationWindowLabelLocked(
  1532. const sp<InputApplicationHandle>& applicationHandle,
  1533. const sp<InputWindowHandle>& windowHandle) {
  1534. if (applicationHandle != NULL) {
  1535. if (windowHandle != NULL) {
  1536. String8 label(applicationHandle->getName());
  1537. label.append(" - ");
  1538. label.append(windowHandle->getName());
  1539. return label;
  1540. } else {
  1541. return applicationHandle->getName();
  1542. }
  1543. } else if (windowHandle != NULL) {
  1544. return windowHandle->getName();
  1545. } else {
  1546. return String8("<unknown application or window>");
  1547. }
  1548. }
  1549. void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
  1550. if (mFocusedWindowHandle != NULL) {
  1551. const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
  1552. if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
  1553. #if DEBUG_DISPATCH_CYCLE
  1554. ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
  1555. #endif
  1556. return;
  1557. }
  1558. }
  1559. int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
  1560. switch (eventEntry->type) {
  1561. case EventEntry::TYPE_MOTION: {
  1562. const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
  1563. if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
  1564. return;
  1565. }
  1566. if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
  1567. eventType = USER_ACTIVITY_EVENT_TOUCH;
  1568. }
  1569. break;
  1570. }
  1571. case EventEntry::TYPE_KEY: {
  1572. const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
  1573. if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
  1574. return;
  1575. }
  1576. eventType = USER_ACTIVITY_EVENT_BUTTON;
  1577. break;
  1578. }
  1579. }
  1580. CommandEntry* commandEntry = postCommandLocked(
  1581. & InputDispatcher::doPokeUserActivityLockedInterruptible);
  1582. commandEntry->eventTime = eventEntry->eventTime;
  1583. commandEntry->userActivityEventType = eventType;
  1584. }
  1585. void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
  1586. const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
  1587. #if DEBUG_DISPATCH_CYCLE
  1588. ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
  1589. "xOffset=%f, yOffset=%f, scaleFactor=%f, "
  1590. "pointerIds=0x%x",
  1591. connection->getInputChannelName(), inputTarget->flags,
  1592. inputTarget->xOffset, inputTarget->yOffset,
  1593. inputTarget->scaleFactor, inputTarget->pointerIds.value);
  1594. #endif
  1595. // Skip this event if the connection status is not normal.
  1596. // We don't want to enqueue additional outbound events if the connection is broken.
  1597. if (connection->status != Connection::STATUS_NORMAL) {
  1598. #if DEBUG_DISPATCH_CYCLE
  1599. ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
  1600. connection->getInputChannelName(), connection->getStatusLabel());
  1601. #endif
  1602. return;
  1603. }
  1604. // Split a motion event if needed.
  1605. if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
  1606. ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
  1607. MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
  1608. if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
  1609. MotionEntry* splitMotionEntry = splitMotionEvent(
  1610. originalMotionEntry, inputTarget->pointerIds);
  1611. if (!splitMotionEntry) {
  1612. return; // split event was dropped
  1613. }
  1614. #if DEBUG_FOCUS
  1615. ALOGD("channel '%s' ~ Split motion event.",
  1616. connection->getInputChannelName());
  1617. logOutboundMotionDetailsLocked(" ", splitMotionEntry);
  1618. #endif
  1619. enqueueDispatchEntriesLocked(currentTime, connection,
  1620. splitMotionEntry, inputTarget);
  1621. splitMotionEntry->release();
  1622. return;
  1623. }
  1624. }
  1625. // Not splitting. Enqueue dispatch entries for the event as is.
  1626. enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
  1627. }
  1628. void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
  1629. const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
  1630. bool wasEmpty = connection->outboundQueue.isEmpty();
  1631. // Enqueue dispatch entries for the requested modes.
  1632. enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
  1633. InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
  1634. enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
  1635. InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
  1636. enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
  1637. InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
  1638. enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
  1639. InputTarget::FLAG_DISPATCH_AS_IS);
  1640. enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
  1641. InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
  1642. enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
  1643. InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
  1644. // If the outbound queue was previously empty, start the dispatch cycle going.
  1645. if (wasEmpty && !connection->outboundQueue.isEmpty()) {
  1646. startDispatchCycleLocked(currentTime, connection);
  1647. }
  1648. }
  1649. void InputDispatcher::enqueueDispatchEntryLocked(
  1650. const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
  1651. int32_t dispatchMode) {
  1652. int32_t inputTargetFlags = inputTarget->flags;
  1653. if (!(inputTargetFlags & dispatchMode)) {
  1654. return;
  1655. }
  1656. inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
  1657. // This is a new event.
  1658. // Enqueue a new dispatch entry onto the outbound queue for this connection.
  1659. DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
  1660. inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
  1661. inputTarget->scaleFactor);
  1662. // Apply target flags and update the connection's input state.
  1663. switch (eventEntry->type) {
  1664. case EventEntry::TYPE_KEY: {
  1665. KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
  1666. dispatchEntry->resolvedAction = keyEntry->action;
  1667. dispatchEntry->resolvedFlags = keyEntry->flags;
  1668. if (!connection->inputState.trackKey(keyEntry,
  1669. dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
  1670. #if DEBUG_DISPATCH_CYCLE
  1671. ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
  1672. connection->getInputChannelName());
  1673. #endif
  1674. delete dispatchEntry;
  1675. return; // skip the inconsistent event
  1676. }
  1677. break;
  1678. }
  1679. case EventEntry::TYPE_MOTION: {
  1680. MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
  1681. if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
  1682. dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
  1683. } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
  1684. dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
  1685. } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
  1686. dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
  1687. } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
  1688. dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
  1689. } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
  1690. dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
  1691. } else {
  1692. dispatchEntry->resolvedAction = motionEntry->action;
  1693. }
  1694. if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
  1695. && !connection->inputState.isHovering(
  1696. motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
  1697. #if DEBUG_DISPATCH_CYCLE
  1698. ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
  1699. connection->getInputChannelName());
  1700. #endif
  1701. dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
  1702. }
  1703. dispatchEntry->resolvedFlags = motionEntry->flags;
  1704. if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
  1705. dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
  1706. }
  1707. if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
  1708. dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
  1709. }
  1710. if (!connection->inputState.trackMotion(motionEntry,
  1711. dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
  1712. #if DEBUG_DISPATCH_CYCLE
  1713. ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
  1714. connection->getInputChannelName());
  1715. #endif
  1716. delete dispatchEntry;
  1717. return; // skip the inconsistent event
  1718. }
  1719. break;
  1720. }
  1721. }
  1722. // Remember that we are waiting for this dispatch to complete.
  1723. if (dispatchEntry->hasForegroundTarget()) {
  1724. incrementPendingForegroundDispatchesLocked(eventEntry);
  1725. }
  1726. // Enqueue the dispatch entry.
  1727. connection->outboundQueue.enqueueAtTail(dispatchEntry);
  1728. traceOutboundQueueLengthLocked(connection);
  1729. }
  1730. void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
  1731. const sp<Connection>& connection) {
  1732. #if DEBUG_DISPATCH_CYCLE
  1733. ALOGD("channel '%s' ~ startDispatchCycle",
  1734. connection->getInputChannelName());
  1735. #endif
  1736. while (connection->status == Connection::STATUS_NORMAL
  1737. && !connection->outboundQueue.isEmpty()) {
  1738. DispatchEntry* dispatchEntry = connection->outboundQueue.head;
  1739. dispatchEntry->deliveryTime = currentTime;
  1740. // Publish the event.
  1741. status_t status;
  1742. EventEntry* eventEntry = dispatchEntry->eventEntry;
  1743. switch (eventEntry->type) {
  1744. case EventEntry::TYPE_KEY: {
  1745. KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
  1746. // Publish the key event.
  1747. status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
  1748. keyEntry->deviceId, keyEntry->source,
  1749. dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
  1750. keyEntry->keyCode, keyEntry->scanCode,
  1751. keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
  1752. keyEntry->eventTime);
  1753. break;
  1754. }
  1755. case EventEntry::TYPE_MOTION: {
  1756. MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
  1757. PointerCoords scaledCoords[MAX_POINTERS];
  1758. const PointerCoords* usingCoords = motionEntry->pointerCoords;
  1759. // Set the X and Y offset depending on the input source.
  1760. float xOffset, yOffset, scaleFactor;
  1761. if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
  1762. && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
  1763. scaleFactor = dispatchEntry->scaleFactor;
  1764. xOffset = dispatchEntry->xOffset * scaleFactor;
  1765. yOffset = dispatchEntry->yOffset * scaleFactor;
  1766. if (scaleFactor != 1.0f) {
  1767. for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
  1768. scaledCoords[i] = motionEntry->pointerCoords[i];
  1769. scaledCoords[i].scale(scaleFactor);
  1770. }
  1771. usingCoords = scaledCoords;
  1772. }
  1773. } else {
  1774. xOffset = 0.0f;
  1775. yOffset = 0.0f;
  1776. scaleFactor = 1.0f;
  1777. // We don't want the dispatch target to know.
  1778. if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
  1779. for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
  1780. scaledCoords[i].clear();
  1781. }
  1782. usingCoords = scaledCoords;
  1783. }
  1784. }
  1785. // Publish the motion event.
  1786. status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
  1787. motionEntry->deviceId, motionEntry->source,
  1788. dispatchEntry->resolvedAction, motionEntry->actionButton,
  1789. dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
  1790. motionEntry->metaState, motionEntry->buttonState,
  1791. xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
  1792. motionEntry->downTime, motionEntry->eventTime,
  1793. motionEntry->pointerCount, motionEntry->pointerProperties,
  1794. usingCoords);
  1795. break;
  1796. }
  1797. default:
  1798. ALOG_ASSERT(false);
  1799. return;
  1800. }
  1801. // Check the result.
  1802. if (status) {
  1803. if (status == WOULD_BLOCK) {
  1804. if (connection->waitQueue.isEmpty()) {
  1805. ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
  1806. "This is unexpected because the wait queue is empty, so the pipe "
  1807. "should be empty and we shouldn't have any problems writing an "
  1808. "event to it, status=%d", connection->getInputChannelName(), status);
  1809. abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
  1810. } else {
  1811. // Pipe is full and we are waiting for the app to finish process some events
  1812. // before sending more events to it.
  1813. #if DEBUG_DISPATCH_CYCLE
  1814. ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
  1815. "waiting for the application to catch up",
  1816. connection->getInputChannelName());
  1817. #endif
  1818. connection->inputPublisherBlocked = true;
  1819. }
  1820. } else {
  1821. ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
  1822. "status=%d", connection->getInputChannelName(), status);
  1823. abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
  1824. }
  1825. return;
  1826. }
  1827. // Re-enqueue the event on the wait queue.
  1828. connection->outboundQueue.dequeue(dispatchEntry);
  1829. traceOutboundQueueLengthLocked(connection);
  1830. connection->waitQueue.enqueueAtTail(dispatchEntry);
  1831. traceWaitQueueLengthLocked(connection);
  1832. }
  1833. }
  1834. void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
  1835. const sp<Connection>& connection, uint32_t seq, bool handled) {
  1836. #if DEBUG_DISPATCH_CYCLE
  1837. ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
  1838. connection->getInputChannelName(), seq, toString(handled));
  1839. #endif
  1840. connection->inputPublisherBlocked = false;
  1841. if (connection->status == Connection::STATUS_BROKEN
  1842. || connection->status == Connection::STATUS_ZOMBIE) {
  1843. return;
  1844. }
  1845. // Notify other system components and prepare to start the next dispatch cycle.
  1846. onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
  1847. }
  1848. void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
  1849. const sp<Connection>& connection, bool notify) {
  1850. #if DEBUG_DISPATCH_CYCLE
  1851. ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
  1852. connection->getInputChannelName(), toString(notify));
  1853. #endif
  1854. // Clear the dispatch queues.
  1855. drainDispatchQueueLocked(&connection->outboundQueue);
  1856. traceOutboundQueueLengthLocked(connection);
  1857. drainDispatchQueueLocked(&connection->waitQueue);
  1858. traceWaitQueueLengthLocked(connection);
  1859. // The connection appears to be unrecoverably broken.
  1860. // Ignore already broken or zombie connections.
  1861. if (connection->status == Connection::STATUS_NORMAL) {
  1862. connection->status = Connection::STATUS_BROKEN;
  1863. if (notify) {
  1864. // Notify other system components.
  1865. onDispatchCycleBrokenLocked(currentTime, connection);
  1866. }
  1867. }
  1868. }
  1869. void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
  1870. while (!queue->isEmpty()) {
  1871. DispatchEntry* dispatchEntry = queue->dequeueAtHead();
  1872. releaseDispatchEntryLocked(dispatchEntry);
  1873. }
  1874. }
  1875. void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
  1876. if (dispatchEntry->hasForegroundTarget()) {
  1877. decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
  1878. }
  1879. delete dispatchEntry;
  1880. }
  1881. int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
  1882. InputDispatcher* d = static_cast<InputDispatcher*>(data);
  1883. { // acquire lock
  1884. AutoMutex _l(d->mLock);
  1885. ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
  1886. if (connectionIndex < 0) {
  1887. ALOGE("Received spurious receive callback for unknown input channel. "
  1888. "fd=%d, events=0x%x", fd, events);
  1889. return 0; // remove the callback
  1890. }
  1891. bool notify;
  1892. sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
  1893. if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
  1894. if (!(events & ALOOPER_EVENT_INPUT)) {
  1895. ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
  1896. "events=0x%x", connection->getInputChannelName(), events);
  1897. return 1;
  1898. }
  1899. nsecs_t currentTime = now();
  1900. bool gotOne = false;
  1901. status_t status;
  1902. for (;;) {
  1903. uint32_t seq;
  1904. bool handled;
  1905. status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
  1906. if (status) {
  1907. break;
  1908. }
  1909. d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
  1910. gotOne = true;
  1911. }
  1912. if (gotOne) {
  1913. d->runCommandsLockedInterruptible();
  1914. if (status == WOULD_BLOCK) {
  1915. return 1;
  1916. }
  1917. }
  1918. notify = status != DEAD_OBJECT || !connection->monitor;
  1919. if (notify) {
  1920. ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
  1921. connection->getInputChannelName(), status);
  1922. }
  1923. } else {
  1924. // Monitor channels are never explicitly unregistered.
  1925. // We do it automatically when the remote endpoint is closed so don't warn
  1926. // about them.
  1927. notify = !connection->monitor;
  1928. if (notify) {
  1929. ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
  1930. "events=0x%x", connection->getInputChannelName(), events);
  1931. }
  1932. }
  1933. // Unregister the channel.
  1934. d->unregisterInputChannelLocked(connection->inputChannel, notify);
  1935. return 0; // remove the callback
  1936. } // release lock
  1937. }
  1938. void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
  1939. const CancelationOptions& options) {
  1940. for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
  1941. synthesizeCancelationEventsForConnectionLocked(
  1942. mConnectionsByFd.valueAt(i), options);
  1943. }
  1944. }
  1945. void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
  1946. const CancelationOptions& options) {
  1947. for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
  1948. synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
  1949. }
  1950. }
  1951. void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
  1952. const sp<InputChannel>& channel, const CancelationOptions& options) {
  1953. ssize_t index = getConnectionIndexLocked(channel);
  1954. if (index >= 0) {
  1955. synthesizeCancelationEventsForConnectionLocked(
  1956. mConnectionsByFd.valueAt(index), options);
  1957. }
  1958. }
  1959. void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
  1960. const sp<Connection>& connection, const CancelationOptions& options) {
  1961. if (connection->status == Connection::STATUS_BROKEN) {
  1962. return;
  1963. }
  1964. nsecs_t currentTime = now();
  1965. Vector<EventEntry*> cancelationEvents;
  1966. connection->inputState.synthesizeCancelationEvents(currentTime,
  1967. cancelationEvents, options);
  1968. if (!cancelationEvents.isEmpty()) {
  1969. #if DEBUG_OUTBOUND_EVENT_DETAILS
  1970. ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
  1971. "with reality: %s, mode=%d.",
  1972. connection->getInputChannelName(), cancelationEvents.size(),
  1973. options.reason, options.mode);
  1974. #endif
  1975. for (size_t i = 0; i < cancelationEvents.size(); i++) {
  1976. EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
  1977. switch (cancelationEventEntry->type) {
  1978. case EventEntry::TYPE_KEY:
  1979. logOutboundKeyDetailsLocked("cancel - ",
  1980. static_cast<KeyEntry*>(cancelationEventEntry));
  1981. break;
  1982. case EventEntry::TYPE_MOTION:
  1983. logOutboundMotionDetailsLocked("cancel - ",
  1984. static_cast<MotionEntry*>(cancelationEventEntry));
  1985. break;
  1986. }
  1987. InputTarget target;
  1988. sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
  1989. if (windowHandle != NULL) {
  1990. const InputWindowInfo* windowInfo = windowHandle->getInfo();
  1991. target.xOffset = -windowInfo->frameLeft;
  1992. target.yOffset = -windowInfo->frameTop;
  1993. target.scaleFactor = windowInfo->scaleFactor;
  1994. } else {
  1995. target.xOffset = 0;
  1996. target.yOffset = 0;
  1997. target.scaleFactor = 1.0f;
  1998. }
  1999. target.inputChannel = connection->inputChannel;
  2000. target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
  2001. enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
  2002. &target, InputTarget::FLAG_DISPATCH_AS_IS);
  2003. cancelationEventEntry->release();
  2004. }
  2005. startDispatchCycleLocked(currentTime, connection);
  2006. }
  2007. }
  2008. InputDispatcher::MotionEntry*
  2009. InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
  2010. ALOG_ASSERT(pointerIds.value != 0);
  2011. uint32_t splitPointerIndexMap[MAX_POINTERS];
  2012. PointerProperties splitPointerProperties[MAX_POINTERS];
  2013. PointerCoords splitPointerCoords[MAX_POINTERS];
  2014. uint32_t originalPointerCount = originalMotionEntry->pointerCount;
  2015. uint32_t splitPointerCount = 0;
  2016. for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
  2017. originalPointerIndex++) {
  2018. const PointerProperties& pointerProperties =
  2019. originalMotionEntry->pointerProperties[originalPointerIndex];
  2020. uint32_t pointerId = uint32_t(pointerProperties.id);
  2021. if (pointerIds.hasBit(pointerId)) {
  2022. splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
  2023. splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
  2024. splitPointerCoords[splitPointerCount].copyFrom(
  2025. originalMotionEntry->pointerCoords[originalPointerIndex]);
  2026. splitPointerCount += 1;
  2027. }
  2028. }
  2029. if (splitPointerCount != pointerIds.count()) {
  2030. // This is bad. We are missing some of the pointers that we expected to deliver.
  2031. // Most likely this indicates that we received an ACTION_MOVE events that has
  2032. // different pointer ids than we expected based on the previous ACTION_DOWN
  2033. // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
  2034. // in this way.
  2035. ALOGW("Dropping split motion event because the pointer count is %d but "
  2036. "we expected there to be %d pointers. This probably means we received "
  2037. "a broken sequence of pointer ids from the input device.",
  2038. splitPointerCount, pointerIds.count());
  2039. return NULL;
  2040. }
  2041. int32_t action = originalMotionEntry->action;
  2042. int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
  2043. if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
  2044. || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
  2045. int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
  2046. const PointerProperties& pointerProperties =
  2047. originalMotionEntry->pointerProperties[originalPointerIndex];
  2048. uint32_t pointerId = uint32_t(pointerProperties.id);
  2049. if (pointerIds.hasBit(pointerId)) {
  2050. if (pointerIds.count() == 1) {
  2051. // The first/last pointer went down/up.
  2052. action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
  2053. ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
  2054. } else {
  2055. // A secondary pointer went down/up.
  2056. uint32_t splitPointerIndex = 0;
  2057. while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
  2058. splitPointerIndex += 1;
  2059. }
  2060. action = maskedAction | (splitPointerIndex
  2061. << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
  2062. }
  2063. } else {
  2064. // An unrelated pointer changed.
  2065. action = AMOTION_EVENT_ACTION_MOVE;
  2066. }
  2067. }
  2068. MotionEntry* splitMotionEntry = new MotionEntry(
  2069. originalMotionEntry->eventTime,
  2070. originalMotionEntry->deviceId,
  2071. originalMotionEntry->source,
  2072. originalMotionEntry->policyFlags,
  2073. action,
  2074. originalMotionEntry->actionButton,
  2075. originalMotionEntry->flags,
  2076. originalMotionEntry->metaState,
  2077. originalMotionEntry->buttonState,
  2078. originalMotionEntry->edgeFlags,
  2079. originalMotionEntry->xPrecision,
  2080. originalMotionEntry->yPrecision,
  2081. originalMotionEntry->downTime,
  2082. originalMotionEntry->displayId,
  2083. splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
  2084. if (originalMotionEntry->injectionState) {
  2085. splitMotionEntry->injectionState = originalMotionEntry->injectionState;
  2086. splitMotionEntry->injectionState->refCount += 1;
  2087. }
  2088. return splitMotionEntry;
  2089. }
  2090. void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
  2091. #if DEBUG_INBOUND_EVENT_DETAILS
  2092. ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
  2093. #endif
  2094. bool needWake;
  2095. { // acquire lock
  2096. AutoMutex _l(mLock);
  2097. ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
  2098. needWake = enqueueInboundEventLocked(newEntry);
  2099. } // release lock
  2100. if (needWake) {
  2101. mLooper->wake();
  2102. }
  2103. }
  2104. void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
  2105. #if DEBUG_INBOUND_EVENT_DETAILS
  2106. ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
  2107. "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
  2108. args->eventTime, args->deviceId, args->source, args->policyFlags,
  2109. args->action, args->flags, args->keyCode, args->scanCode,
  2110. args->metaState, args->downTime);
  2111. #endif
  2112. if (!validateKeyEvent(args->action)) {
  2113. return;
  2114. }
  2115. uint32_t policyFlags = args->policyFlags;
  2116. int32_t flags = args->flags;
  2117. int32_t metaState = args->metaState;
  2118. if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
  2119. policyFlags |= POLICY_FLAG_VIRTUAL;
  2120. flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
  2121. }
  2122. if (policyFlags & POLICY_FLAG_FUNCTION) {
  2123. metaState |= AMETA_FUNCTION_ON;
  2124. }
  2125. policyFlags |= POLICY_FLAG_TRUSTED;
  2126. int32_t keyCode = args->keyCode;
  2127. if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
  2128. int32_t newKeyCode = AKEYCODE_UNKNOWN;
  2129. if (keyCode == AKEYCODE_DEL) {
  2130. newKeyCode = AKEYCODE_BACK;
  2131. } else if (keyCode == AKEYCODE_ENTER) {
  2132. newKeyCode = AKEYCODE_HOME;
  2133. }
  2134. if (newKeyCode != AKEYCODE_UNKNOWN) {
  2135. AutoMutex _l(mLock);
  2136. struct KeyReplacement replacement = {keyCode, args->deviceId};
  2137. mReplacedKeys.add(replacement, newKeyCode);
  2138. keyCode = newKeyCode;
  2139. metaState &= ~AMETA_META_ON;
  2140. }
  2141. } else if (args->action == AKEY_EVENT_ACTION_UP) {
  2142. // In order to maintain a consistent stream of up and down events, check to see if the key
  2143. // going up is one we've replaced in a down event and haven't yet replaced in an up event,
  2144. // even if the modifier was released between the down and the up events.
  2145. AutoMutex _l(mLock);
  2146. struct KeyReplacement replacement = {keyCode, args->deviceId};
  2147. ssize_t index = mReplacedKeys.indexOfKey(replacement);
  2148. if (index >= 0) {
  2149. keyCode = mReplacedKeys.valueAt(index);
  2150. mReplacedKeys.removeItemsAt(index);
  2151. metaState &= ~AMETA_META_ON;
  2152. }
  2153. }
  2154. KeyEvent event;
  2155. event.initialize(args->deviceId, args->source, args->action,
  2156. flags, keyCode, args->scanCode, metaState, 0,
  2157. args->downTime, args->eventTime);
  2158. mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
  2159. bool needWake;
  2160. { // acquire lock
  2161. mLock.lock();
  2162. if (shouldSendKeyToInputFilterLocked(args)) {
  2163. mLock.unlock();
  2164. policyFlags |= POLICY_FLAG_FILTERED;
  2165. if (!mPolicy->filterInputEvent(&event, policyFlags)) {
  2166. return; // event was consumed by the filter
  2167. }
  2168. mLock.lock();
  2169. }
  2170. int32_t repeatCount = 0;
  2171. KeyEntry* newEntry = new KeyEntry(args->eventTime,
  2172. args->deviceId, args->source, policyFlags,
  2173. args->action, flags, keyCode, args->scanCode,
  2174. metaState, repeatCount, args->downTime);
  2175. needWake = enqueueInboundEventLocked(newEntry);
  2176. mLock.unlock();
  2177. } // release lock
  2178. if (needWake) {
  2179. mLooper->wake();
  2180. }
  2181. }
  2182. bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
  2183. return mInputFilterEnabled;
  2184. }
  2185. void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
  2186. #if DEBUG_INBOUND_EVENT_DETAILS
  2187. ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
  2188. "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
  2189. "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
  2190. args->eventTime, args->deviceId, args->source, args->policyFlags,
  2191. args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
  2192. args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
  2193. for (uint32_t i = 0; i < args->pointerCount; i++) {
  2194. ALOGD(" Pointer %d: id=%d, toolType=%d, "
  2195. "x=%f, y=%f, pressure=%f, size=%f, "
  2196. "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
  2197. "orientation=%f",
  2198. i, args->pointerProperties[i].id,
  2199. args->pointerProperties[i].toolType,
  2200. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
  2201. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
  2202. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
  2203. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
  2204. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
  2205. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
  2206. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
  2207. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
  2208. args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
  2209. }
  2210. #endif
  2211. if (!validateMotionEvent(args->action, args->actionButton,
  2212. args->pointerCount, args->pointerProperties)) {
  2213. return;
  2214. }
  2215. uint32_t policyFlags = args->policyFlags;
  2216. policyFlags |= POLICY_FLAG_TRUSTED;
  2217. mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
  2218. bool needWake;
  2219. { // acquire lock
  2220. mLock.lock();
  2221. if (shouldSendMotionToInputFilterLocked(args)) {
  2222. mLock.unlock();
  2223. MotionEvent event;
  2224. event.initialize(args->deviceId, args->source, args->action, args->actionButton,
  2225. args->flags, args->edgeFlags, args->metaState, args->buttonState,
  2226. 0, 0, args->xPrecision, args->yPrecision,
  2227. args->downTime, args->eventTime,
  2228. args->pointerCount, args->pointerProperties, args->pointerCoords);
  2229. policyFlags |= POLICY_FLAG_FILTERED;
  2230. if (!mPolicy->filterInputEvent(&event, policyFlags)) {
  2231. return; // event was consumed by the filter
  2232. }
  2233. mLock.lock();
  2234. }
  2235. // Just enqueue a new motion event.
  2236. MotionEntry* newEntry = new MotionEntry(args->eventTime,
  2237. args->deviceId, args->source, policyFlags,
  2238. args->action, args->actionButton, args->flags,
  2239. args->metaState, args->buttonState,
  2240. args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
  2241. args->displayId,
  2242. args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
  2243. needWake = enqueueInboundEventLocked(newEntry);
  2244. mLock.unlock();
  2245. } // release lock
  2246. if (needWake) {
  2247. mLooper->wake();
  2248. }
  2249. }
  2250. bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
  2251. // TODO: support sending secondary display events to input filter
  2252. return mInputFilterEnabled && isMainDisplay(args->displayId);
  2253. }
  2254. void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
  2255. #if DEBUG_INBOUND_EVENT_DETAILS
  2256. ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
  2257. args->eventTime, args->policyFlags,
  2258. args->switchValues, args->switchMask);
  2259. #endif
  2260. uint32_t policyFlags = args->policyFlags;
  2261. policyFlags |= POLICY_FLAG_TRUSTED;
  2262. mPolicy->notifySwitch(args->eventTime,
  2263. args->switchValues, args->switchMask, policyFlags);
  2264. }
  2265. void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
  2266. #if DEBUG_INBOUND_EVENT_DETAILS
  2267. ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
  2268. args->eventTime, args->deviceId);
  2269. #endif
  2270. bool needWake;
  2271. { // acquire lock
  2272. AutoMutex _l(mLock);
  2273. DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
  2274. needWake = enqueueInboundEventLocked(newEntry);
  2275. } // release lock
  2276. if (needWake) {
  2277. mLooper->wake();
  2278. }
  2279. }
  2280. int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
  2281. int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
  2282. uint32_t policyFlags) {
  2283. #if DEBUG_INBOUND_EVENT_DETAILS
  2284. ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
  2285. "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
  2286. event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
  2287. #endif
  2288. nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
  2289. policyFlags |= POLICY_FLAG_INJECTED;
  2290. if (hasInjectionPermission(injectorPid, injectorUid)) {
  2291. policyFlags |= POLICY_FLAG_TRUSTED;
  2292. }
  2293. EventEntry* firstInjectedEntry;
  2294. EventEntry* lastInjectedEntry;
  2295. switch (event->getType()) {
  2296. case AINPUT_EVENT_TYPE_KEY: {
  2297. const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
  2298. int32_t action = keyEvent->getAction();
  2299. if (! validateKeyEvent(action)) {
  2300. return INPUT_EVENT_INJECTION_FAILED;
  2301. }
  2302. int32_t flags = keyEvent->getFlags();
  2303. if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
  2304. policyFlags |= POLICY_FLAG_VIRTUAL;
  2305. }
  2306. if (!(policyFlags & POLICY_FLAG_FILTERED)) {
  2307. mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
  2308. }
  2309. mLock.lock();
  2310. firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
  2311. keyEvent->getDeviceId(), keyEvent->getSource(),
  2312. policyFlags, action, flags,
  2313. keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
  2314. keyEvent->getRepeatCount(), keyEvent->getDownTime());
  2315. lastInjectedEntry = firstInjectedEntry;
  2316. break;
  2317. }
  2318. case AINPUT_EVENT_TYPE_MOTION: {
  2319. const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
  2320. int32_t action = motionEvent->getAction();
  2321. size_t pointerCount = motionEvent->getPointerCount();
  2322. const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
  2323. int32_t actionButton = motionEvent->getActionButton();
  2324. if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
  2325. return INPUT_EVENT_INJECTION_FAILED;
  2326. }
  2327. if (!(policyFlags & POLICY_FLAG_FILTERED)) {
  2328. nsecs_t eventTime = motionEvent->getEventTime();
  2329. mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
  2330. }
  2331. mLock.lock();
  2332. const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
  2333. const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
  2334. firstInjectedEntry = new MotionEntry(*sampleEventTimes,
  2335. motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
  2336. action, actionButton, motionEvent->getFlags(),
  2337. motionEvent->getMetaState(), motionEvent->getButtonState(),
  2338. motionEvent->getEdgeFlags(),
  2339. motionEvent->getXPrecision(), motionEvent->getYPrecision(),
  2340. motionEvent->getDownTime(), displayId,
  2341. uint32_t(pointerCount), pointerProperties, samplePointerCoords,
  2342. motionEvent->getXOffset(), motionEvent->getYOffset());
  2343. lastInjectedEntry = firstInjectedEntry;
  2344. for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
  2345. sampleEventTimes += 1;
  2346. samplePointerCoords += pointerCount;
  2347. MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
  2348. motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
  2349. action, actionButton, motionEvent->getFlags(),
  2350. motionEvent->getMetaState(), motionEvent->getButtonState(),
  2351. motionEvent->getEdgeFlags(),
  2352. motionEvent->getXPrecision(), motionEvent->getYPrecision(),
  2353. motionEvent->getDownTime(), displayId,
  2354. uint32_t(pointerCount), pointerProperties, samplePointerCoords,
  2355. motionEvent->getXOffset(), motionEvent->getYOffset());
  2356. lastInjectedEntry->next = nextInjectedEntry;
  2357. lastInjectedEntry = nextInjectedEntry;
  2358. }
  2359. break;
  2360. }
  2361. default:
  2362. ALOGW("Cannot inject event of type %d", event->getType());
  2363. return INPUT_EVENT_INJECTION_FAILED;
  2364. }
  2365. InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
  2366. if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
  2367. injectionState->injectionIsAsync = true;
  2368. }
  2369. injectionState->refCount += 1;
  2370. lastInjectedEntry->injectionState = injectionState;
  2371. bool needWake = false;
  2372. for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
  2373. EventEntry* nextEntry = entry->next;
  2374. needWake |= enqueueInboundEventLocked(entry);
  2375. entry = nextEntry;
  2376. }
  2377. mLock.unlock();
  2378. if (needWake) {
  2379. mLooper->wake();
  2380. }
  2381. int32_t injectionResult;
  2382. { // acquire lock
  2383. AutoMutex _l(mLock);
  2384. if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
  2385. injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
  2386. } else {
  2387. for (;;) {
  2388. injectionResult = injectionState->injectionResult;
  2389. if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
  2390. break;
  2391. }
  2392. nsecs_t remainingTimeout = endTime - now();
  2393. if (remainingTimeout <= 0) {
  2394. #if DEBUG_INJECTION
  2395. ALOGD("injectInputEvent - Timed out waiting for injection result "
  2396. "to become available.");
  2397. #endif
  2398. injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
  2399. break;
  2400. }
  2401. mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
  2402. }
  2403. if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
  2404. && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
  2405. while (injectionState->pendingForegroundDispatches != 0) {
  2406. #if DEBUG_INJECTION
  2407. ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
  2408. injectionState->pendingForegroundDispatches);
  2409. #endif
  2410. nsecs_t remainingTimeout = endTime - now();
  2411. if (remainingTimeout <= 0) {
  2412. #if DEBUG_INJECTION
  2413. ALOGD("injectInputEvent - Timed out waiting for pending foreground "
  2414. "dispatches to finish.");
  2415. #endif
  2416. injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
  2417. break;
  2418. }
  2419. mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
  2420. }
  2421. }
  2422. }
  2423. injectionState->release();
  2424. } // release lock
  2425. #if DEBUG_INJECTION
  2426. ALOGD("injectInputEvent - Finished with result %d. "
  2427. "injectorPid=%d, injectorUid=%d",
  2428. injectionResult, injectorPid, injectorUid);
  2429. #endif
  2430. return injectionResult;
  2431. }
  2432. bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
  2433. return injectorUid == 0
  2434. || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
  2435. }
  2436. void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
  2437. InjectionState* injectionState = entry->injectionState;
  2438. if (injectionState) {
  2439. #if DEBUG_INJECTION
  2440. ALOGD("Setting input event injection result to %d. "
  2441. "injectorPid=%d, injectorUid=%d",
  2442. injectionResult, injectionState->injectorPid, injectionState->injectorUid);
  2443. #endif
  2444. if (injectionState->injectionIsAsync
  2445. && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
  2446. // Log the outcome since the injector did not wait for the injection result.
  2447. switch (injectionResult) {
  2448. case INPUT_EVENT_INJECTION_SUCCEEDED:
  2449. ALOGV("Asynchronous input event injection succeeded.");
  2450. break;
  2451. case INPUT_EVENT_INJECTION_FAILED:
  2452. ALOGW("Asynchronous input event injection failed.");
  2453. break;
  2454. case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
  2455. ALOGW("Asynchronous input event injection permission denied.");
  2456. break;
  2457. case INPUT_EVENT_INJECTION_TIMED_OUT:
  2458. ALOGW("Asynchronous input event injection timed out.");
  2459. break;
  2460. }
  2461. }
  2462. injectionState->injectionResult = injectionResult;
  2463. mInjectionResultAvailableCondition.broadcast();
  2464. }
  2465. }
  2466. void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
  2467. InjectionState* injectionState = entry->injectionState;
  2468. if (injectionState) {
  2469. injectionState->pendingForegroundDispatches += 1;
  2470. }
  2471. }
  2472. void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
  2473. InjectionState* injectionState = entry->injectionState;
  2474. if (injectionState) {
  2475. injectionState->pendingForegroundDispatches -= 1;
  2476. if (injectionState->pendingForegroundDispatches == 0) {
  2477. mInjectionSyncFinishedCondition.broadcast();
  2478. }
  2479. }
  2480. }
  2481. sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
  2482. const sp<InputChannel>& inputChannel) const {
  2483. size_t numWindows = mWindowHandles.size();
  2484. for (size_t i = 0; i < numWindows; i++) {
  2485. const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
  2486. if (windowHandle->getInputChannel() == inputChannel) {
  2487. return windowHandle;
  2488. }
  2489. }
  2490. return NULL;
  2491. }
  2492. bool InputDispatcher::hasWindowHandleLocked(
  2493. const sp<InputWindowHandle>& windowHandle) const {
  2494. size_t numWindows = mWindowHandles.size();
  2495. for (size_t i = 0; i < numWindows; i++) {
  2496. if (mWindowHandles.itemAt(i) == windowHandle) {
  2497. return true;
  2498. }
  2499. }
  2500. return false;
  2501. }
  2502. void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
  2503. #if DEBUG_FOCUS
  2504. ALOGD("setInputWindows");
  2505. #endif
  2506. { // acquire lock
  2507. AutoMutex _l(mLock);
  2508. Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
  2509. mWindowHandles = inputWindowHandles;
  2510. sp<InputWindowHandle> newFocusedWindowHandle;
  2511. bool foundHoveredWindow = false;
  2512. for (size_t i = 0; i < mWindowHandles.size(); i++) {
  2513. const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
  2514. if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
  2515. mWindowHandles.removeAt(i--);
  2516. continue;
  2517. }
  2518. if (windowHandle->getInfo()->hasFocus) {
  2519. newFocusedWindowHandle = windowHandle;
  2520. }
  2521. if (windowHandle == mLastHoverWindowHandle) {
  2522. foundHoveredWindow = true;
  2523. }
  2524. }
  2525. if (!foundHoveredWindow) {
  2526. mLastHoverWindowHandle = NULL;
  2527. }
  2528. if (mFocusedWindowHandle != newFocusedWindowHandle) {
  2529. if (mFocusedWindowHandle != NULL) {
  2530. #if DEBUG_FOCUS
  2531. ALOGD("Focus left window: %s",
  2532. mFocusedWindowHandle->getName().string());
  2533. #endif
  2534. sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
  2535. if (focusedInputChannel != NULL) {
  2536. CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
  2537. "focus left window");
  2538. synthesizeCancelationEventsForInputChannelLocked(
  2539. focusedInputChannel, options);
  2540. }
  2541. }
  2542. if (newFocusedWindowHandle != NULL) {
  2543. #if DEBUG_FOCUS
  2544. ALOGD("Focus entered window: %s",
  2545. newFocusedWindowHandle->getName().string());
  2546. #endif
  2547. }
  2548. mFocusedWindowHandle = newFocusedWindowHandle;
  2549. }
  2550. for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
  2551. TouchState& state = mTouchStatesByDisplay.editValueAt(d);
  2552. for (size_t i = 0; i < state.windows.size(); i++) {
  2553. TouchedWindow& touchedWindow = state.windows.editItemAt(i);
  2554. if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
  2555. #if DEBUG_FOCUS
  2556. ALOGD("Touched window was removed: %s",
  2557. touchedWindow.windowHandle->getName().string());
  2558. #endif
  2559. sp<InputChannel> touchedInputChannel =
  2560. touchedWindow.windowHandle->getInputChannel();
  2561. if (touchedInputChannel != NULL) {
  2562. CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
  2563. "touched window was removed");
  2564. synthesizeCancelationEventsForInputChannelLocked(
  2565. touchedInputChannel, options);
  2566. }
  2567. state.windows.removeAt(i--);
  2568. }
  2569. }
  2570. }
  2571. // Release information for windows that are no longer present.
  2572. // This ensures that unused input channels are released promptly.
  2573. // Otherwise, they might stick around until the window handle is destroyed
  2574. // which might not happen until the next GC.
  2575. for (size_t i = 0; i < oldWindowHandles.size(); i++) {
  2576. const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
  2577. if (!hasWindowHandleLocked(oldWindowHandle)) {
  2578. #if DEBUG_FOCUS
  2579. ALOGD("Window went away: %s", oldWindowHandle->getName().string());
  2580. #endif
  2581. oldWindowHandle->releaseInfo();
  2582. }
  2583. }
  2584. } // release lock
  2585. // Wake up poll loop since it may need to make new input dispatching choices.
  2586. mLooper->wake();
  2587. }
  2588. void InputDispatcher::setFocusedApplication(
  2589. const sp<InputApplicationHandle>& inputApplicationHandle) {
  2590. #if DEBUG_FOCUS
  2591. ALOGD("setFocusedApplication");
  2592. #endif
  2593. { // acquire lock
  2594. AutoMutex _l(mLock);
  2595. if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
  2596. if (mFocusedApplicationHandle != inputApplicationHandle) {
  2597. if (mFocusedApplicationHandle != NULL) {
  2598. resetANRTimeoutsLocked();
  2599. mFocusedApplicationHandle->releaseInfo();
  2600. }
  2601. mFocusedApplicationHandle = inputApplicationHandle;
  2602. }
  2603. } else if (mFocusedApplicationHandle != NULL) {
  2604. resetANRTimeoutsLocked();
  2605. mFocusedApplicationHandle->releaseInfo();
  2606. mFocusedApplicationHandle.clear();
  2607. }
  2608. #if DEBUG_FOCUS
  2609. //logDispatchStateLocked();
  2610. #endif
  2611. } // release lock
  2612. // Wake up poll loop since it may need to make new input dispatching choices.
  2613. mLooper->wake();
  2614. }
  2615. void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
  2616. #if DEBUG_FOCUS
  2617. ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
  2618. #endif
  2619. bool changed;
  2620. { // acquire lock
  2621. AutoMutex _l(mLock);
  2622. if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
  2623. if (mDispatchFrozen && !frozen) {
  2624. resetANRTimeoutsLocked();
  2625. }
  2626. if (mDispatchEnabled && !enabled) {
  2627. resetAndDropEverythingLocked("dispatcher is being disabled");
  2628. }
  2629. mDispatchEnabled = enabled;
  2630. mDispatchFrozen = frozen;
  2631. changed = true;
  2632. } else {
  2633. changed = false;
  2634. }
  2635. #if DEBUG_FOCUS
  2636. //logDispatchStateLocked();
  2637. #endif
  2638. } // release lock
  2639. if (changed) {
  2640. // Wake up poll loop since it may need to make new input dispatching choices.
  2641. mLooper->wake();
  2642. }
  2643. }
  2644. void InputDispatcher::setInputFilterEnabled(bool enabled) {
  2645. #if DEBUG_FOCUS
  2646. ALOGD("setInputFilterEnabled: enabled=%d", enabled);
  2647. #endif
  2648. { // acquire lock
  2649. AutoMutex _l(mLock);
  2650. if (mInputFilterEnabled == enabled) {
  2651. return;
  2652. }
  2653. mInputFilterEnabled = enabled;
  2654. resetAndDropEverythingLocked("input filter is being enabled or disabled");
  2655. } // release lock
  2656. // Wake up poll loop since there might be work to do to drop everything.
  2657. mLooper->wake();
  2658. }
  2659. bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
  2660. const sp<InputChannel>& toChannel) {
  2661. #if DEBUG_FOCUS
  2662. ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
  2663. fromChannel->getName().string(), toChannel->getName().string());
  2664. #endif
  2665. { // acquire lock
  2666. AutoMutex _l(mLock);
  2667. sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
  2668. sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
  2669. if (fromWindowHandle == NULL || toWindowHandle == NULL) {
  2670. #if DEBUG_FOCUS
  2671. ALOGD("Cannot transfer focus because from or to window not found.");
  2672. #endif
  2673. return false;
  2674. }
  2675. if (fromWindowHandle == toWindowHandle) {
  2676. #if DEBUG_FOCUS
  2677. ALOGD("Trivial transfer to same window.");
  2678. #endif
  2679. return true;
  2680. }
  2681. if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
  2682. #if DEBUG_FOCUS
  2683. ALOGD("Cannot transfer focus because windows are on different displays.");
  2684. #endif
  2685. return false;
  2686. }
  2687. bool found = false;
  2688. for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
  2689. TouchState& state = mTouchStatesByDisplay.editValueAt(d);
  2690. for (size_t i = 0; i < state.windows.size(); i++) {
  2691. const TouchedWindow& touchedWindow = state.windows[i];
  2692. if (touchedWindow.windowHandle == fromWindowHandle) {
  2693. int32_t oldTargetFlags = touchedWindow.targetFlags;
  2694. BitSet32 pointerIds = touchedWindow.pointerIds;
  2695. state.windows.removeAt(i);
  2696. int32_t newTargetFlags = oldTargetFlags
  2697. & (InputTarget::FLAG_FOREGROUND
  2698. | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
  2699. state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
  2700. found = true;
  2701. goto Found;
  2702. }
  2703. }
  2704. }
  2705. Found:
  2706. if (! found) {
  2707. #if DEBUG_FOCUS
  2708. ALOGD("Focus transfer failed because from window did not have focus.");
  2709. #endif
  2710. return false;
  2711. }
  2712. ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
  2713. ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
  2714. if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
  2715. sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
  2716. sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
  2717. fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
  2718. CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
  2719. "transferring touch focus from this window to another window");
  2720. synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
  2721. }
  2722. #if DEBUG_FOCUS
  2723. logDispatchStateLocked();
  2724. #endif
  2725. } // release lock
  2726. // Wake up poll loop since it may need to make new input dispatching choices.
  2727. mLooper->wake();
  2728. return true;
  2729. }
  2730. void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
  2731. #if DEBUG_FOCUS
  2732. ALOGD("Resetting and dropping all events (%s).", reason);
  2733. #endif
  2734. CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
  2735. synthesizeCancelationEventsForAllConnectionsLocked(options);
  2736. resetKeyRepeatLocked();
  2737. releasePendingEventLocked();
  2738. drainInboundQueueLocked();
  2739. resetANRTimeoutsLocked();
  2740. mTouchStatesByDisplay.clear();
  2741. mLastHoverWindowHandle.clear();
  2742. mReplacedKeys.clear();
  2743. }
  2744. void InputDispatcher::logDispatchStateLocked() {
  2745. String8 dump;
  2746. dumpDispatchStateLocked(dump);
  2747. char* text = dump.lockBuffer(dump.size());
  2748. char* start = text;
  2749. while (*start != '\0') {
  2750. char* end = strchr(start, '\n');
  2751. if (*end == '\n') {
  2752. *(end++) = '\0';
  2753. }
  2754. ALOGD("%s", start);
  2755. start = end;
  2756. }
  2757. }
  2758. void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
  2759. dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
  2760. dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
  2761. if (mFocusedApplicationHandle != NULL) {
  2762. dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
  2763. mFocusedApplicationHandle->getName().string(),
  2764. mFocusedApplicationHandle->getDispatchingTimeout(
  2765. DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
  2766. } else {
  2767. dump.append(INDENT "FocusedApplication: <null>\n");
  2768. }
  2769. dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
  2770. mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
  2771. if (!mTouchStatesByDisplay.isEmpty()) {
  2772. dump.appendFormat(INDENT "TouchStatesByDisplay:\n");
  2773. for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
  2774. const TouchState& state = mTouchStatesByDisplay.valueAt(i);
  2775. dump.appendFormat(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
  2776. state.displayId, toString(state.down), toString(state.split),
  2777. state.deviceId, state.source);
  2778. if (!state.windows.isEmpty()) {
  2779. dump.append(INDENT3 "Windows:\n");
  2780. for (size_t i = 0; i < state.windows.size(); i++) {
  2781. const TouchedWindow& touchedWindow = state.windows[i];
  2782. dump.appendFormat(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
  2783. i, touchedWindow.windowHandle->getName().string(),
  2784. touchedWindow.pointerIds.value,
  2785. touchedWindow.targetFlags);
  2786. }
  2787. } else {
  2788. dump.append(INDENT3 "Windows: <none>\n");
  2789. }
  2790. }
  2791. } else {
  2792. dump.append(INDENT "TouchStates: <no displays touched>\n");
  2793. }
  2794. if (!mWindowHandles.isEmpty()) {
  2795. dump.append(INDENT "Windows:\n");
  2796. for (size_t i = 0; i < mWindowHandles.size(); i++) {
  2797. const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
  2798. const InputWindowInfo* windowInfo = windowHandle->getInfo();
  2799. dump.appendFormat(INDENT2 "%zu: name='%s', displayId=%d, "
  2800. "paused=%s, hasFocus=%s, hasWallpaper=%s, "
  2801. "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
  2802. "frame=[%d,%d][%d,%d], scale=%f, "
  2803. "touchableRegion=",
  2804. i, windowInfo->name.string(), windowInfo->displayId,
  2805. toString(windowInfo->paused),
  2806. toString(windowInfo->hasFocus),
  2807. toString(windowInfo->hasWallpaper),
  2808. toString(windowInfo->visible),
  2809. toString(windowInfo->canReceiveKeys),
  2810. windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
  2811. windowInfo->layer,
  2812. windowInfo->frameLeft, windowInfo->frameTop,
  2813. windowInfo->frameRight, windowInfo->frameBottom,
  2814. windowInfo->scaleFactor);
  2815. dumpRegion(dump, windowInfo->touchableRegion);
  2816. dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
  2817. dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
  2818. windowInfo->ownerPid, windowInfo->ownerUid,
  2819. windowInfo->dispatchingTimeout / 1000000.0);
  2820. }
  2821. } else {
  2822. dump.append(INDENT "Windows: <none>\n");
  2823. }
  2824. if (!mMonitoringChannels.isEmpty()) {
  2825. dump.append(INDENT "MonitoringChannels:\n");
  2826. for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
  2827. const sp<InputChannel>& channel = mMonitoringChannels[i];
  2828. dump.appendFormat(INDENT2 "%zu: '%s'\n", i, channel->getName().string());
  2829. }
  2830. } else {
  2831. dump.append(INDENT "MonitoringChannels: <none>\n");
  2832. }
  2833. nsecs_t currentTime = now();
  2834. // Dump recently dispatched or dropped events from oldest to newest.
  2835. if (!mRecentQueue.isEmpty()) {
  2836. dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
  2837. for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
  2838. dump.append(INDENT2);
  2839. entry->appendDescription(dump);
  2840. dump.appendFormat(", age=%0.1fms\n",
  2841. (currentTime - entry->eventTime) * 0.000001f);
  2842. }
  2843. } else {
  2844. dump.append(INDENT "RecentQueue: <empty>\n");
  2845. }
  2846. // Dump event currently being dispatched.
  2847. if (mPendingEvent) {
  2848. dump.append(INDENT "PendingEvent:\n");
  2849. dump.append(INDENT2);
  2850. mPendingEvent->appendDescription(dump);
  2851. dump.appendFormat(", age=%0.1fms\n",
  2852. (currentTime - mPendingEvent->eventTime) * 0.000001f);
  2853. } else {
  2854. dump.append(INDENT "PendingEvent: <none>\n");
  2855. }
  2856. // Dump inbound events from oldest to newest.
  2857. if (!mInboundQueue.isEmpty()) {
  2858. dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
  2859. for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
  2860. dump.append(INDENT2);
  2861. entry->appendDescription(dump);
  2862. dump.appendFormat(", age=%0.1fms\n",
  2863. (currentTime - entry->eventTime) * 0.000001f);
  2864. }
  2865. } else {
  2866. dump.append(INDENT "InboundQueue: <empty>\n");
  2867. }
  2868. if (!mReplacedKeys.isEmpty()) {
  2869. dump.append(INDENT "ReplacedKeys:\n");
  2870. for (size_t i = 0; i < mReplacedKeys.size(); i++) {
  2871. const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
  2872. int32_t newKeyCode = mReplacedKeys.valueAt(i);
  2873. dump.appendFormat(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
  2874. i, replacement.keyCode, replacement.deviceId, newKeyCode);
  2875. }
  2876. } else {
  2877. dump.append(INDENT "ReplacedKeys: <empty>\n");
  2878. }
  2879. if (!mConnectionsByFd.isEmpty()) {
  2880. dump.append(INDENT "Connections:\n");
  2881. for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
  2882. const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
  2883. dump.appendFormat(INDENT2 "%zu: channelName='%s', windowName='%s', "
  2884. "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
  2885. i, connection->getInputChannelName(), connection->getWindowName(),
  2886. connection->getStatusLabel(), toString(connection->monitor),
  2887. toString(connection->inputPublisherBlocked));
  2888. if (!connection->outboundQueue.isEmpty()) {
  2889. dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
  2890. connection->outboundQueue.count());
  2891. for (DispatchEntry* entry = connection->outboundQueue.head; entry;
  2892. entry = entry->next) {
  2893. dump.append(INDENT4);
  2894. entry->eventEntry->appendDescription(dump);
  2895. dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
  2896. entry->targetFlags, entry->resolvedAction,
  2897. (currentTime - entry->eventEntry->eventTime) * 0.000001f);
  2898. }
  2899. } else {
  2900. dump.append(INDENT3 "OutboundQueue: <empty>\n");
  2901. }
  2902. if (!connection->waitQueue.isEmpty()) {
  2903. dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
  2904. connection->waitQueue.count());
  2905. for (DispatchEntry* entry = connection->waitQueue.head; entry;
  2906. entry = entry->next) {
  2907. dump.append(INDENT4);
  2908. entry->eventEntry->appendDescription(dump);
  2909. dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
  2910. "age=%0.1fms, wait=%0.1fms\n",
  2911. entry->targetFlags, entry->resolvedAction,
  2912. (currentTime - entry->eventEntry->eventTime) * 0.000001f,
  2913. (currentTime - entry->deliveryTime) * 0.000001f);
  2914. }
  2915. } else {
  2916. dump.append(INDENT3 "WaitQueue: <empty>\n");
  2917. }
  2918. }
  2919. } else {
  2920. dump.append(INDENT "Connections: <none>\n");
  2921. }
  2922. if (isAppSwitchPendingLocked()) {
  2923. dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
  2924. (mAppSwitchDueTime - now()) / 1000000.0);
  2925. } else {
  2926. dump.append(INDENT "AppSwitch: not pending\n");
  2927. }
  2928. dump.append(INDENT "Configuration:\n");
  2929. dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
  2930. mConfig.keyRepeatDelay * 0.000001f);
  2931. dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
  2932. mConfig.keyRepeatTimeout * 0.000001f);
  2933. }
  2934. status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
  2935. const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
  2936. #if DEBUG_REGISTRATION
  2937. ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
  2938. toString(monitor));
  2939. #endif
  2940. { // acquire lock
  2941. AutoMutex _l(mLock);
  2942. if (getConnectionIndexLocked(inputChannel) >= 0) {
  2943. ALOGW("Attempted to register already registered input channel '%s'",
  2944. inputChannel->getName().string());
  2945. return BAD_VALUE;
  2946. }
  2947. sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
  2948. int fd = inputChannel->getFd();
  2949. mConnectionsByFd.add(fd, connection);
  2950. if (monitor) {
  2951. mMonitoringChannels.push(inputChannel);
  2952. }
  2953. mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
  2954. } // release lock
  2955. // Wake the looper because some connections have changed.
  2956. mLooper->wake();
  2957. return OK;
  2958. }
  2959. status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
  2960. #if DEBUG_REGISTRATION
  2961. ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
  2962. #endif
  2963. { // acquire lock
  2964. AutoMutex _l(mLock);
  2965. status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
  2966. if (status) {
  2967. return status;
  2968. }
  2969. } // release lock
  2970. // Wake the poll loop because removing the connection may have changed the current
  2971. // synchronization state.
  2972. mLooper->wake();
  2973. return OK;
  2974. }
  2975. status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
  2976. bool notify) {
  2977. ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
  2978. if (connectionIndex < 0) {
  2979. ALOGW("Attempted to unregister already unregistered input channel '%s'",
  2980. inputChannel->getName().string());
  2981. return BAD_VALUE;
  2982. }
  2983. sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
  2984. mConnectionsByFd.removeItemsAt(connectionIndex);
  2985. if (connection->monitor) {
  2986. removeMonitorChannelLocked(inputChannel);
  2987. }
  2988. mLooper->removeFd(inputChannel->getFd());
  2989. nsecs_t currentTime = now();
  2990. abortBrokenDispatchCycleLocked(currentTime, connection, notify);
  2991. connection->status = Connection::STATUS_ZOMBIE;
  2992. return OK;
  2993. }
  2994. void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
  2995. for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
  2996. if (mMonitoringChannels[i] == inputChannel) {
  2997. mMonitoringChannels.removeAt(i);
  2998. break;
  2999. }
  3000. }
  3001. }
  3002. ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
  3003. ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
  3004. if (connectionIndex >= 0) {
  3005. sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
  3006. if (connection->inputChannel.get() == inputChannel.get()) {
  3007. return connectionIndex;
  3008. }
  3009. }
  3010. return -1;
  3011. }
  3012. void InputDispatcher::onDispatchCycleFinishedLocked(
  3013. nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
  3014. CommandEntry* commandEntry = postCommandLocked(
  3015. & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
  3016. commandEntry->connection = connection;
  3017. commandEntry->eventTime = currentTime;
  3018. commandEntry->seq = seq;
  3019. commandEntry->handled = handled;
  3020. }
  3021. void InputDispatcher::onDispatchCycleBrokenLocked(
  3022. nsecs_t currentTime, const sp<Connection>& connection) {
  3023. ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
  3024. connection->getInputChannelName());
  3025. CommandEntry* commandEntry = postCommandLocked(
  3026. & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
  3027. commandEntry->connection = connection;
  3028. }
  3029. void InputDispatcher::onANRLocked(
  3030. nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
  3031. const sp<InputWindowHandle>& windowHandle,
  3032. nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
  3033. float dispatchLatency = (currentTime - eventTime) * 0.000001f;
  3034. float waitDuration = (currentTime - waitStartTime) * 0.000001f;
  3035. ALOGI("Application is not responding: %s. "
  3036. "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
  3037. getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
  3038. dispatchLatency, waitDuration, reason);
  3039. // Capture a record of the InputDispatcher state at the time of the ANR.
  3040. time_t t = time(NULL);
  3041. struct tm tm;
  3042. localtime_r(&t, &tm);
  3043. char timestr[64];
  3044. strftime(timestr, sizeof(timestr), "%F %T", &tm);
  3045. mLastANRState.clear();
  3046. mLastANRState.append(INDENT "ANR:\n");
  3047. mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
  3048. mLastANRState.appendFormat(INDENT2 "Window: %s\n",
  3049. getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
  3050. mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
  3051. mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
  3052. mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
  3053. dumpDispatchStateLocked(mLastANRState);
  3054. CommandEntry* commandEntry = postCommandLocked(
  3055. & InputDispatcher::doNotifyANRLockedInterruptible);
  3056. commandEntry->inputApplicationHandle = applicationHandle;
  3057. commandEntry->inputWindowHandle = windowHandle;
  3058. commandEntry->reason = reason;
  3059. }
  3060. void InputDispatcher::doNotifyConfigurationChangedInterruptible(
  3061. CommandEntry* commandEntry) {
  3062. mLock.unlock();
  3063. mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
  3064. mLock.lock();
  3065. }
  3066. void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
  3067. CommandEntry* commandEntry) {
  3068. sp<Connection> connection = commandEntry->connection;
  3069. if (connection->status != Connection::STATUS_ZOMBIE) {
  3070. mLock.unlock();
  3071. mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
  3072. mLock.lock();
  3073. }
  3074. }
  3075. void InputDispatcher::doNotifyANRLockedInterruptible(
  3076. CommandEntry* commandEntry) {
  3077. mLock.unlock();
  3078. nsecs_t newTimeout = mPolicy->notifyANR(
  3079. commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
  3080. commandEntry->reason);
  3081. mLock.lock();
  3082. resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
  3083. commandEntry->inputWindowHandle != NULL
  3084. ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
  3085. }
  3086. void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
  3087. CommandEntry* commandEntry) {
  3088. KeyEntry* entry = commandEntry->keyEntry;
  3089. KeyEvent event;
  3090. initializeKeyEvent(&event, entry);
  3091. mLock.unlock();
  3092. nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
  3093. &event, entry->policyFlags);
  3094. mLock.lock();
  3095. if (delay < 0) {
  3096. entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
  3097. } else if (!delay) {
  3098. entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
  3099. } else {
  3100. entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
  3101. entry->interceptKeyWakeupTime = now() + delay;
  3102. }
  3103. entry->release();
  3104. }
  3105. void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
  3106. CommandEntry* commandEntry) {
  3107. sp<Connection> connection = commandEntry->connection;
  3108. nsecs_t finishTime = commandEntry->eventTime;
  3109. uint32_t seq = commandEntry->seq;
  3110. bool handled = commandEntry->handled;
  3111. // Handle post-event policy actions.
  3112. DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
  3113. if (dispatchEntry) {
  3114. nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
  3115. if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
  3116. String8 msg;
  3117. msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
  3118. connection->getWindowName(), eventDuration * 0.000001f);
  3119. dispatchEntry->eventEntry->appendDescription(msg);
  3120. ALOGI("%s", msg.string());
  3121. }
  3122. bool restartEvent;
  3123. if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
  3124. KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
  3125. restartEvent = afterKeyEventLockedInterruptible(connection,
  3126. dispatchEntry, keyEntry, handled);
  3127. } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
  3128. MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
  3129. restartEvent = afterMotionEventLockedInterruptible(connection,
  3130. dispatchEntry, motionEntry, handled);
  3131. } else {
  3132. restartEvent = false;
  3133. }
  3134. // Dequeue the event and start the next cycle.
  3135. // Note that because the lock might have been released, it is possible that the
  3136. // contents of the wait queue to have been drained, so we need to double-check
  3137. // a few things.
  3138. if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
  3139. connection->waitQueue.dequeue(dispatchEntry);
  3140. traceWaitQueueLengthLocked(connection);
  3141. if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
  3142. connection->outboundQueue.enqueueAtHead(dispatchEntry);
  3143. traceOutboundQueueLengthLocked(connection);
  3144. } else {
  3145. releaseDispatchEntryLocked(dispatchEntry);
  3146. }
  3147. }
  3148. // Start the next dispatch cycle for this connection.
  3149. startDispatchCycleLocked(now(), connection);
  3150. }
  3151. }
  3152. bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
  3153. DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
  3154. if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
  3155. // Get the fallback key state.
  3156. // Clear it out after dispatching the UP.
  3157. int32_t originalKeyCode = keyEntry->keyCode;
  3158. int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
  3159. if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
  3160. connection->inputState.removeFallbackKey(originalKeyCode);
  3161. }
  3162. if (handled || !dispatchEntry->hasForegroundTarget()) {
  3163. // If the application handles the original key for which we previously
  3164. // generated a fallback or if the window is not a foreground window,
  3165. // then cancel the associated fallback key, if any.
  3166. if (fallbackKeyCode != -1) {
  3167. // Dispatch the unhandled key to the policy with the cancel flag.
  3168. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3169. ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
  3170. "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
  3171. keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
  3172. keyEntry->policyFlags);
  3173. #endif
  3174. KeyEvent event;
  3175. initializeKeyEvent(&event, keyEntry);
  3176. event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
  3177. mLock.unlock();
  3178. mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
  3179. &event, keyEntry->policyFlags, &event);
  3180. mLock.lock();
  3181. // Cancel the fallback key.
  3182. if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
  3183. CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
  3184. "application handled the original non-fallback key "
  3185. "or is no longer a foreground target, "
  3186. "canceling previously dispatched fallback key");
  3187. options.keyCode = fallbackKeyCode;
  3188. synthesizeCancelationEventsForConnectionLocked(connection, options);
  3189. }
  3190. connection->inputState.removeFallbackKey(originalKeyCode);
  3191. }
  3192. } else {
  3193. // If the application did not handle a non-fallback key, first check
  3194. // that we are in a good state to perform unhandled key event processing
  3195. // Then ask the policy what to do with it.
  3196. bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
  3197. && keyEntry->repeatCount == 0;
  3198. if (fallbackKeyCode == -1 && !initialDown) {
  3199. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3200. ALOGD("Unhandled key event: Skipping unhandled key event processing "
  3201. "since this is not an initial down. "
  3202. "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
  3203. originalKeyCode, keyEntry->action, keyEntry->repeatCount,
  3204. keyEntry->policyFlags);
  3205. #endif
  3206. return false;
  3207. }
  3208. // Dispatch the unhandled key to the policy.
  3209. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3210. ALOGD("Unhandled key event: Asking policy to perform fallback action. "
  3211. "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
  3212. keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
  3213. keyEntry->policyFlags);
  3214. #endif
  3215. KeyEvent event;
  3216. initializeKeyEvent(&event, keyEntry);
  3217. mLock.unlock();
  3218. bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
  3219. &event, keyEntry->policyFlags, &event);
  3220. mLock.lock();
  3221. if (connection->status != Connection::STATUS_NORMAL) {
  3222. connection->inputState.removeFallbackKey(originalKeyCode);
  3223. return false;
  3224. }
  3225. // Latch the fallback keycode for this key on an initial down.
  3226. // The fallback keycode cannot change at any other point in the lifecycle.
  3227. if (initialDown) {
  3228. if (fallback) {
  3229. fallbackKeyCode = event.getKeyCode();
  3230. } else {
  3231. fallbackKeyCode = AKEYCODE_UNKNOWN;
  3232. }
  3233. connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
  3234. }
  3235. ALOG_ASSERT(fallbackKeyCode != -1);
  3236. // Cancel the fallback key if the policy decides not to send it anymore.
  3237. // We will continue to dispatch the key to the policy but we will no
  3238. // longer dispatch a fallback key to the application.
  3239. if (fallbackKeyCode != AKEYCODE_UNKNOWN
  3240. && (!fallback || fallbackKeyCode != event.getKeyCode())) {
  3241. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3242. if (fallback) {
  3243. ALOGD("Unhandled key event: Policy requested to send key %d"
  3244. "as a fallback for %d, but on the DOWN it had requested "
  3245. "to send %d instead. Fallback canceled.",
  3246. event.getKeyCode(), originalKeyCode, fallbackKeyCode);
  3247. } else {
  3248. ALOGD("Unhandled key event: Policy did not request fallback for %d, "
  3249. "but on the DOWN it had requested to send %d. "
  3250. "Fallback canceled.",
  3251. originalKeyCode, fallbackKeyCode);
  3252. }
  3253. #endif
  3254. CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
  3255. "canceling fallback, policy no longer desires it");
  3256. options.keyCode = fallbackKeyCode;
  3257. synthesizeCancelationEventsForConnectionLocked(connection, options);
  3258. fallback = false;
  3259. fallbackKeyCode = AKEYCODE_UNKNOWN;
  3260. if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
  3261. connection->inputState.setFallbackKey(originalKeyCode,
  3262. fallbackKeyCode);
  3263. }
  3264. }
  3265. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3266. {
  3267. String8 msg;
  3268. const KeyedVector<int32_t, int32_t>& fallbackKeys =
  3269. connection->inputState.getFallbackKeys();
  3270. for (size_t i = 0; i < fallbackKeys.size(); i++) {
  3271. msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
  3272. fallbackKeys.valueAt(i));
  3273. }
  3274. ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
  3275. fallbackKeys.size(), msg.string());
  3276. }
  3277. #endif
  3278. if (fallback) {
  3279. // Restart the dispatch cycle using the fallback key.
  3280. keyEntry->eventTime = event.getEventTime();
  3281. keyEntry->deviceId = event.getDeviceId();
  3282. keyEntry->source = event.getSource();
  3283. keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
  3284. keyEntry->keyCode = fallbackKeyCode;
  3285. keyEntry->scanCode = event.getScanCode();
  3286. keyEntry->metaState = event.getMetaState();
  3287. keyEntry->repeatCount = event.getRepeatCount();
  3288. keyEntry->downTime = event.getDownTime();
  3289. keyEntry->syntheticRepeat = false;
  3290. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3291. ALOGD("Unhandled key event: Dispatching fallback key. "
  3292. "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
  3293. originalKeyCode, fallbackKeyCode, keyEntry->metaState);
  3294. #endif
  3295. return true; // restart the event
  3296. } else {
  3297. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3298. ALOGD("Unhandled key event: No fallback key.");
  3299. #endif
  3300. }
  3301. }
  3302. }
  3303. return false;
  3304. }
  3305. bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
  3306. DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
  3307. return false;
  3308. }
  3309. void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
  3310. mLock.unlock();
  3311. mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
  3312. mLock.lock();
  3313. }
  3314. void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
  3315. event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
  3316. entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
  3317. entry->downTime, entry->eventTime);
  3318. }
  3319. void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
  3320. int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
  3321. // TODO Write some statistics about how long we spend waiting.
  3322. }
  3323. void InputDispatcher::traceInboundQueueLengthLocked() {
  3324. if (ATRACE_ENABLED()) {
  3325. ATRACE_INT("iq", mInboundQueue.count());
  3326. }
  3327. }
  3328. void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
  3329. if (ATRACE_ENABLED()) {
  3330. char counterName[40];
  3331. snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
  3332. ATRACE_INT(counterName, connection->outboundQueue.count());
  3333. }
  3334. }
  3335. void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
  3336. if (ATRACE_ENABLED()) {
  3337. char counterName[40];
  3338. snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
  3339. ATRACE_INT(counterName, connection->waitQueue.count());
  3340. }
  3341. }
  3342. void InputDispatcher::dump(String8& dump) {
  3343. AutoMutex _l(mLock);
  3344. dump.append("Input Dispatcher State:\n");
  3345. dumpDispatchStateLocked(dump);
  3346. if (!mLastANRState.isEmpty()) {
  3347. dump.append("\nInput Dispatcher State at time of last ANR:\n");
  3348. dump.append(mLastANRState);
  3349. }
  3350. }
  3351. void InputDispatcher::monitor() {
  3352. // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
  3353. mLock.lock();
  3354. mLooper->wake();
  3355. mDispatcherIsAliveCondition.wait(mLock);
  3356. mLock.unlock();
  3357. }
  3358. // --- InputDispatcher::InjectionState ---
  3359. InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
  3360. refCount(1),
  3361. injectorPid(injectorPid), injectorUid(injectorUid),
  3362. injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
  3363. pendingForegroundDispatches(0) {
  3364. }
  3365. InputDispatcher::InjectionState::~InjectionState() {
  3366. }
  3367. void InputDispatcher::InjectionState::release() {
  3368. refCount -= 1;
  3369. if (refCount == 0) {
  3370. delete this;
  3371. } else {
  3372. ALOG_ASSERT(refCount > 0);
  3373. }
  3374. }
  3375. // --- InputDispatcher::EventEntry ---
  3376. InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
  3377. refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
  3378. injectionState(NULL), dispatchInProgress(false) {
  3379. }
  3380. InputDispatcher::EventEntry::~EventEntry() {
  3381. releaseInjectionState();
  3382. }
  3383. void InputDispatcher::EventEntry::release() {
  3384. refCount -= 1;
  3385. if (refCount == 0) {
  3386. delete this;
  3387. } else {
  3388. ALOG_ASSERT(refCount > 0);
  3389. }
  3390. }
  3391. void InputDispatcher::EventEntry::releaseInjectionState() {
  3392. if (injectionState) {
  3393. injectionState->release();
  3394. injectionState = NULL;
  3395. }
  3396. }
  3397. // --- InputDispatcher::ConfigurationChangedEntry ---
  3398. InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
  3399. EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
  3400. }
  3401. InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
  3402. }
  3403. void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
  3404. msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
  3405. policyFlags);
  3406. }
  3407. // --- InputDispatcher::DeviceResetEntry ---
  3408. InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
  3409. EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
  3410. deviceId(deviceId) {
  3411. }
  3412. InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
  3413. }
  3414. void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
  3415. msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
  3416. deviceId, policyFlags);
  3417. }
  3418. // --- InputDispatcher::KeyEntry ---
  3419. InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
  3420. int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
  3421. int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
  3422. int32_t repeatCount, nsecs_t downTime) :
  3423. EventEntry(TYPE_KEY, eventTime, policyFlags),
  3424. deviceId(deviceId), source(source), action(action), flags(flags),
  3425. keyCode(keyCode), scanCode(scanCode), metaState(metaState),
  3426. repeatCount(repeatCount), downTime(downTime),
  3427. syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
  3428. interceptKeyWakeupTime(0) {
  3429. }
  3430. InputDispatcher::KeyEntry::~KeyEntry() {
  3431. }
  3432. void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
  3433. msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
  3434. "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
  3435. "repeatCount=%d), policyFlags=0x%08x",
  3436. deviceId, source, action, flags, keyCode, scanCode, metaState,
  3437. repeatCount, policyFlags);
  3438. }
  3439. void InputDispatcher::KeyEntry::recycle() {
  3440. releaseInjectionState();
  3441. dispatchInProgress = false;
  3442. syntheticRepeat = false;
  3443. interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
  3444. interceptKeyWakeupTime = 0;
  3445. }
  3446. // --- InputDispatcher::MotionEntry ---
  3447. InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
  3448. uint32_t source, uint32_t policyFlags, int32_t action, int32_t actionButton,
  3449. int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
  3450. float xPrecision, float yPrecision, nsecs_t downTime,
  3451. int32_t displayId, uint32_t pointerCount,
  3452. const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
  3453. float xOffset, float yOffset) :
  3454. EventEntry(TYPE_MOTION, eventTime, policyFlags),
  3455. eventTime(eventTime),
  3456. deviceId(deviceId), source(source), action(action), actionButton(actionButton),
  3457. flags(flags), metaState(metaState), buttonState(buttonState),
  3458. edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
  3459. downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
  3460. for (uint32_t i = 0; i < pointerCount; i++) {
  3461. this->pointerProperties[i].copyFrom(pointerProperties[i]);
  3462. this->pointerCoords[i].copyFrom(pointerCoords[i]);
  3463. if (xOffset || yOffset) {
  3464. this->pointerCoords[i].applyOffset(xOffset, yOffset);
  3465. }
  3466. }
  3467. }
  3468. InputDispatcher::MotionEntry::~MotionEntry() {
  3469. }
  3470. void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
  3471. msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, actionButton=0x%08x, "
  3472. "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
  3473. "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
  3474. deviceId, source, action, actionButton, flags, metaState, buttonState, edgeFlags,
  3475. xPrecision, yPrecision, displayId);
  3476. for (uint32_t i = 0; i < pointerCount; i++) {
  3477. if (i) {
  3478. msg.append(", ");
  3479. }
  3480. msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
  3481. pointerCoords[i].getX(), pointerCoords[i].getY());
  3482. }
  3483. msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
  3484. }
  3485. // --- InputDispatcher::DispatchEntry ---
  3486. volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
  3487. InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
  3488. int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
  3489. seq(nextSeq()),
  3490. eventEntry(eventEntry), targetFlags(targetFlags),
  3491. xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
  3492. deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
  3493. eventEntry->refCount += 1;
  3494. }
  3495. InputDispatcher::DispatchEntry::~DispatchEntry() {
  3496. eventEntry->release();
  3497. }
  3498. uint32_t InputDispatcher::DispatchEntry::nextSeq() {
  3499. // Sequence number 0 is reserved and will never be returned.
  3500. uint32_t seq;
  3501. do {
  3502. seq = android_atomic_inc(&sNextSeqAtomic);
  3503. } while (!seq);
  3504. return seq;
  3505. }
  3506. // --- InputDispatcher::InputState ---
  3507. InputDispatcher::InputState::InputState() {
  3508. }
  3509. InputDispatcher::InputState::~InputState() {
  3510. }
  3511. bool InputDispatcher::InputState::isNeutral() const {
  3512. return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
  3513. }
  3514. bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
  3515. int32_t displayId) const {
  3516. for (size_t i = 0; i < mMotionMementos.size(); i++) {
  3517. const MotionMemento& memento = mMotionMementos.itemAt(i);
  3518. if (memento.deviceId == deviceId
  3519. && memento.source == source
  3520. && memento.displayId == displayId
  3521. && memento.hovering) {
  3522. return true;
  3523. }
  3524. }
  3525. return false;
  3526. }
  3527. bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
  3528. int32_t action, int32_t flags) {
  3529. switch (action) {
  3530. case AKEY_EVENT_ACTION_UP: {
  3531. if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
  3532. for (size_t i = 0; i < mFallbackKeys.size(); ) {
  3533. if (mFallbackKeys.valueAt(i) == entry->keyCode) {
  3534. mFallbackKeys.removeItemsAt(i);
  3535. } else {
  3536. i += 1;
  3537. }
  3538. }
  3539. }
  3540. ssize_t index = findKeyMemento(entry);
  3541. if (index >= 0) {
  3542. mKeyMementos.removeAt(index);
  3543. return true;
  3544. }
  3545. /* FIXME: We can't just drop the key up event because that prevents creating
  3546. * popup windows that are automatically shown when a key is held and then
  3547. * dismissed when the key is released. The problem is that the popup will
  3548. * not have received the original key down, so the key up will be considered
  3549. * to be inconsistent with its observed state. We could perhaps handle this
  3550. * by synthesizing a key down but that will cause other problems.
  3551. *
  3552. * So for now, allow inconsistent key up events to be dispatched.
  3553. *
  3554. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3555. ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
  3556. "keyCode=%d, scanCode=%d",
  3557. entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
  3558. #endif
  3559. return false;
  3560. */
  3561. return true;
  3562. }
  3563. case AKEY_EVENT_ACTION_DOWN: {
  3564. ssize_t index = findKeyMemento(entry);
  3565. if (index >= 0) {
  3566. mKeyMementos.removeAt(index);
  3567. }
  3568. addKeyMemento(entry, flags);
  3569. return true;
  3570. }
  3571. default:
  3572. return true;
  3573. }
  3574. }
  3575. bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
  3576. int32_t action, int32_t flags) {
  3577. int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
  3578. switch (actionMasked) {
  3579. case AMOTION_EVENT_ACTION_UP:
  3580. case AMOTION_EVENT_ACTION_CANCEL: {
  3581. ssize_t index = findMotionMemento(entry, false /*hovering*/);
  3582. if (index >= 0) {
  3583. mMotionMementos.removeAt(index);
  3584. return true;
  3585. }
  3586. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3587. ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
  3588. "actionMasked=%d",
  3589. entry->deviceId, entry->source, actionMasked);
  3590. #endif
  3591. return false;
  3592. }
  3593. case AMOTION_EVENT_ACTION_DOWN: {
  3594. ssize_t index = findMotionMemento(entry, false /*hovering*/);
  3595. if (index >= 0) {
  3596. mMotionMementos.removeAt(index);
  3597. }
  3598. addMotionMemento(entry, flags, false /*hovering*/);
  3599. return true;
  3600. }
  3601. case AMOTION_EVENT_ACTION_POINTER_UP:
  3602. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  3603. case AMOTION_EVENT_ACTION_MOVE: {
  3604. if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
  3605. // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
  3606. // generate cancellation events for these since they're based in relative rather than
  3607. // absolute units.
  3608. return true;
  3609. }
  3610. ssize_t index = findMotionMemento(entry, false /*hovering*/);
  3611. if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
  3612. // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
  3613. // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
  3614. // other value and we need to track the motion so we can send cancellation events for
  3615. // anything generating fallback events (e.g. DPad keys for joystick movements).
  3616. if (index >= 0) {
  3617. if (entry->pointerCoords[0].isEmpty()) {
  3618. mMotionMementos.removeAt(index);
  3619. } else {
  3620. MotionMemento& memento = mMotionMementos.editItemAt(index);
  3621. memento.setPointers(entry);
  3622. }
  3623. } else if (!entry->pointerCoords[0].isEmpty()) {
  3624. addMotionMemento(entry, flags, false /*hovering*/);
  3625. }
  3626. // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
  3627. return true;
  3628. }
  3629. if (index >= 0) {
  3630. MotionMemento& memento = mMotionMementos.editItemAt(index);
  3631. memento.setPointers(entry);
  3632. return true;
  3633. }
  3634. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3635. ALOGD("Dropping inconsistent motion pointer up/down or move event: "
  3636. "deviceId=%d, source=%08x, actionMasked=%d",
  3637. entry->deviceId, entry->source, actionMasked);
  3638. #endif
  3639. return false;
  3640. }
  3641. case AMOTION_EVENT_ACTION_HOVER_EXIT: {
  3642. ssize_t index = findMotionMemento(entry, true /*hovering*/);
  3643. if (index >= 0) {
  3644. mMotionMementos.removeAt(index);
  3645. return true;
  3646. }
  3647. #if DEBUG_OUTBOUND_EVENT_DETAILS
  3648. ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
  3649. entry->deviceId, entry->source);
  3650. #endif
  3651. return false;
  3652. }
  3653. case AMOTION_EVENT_ACTION_HOVER_ENTER:
  3654. case AMOTION_EVENT_ACTION_HOVER_MOVE: {
  3655. ssize_t index = findMotionMemento(entry, true /*hovering*/);
  3656. if (index >= 0) {
  3657. mMotionMementos.removeAt(index);
  3658. }
  3659. addMotionMemento(entry, flags, true /*hovering*/);
  3660. return true;
  3661. }
  3662. default:
  3663. return true;
  3664. }
  3665. }
  3666. ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
  3667. for (size_t i = 0; i < mKeyMementos.size(); i++) {
  3668. const KeyMemento& memento = mKeyMementos.itemAt(i);
  3669. if (memento.deviceId == entry->deviceId
  3670. && memento.source == entry->source
  3671. && memento.keyCode == entry->keyCode
  3672. && memento.scanCode == entry->scanCode) {
  3673. return i;
  3674. }
  3675. }
  3676. return -1;
  3677. }
  3678. ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
  3679. bool hovering) const {
  3680. for (size_t i = 0; i < mMotionMementos.size(); i++) {
  3681. const MotionMemento& memento = mMotionMementos.itemAt(i);
  3682. if (memento.deviceId == entry->deviceId
  3683. && memento.source == entry->source
  3684. && memento.displayId == entry->displayId
  3685. && memento.hovering == hovering) {
  3686. return i;
  3687. }
  3688. }
  3689. return -1;
  3690. }
  3691. void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
  3692. mKeyMementos.push();
  3693. KeyMemento& memento = mKeyMementos.editTop();
  3694. memento.deviceId = entry->deviceId;
  3695. memento.source = entry->source;
  3696. memento.keyCode = entry->keyCode;
  3697. memento.scanCode = entry->scanCode;
  3698. memento.metaState = entry->metaState;
  3699. memento.flags = flags;
  3700. memento.downTime = entry->downTime;
  3701. memento.policyFlags = entry->policyFlags;
  3702. }
  3703. void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
  3704. int32_t flags, bool hovering) {
  3705. mMotionMementos.push();
  3706. MotionMemento& memento = mMotionMementos.editTop();
  3707. memento.deviceId = entry->deviceId;
  3708. memento.source = entry->source;
  3709. memento.flags = flags;
  3710. memento.xPrecision = entry->xPrecision;
  3711. memento.yPrecision = entry->yPrecision;
  3712. memento.downTime = entry->downTime;
  3713. memento.displayId = entry->displayId;
  3714. memento.setPointers(entry);
  3715. memento.hovering = hovering;
  3716. memento.policyFlags = entry->policyFlags;
  3717. }
  3718. void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
  3719. pointerCount = entry->pointerCount;
  3720. for (uint32_t i = 0; i < entry->pointerCount; i++) {
  3721. pointerProperties[i].copyFrom(entry->pointerProperties[i]);
  3722. pointerCoords[i].copyFrom(entry->pointerCoords[i]);
  3723. }
  3724. }
  3725. void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
  3726. Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
  3727. for (size_t i = 0; i < mKeyMementos.size(); i++) {
  3728. const KeyMemento& memento = mKeyMementos.itemAt(i);
  3729. if (shouldCancelKey(memento, options)) {
  3730. outEvents.push(new KeyEntry(currentTime,
  3731. memento.deviceId, memento.source, memento.policyFlags,
  3732. AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
  3733. memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
  3734. }
  3735. }
  3736. for (size_t i = 0; i < mMotionMementos.size(); i++) {
  3737. const MotionMemento& memento = mMotionMementos.itemAt(i);
  3738. if (shouldCancelMotion(memento, options)) {
  3739. outEvents.push(new MotionEntry(currentTime,
  3740. memento.deviceId, memento.source, memento.policyFlags,
  3741. memento.hovering
  3742. ? AMOTION_EVENT_ACTION_HOVER_EXIT
  3743. : AMOTION_EVENT_ACTION_CANCEL,
  3744. memento.flags, 0, 0, 0, 0,
  3745. memento.xPrecision, memento.yPrecision, memento.downTime,
  3746. memento.displayId,
  3747. memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
  3748. 0, 0));
  3749. }
  3750. }
  3751. }
  3752. void InputDispatcher::InputState::clear() {
  3753. mKeyMementos.clear();
  3754. mMotionMementos.clear();
  3755. mFallbackKeys.clear();
  3756. }
  3757. void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
  3758. for (size_t i = 0; i < mMotionMementos.size(); i++) {
  3759. const MotionMemento& memento = mMotionMementos.itemAt(i);
  3760. if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
  3761. for (size_t j = 0; j < other.mMotionMementos.size(); ) {
  3762. const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
  3763. if (memento.deviceId == otherMemento.deviceId
  3764. && memento.source == otherMemento.source
  3765. && memento.displayId == otherMemento.displayId) {
  3766. other.mMotionMementos.removeAt(j);
  3767. } else {
  3768. j += 1;
  3769. }
  3770. }
  3771. other.mMotionMementos.push(memento);
  3772. }
  3773. }
  3774. }
  3775. int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
  3776. ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
  3777. return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
  3778. }
  3779. void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
  3780. int32_t fallbackKeyCode) {
  3781. ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
  3782. if (index >= 0) {
  3783. mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
  3784. } else {
  3785. mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
  3786. }
  3787. }
  3788. void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
  3789. mFallbackKeys.removeItem(originalKeyCode);
  3790. }
  3791. bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
  3792. const CancelationOptions& options) {
  3793. if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
  3794. return false;
  3795. }
  3796. if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
  3797. return false;
  3798. }
  3799. switch (options.mode) {
  3800. case CancelationOptions::CANCEL_ALL_EVENTS:
  3801. case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
  3802. return true;
  3803. case CancelationOptions::CANCEL_FALLBACK_EVENTS:
  3804. return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
  3805. default:
  3806. return false;
  3807. }
  3808. }
  3809. bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
  3810. const CancelationOptions& options) {
  3811. if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
  3812. return false;
  3813. }
  3814. switch (options.mode) {
  3815. case CancelationOptions::CANCEL_ALL_EVENTS:
  3816. return true;
  3817. case CancelationOptions::CANCEL_POINTER_EVENTS:
  3818. return memento.source & AINPUT_SOURCE_CLASS_POINTER;
  3819. case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
  3820. return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
  3821. default:
  3822. return false;
  3823. }
  3824. }
  3825. // --- InputDispatcher::Connection ---
  3826. InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
  3827. const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
  3828. status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
  3829. monitor(monitor),
  3830. inputPublisher(inputChannel), inputPublisherBlocked(false) {
  3831. }
  3832. InputDispatcher::Connection::~Connection() {
  3833. }
  3834. const char* InputDispatcher::Connection::getWindowName() const {
  3835. if (inputWindowHandle != NULL) {
  3836. return inputWindowHandle->getName().string();
  3837. }
  3838. if (monitor) {
  3839. return "monitor";
  3840. }
  3841. return "?";
  3842. }
  3843. const char* InputDispatcher::Connection::getStatusLabel() const {
  3844. switch (status) {
  3845. case STATUS_NORMAL:
  3846. return "NORMAL";
  3847. case STATUS_BROKEN:
  3848. return "BROKEN";
  3849. case STATUS_ZOMBIE:
  3850. return "ZOMBIE";
  3851. default:
  3852. return "UNKNOWN";
  3853. }
  3854. }
  3855. InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
  3856. for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
  3857. if (entry->seq == seq) {
  3858. return entry;
  3859. }
  3860. }
  3861. return NULL;
  3862. }
  3863. // --- InputDispatcher::CommandEntry ---
  3864. InputDispatcher::CommandEntry::CommandEntry(Command command) :
  3865. command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
  3866. seq(0), handled(false) {
  3867. }
  3868. InputDispatcher::CommandEntry::~CommandEntry() {
  3869. }
  3870. // --- InputDispatcher::TouchState ---
  3871. InputDispatcher::TouchState::TouchState() :
  3872. down(false), split(false), deviceId(-1), source(0), displayId(-1) {
  3873. }
  3874. InputDispatcher::TouchState::~TouchState() {
  3875. }
  3876. void InputDispatcher::TouchState::reset() {
  3877. down = false;
  3878. split = false;
  3879. deviceId = -1;
  3880. source = 0;
  3881. displayId = -1;
  3882. windows.clear();
  3883. }
  3884. void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
  3885. down = other.down;
  3886. split = other.split;
  3887. deviceId = other.deviceId;
  3888. source = other.source;
  3889. displayId = other.displayId;
  3890. windows = other.windows;
  3891. }
  3892. void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
  3893. int32_t targetFlags, BitSet32 pointerIds) {
  3894. if (targetFlags & InputTarget::FLAG_SPLIT) {
  3895. split = true;
  3896. }
  3897. for (size_t i = 0; i < windows.size(); i++) {
  3898. TouchedWindow& touchedWindow = windows.editItemAt(i);
  3899. if (touchedWindow.windowHandle == windowHandle) {
  3900. touchedWindow.targetFlags |= targetFlags;
  3901. if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
  3902. touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
  3903. }
  3904. touchedWindow.pointerIds.value |= pointerIds.value;
  3905. return;
  3906. }
  3907. }
  3908. windows.push();
  3909. TouchedWindow& touchedWindow = windows.editTop();
  3910. touchedWindow.windowHandle = windowHandle;
  3911. touchedWindow.targetFlags = targetFlags;
  3912. touchedWindow.pointerIds = pointerIds;
  3913. }
  3914. void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
  3915. for (size_t i = 0; i < windows.size(); i++) {
  3916. if (windows.itemAt(i).windowHandle == windowHandle) {
  3917. windows.removeAt(i);
  3918. return;
  3919. }
  3920. }
  3921. }
  3922. void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
  3923. for (size_t i = 0 ; i < windows.size(); ) {
  3924. TouchedWindow& window = windows.editItemAt(i);
  3925. if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
  3926. | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
  3927. window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
  3928. window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
  3929. i += 1;
  3930. } else {
  3931. windows.removeAt(i);
  3932. }
  3933. }
  3934. }
  3935. sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
  3936. for (size_t i = 0; i < windows.size(); i++) {
  3937. const TouchedWindow& window = windows.itemAt(i);
  3938. if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
  3939. return window.windowHandle;
  3940. }
  3941. }
  3942. return NULL;
  3943. }
  3944. bool InputDispatcher::TouchState::isSlippery() const {
  3945. // Must have exactly one foreground window.
  3946. bool haveSlipperyForegroundWindow = false;
  3947. for (size_t i = 0; i < windows.size(); i++) {
  3948. const TouchedWindow& window = windows.itemAt(i);
  3949. if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
  3950. if (haveSlipperyForegroundWindow
  3951. || !(window.windowHandle->getInfo()->layoutParamsFlags
  3952. & InputWindowInfo::FLAG_SLIPPERY)) {
  3953. return false;
  3954. }
  3955. haveSlipperyForegroundWindow = true;
  3956. }
  3957. }
  3958. return haveSlipperyForegroundWindow;
  3959. }
  3960. // --- InputDispatcherThread ---
  3961. InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
  3962. Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
  3963. }
  3964. InputDispatcherThread::~InputDispatcherThread() {
  3965. }
  3966. bool InputDispatcherThread::threadLoop() {
  3967. mDispatcher->dispatchOnce();
  3968. return true;
  3969. }
  3970. } // namespace android