nsDisplayList.cpp 269 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  2. * This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. */
  6. /*
  7. * structures that represent things to be painted (ordered in z-order),
  8. * used during painting and hit testing
  9. */
  10. #include "nsDisplayList.h"
  11. #include <stdint.h>
  12. #include <algorithm>
  13. #include <limits>
  14. #include "gfxUtils.h"
  15. #include "mozilla/dom/TabChild.h"
  16. #include "mozilla/dom/KeyframeEffectReadOnly.h"
  17. #include "mozilla/gfx/2D.h"
  18. #include "mozilla/layers/PLayerTransaction.h"
  19. #include "nsCSSRendering.h"
  20. #include "nsRenderingContext.h"
  21. #include "nsISelectionController.h"
  22. #include "nsIPresShell.h"
  23. #include "nsRegion.h"
  24. #include "nsStyleStructInlines.h"
  25. #include "nsStyleTransformMatrix.h"
  26. #include "gfxMatrix.h"
  27. #include "gfxPrefs.h"
  28. #include "nsSVGIntegrationUtils.h"
  29. #include "nsSVGUtils.h"
  30. #include "nsLayoutUtils.h"
  31. #include "nsIScrollableFrame.h"
  32. #include "nsIFrameInlines.h"
  33. #include "nsThemeConstants.h"
  34. #include "LayerTreeInvalidation.h"
  35. #include "imgIContainer.h"
  36. #include "BasicLayers.h"
  37. #include "nsBoxFrame.h"
  38. #include "nsViewportFrame.h"
  39. #include "nsSubDocumentFrame.h"
  40. #include "nsSVGEffects.h"
  41. #include "nsSVGElement.h"
  42. #include "nsSVGClipPathFrame.h"
  43. #include "GeckoProfiler.h"
  44. #include "nsViewManager.h"
  45. #include "ImageLayers.h"
  46. #include "ImageContainer.h"
  47. #include "nsCanvasFrame.h"
  48. #include "StickyScrollContainer.h"
  49. #include "mozilla/AnimationPerformanceWarning.h"
  50. #include "mozilla/AnimationUtils.h"
  51. #include "mozilla/EffectCompositor.h"
  52. #include "mozilla/EffectSet.h"
  53. #include "mozilla/EventStates.h"
  54. #include "mozilla/LookAndFeel.h"
  55. #include "mozilla/OperatorNewExtensions.h"
  56. #include "mozilla/PendingAnimationTracker.h"
  57. #include "mozilla/Preferences.h"
  58. #include "mozilla/UniquePtr.h"
  59. #include "mozilla/Unused.h"
  60. #include "mozilla/gfx/gfxVars.h"
  61. #include "ActiveLayerTracker.h"
  62. #include "nsContentUtils.h"
  63. #include "nsPrintfCString.h"
  64. #include "UnitTransforms.h"
  65. #include "LayersLogging.h"
  66. #include "FrameLayerBuilder.h"
  67. #include "mozilla/EventStateManager.h"
  68. #include "mozilla/RestyleManager.h"
  69. #include "nsCaret.h"
  70. #include "nsISelection.h"
  71. #include "nsDOMTokenList.h"
  72. #include "mozilla/RuleNodeCacheConditions.h"
  73. #include "nsCSSProps.h"
  74. #include "nsPluginFrame.h"
  75. #include "DisplayItemScrollClip.h"
  76. #include "nsSVGMaskFrame.h"
  77. #include "nsTableCellFrame.h"
  78. #include "nsTableColFrame.h"
  79. // GetCurrentTime is defined in winbase.h as zero argument macro forwarding to
  80. // GetTickCount().
  81. #ifdef GetCurrentTime
  82. #undef GetCurrentTime
  83. #endif
  84. using namespace mozilla;
  85. using namespace mozilla::layers;
  86. using namespace mozilla::dom;
  87. using namespace mozilla::layout;
  88. using namespace mozilla::gfx;
  89. typedef FrameMetrics::ViewID ViewID;
  90. typedef nsStyleTransformMatrix::TransformReferenceBox TransformReferenceBox;
  91. #ifdef DEBUG
  92. static bool
  93. SpammyLayoutWarningsEnabled()
  94. {
  95. static bool sValue = false;
  96. static bool sValueInitialized = false;
  97. if (!sValueInitialized) {
  98. Preferences::GetBool("layout.spammy_warnings.enabled", &sValue);
  99. sValueInitialized = true;
  100. }
  101. return sValue;
  102. }
  103. #endif
  104. void*
  105. AnimatedGeometryRoot::operator new(size_t aSize, nsDisplayListBuilder* aBuilder)
  106. {
  107. return aBuilder->Allocate(aSize);
  108. }
  109. static inline CSSAngle
  110. MakeCSSAngle(const nsCSSValue& aValue)
  111. {
  112. return CSSAngle(aValue.GetAngleValue(), aValue.GetUnit());
  113. }
  114. static void AddTransformFunctions(nsCSSValueList* aList,
  115. nsStyleContext* aContext,
  116. nsPresContext* aPresContext,
  117. TransformReferenceBox& aRefBox,
  118. InfallibleTArray<TransformFunction>& aFunctions)
  119. {
  120. if (aList->mValue.GetUnit() == eCSSUnit_None) {
  121. return;
  122. }
  123. for (const nsCSSValueList* curr = aList; curr; curr = curr->mNext) {
  124. const nsCSSValue& currElem = curr->mValue;
  125. NS_ASSERTION(currElem.GetUnit() == eCSSUnit_Function,
  126. "Stream should consist solely of functions!");
  127. nsCSSValue::Array* array = currElem.GetArrayValue();
  128. RuleNodeCacheConditions conditions;
  129. switch (nsStyleTransformMatrix::TransformFunctionOf(array)) {
  130. case eCSSKeyword_rotatex:
  131. {
  132. CSSAngle theta = MakeCSSAngle(array->Item(1));
  133. aFunctions.AppendElement(RotationX(theta));
  134. break;
  135. }
  136. case eCSSKeyword_rotatey:
  137. {
  138. CSSAngle theta = MakeCSSAngle(array->Item(1));
  139. aFunctions.AppendElement(RotationY(theta));
  140. break;
  141. }
  142. case eCSSKeyword_rotatez:
  143. {
  144. CSSAngle theta = MakeCSSAngle(array->Item(1));
  145. aFunctions.AppendElement(RotationZ(theta));
  146. break;
  147. }
  148. case eCSSKeyword_rotate:
  149. {
  150. CSSAngle theta = MakeCSSAngle(array->Item(1));
  151. aFunctions.AppendElement(Rotation(theta));
  152. break;
  153. }
  154. case eCSSKeyword_rotate3d:
  155. {
  156. double x = array->Item(1).GetFloatValue();
  157. double y = array->Item(2).GetFloatValue();
  158. double z = array->Item(3).GetFloatValue();
  159. CSSAngle theta = MakeCSSAngle(array->Item(4));
  160. aFunctions.AppendElement(Rotation3D(x, y, z, theta));
  161. break;
  162. }
  163. case eCSSKeyword_scalex:
  164. {
  165. double x = array->Item(1).GetFloatValue();
  166. aFunctions.AppendElement(Scale(x, 1, 1));
  167. break;
  168. }
  169. case eCSSKeyword_scaley:
  170. {
  171. double y = array->Item(1).GetFloatValue();
  172. aFunctions.AppendElement(Scale(1, y, 1));
  173. break;
  174. }
  175. case eCSSKeyword_scalez:
  176. {
  177. double z = array->Item(1).GetFloatValue();
  178. aFunctions.AppendElement(Scale(1, 1, z));
  179. break;
  180. }
  181. case eCSSKeyword_scale:
  182. {
  183. double x = array->Item(1).GetFloatValue();
  184. // scale(x) is shorthand for scale(x, x);
  185. double y = array->Count() == 2 ? x : array->Item(2).GetFloatValue();
  186. aFunctions.AppendElement(Scale(x, y, 1));
  187. break;
  188. }
  189. case eCSSKeyword_scale3d:
  190. {
  191. double x = array->Item(1).GetFloatValue();
  192. double y = array->Item(2).GetFloatValue();
  193. double z = array->Item(3).GetFloatValue();
  194. aFunctions.AppendElement(Scale(x, y, z));
  195. break;
  196. }
  197. case eCSSKeyword_translatex:
  198. {
  199. double x = nsStyleTransformMatrix::ProcessTranslatePart(
  200. array->Item(1), aContext, aPresContext, conditions,
  201. &aRefBox, &TransformReferenceBox::Width);
  202. aFunctions.AppendElement(Translation(x, 0, 0));
  203. break;
  204. }
  205. case eCSSKeyword_translatey:
  206. {
  207. double y = nsStyleTransformMatrix::ProcessTranslatePart(
  208. array->Item(1), aContext, aPresContext, conditions,
  209. &aRefBox, &TransformReferenceBox::Height);
  210. aFunctions.AppendElement(Translation(0, y, 0));
  211. break;
  212. }
  213. case eCSSKeyword_translatez:
  214. {
  215. double z = nsStyleTransformMatrix::ProcessTranslatePart(
  216. array->Item(1), aContext, aPresContext, conditions,
  217. nullptr);
  218. aFunctions.AppendElement(Translation(0, 0, z));
  219. break;
  220. }
  221. case eCSSKeyword_translate:
  222. {
  223. double x = nsStyleTransformMatrix::ProcessTranslatePart(
  224. array->Item(1), aContext, aPresContext, conditions,
  225. &aRefBox, &TransformReferenceBox::Width);
  226. // translate(x) is shorthand for translate(x, 0)
  227. double y = 0;
  228. if (array->Count() == 3) {
  229. y = nsStyleTransformMatrix::ProcessTranslatePart(
  230. array->Item(2), aContext, aPresContext, conditions,
  231. &aRefBox, &TransformReferenceBox::Height);
  232. }
  233. aFunctions.AppendElement(Translation(x, y, 0));
  234. break;
  235. }
  236. case eCSSKeyword_translate3d:
  237. {
  238. double x = nsStyleTransformMatrix::ProcessTranslatePart(
  239. array->Item(1), aContext, aPresContext, conditions,
  240. &aRefBox, &TransformReferenceBox::Width);
  241. double y = nsStyleTransformMatrix::ProcessTranslatePart(
  242. array->Item(2), aContext, aPresContext, conditions,
  243. &aRefBox, &TransformReferenceBox::Height);
  244. double z = nsStyleTransformMatrix::ProcessTranslatePart(
  245. array->Item(3), aContext, aPresContext, conditions,
  246. nullptr);
  247. aFunctions.AppendElement(Translation(x, y, z));
  248. break;
  249. }
  250. case eCSSKeyword_skewx:
  251. {
  252. CSSAngle x = MakeCSSAngle(array->Item(1));
  253. aFunctions.AppendElement(SkewX(x));
  254. break;
  255. }
  256. case eCSSKeyword_skewy:
  257. {
  258. CSSAngle y = MakeCSSAngle(array->Item(1));
  259. aFunctions.AppendElement(SkewY(y));
  260. break;
  261. }
  262. case eCSSKeyword_skew:
  263. {
  264. CSSAngle x = MakeCSSAngle(array->Item(1));
  265. // skew(x) is shorthand for skew(x, 0)
  266. CSSAngle y(0.0f, eCSSUnit_Degree);
  267. if (array->Count() == 3) {
  268. y = MakeCSSAngle(array->Item(2));
  269. }
  270. aFunctions.AppendElement(Skew(x, y));
  271. break;
  272. }
  273. case eCSSKeyword_matrix:
  274. {
  275. gfx::Matrix4x4 matrix;
  276. matrix._11 = array->Item(1).GetFloatValue();
  277. matrix._12 = array->Item(2).GetFloatValue();
  278. matrix._13 = 0;
  279. matrix._14 = 0;
  280. matrix._21 = array->Item(3).GetFloatValue();
  281. matrix._22 = array->Item(4).GetFloatValue();
  282. matrix._23 = 0;
  283. matrix._24 = 0;
  284. matrix._31 = 0;
  285. matrix._32 = 0;
  286. matrix._33 = 1;
  287. matrix._34 = 0;
  288. matrix._41 = array->Item(5).GetFloatValue();
  289. matrix._42 = array->Item(6).GetFloatValue();
  290. matrix._43 = 0;
  291. matrix._44 = 1;
  292. aFunctions.AppendElement(TransformMatrix(matrix));
  293. break;
  294. }
  295. case eCSSKeyword_matrix3d:
  296. {
  297. gfx::Matrix4x4 matrix;
  298. matrix._11 = array->Item(1).GetFloatValue();
  299. matrix._12 = array->Item(2).GetFloatValue();
  300. matrix._13 = array->Item(3).GetFloatValue();
  301. matrix._14 = array->Item(4).GetFloatValue();
  302. matrix._21 = array->Item(5).GetFloatValue();
  303. matrix._22 = array->Item(6).GetFloatValue();
  304. matrix._23 = array->Item(7).GetFloatValue();
  305. matrix._24 = array->Item(8).GetFloatValue();
  306. matrix._31 = array->Item(9).GetFloatValue();
  307. matrix._32 = array->Item(10).GetFloatValue();
  308. matrix._33 = array->Item(11).GetFloatValue();
  309. matrix._34 = array->Item(12).GetFloatValue();
  310. matrix._41 = array->Item(13).GetFloatValue();
  311. matrix._42 = array->Item(14).GetFloatValue();
  312. matrix._43 = array->Item(15).GetFloatValue();
  313. matrix._44 = array->Item(16).GetFloatValue();
  314. aFunctions.AppendElement(TransformMatrix(matrix));
  315. break;
  316. }
  317. case eCSSKeyword_interpolatematrix:
  318. {
  319. bool dummy;
  320. Matrix4x4 matrix;
  321. nsStyleTransformMatrix::ProcessInterpolateMatrix(matrix, array,
  322. aContext,
  323. aPresContext,
  324. conditions,
  325. aRefBox,
  326. &dummy);
  327. aFunctions.AppendElement(TransformMatrix(matrix));
  328. break;
  329. }
  330. case eCSSKeyword_perspective:
  331. {
  332. aFunctions.AppendElement(Perspective(array->Item(1).GetFloatValue()));
  333. break;
  334. }
  335. default:
  336. NS_ERROR("Function not handled yet!");
  337. }
  338. }
  339. }
  340. static TimingFunction
  341. ToTimingFunction(const Maybe<ComputedTimingFunction>& aCTF)
  342. {
  343. if (aCTF.isNothing()) {
  344. return TimingFunction(null_t());
  345. }
  346. if (aCTF->HasSpline()) {
  347. const nsSMILKeySpline* spline = aCTF->GetFunction();
  348. return TimingFunction(CubicBezierFunction(spline->X1(), spline->Y1(),
  349. spline->X2(), spline->Y2()));
  350. }
  351. uint32_t type = aCTF->GetType() == nsTimingFunction::Type::StepStart ? 1 : 2;
  352. return TimingFunction(StepFunction(aCTF->GetSteps(), type));
  353. }
  354. static void
  355. AddAnimationForProperty(nsIFrame* aFrame, const AnimationProperty& aProperty,
  356. dom::Animation* aAnimation, Layer* aLayer,
  357. AnimationData& aData, bool aPending)
  358. {
  359. MOZ_ASSERT(aLayer->AsContainerLayer(), "Should only animate ContainerLayer");
  360. MOZ_ASSERT(aAnimation->GetEffect(),
  361. "Should not be adding an animation without an effect");
  362. MOZ_ASSERT(!aAnimation->GetCurrentOrPendingStartTime().IsNull() ||
  363. (aAnimation->GetTimeline() &&
  364. aAnimation->GetTimeline()->TracksWallclockTime()),
  365. "Animation should either have a resolved start time or "
  366. "a timeline that tracks wallclock time");
  367. nsStyleContext* styleContext = aFrame->StyleContext();
  368. nsPresContext* presContext = aFrame->PresContext();
  369. TransformReferenceBox refBox(aFrame);
  370. layers::Animation* animation =
  371. aPending ?
  372. aLayer->AddAnimationForNextTransaction() :
  373. aLayer->AddAnimation();
  374. const TimingParams& timing = aAnimation->GetEffect()->SpecifiedTiming();
  375. // If we are starting a new transition that replaces an existing transition
  376. // running on the compositor, it is possible that the animation on the
  377. // compositor will have advanced ahead of the main thread. If we use as
  378. // the starting point of the new transition, the current value of the
  379. // replaced transition as calculated on the main thread using the refresh
  380. // driver time, the new transition will jump when it starts. Instead, we
  381. // re-calculate the starting point of the new transition by applying the
  382. // current TimeStamp to the parameters of the replaced transition.
  383. //
  384. // We need to do this here, rather than when we generate the new transition,
  385. // since after generating the new transition other requestAnimationFrame
  386. // callbacks may run that introduce further lag between the main thread and
  387. // the compositor.
  388. if (aAnimation->AsCSSTransition() &&
  389. aAnimation->GetEffect() &&
  390. aAnimation->GetEffect()->AsTransition()) {
  391. // We update startValue from the replaced transition only if the effect is
  392. // an ElementPropertyTransition.
  393. aAnimation->GetEffect()->AsTransition()->
  394. UpdateStartValueFromReplacedTransition();
  395. }
  396. const ComputedTiming computedTiming =
  397. aAnimation->GetEffect()->GetComputedTiming();
  398. Nullable<TimeDuration> startTime = aAnimation->GetCurrentOrPendingStartTime();
  399. animation->startTime() = startTime.IsNull()
  400. ? TimeStamp()
  401. : aAnimation->GetTimeline()->
  402. ToTimeStamp(startTime.Value());
  403. animation->initialCurrentTime() = aAnimation->GetCurrentTime().Value()
  404. - timing.mDelay;
  405. animation->delay() = timing.mDelay;
  406. animation->duration() = computedTiming.mDuration;
  407. animation->iterations() = computedTiming.mIterations;
  408. animation->iterationStart() = computedTiming.mIterationStart;
  409. animation->direction() = static_cast<uint8_t>(timing.mDirection);
  410. animation->fillMode() = static_cast<uint8_t>(computedTiming.mFill);
  411. animation->property() = aProperty.mProperty;
  412. animation->playbackRate() = aAnimation->PlaybackRate();
  413. animation->data() = aData;
  414. animation->easingFunction() = ToTimingFunction(timing.mFunction);
  415. animation->iterationComposite() =
  416. static_cast<uint8_t>(aAnimation->GetEffect()->
  417. AsKeyframeEffect()->IterationComposite());
  418. for (uint32_t segIdx = 0; segIdx < aProperty.mSegments.Length(); segIdx++) {
  419. const AnimationPropertySegment& segment = aProperty.mSegments[segIdx];
  420. AnimationSegment* animSegment = animation->segments().AppendElement();
  421. if (aProperty.mProperty == eCSSProperty_transform) {
  422. animSegment->startState() = InfallibleTArray<TransformFunction>();
  423. animSegment->endState() = InfallibleTArray<TransformFunction>();
  424. nsCSSValueSharedList* list =
  425. segment.mFromValue.GetCSSValueSharedListValue();
  426. AddTransformFunctions(list->mHead, styleContext, presContext, refBox,
  427. animSegment->startState().get_ArrayOfTransformFunction());
  428. list = segment.mToValue.GetCSSValueSharedListValue();
  429. AddTransformFunctions(list->mHead, styleContext, presContext, refBox,
  430. animSegment->endState().get_ArrayOfTransformFunction());
  431. } else if (aProperty.mProperty == eCSSProperty_opacity) {
  432. animSegment->startState() = segment.mFromValue.GetFloatValue();
  433. animSegment->endState() = segment.mToValue.GetFloatValue();
  434. }
  435. animSegment->startPortion() = segment.mFromKey;
  436. animSegment->endPortion() = segment.mToKey;
  437. animSegment->sampleFn() = ToTimingFunction(segment.mTimingFunction);
  438. }
  439. }
  440. static void
  441. AddAnimationsForProperty(nsIFrame* aFrame, nsCSSPropertyID aProperty,
  442. nsTArray<RefPtr<dom::Animation>>& aAnimations,
  443. Layer* aLayer, AnimationData& aData,
  444. bool aPending)
  445. {
  446. MOZ_ASSERT(nsCSSProps::PropHasFlags(aProperty,
  447. CSS_PROPERTY_CAN_ANIMATE_ON_COMPOSITOR),
  448. "inconsistent property flags");
  449. DebugOnly<EffectSet*> effects = EffectSet::GetEffectSet(aFrame);
  450. MOZ_ASSERT(effects);
  451. // Add from first to last (since last overrides)
  452. for (size_t animIdx = 0; animIdx < aAnimations.Length(); animIdx++) {
  453. dom::Animation* anim = aAnimations[animIdx];
  454. if (!anim->IsPlayableOnCompositor()) {
  455. continue;
  456. }
  457. dom::KeyframeEffectReadOnly* keyframeEffect =
  458. anim->GetEffect() ? anim->GetEffect()->AsKeyframeEffect() : nullptr;
  459. MOZ_ASSERT(keyframeEffect,
  460. "A playing animation should have a keyframe effect");
  461. const AnimationProperty* property =
  462. keyframeEffect->GetEffectiveAnimationOfProperty(aProperty);
  463. if (!property) {
  464. continue;
  465. }
  466. // Note that if the property is overridden by !important rules,
  467. // GetEffectiveAnimationOfProperty returns null instead.
  468. // This is what we want, since if we have animations overridden by
  469. // !important rules, we don't want to send them to the compositor.
  470. MOZ_ASSERT(anim->CascadeLevel() !=
  471. EffectCompositor::CascadeLevel::Animations ||
  472. !effects->PropertiesWithImportantRules()
  473. .HasProperty(aProperty),
  474. "GetEffectiveAnimationOfProperty already tested the property "
  475. "is not overridden by !important rules");
  476. // Don't add animations that are pending if their timeline does not
  477. // track wallclock time. This is because any pending animations on layers
  478. // will have their start time updated with the current wallclock time.
  479. // If we can't convert that wallclock time back to an equivalent timeline
  480. // time, we won't be able to update the content animation and it will end
  481. // up being out of sync with the layer animation.
  482. //
  483. // Currently this only happens when the timeline is driven by a refresh
  484. // driver under test control. In this case, the next time the refresh
  485. // driver is advanced it will trigger any pending animations.
  486. if (anim->PlayState() == AnimationPlayState::Pending &&
  487. (!anim->GetTimeline() ||
  488. !anim->GetTimeline()->TracksWallclockTime())) {
  489. continue;
  490. }
  491. AddAnimationForProperty(aFrame, *property, anim, aLayer, aData, aPending);
  492. keyframeEffect->SetIsRunningOnCompositor(aProperty, true);
  493. }
  494. }
  495. static bool
  496. GenerateAndPushTextMask(nsIFrame* aFrame, nsRenderingContext* aContext,
  497. const nsRect& aFillRect, nsDisplayListBuilder* aBuilder)
  498. {
  499. if (aBuilder->IsForGenerateGlyphMask() ||
  500. aBuilder->IsForPaintingSelectionBG()) {
  501. return false;
  502. }
  503. // The main function of enabling background-clip:text property value.
  504. // When a nsDisplayBackgroundImage detects "text" bg-clip style, it will call
  505. // this function to
  506. // 1. Paint background color of the selection text if any.
  507. // 2. Generate a mask by all descendant text frames
  508. // 3. Push the generated mask into aContext.
  509. //
  510. // TBD: we actually generate display list of aFrame twice here. It's better
  511. // to reuse the same display list and paint that one twice, one for selection
  512. // background, one for generating text mask.
  513. gfxContext* sourceCtx = aContext->ThebesContext();
  514. gfxRect bounds =
  515. nsLayoutUtils::RectToGfxRect(aFillRect,
  516. aFrame->PresContext()->AppUnitsPerDevPixel());
  517. {
  518. // Paint text selection background into sourceCtx.
  519. gfxContextMatrixAutoSaveRestore save(sourceCtx);
  520. sourceCtx->SetMatrix(sourceCtx->CurrentMatrix().Translate(bounds.TopLeft()));
  521. nsLayoutUtils::PaintFrame(aContext, aFrame,
  522. nsRect(nsPoint(0, 0), aFrame->GetSize()),
  523. NS_RGB(255, 255, 255),
  524. nsDisplayListBuilderMode::PAINTING_SELECTION_BACKGROUND);
  525. }
  526. // Evaluate required surface size.
  527. IntRect drawRect;
  528. {
  529. gfxContextMatrixAutoSaveRestore matRestore(sourceCtx);
  530. sourceCtx->SetMatrix(gfxMatrix());
  531. gfxRect clipRect = sourceCtx->GetClipExtents();
  532. drawRect = RoundedOut(ToRect(clipRect));
  533. }
  534. // Create a mask surface.
  535. RefPtr<DrawTarget> sourceTarget = sourceCtx->GetDrawTarget();
  536. RefPtr<DrawTarget> maskDT =
  537. sourceTarget->CreateSimilarDrawTarget(drawRect.Size(),
  538. SurfaceFormat::A8);
  539. if (!maskDT || !maskDT->IsValid()) {
  540. return false;
  541. }
  542. RefPtr<gfxContext> maskCtx = gfxContext::CreatePreservingTransformOrNull(maskDT);
  543. MOZ_ASSERT(maskCtx);
  544. gfxMatrix currentMatrix = sourceCtx->CurrentMatrix();
  545. maskCtx->SetMatrix(gfxMatrix::Translation(bounds.TopLeft()) *
  546. currentMatrix *
  547. gfxMatrix::Translation(-drawRect.TopLeft()));
  548. // Shade text shape into mask A8 surface.
  549. nsRenderingContext rc(maskCtx);
  550. nsLayoutUtils::PaintFrame(&rc, aFrame,
  551. nsRect(nsPoint(0, 0), aFrame->GetSize()),
  552. NS_RGB(255, 255, 255),
  553. nsDisplayListBuilderMode::GENERATE_GLYPH);
  554. // Push the generated mask into aContext, so that the caller can pop and
  555. // blend with it.
  556. Matrix maskTransform = ToMatrix(currentMatrix) *
  557. Matrix::Translation(-drawRect.x, -drawRect.y);
  558. maskTransform.Invert();
  559. RefPtr<SourceSurface> maskSurface = maskDT->Snapshot();
  560. sourceCtx->PushGroupForBlendBack(gfxContentType::COLOR_ALPHA, 1.0, maskSurface, maskTransform);
  561. return true;
  562. }
  563. /* static */ void
  564. nsDisplayListBuilder::AddAnimationsAndTransitionsToLayer(Layer* aLayer,
  565. nsDisplayListBuilder* aBuilder,
  566. nsDisplayItem* aItem,
  567. nsIFrame* aFrame,
  568. nsCSSPropertyID aProperty)
  569. {
  570. MOZ_ASSERT(nsCSSProps::PropHasFlags(aProperty,
  571. CSS_PROPERTY_CAN_ANIMATE_ON_COMPOSITOR),
  572. "inconsistent property flags");
  573. // This function can be called in two ways: from
  574. // nsDisplay*::BuildLayer while constructing a layer (with all
  575. // pointers non-null), or from RestyleManager's handling of
  576. // UpdateOpacityLayer/UpdateTransformLayer hints.
  577. MOZ_ASSERT(!aBuilder == !aItem,
  578. "should only be called in two configurations, with both "
  579. "aBuilder and aItem, or with neither");
  580. MOZ_ASSERT(!aItem || aFrame == aItem->Frame(), "frame mismatch");
  581. // Only send animations to a layer that is actually using
  582. // off-main-thread compositing.
  583. if (aLayer->Manager()->GetBackendType() !=
  584. layers::LayersBackend::LAYERS_CLIENT) {
  585. return;
  586. }
  587. bool pending = !aBuilder;
  588. if (pending) {
  589. aLayer->ClearAnimationsForNextTransaction();
  590. } else {
  591. aLayer->ClearAnimations();
  592. }
  593. // Update the animation generation on the layer. We need to do this before
  594. // any early returns since even if we don't add any animations to the
  595. // layer, we still need to mark it as up-to-date with regards to animations.
  596. // Otherwise, in RestyleManager we'll notice the discrepancy between the
  597. // animation generation numbers and update the layer indefinitely.
  598. uint64_t animationGeneration =
  599. RestyleManager::GetAnimationGenerationForFrame(aFrame);
  600. aLayer->SetAnimationGeneration(animationGeneration);
  601. EffectCompositor::ClearIsRunningOnCompositor(aFrame, aProperty);
  602. nsTArray<RefPtr<dom::Animation>> compositorAnimations =
  603. EffectCompositor::GetAnimationsForCompositor(aFrame, aProperty);
  604. if (compositorAnimations.IsEmpty()) {
  605. return;
  606. }
  607. // If the frame is not prerendered, bail out.
  608. // Do this check only during layer construction; during updating the
  609. // caller is required to check it appropriately.
  610. if (aItem && !aItem->CanUseAsyncAnimations(aBuilder)) {
  611. // EffectCompositor needs to know that we refused to run this animation
  612. // asynchronously so that it will not throttle the main thread
  613. // animation.
  614. aFrame->SetProperty(nsIFrame::RefusedAsyncAnimationProperty(), true);
  615. // We need to schedule another refresh driver run so that EffectCompositor
  616. // gets a chance to unthrottle the animation.
  617. aFrame->SchedulePaint();
  618. return;
  619. }
  620. AnimationData data;
  621. if (aProperty == eCSSProperty_transform) {
  622. // XXX Performance here isn't ideal for SVG. We'd prefer to avoid resolving
  623. // the dimensions of refBox. That said, we only get here if there are CSS
  624. // animations or transitions on this element, and that is likely to be a
  625. // lot rarer than transforms on SVG (the frequency of which drives the need
  626. // for TransformReferenceBox).
  627. TransformReferenceBox refBox(aFrame);
  628. nsRect bounds(0, 0, refBox.Width(), refBox.Height());
  629. // all data passed directly to the compositor should be in dev pixels
  630. int32_t devPixelsToAppUnits = aFrame->PresContext()->AppUnitsPerDevPixel();
  631. float scale = devPixelsToAppUnits;
  632. Point3D offsetToTransformOrigin =
  633. nsDisplayTransform::GetDeltaToTransformOrigin(aFrame, scale, &bounds);
  634. nsPoint origin;
  635. if (aItem) {
  636. // This branch is for display items to leverage the cache of
  637. // nsDisplayListBuilder.
  638. origin = aItem->ToReferenceFrame();
  639. } else {
  640. // This branch is running for restyling.
  641. // Animations are animated at the coordination of the reference
  642. // frame outside, not the given frame itself. The given frame
  643. // is also reference frame too, so the parent's reference frame
  644. // are used.
  645. nsIFrame* referenceFrame =
  646. nsLayoutUtils::GetReferenceFrame(nsLayoutUtils::GetCrossDocParentFrame(aFrame));
  647. origin = aFrame->GetOffsetToCrossDoc(referenceFrame);
  648. }
  649. data = TransformData(origin, offsetToTransformOrigin,
  650. bounds, devPixelsToAppUnits);
  651. } else if (aProperty == eCSSProperty_opacity) {
  652. data = null_t();
  653. }
  654. AddAnimationsForProperty(aFrame, aProperty, compositorAnimations,
  655. aLayer, data, pending);
  656. }
  657. nsDisplayListBuilder::nsDisplayListBuilder(nsIFrame* aReferenceFrame,
  658. nsDisplayListBuilderMode aMode, bool aBuildCaret)
  659. : mReferenceFrame(aReferenceFrame),
  660. mIgnoreScrollFrame(nullptr),
  661. mLayerEventRegions(nullptr),
  662. mCurrentFrame(aReferenceFrame),
  663. mCurrentReferenceFrame(aReferenceFrame),
  664. mCurrentAGR(&mRootAGR),
  665. mRootAGR(aReferenceFrame, nullptr),
  666. mUsedAGRBudget(0),
  667. mDirtyRect(-1,-1,-1,-1),
  668. mGlassDisplayItem(nullptr),
  669. mScrollInfoItemsForHoisting(nullptr),
  670. mMode(aMode),
  671. mTableBackgroundSet(nullptr),
  672. mCurrentScrollParentId(FrameMetrics::NULL_SCROLL_ID),
  673. mCurrentScrollbarTarget(FrameMetrics::NULL_SCROLL_ID),
  674. mCurrentScrollbarFlags(0),
  675. mPerspectiveItemIndex(0),
  676. mSVGEffectsBuildingDepth(0),
  677. mContainsBlendMode(false),
  678. mIsBuildingScrollbar(false),
  679. mCurrentScrollbarWillHaveLayer(false),
  680. mBuildCaret(aBuildCaret),
  681. mIgnoreSuppression(false),
  682. mIsAtRootOfPseudoStackingContext(false),
  683. mIncludeAllOutOfFlows(false),
  684. mDescendIntoSubdocuments(true),
  685. mSelectedFramesOnly(false),
  686. mAccurateVisibleRegions(false),
  687. mAllowMergingAndFlattening(true),
  688. mWillComputePluginGeometry(false),
  689. mInTransform(false),
  690. mIsInChromePresContext(false),
  691. mSyncDecodeImages(false),
  692. mIsPaintingToWindow(false),
  693. mIsCompositingCheap(false),
  694. mContainsPluginItem(false),
  695. mAncestorHasApzAwareEventHandler(false),
  696. mHaveScrollableDisplayPort(false),
  697. mWindowDraggingAllowed(false),
  698. mIsBuildingForPopup(nsLayoutUtils::IsPopup(aReferenceFrame)),
  699. mForceLayerForScrollParent(false),
  700. mAsyncPanZoomEnabled(nsLayoutUtils::AsyncPanZoomEnabled(aReferenceFrame)),
  701. mBuildingInvisibleItems(false)
  702. {
  703. MOZ_COUNT_CTOR(nsDisplayListBuilder);
  704. PL_InitArenaPool(&mPool, "displayListArena", 4096,
  705. std::max(NS_ALIGNMENT_OF(void*),NS_ALIGNMENT_OF(double))-1);
  706. nsPresContext* pc = aReferenceFrame->PresContext();
  707. nsIPresShell *shell = pc->PresShell();
  708. if (pc->IsRenderingOnlySelection()) {
  709. nsCOMPtr<nsISelectionController> selcon(do_QueryInterface(shell));
  710. if (selcon) {
  711. selcon->GetSelection(nsISelectionController::SELECTION_NORMAL,
  712. getter_AddRefs(mBoundingSelection));
  713. }
  714. }
  715. mFrameToAnimatedGeometryRootMap.Put(aReferenceFrame, &mRootAGR);
  716. nsCSSRendering::BeginFrameTreesLocked();
  717. static_assert(nsDisplayItem::TYPE_MAX < (1 << nsDisplayItem::TYPE_BITS),
  718. "Check nsDisplayItem::TYPE_MAX should not overflow");
  719. }
  720. static void MarkFrameForDisplay(nsIFrame* aFrame, nsIFrame* aStopAtFrame) {
  721. for (nsIFrame* f = aFrame; f;
  722. f = nsLayoutUtils::GetParentOrPlaceholderFor(f)) {
  723. if (f->GetStateBits() & NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)
  724. return;
  725. f->AddStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO);
  726. if (f == aStopAtFrame) {
  727. // we've reached a frame that we know will be painted, so we can stop.
  728. break;
  729. }
  730. }
  731. }
  732. bool nsDisplayListBuilder::NeedToForceTransparentSurfaceForItem(nsDisplayItem* aItem)
  733. {
  734. return aItem == mGlassDisplayItem || aItem->ClearsBackground();
  735. }
  736. AnimatedGeometryRoot*
  737. nsDisplayListBuilder::WrapAGRForFrame(nsIFrame* aAnimatedGeometryRoot,
  738. AnimatedGeometryRoot* aParent /* = nullptr */)
  739. {
  740. MOZ_ASSERT(IsAnimatedGeometryRoot(aAnimatedGeometryRoot));
  741. AnimatedGeometryRoot* result = nullptr;
  742. if (!mFrameToAnimatedGeometryRootMap.Get(aAnimatedGeometryRoot, &result)) {
  743. MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(RootReferenceFrame(), aAnimatedGeometryRoot));
  744. AnimatedGeometryRoot* parent = aParent;
  745. if (!parent) {
  746. nsIFrame* parentFrame = nsLayoutUtils::GetCrossDocParentFrame(aAnimatedGeometryRoot);
  747. if (parentFrame) {
  748. nsIFrame* parentAGRFrame = FindAnimatedGeometryRootFrameFor(parentFrame);
  749. parent = WrapAGRForFrame(parentAGRFrame);
  750. }
  751. }
  752. result = new (this) AnimatedGeometryRoot(aAnimatedGeometryRoot, parent);
  753. mFrameToAnimatedGeometryRootMap.Put(aAnimatedGeometryRoot, result);
  754. }
  755. MOZ_ASSERT(!aParent || result->mParentAGR == aParent);
  756. return result;
  757. }
  758. AnimatedGeometryRoot*
  759. nsDisplayListBuilder::FindAnimatedGeometryRootFor(nsIFrame* aFrame)
  760. {
  761. if (!IsPaintingToWindow()) {
  762. return &mRootAGR;
  763. }
  764. if (aFrame == mCurrentFrame) {
  765. return mCurrentAGR;
  766. }
  767. AnimatedGeometryRoot* result = nullptr;
  768. if (mFrameToAnimatedGeometryRootMap.Get(aFrame, &result)) {
  769. return result;
  770. }
  771. nsIFrame* agrFrame = FindAnimatedGeometryRootFrameFor(aFrame);
  772. result = WrapAGRForFrame(agrFrame);
  773. mFrameToAnimatedGeometryRootMap.Put(aFrame, result);
  774. return result;
  775. }
  776. AnimatedGeometryRoot*
  777. nsDisplayListBuilder::FindAnimatedGeometryRootFor(nsDisplayItem* aItem)
  778. {
  779. if (aItem->ShouldFixToViewport(this)) {
  780. // Make its active scrolled root be the active scrolled root of
  781. // the enclosing viewport, since it shouldn't be scrolled by scrolled
  782. // frames in its document. InvalidateFixedBackgroundFramesFromList in
  783. // nsGfxScrollFrame will not repaint this item when scrolling occurs.
  784. nsIFrame* viewportFrame =
  785. nsLayoutUtils::GetClosestFrameOfType(aItem->Frame(), nsGkAtoms::viewportFrame, RootReferenceFrame());
  786. if (viewportFrame) {
  787. return FindAnimatedGeometryRootFor(viewportFrame);
  788. }
  789. }
  790. return FindAnimatedGeometryRootFor(aItem->Frame());
  791. }
  792. void nsDisplayListBuilder::MarkOutOfFlowFrameForDisplay(nsIFrame* aDirtyFrame,
  793. nsIFrame* aFrame)
  794. {
  795. nsRect dirtyRectRelativeToDirtyFrame = GetDirtyRect();
  796. if (nsLayoutUtils::IsFixedPosFrameInDisplayPort(aFrame) &&
  797. IsPaintingToWindow()) {
  798. NS_ASSERTION(aDirtyFrame == aFrame->GetParent(), "Dirty frame should be viewport frame");
  799. // position: fixed items are reflowed into and only drawn inside the
  800. // viewport, or the scroll position clamping scrollport size, if one is
  801. // set.
  802. nsIPresShell* ps = aFrame->PresContext()->PresShell();
  803. dirtyRectRelativeToDirtyFrame.MoveTo(0, 0);
  804. if (ps->IsScrollPositionClampingScrollPortSizeSet()) {
  805. dirtyRectRelativeToDirtyFrame.SizeTo(ps->GetScrollPositionClampingScrollPortSize());
  806. } else {
  807. dirtyRectRelativeToDirtyFrame.SizeTo(aDirtyFrame->GetSize());
  808. }
  809. }
  810. nsRect dirty = dirtyRectRelativeToDirtyFrame - aFrame->GetOffsetTo(aDirtyFrame);
  811. nsRect overflowRect = aFrame->GetVisualOverflowRect();
  812. if (aFrame->IsTransformed() &&
  813. EffectCompositor::HasAnimationsForCompositor(aFrame,
  814. eCSSProperty_transform)) {
  815. /**
  816. * Add a fuzz factor to the overflow rectangle so that elements only just
  817. * out of view are pulled into the display list, so they can be
  818. * prerendered if necessary.
  819. */
  820. overflowRect.Inflate(nsPresContext::CSSPixelsToAppUnits(32));
  821. }
  822. if (!dirty.IntersectRect(dirty, overflowRect) &&
  823. !(aFrame->GetStateBits() & NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO)) {
  824. return;
  825. }
  826. const DisplayItemClip* oldClip = mClipState.GetClipForContainingBlockDescendants();
  827. const DisplayItemScrollClip* sc = mClipState.GetCurrentInnermostScrollClip();
  828. OutOfFlowDisplayData* data = new OutOfFlowDisplayData(oldClip, sc, dirty);
  829. aFrame->SetProperty(nsDisplayListBuilder::OutOfFlowDisplayDataProperty(), data);
  830. MarkFrameForDisplay(aFrame, aDirtyFrame);
  831. }
  832. static void UnmarkFrameForDisplay(nsIFrame* aFrame) {
  833. aFrame->DeleteProperty(nsDisplayListBuilder::OutOfFlowDisplayDataProperty());
  834. for (nsIFrame* f = aFrame; f;
  835. f = nsLayoutUtils::GetParentOrPlaceholderFor(f)) {
  836. if (!(f->GetStateBits() & NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO))
  837. return;
  838. f->RemoveStateBits(NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO);
  839. }
  840. }
  841. nsDisplayListBuilder::~nsDisplayListBuilder() {
  842. NS_ASSERTION(mFramesMarkedForDisplay.Length() == 0,
  843. "All frames should have been unmarked");
  844. NS_ASSERTION(mPresShellStates.Length() == 0,
  845. "All presshells should have been exited");
  846. nsCSSRendering::EndFrameTreesLocked();
  847. for (DisplayItemClip* c : mDisplayItemClipsToDestroy) {
  848. c->DisplayItemClip::~DisplayItemClip();
  849. }
  850. for (DisplayItemScrollClip* c : mScrollClipsToDestroy) {
  851. c->DisplayItemScrollClip::~DisplayItemScrollClip();
  852. }
  853. PL_FinishArenaPool(&mPool);
  854. MOZ_COUNT_DTOR(nsDisplayListBuilder);
  855. }
  856. uint32_t
  857. nsDisplayListBuilder::GetBackgroundPaintFlags() {
  858. uint32_t flags = 0;
  859. if (mSyncDecodeImages) {
  860. flags |= nsCSSRendering::PAINTBG_SYNC_DECODE_IMAGES;
  861. }
  862. if (mIsPaintingToWindow) {
  863. flags |= nsCSSRendering::PAINTBG_TO_WINDOW;
  864. }
  865. return flags;
  866. }
  867. void
  868. nsDisplayListBuilder::SubtractFromVisibleRegion(nsRegion* aVisibleRegion,
  869. const nsRegion& aRegion)
  870. {
  871. if (aRegion.IsEmpty())
  872. return;
  873. nsRegion tmp;
  874. tmp.Sub(*aVisibleRegion, aRegion);
  875. // Don't let *aVisibleRegion get too complex, but don't let it fluff out
  876. // to its bounds either, which can be very bad (see bug 516740).
  877. // Do let aVisibleRegion get more complex if by doing so we reduce its
  878. // area by at least half.
  879. if (GetAccurateVisibleRegions() || tmp.GetNumRects() <= 15 ||
  880. tmp.Area() <= aVisibleRegion->Area()/2) {
  881. *aVisibleRegion = tmp;
  882. }
  883. }
  884. nsCaret *
  885. nsDisplayListBuilder::GetCaret() {
  886. RefPtr<nsCaret> caret = CurrentPresShellState()->mPresShell->GetCaret();
  887. return caret;
  888. }
  889. void
  890. nsDisplayListBuilder::EnterPresShell(nsIFrame* aReferenceFrame,
  891. bool aPointerEventsNoneDoc)
  892. {
  893. PresShellState* state = mPresShellStates.AppendElement();
  894. state->mPresShell = aReferenceFrame->PresContext()->PresShell();
  895. state->mCaretFrame = nullptr;
  896. state->mFirstFrameMarkedForDisplay = mFramesMarkedForDisplay.Length();
  897. state->mPresShell->UpdateCanvasBackground();
  898. if (mIsPaintingToWindow) {
  899. mReferenceFrame->AddPaintedPresShell(state->mPresShell);
  900. state->mPresShell->IncrementPaintCount();
  901. }
  902. bool buildCaret = mBuildCaret;
  903. if (mIgnoreSuppression || !state->mPresShell->IsPaintingSuppressed()) {
  904. state->mIsBackgroundOnly = false;
  905. } else {
  906. state->mIsBackgroundOnly = true;
  907. buildCaret = false;
  908. }
  909. bool pointerEventsNone = aPointerEventsNoneDoc;
  910. if (IsInSubdocument()) {
  911. pointerEventsNone |= mPresShellStates[mPresShellStates.Length() - 2].mInsidePointerEventsNoneDoc;
  912. }
  913. state->mInsidePointerEventsNoneDoc = pointerEventsNone;
  914. state->mPresShellIgnoreScrollFrame =
  915. state->mPresShell->IgnoringViewportScrolling()
  916. ? state->mPresShell->GetRootScrollFrame()
  917. : nullptr;
  918. nsPresContext* pc = aReferenceFrame->PresContext();
  919. nsCOMPtr<nsIDocShell> docShell = pc->GetDocShell();
  920. if (docShell) {
  921. docShell->GetWindowDraggingAllowed(&mWindowDraggingAllowed);
  922. }
  923. mIsInChromePresContext = pc->IsChrome();
  924. if (!buildCaret) {
  925. return;
  926. }
  927. RefPtr<nsCaret> caret = state->mPresShell->GetCaret();
  928. state->mCaretFrame = caret->GetPaintGeometry(&state->mCaretRect);
  929. if (state->mCaretFrame) {
  930. mFramesMarkedForDisplay.AppendElement(state->mCaretFrame);
  931. MarkFrameForDisplay(state->mCaretFrame, nullptr);
  932. }
  933. }
  934. // A non-blank paint is a paint that does not just contain the canvas background.
  935. static bool
  936. DisplayListIsNonBlank(nsDisplayList* aList)
  937. {
  938. for (nsDisplayItem* i = aList->GetBottom(); i != nullptr; i = i->GetAbove()) {
  939. switch (i->GetType()) {
  940. case nsDisplayItem::TYPE_LAYER_EVENT_REGIONS:
  941. case nsDisplayItem::TYPE_CANVAS_BACKGROUND_COLOR:
  942. case nsDisplayItem::TYPE_CANVAS_BACKGROUND_IMAGE:
  943. continue;
  944. case nsDisplayItem::TYPE_SOLID_COLOR:
  945. case nsDisplayItem::TYPE_BACKGROUND:
  946. case nsDisplayItem::TYPE_BACKGROUND_COLOR:
  947. if (i->Frame()->GetType() == nsGkAtoms::canvasFrame) {
  948. continue;
  949. }
  950. return true;
  951. default:
  952. return true;
  953. }
  954. }
  955. return false;
  956. }
  957. void
  958. nsDisplayListBuilder::LeavePresShell(nsIFrame* aReferenceFrame, nsDisplayList* aPaintedContents)
  959. {
  960. NS_ASSERTION(CurrentPresShellState()->mPresShell ==
  961. aReferenceFrame->PresContext()->PresShell(),
  962. "Presshell mismatch");
  963. if (mIsPaintingToWindow) {
  964. nsPresContext* pc = aReferenceFrame->PresContext();
  965. if (!pc->HadNonBlankPaint()) {
  966. if (!CurrentPresShellState()->mIsBackgroundOnly &&
  967. DisplayListIsNonBlank(aPaintedContents)) {
  968. pc->NotifyNonBlankPaint();
  969. }
  970. }
  971. }
  972. ResetMarkedFramesForDisplayList();
  973. mPresShellStates.SetLength(mPresShellStates.Length() - 1);
  974. if (!mPresShellStates.IsEmpty()) {
  975. nsPresContext* pc = CurrentPresContext();
  976. nsCOMPtr<nsIDocShell> docShell = pc->GetDocShell();
  977. if (docShell) {
  978. docShell->GetWindowDraggingAllowed(&mWindowDraggingAllowed);
  979. }
  980. mIsInChromePresContext = pc->IsChrome();
  981. }
  982. }
  983. void
  984. nsDisplayListBuilder::ResetMarkedFramesForDisplayList()
  985. {
  986. // Unmark and pop off the frames marked for display in this pres shell.
  987. uint32_t firstFrameForShell = CurrentPresShellState()->mFirstFrameMarkedForDisplay;
  988. for (uint32_t i = firstFrameForShell;
  989. i < mFramesMarkedForDisplay.Length(); ++i) {
  990. UnmarkFrameForDisplay(mFramesMarkedForDisplay[i]);
  991. }
  992. mFramesMarkedForDisplay.SetLength(firstFrameForShell);
  993. }
  994. void
  995. nsDisplayListBuilder::MarkFramesForDisplayList(nsIFrame* aDirtyFrame,
  996. const nsFrameList& aFrames) {
  997. for (nsIFrame* e : aFrames) {
  998. // Skip the AccessibleCaret frame when building no caret.
  999. if (!IsBuildingCaret()) {
  1000. nsIContent* content = e->GetContent();
  1001. if (content && content->IsInNativeAnonymousSubtree() && content->IsElement()) {
  1002. auto classList = content->AsElement()->ClassList();
  1003. if (classList->Contains(NS_LITERAL_STRING("moz-accessiblecaret"))) {
  1004. continue;
  1005. }
  1006. }
  1007. }
  1008. mFramesMarkedForDisplay.AppendElement(e);
  1009. MarkOutOfFlowFrameForDisplay(aDirtyFrame, e);
  1010. }
  1011. }
  1012. /**
  1013. * Mark all preserve-3d children with
  1014. * NS_FRAME_FORCE_DISPLAY_LIST_DESCEND_INTO to make sure
  1015. * nsFrame::BuildDisplayListForChild() would visit them. Also compute
  1016. * dirty rect for preserve-3d children.
  1017. *
  1018. * @param aDirtyFrame is the frame to mark children extending context.
  1019. */
  1020. void
  1021. nsDisplayListBuilder::MarkPreserve3DFramesForDisplayList(nsIFrame* aDirtyFrame)
  1022. {
  1023. AutoTArray<nsIFrame::ChildList,4> childListArray;
  1024. aDirtyFrame->GetChildLists(&childListArray);
  1025. nsIFrame::ChildListArrayIterator lists(childListArray);
  1026. for (; !lists.IsDone(); lists.Next()) {
  1027. nsFrameList::Enumerator childFrames(lists.CurrentList());
  1028. for (; !childFrames.AtEnd(); childFrames.Next()) {
  1029. nsIFrame *child = childFrames.get();
  1030. if (child->Combines3DTransformWithAncestors()) {
  1031. mFramesMarkedForDisplay.AppendElement(child);
  1032. MarkFrameForDisplay(child, aDirtyFrame);
  1033. }
  1034. }
  1035. }
  1036. }
  1037. void*
  1038. nsDisplayListBuilder::Allocate(size_t aSize)
  1039. {
  1040. void *tmp;
  1041. PL_ARENA_ALLOCATE(tmp, &mPool, aSize);
  1042. if (!tmp) {
  1043. NS_ABORT_OOM(aSize);
  1044. }
  1045. return tmp;
  1046. }
  1047. const DisplayItemClip*
  1048. nsDisplayListBuilder::AllocateDisplayItemClip(const DisplayItemClip& aOriginal)
  1049. {
  1050. void* p = Allocate(sizeof(DisplayItemClip));
  1051. if (!aOriginal.GetRoundedRectCount()) {
  1052. memcpy(p, &aOriginal, sizeof(DisplayItemClip));
  1053. return static_cast<DisplayItemClip*>(p);
  1054. }
  1055. DisplayItemClip* c = new (KnownNotNull, p) DisplayItemClip(aOriginal);
  1056. mDisplayItemClipsToDestroy.AppendElement(c);
  1057. return c;
  1058. }
  1059. DisplayItemScrollClip*
  1060. nsDisplayListBuilder::AllocateDisplayItemScrollClip(const DisplayItemScrollClip* aParent,
  1061. nsIScrollableFrame* aScrollableFrame,
  1062. const DisplayItemClip* aClip,
  1063. bool aIsAsyncScrollable)
  1064. {
  1065. void* p = Allocate(sizeof(DisplayItemScrollClip));
  1066. DisplayItemScrollClip* c =
  1067. new (KnownNotNull, p) DisplayItemScrollClip(aParent, aScrollableFrame,
  1068. aClip, aIsAsyncScrollable);
  1069. mScrollClipsToDestroy.AppendElement(c);
  1070. return c;
  1071. }
  1072. const nsIFrame*
  1073. nsDisplayListBuilder::FindReferenceFrameFor(const nsIFrame *aFrame,
  1074. nsPoint* aOffset)
  1075. {
  1076. if (aFrame == mCurrentFrame) {
  1077. if (aOffset) {
  1078. *aOffset = mCurrentOffsetToReferenceFrame;
  1079. }
  1080. return mCurrentReferenceFrame;
  1081. }
  1082. for (const nsIFrame* f = aFrame; f; f = nsLayoutUtils::GetCrossDocParentFrame(f))
  1083. {
  1084. if (f == mReferenceFrame || f->IsTransformed()) {
  1085. if (aOffset) {
  1086. *aOffset = aFrame->GetOffsetToCrossDoc(f);
  1087. }
  1088. return f;
  1089. }
  1090. }
  1091. if (aOffset) {
  1092. *aOffset = aFrame->GetOffsetToCrossDoc(mReferenceFrame);
  1093. }
  1094. return mReferenceFrame;
  1095. }
  1096. // Sticky frames are active if their nearest scrollable frame is also active.
  1097. static bool
  1098. IsStickyFrameActive(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsIFrame* aParent)
  1099. {
  1100. MOZ_ASSERT(aFrame->StyleDisplay()->mPosition == NS_STYLE_POSITION_STICKY);
  1101. // Find the nearest scrollframe.
  1102. nsIFrame* cursor = aFrame;
  1103. nsIFrame* parent = aParent;
  1104. if (!parent) {
  1105. parent = nsLayoutUtils::GetCrossDocParentFrame(aFrame);
  1106. }
  1107. while (parent->GetType() != nsGkAtoms::scrollFrame) {
  1108. cursor = parent;
  1109. if ((parent = nsLayoutUtils::GetCrossDocParentFrame(cursor)) == nullptr) {
  1110. return false;
  1111. }
  1112. }
  1113. nsIScrollableFrame* sf = do_QueryFrame(parent);
  1114. return sf->IsScrollingActive(aBuilder) && sf->GetScrolledFrame() == cursor;
  1115. }
  1116. bool
  1117. nsDisplayListBuilder::IsAnimatedGeometryRoot(nsIFrame* aFrame, nsIFrame** aParent)
  1118. {
  1119. if (aFrame == mReferenceFrame) {
  1120. return true;
  1121. }
  1122. if (!IsPaintingToWindow()) {
  1123. if (aParent) {
  1124. *aParent = nsLayoutUtils::GetCrossDocParentFrame(aFrame);
  1125. }
  1126. return false;
  1127. }
  1128. if (nsLayoutUtils::IsPopup(aFrame))
  1129. return true;
  1130. if (ActiveLayerTracker::IsOffsetOrMarginStyleAnimated(aFrame)) {
  1131. const bool inBudget = AddToAGRBudget(aFrame);
  1132. if (inBudget) {
  1133. return true;
  1134. }
  1135. }
  1136. if (!aFrame->GetParent() &&
  1137. nsLayoutUtils::ViewportHasDisplayPort(aFrame->PresContext())) {
  1138. // Viewport frames in a display port need to be animated geometry roots
  1139. // for background-attachment:fixed elements.
  1140. return true;
  1141. }
  1142. if (aFrame->IsTransformed()) {
  1143. return true;
  1144. }
  1145. nsIFrame* parent = nsLayoutUtils::GetCrossDocParentFrame(aFrame);
  1146. if (!parent)
  1147. return true;
  1148. nsIAtom* parentType = parent->GetType();
  1149. // Treat the slider thumb as being as an active scrolled root when it wants
  1150. // its own layer so that it can move without repainting.
  1151. if (parentType == nsGkAtoms::sliderFrame && nsLayoutUtils::IsScrollbarThumbLayerized(aFrame)) {
  1152. return true;
  1153. }
  1154. if (aFrame->StyleDisplay()->mPosition == NS_STYLE_POSITION_STICKY &&
  1155. IsStickyFrameActive(this, aFrame, parent))
  1156. {
  1157. return true;
  1158. }
  1159. if (parentType == nsGkAtoms::scrollFrame || parentType == nsGkAtoms::listControlFrame) {
  1160. nsIScrollableFrame* sf = do_QueryFrame(parent);
  1161. if (sf->IsScrollingActive(this) && sf->GetScrolledFrame() == aFrame) {
  1162. return true;
  1163. }
  1164. }
  1165. // Fixed-pos frames are parented by the viewport frame, which has no parent.
  1166. if (nsLayoutUtils::IsFixedPosFrameInDisplayPort(aFrame)) {
  1167. return true;
  1168. }
  1169. if (aParent) {
  1170. *aParent = parent;
  1171. }
  1172. return false;
  1173. }
  1174. nsIFrame*
  1175. nsDisplayListBuilder::FindAnimatedGeometryRootFrameFor(nsIFrame* aFrame)
  1176. {
  1177. MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(RootReferenceFrame(), aFrame));
  1178. nsIFrame* cursor = aFrame;
  1179. while (cursor != RootReferenceFrame()) {
  1180. nsIFrame* next;
  1181. if (IsAnimatedGeometryRoot(cursor, &next))
  1182. return cursor;
  1183. cursor = next;
  1184. }
  1185. return cursor;
  1186. }
  1187. void
  1188. nsDisplayListBuilder::RecomputeCurrentAnimatedGeometryRoot()
  1189. {
  1190. if (*mCurrentAGR != mCurrentFrame &&
  1191. IsAnimatedGeometryRoot(const_cast<nsIFrame*>(mCurrentFrame))) {
  1192. AnimatedGeometryRoot* oldAGR = mCurrentAGR;
  1193. mCurrentAGR = WrapAGRForFrame(const_cast<nsIFrame*>(mCurrentFrame), mCurrentAGR);
  1194. // Iterate the AGR cache and look for any objects that reference the old AGR and check
  1195. // to see if they need to be updated. AGRs can be in the cache multiple times, so we may
  1196. // end up doing the work multiple times for AGRs that don't change.
  1197. for (auto iter = mFrameToAnimatedGeometryRootMap.Iter(); !iter.Done(); iter.Next()) {
  1198. AnimatedGeometryRoot* cached = iter.UserData();
  1199. if (cached->mParentAGR == oldAGR && cached != mCurrentAGR) {
  1200. // It's possible that this cached AGR struct that has the old AGR as a parent
  1201. // should instead have mCurrentFrame has a parent.
  1202. nsIFrame* parent = FindAnimatedGeometryRootFrameFor(*cached);
  1203. MOZ_ASSERT(parent == mCurrentFrame || parent == *oldAGR);
  1204. if (parent == mCurrentFrame) {
  1205. cached->mParentAGR = mCurrentAGR;
  1206. }
  1207. }
  1208. }
  1209. }
  1210. }
  1211. void
  1212. nsDisplayListBuilder::AdjustWindowDraggingRegion(nsIFrame* aFrame)
  1213. {
  1214. if (!mWindowDraggingAllowed || !IsForPainting()) {
  1215. return;
  1216. }
  1217. const nsStyleUIReset* styleUI = aFrame->StyleUIReset();
  1218. if (styleUI->mWindowDragging == StyleWindowDragging::Default) {
  1219. // This frame has the default value and doesn't influence the window
  1220. // dragging region.
  1221. return;
  1222. }
  1223. LayoutDeviceToLayoutDeviceMatrix4x4 referenceFrameToRootReferenceFrame;
  1224. // The const_cast is for nsLayoutUtils::GetTransformToAncestor.
  1225. nsIFrame* referenceFrame = const_cast<nsIFrame*>(FindReferenceFrameFor(aFrame));
  1226. if (IsInTransform()) {
  1227. // Only support 2d rectilinear transforms. Transform support is needed for
  1228. // the horizontal flip transform that's applied to the urlbar textbox in
  1229. // RTL mode - it should be able to exclude itself from the draggable region.
  1230. referenceFrameToRootReferenceFrame =
  1231. ViewAs<LayoutDeviceToLayoutDeviceMatrix4x4>(
  1232. nsLayoutUtils::GetTransformToAncestor(referenceFrame, mReferenceFrame));
  1233. Matrix referenceFrameToRootReferenceFrame2d;
  1234. if (!referenceFrameToRootReferenceFrame.Is2D(&referenceFrameToRootReferenceFrame2d) ||
  1235. !referenceFrameToRootReferenceFrame2d.IsRectilinear()) {
  1236. return;
  1237. }
  1238. } else {
  1239. MOZ_ASSERT(referenceFrame == mReferenceFrame,
  1240. "referenceFrameToRootReferenceFrame needs to be adjusted");
  1241. }
  1242. // We do some basic visibility checking on the frame's border box here.
  1243. // We intersect it both with the current dirty rect and with the current
  1244. // clip. Either one is just a conservative approximation on its own, but
  1245. // their intersection luckily works well enough for our purposes, so that
  1246. // we don't have to do full-blown visibility computations.
  1247. // The most important case we need to handle is the scrolled-off tab:
  1248. // If the tab bar overflows, tab parts that are clipped by the scrollbox
  1249. // should not be allowed to interfere with the window dragging region. Using
  1250. // just the current DisplayItemClip is not enough to cover this case
  1251. // completely because clips are reset while building stacking context
  1252. // contents, so for example we'd fail to clip frames that have a clip path
  1253. // applied to them. But the current dirty rect doesn't get reset in that
  1254. // case, so we use it to make this case work.
  1255. nsRect borderBox = aFrame->GetRectRelativeToSelf().Intersect(mDirtyRect);
  1256. borderBox += ToReferenceFrame(aFrame);
  1257. const DisplayItemClip* clip = ClipState().GetCurrentCombinedClip(this);
  1258. if (clip) {
  1259. borderBox = clip->ApplyNonRoundedIntersection(borderBox);
  1260. }
  1261. if (!borderBox.IsEmpty()) {
  1262. LayoutDeviceRect devPixelBorderBox =
  1263. LayoutDevicePixel::FromAppUnits(borderBox, aFrame->PresContext()->AppUnitsPerDevPixel());
  1264. LayoutDeviceRect transformedDevPixelBorderBox =
  1265. TransformBy(referenceFrameToRootReferenceFrame, devPixelBorderBox);
  1266. transformedDevPixelBorderBox.Round();
  1267. LayoutDeviceIntRect transformedDevPixelBorderBoxInt;
  1268. if (transformedDevPixelBorderBox.ToIntRect(&transformedDevPixelBorderBoxInt)) {
  1269. if (styleUI->mWindowDragging == StyleWindowDragging::Drag) {
  1270. mWindowDraggingRegion.OrWith(transformedDevPixelBorderBoxInt);
  1271. } else {
  1272. mWindowNoDraggingRegion.OrWith(transformedDevPixelBorderBoxInt);
  1273. }
  1274. }
  1275. }
  1276. }
  1277. LayoutDeviceIntRegion
  1278. nsDisplayListBuilder::GetWindowDraggingRegion() const
  1279. {
  1280. LayoutDeviceIntRegion result;
  1281. result.Sub(mWindowDraggingRegion, mWindowNoDraggingRegion);;
  1282. return result;
  1283. }
  1284. const uint32_t gWillChangeAreaMultiplier = 3;
  1285. static uint32_t GetLayerizationCost(const nsSize& aSize) {
  1286. // There's significant overhead for each layer created from Gecko
  1287. // (IPC+Shared Objects) and from the backend (like an OpenGL texture).
  1288. // Therefore we set a minimum cost threshold of a 64x64 area.
  1289. int minBudgetCost = 64 * 64;
  1290. uint32_t budgetCost =
  1291. std::max(minBudgetCost,
  1292. nsPresContext::AppUnitsToIntCSSPixels(aSize.width) *
  1293. nsPresContext::AppUnitsToIntCSSPixels(aSize.height));
  1294. return budgetCost;
  1295. }
  1296. bool
  1297. nsDisplayListBuilder::AddToWillChangeBudget(nsIFrame* aFrame,
  1298. const nsSize& aSize) {
  1299. if (mWillChangeBudgetSet.Contains(aFrame)) {
  1300. return true; // Already accounted
  1301. }
  1302. nsPresContext* key = aFrame->PresContext();
  1303. if (!mWillChangeBudget.Contains(key)) {
  1304. mWillChangeBudget.Put(key, DocumentWillChangeBudget());
  1305. }
  1306. DocumentWillChangeBudget budget;
  1307. mWillChangeBudget.Get(key, &budget);
  1308. nsRect area = aFrame->PresContext()->GetVisibleArea();
  1309. uint32_t budgetLimit = nsPresContext::AppUnitsToIntCSSPixels(area.width) *
  1310. nsPresContext::AppUnitsToIntCSSPixels(area.height);
  1311. uint32_t cost = GetLayerizationCost(aSize);
  1312. bool onBudget = (budget.mBudget + cost) /
  1313. gWillChangeAreaMultiplier < budgetLimit;
  1314. if (onBudget) {
  1315. budget.mBudget += cost;
  1316. mWillChangeBudget.Put(key, budget);
  1317. mWillChangeBudgetSet.PutEntry(aFrame);
  1318. }
  1319. return onBudget;
  1320. }
  1321. bool
  1322. nsDisplayListBuilder::IsInWillChangeBudget(nsIFrame* aFrame,
  1323. const nsSize& aSize) {
  1324. bool onBudget = AddToWillChangeBudget(aFrame, aSize);
  1325. if (!onBudget) {
  1326. nsString usageStr;
  1327. usageStr.AppendInt(GetLayerizationCost(aSize));
  1328. nsString multiplierStr;
  1329. multiplierStr.AppendInt(gWillChangeAreaMultiplier);
  1330. nsString limitStr;
  1331. nsRect area = aFrame->PresContext()->GetVisibleArea();
  1332. uint32_t budgetLimit = nsPresContext::AppUnitsToIntCSSPixels(area.width) *
  1333. nsPresContext::AppUnitsToIntCSSPixels(area.height);
  1334. limitStr.AppendInt(budgetLimit);
  1335. const char16_t* params[] = { multiplierStr.get(), limitStr.get() };
  1336. aFrame->PresContext()->Document()->WarnOnceAbout(
  1337. nsIDocument::eIgnoringWillChangeOverBudget, false,
  1338. params, ArrayLength(params));
  1339. }
  1340. return onBudget;
  1341. }
  1342. const float gAGRBudgetAreaMultiplier = 3.0;
  1343. bool
  1344. nsDisplayListBuilder::AddToAGRBudget(nsIFrame* aFrame)
  1345. {
  1346. if (mAGRBudgetSet.Contains(aFrame)) {
  1347. return true;
  1348. }
  1349. const nsPresContext* presContext = aFrame->PresContext()->GetRootPresContext();
  1350. if (!presContext) {
  1351. return false;
  1352. }
  1353. const nsRect area = presContext->GetVisibleArea();
  1354. const uint32_t budgetLimit = gAGRBudgetAreaMultiplier *
  1355. nsPresContext::AppUnitsToIntCSSPixels(area.width) *
  1356. nsPresContext::AppUnitsToIntCSSPixels(area.height);
  1357. const uint32_t cost = GetLayerizationCost(aFrame->GetSize());
  1358. const bool onBudget = mUsedAGRBudget + cost < budgetLimit;
  1359. if (onBudget) {
  1360. mUsedAGRBudget += cost;
  1361. mAGRBudgetSet.PutEntry(aFrame);
  1362. }
  1363. return onBudget;
  1364. }
  1365. void
  1366. nsDisplayListBuilder::EnterSVGEffectsContents(nsDisplayList* aHoistedItemsStorage)
  1367. {
  1368. MOZ_ASSERT(mSVGEffectsBuildingDepth >= 0);
  1369. MOZ_ASSERT(aHoistedItemsStorage);
  1370. if (mSVGEffectsBuildingDepth == 0) {
  1371. MOZ_ASSERT(!mScrollInfoItemsForHoisting);
  1372. mScrollInfoItemsForHoisting = aHoistedItemsStorage;
  1373. }
  1374. mSVGEffectsBuildingDepth++;
  1375. }
  1376. void
  1377. nsDisplayListBuilder::ExitSVGEffectsContents()
  1378. {
  1379. mSVGEffectsBuildingDepth--;
  1380. MOZ_ASSERT(mSVGEffectsBuildingDepth >= 0);
  1381. MOZ_ASSERT(mScrollInfoItemsForHoisting);
  1382. if (mSVGEffectsBuildingDepth == 0) {
  1383. mScrollInfoItemsForHoisting = nullptr;
  1384. }
  1385. }
  1386. void
  1387. nsDisplayListBuilder::AppendNewScrollInfoItemForHoisting(nsDisplayScrollInfoLayer* aScrollInfoItem)
  1388. {
  1389. MOZ_ASSERT(ShouldBuildScrollInfoItemsForHoisting());
  1390. MOZ_ASSERT(mScrollInfoItemsForHoisting);
  1391. mScrollInfoItemsForHoisting->AppendNewToTop(aScrollInfoItem);
  1392. }
  1393. bool
  1394. nsDisplayListBuilder::IsBuildingLayerEventRegions()
  1395. {
  1396. if (IsPaintingToWindow()) {
  1397. // Note: this function and LayerEventRegionsEnabled are the only places
  1398. // that get to query LayoutEventRegionsEnabled 'directly' - other code
  1399. // should call this function.
  1400. return gfxPrefs::LayoutEventRegionsEnabledDoNotUseDirectly() ||
  1401. mAsyncPanZoomEnabled;
  1402. }
  1403. return false;
  1404. }
  1405. /* static */ bool
  1406. nsDisplayListBuilder::LayerEventRegionsEnabled()
  1407. {
  1408. // Note: this function and IsBuildingLayerEventRegions are the only places
  1409. // that get to query LayoutEventRegionsEnabled 'directly' - other code
  1410. // should call this function.
  1411. return gfxPrefs::LayoutEventRegionsEnabledDoNotUseDirectly() ||
  1412. gfxPlatform::AsyncPanZoomEnabled();
  1413. }
  1414. void nsDisplayListSet::MoveTo(const nsDisplayListSet& aDestination) const
  1415. {
  1416. aDestination.BorderBackground()->AppendToTop(BorderBackground());
  1417. aDestination.BlockBorderBackgrounds()->AppendToTop(BlockBorderBackgrounds());
  1418. aDestination.Floats()->AppendToTop(Floats());
  1419. aDestination.Content()->AppendToTop(Content());
  1420. aDestination.PositionedDescendants()->AppendToTop(PositionedDescendants());
  1421. aDestination.Outlines()->AppendToTop(Outlines());
  1422. }
  1423. static void
  1424. MoveListTo(nsDisplayList* aList, nsTArray<nsDisplayItem*>* aElements) {
  1425. nsDisplayItem* item;
  1426. while ((item = aList->RemoveBottom()) != nullptr) {
  1427. aElements->AppendElement(item);
  1428. }
  1429. }
  1430. nsRect
  1431. nsDisplayList::GetBounds(nsDisplayListBuilder* aBuilder) const {
  1432. nsRect bounds;
  1433. for (nsDisplayItem* i = GetBottom(); i != nullptr; i = i->GetAbove()) {
  1434. bounds.UnionRect(bounds, i->GetClippedBounds(aBuilder));
  1435. }
  1436. return bounds;
  1437. }
  1438. nsRect
  1439. nsDisplayList::GetScrollClippedBoundsUpTo(nsDisplayListBuilder* aBuilder,
  1440. const DisplayItemScrollClip* aIncludeScrollClipsUpTo) const {
  1441. nsRect bounds;
  1442. for (nsDisplayItem* i = GetBottom(); i != nullptr; i = i->GetAbove()) {
  1443. nsRect r = i->GetClippedBounds(aBuilder);
  1444. if (r.IsEmpty()) {
  1445. continue;
  1446. }
  1447. for (auto* sc = i->ScrollClip(); sc && sc != aIncludeScrollClipsUpTo; sc = sc->mParent) {
  1448. if (sc->mClip && sc->mClip->HasClip()) {
  1449. if (sc->mIsAsyncScrollable) {
  1450. // Assume the item can move anywhere in the scroll clip's clip rect.
  1451. r = sc->mClip->GetClipRect();
  1452. } else {
  1453. r = sc->mClip->ApplyNonRoundedIntersection(r);
  1454. }
  1455. }
  1456. }
  1457. bounds.UnionRect(bounds, r);
  1458. }
  1459. return bounds;
  1460. }
  1461. nsRect
  1462. nsDisplayList::GetVisibleRect() const {
  1463. nsRect result;
  1464. for (nsDisplayItem* i = GetBottom(); i != nullptr; i = i->GetAbove()) {
  1465. result.UnionRect(result, i->GetVisibleRect());
  1466. }
  1467. return result;
  1468. }
  1469. bool
  1470. nsDisplayList::ComputeVisibilityForRoot(nsDisplayListBuilder* aBuilder,
  1471. nsRegion* aVisibleRegion) {
  1472. PROFILER_LABEL("nsDisplayList", "ComputeVisibilityForRoot",
  1473. js::ProfileEntry::Category::GRAPHICS);
  1474. nsRegion r;
  1475. r.And(*aVisibleRegion, GetBounds(aBuilder));
  1476. return ComputeVisibilityForSublist(aBuilder, aVisibleRegion, r.GetBounds());
  1477. }
  1478. static nsRegion
  1479. TreatAsOpaque(nsDisplayItem* aItem, nsDisplayListBuilder* aBuilder)
  1480. {
  1481. bool snap;
  1482. nsRegion opaque = aItem->GetOpaqueRegion(aBuilder, &snap);
  1483. if (aBuilder->IsForPluginGeometry() &&
  1484. aItem->GetType() != nsDisplayItem::TYPE_LAYER_EVENT_REGIONS)
  1485. {
  1486. // Treat all leaf chrome items as opaque, unless their frames are opacity:0.
  1487. // Since opacity:0 frames generate an nsDisplayOpacity, that item will
  1488. // not be treated as opaque here, so opacity:0 chrome content will be
  1489. // effectively ignored, as it should be.
  1490. // We treat leaf chrome items as opaque to ensure that they cover
  1491. // content plugins, for security reasons.
  1492. // Non-leaf chrome items don't render contents of their own so shouldn't
  1493. // be treated as opaque (and their bounds is just the union of their
  1494. // children, which might be a large area their contents don't really cover).
  1495. nsIFrame* f = aItem->Frame();
  1496. if (f->PresContext()->IsChrome() && !aItem->GetChildren() &&
  1497. f->StyleEffects()->mOpacity != 0.0) {
  1498. opaque = aItem->GetBounds(aBuilder, &snap);
  1499. }
  1500. }
  1501. if (opaque.IsEmpty()) {
  1502. return opaque;
  1503. }
  1504. nsRegion opaqueClipped;
  1505. for (auto iter = opaque.RectIter(); !iter.Done(); iter.Next()) {
  1506. opaqueClipped.Or(opaqueClipped,
  1507. aItem->GetClip().ApproximateIntersectInward(iter.Get()));
  1508. }
  1509. return opaqueClipped;
  1510. }
  1511. bool
  1512. nsDisplayList::ComputeVisibilityForSublist(nsDisplayListBuilder* aBuilder,
  1513. nsRegion* aVisibleRegion,
  1514. const nsRect& aListVisibleBounds)
  1515. {
  1516. #ifdef DEBUG
  1517. nsRegion r;
  1518. r.And(*aVisibleRegion, GetBounds(aBuilder));
  1519. NS_ASSERTION(r.GetBounds().IsEqualInterior(aListVisibleBounds),
  1520. "bad aListVisibleBounds");
  1521. #endif
  1522. bool anyVisible = false;
  1523. AutoTArray<nsDisplayItem*, 512> elements;
  1524. MoveListTo(this, &elements);
  1525. for (int32_t i = elements.Length() - 1; i >= 0; --i) {
  1526. nsDisplayItem* item = elements[i];
  1527. if (item->mForceNotVisible && !item->GetSameCoordinateSystemChildren()) {
  1528. NS_ASSERTION(item->mVisibleRect.IsEmpty(),
  1529. "invisible items should have empty vis rect");
  1530. } else {
  1531. nsRect bounds = item->GetClippedBounds(aBuilder);
  1532. nsRegion itemVisible;
  1533. itemVisible.And(*aVisibleRegion, bounds);
  1534. item->mVisibleRect = itemVisible.GetBounds();
  1535. }
  1536. if (item->ComputeVisibility(aBuilder, aVisibleRegion)) {
  1537. anyVisible = true;
  1538. nsRegion opaque = TreatAsOpaque(item, aBuilder);
  1539. // Subtract opaque item from the visible region
  1540. aBuilder->SubtractFromVisibleRegion(aVisibleRegion, opaque);
  1541. }
  1542. AppendToBottom(item);
  1543. }
  1544. mIsOpaque = !aVisibleRegion->Intersects(aListVisibleBounds);
  1545. return anyVisible;
  1546. }
  1547. static bool
  1548. TriggerPendingAnimationsOnSubDocuments(nsIDocument* aDocument, void* aReadyTime)
  1549. {
  1550. PendingAnimationTracker* tracker = aDocument->GetPendingAnimationTracker();
  1551. if (tracker) {
  1552. nsIPresShell* shell = aDocument->GetShell();
  1553. // If paint-suppression is in effect then we haven't finished painting
  1554. // this document yet so we shouldn't start animations
  1555. if (!shell || !shell->IsPaintingSuppressed()) {
  1556. const TimeStamp& readyTime = *static_cast<TimeStamp*>(aReadyTime);
  1557. tracker->TriggerPendingAnimationsOnNextTick(readyTime);
  1558. }
  1559. }
  1560. aDocument->EnumerateSubDocuments(TriggerPendingAnimationsOnSubDocuments,
  1561. aReadyTime);
  1562. return true;
  1563. }
  1564. static void
  1565. TriggerPendingAnimations(nsIDocument* aDocument,
  1566. const TimeStamp& aReadyTime) {
  1567. MOZ_ASSERT(!aReadyTime.IsNull(),
  1568. "Animation ready time is not set. Perhaps we're using a layer"
  1569. " manager that doesn't update it");
  1570. TriggerPendingAnimationsOnSubDocuments(aDocument,
  1571. const_cast<TimeStamp*>(&aReadyTime));
  1572. }
  1573. LayerManager*
  1574. nsDisplayListBuilder::GetWidgetLayerManager(nsView** aView)
  1575. {
  1576. nsView* view = RootReferenceFrame()->GetView();
  1577. if (aView) {
  1578. *aView = view;
  1579. }
  1580. if (RootReferenceFrame() != nsLayoutUtils::GetDisplayRootFrame(RootReferenceFrame())) {
  1581. return nullptr;
  1582. }
  1583. nsIWidget* window = RootReferenceFrame()->GetNearestWidget();
  1584. if (window) {
  1585. return window->GetLayerManager();
  1586. }
  1587. return nullptr;
  1588. }
  1589. /**
  1590. * We paint by executing a layer manager transaction, constructing a
  1591. * single layer representing the display list, and then making it the
  1592. * root of the layer manager, drawing into the PaintedLayers.
  1593. */
  1594. already_AddRefed<LayerManager> nsDisplayList::PaintRoot(nsDisplayListBuilder* aBuilder,
  1595. nsRenderingContext* aCtx,
  1596. uint32_t aFlags) {
  1597. PROFILER_LABEL("nsDisplayList", "PaintRoot",
  1598. js::ProfileEntry::Category::GRAPHICS);
  1599. RefPtr<LayerManager> layerManager;
  1600. bool widgetTransaction = false;
  1601. bool doBeginTransaction = true;
  1602. nsView *view = nullptr;
  1603. if (aFlags & PAINT_USE_WIDGET_LAYERS) {
  1604. layerManager = aBuilder->GetWidgetLayerManager(&view);
  1605. if (layerManager) {
  1606. doBeginTransaction = !(aFlags & PAINT_EXISTING_TRANSACTION);
  1607. widgetTransaction = true;
  1608. }
  1609. }
  1610. if (!layerManager) {
  1611. if (!aCtx) {
  1612. NS_WARNING("Nowhere to paint into");
  1613. return nullptr;
  1614. }
  1615. layerManager = new BasicLayerManager(BasicLayerManager::BLM_OFFSCREEN);
  1616. }
  1617. // Store the existing layer builder to reinstate it on return.
  1618. FrameLayerBuilder *oldBuilder = layerManager->GetLayerBuilder();
  1619. FrameLayerBuilder *layerBuilder = new FrameLayerBuilder();
  1620. layerBuilder->Init(aBuilder, layerManager);
  1621. if (aFlags & PAINT_COMPRESSED) {
  1622. layerBuilder->SetLayerTreeCompressionMode();
  1623. }
  1624. if (doBeginTransaction) {
  1625. if (aCtx) {
  1626. if (!layerManager->BeginTransactionWithTarget(aCtx->ThebesContext())) {
  1627. return nullptr;
  1628. }
  1629. } else {
  1630. if (!layerManager->BeginTransaction()) {
  1631. return nullptr;
  1632. }
  1633. }
  1634. }
  1635. if (XRE_IsContentProcess() && gfxPrefs::AlwaysPaint()) {
  1636. FrameLayerBuilder::InvalidateAllLayers(layerManager);
  1637. }
  1638. if (widgetTransaction) {
  1639. layerBuilder->DidBeginRetainedLayerTransaction(layerManager);
  1640. }
  1641. nsIFrame* frame = aBuilder->RootReferenceFrame();
  1642. nsPresContext* presContext = frame->PresContext();
  1643. nsIPresShell* presShell = presContext->PresShell();
  1644. nsRootPresContext* rootPresContext = presContext->GetRootPresContext();
  1645. NotifySubDocInvalidationFunc computeInvalidFunc =
  1646. presContext->MayHavePaintEventListenerInSubDocument() ? nsPresContext::NotifySubDocInvalidation : 0;
  1647. bool computeInvalidRect = (computeInvalidFunc ||
  1648. (!layerManager->IsCompositingCheap() && layerManager->NeedsWidgetInvalidation())) &&
  1649. widgetTransaction;
  1650. UniquePtr<LayerProperties> props;
  1651. if (computeInvalidRect) {
  1652. props = Move(LayerProperties::CloneFrom(layerManager->GetRoot()));
  1653. }
  1654. // Clear any ScrollMetadata that may have been set on the root layer on a
  1655. // previous paint. This paint will set new metrics if necessary, and if we
  1656. // don't clear the old one here, we may be left with extra metrics.
  1657. if (Layer* root = layerManager->GetRoot()) {
  1658. root->SetScrollMetadata(nsTArray<ScrollMetadata>());
  1659. }
  1660. ContainerLayerParameters containerParameters
  1661. (presShell->GetResolution(), presShell->GetResolution());
  1662. RefPtr<ContainerLayer> root;
  1663. {
  1664. root = layerBuilder->
  1665. BuildContainerLayerFor(aBuilder, layerManager, frame, nullptr, this,
  1666. containerParameters, nullptr);
  1667. }
  1668. nsIDocument* document = presShell->GetDocument();
  1669. if (!root) {
  1670. layerManager->SetUserData(&gLayerManagerLayerBuilder, oldBuilder);
  1671. return nullptr;
  1672. }
  1673. // Root is being scaled up by the X/Y resolution. Scale it back down.
  1674. root->SetPostScale(1.0f/containerParameters.mXScale,
  1675. 1.0f/containerParameters.mYScale);
  1676. root->SetScaleToResolution(presShell->ScaleToResolution(),
  1677. containerParameters.mXScale);
  1678. if (aBuilder->IsBuildingLayerEventRegions() &&
  1679. nsLayoutUtils::HasDocumentLevelListenersForApzAwareEvents(presShell)) {
  1680. root->SetEventRegionsOverride(EventRegionsOverride::ForceDispatchToContent);
  1681. } else {
  1682. root->SetEventRegionsOverride(EventRegionsOverride::NoOverride);
  1683. }
  1684. // If we're using containerless scrolling, there is still one case where we
  1685. // want the root container layer to have metrics. If the parent process is
  1686. // using XUL windows, there is no root scrollframe, and without explicitly
  1687. // creating metrics there will be no guaranteed top-level APZC.
  1688. bool addMetrics = gfxPrefs::LayoutUseContainersForRootFrames() ||
  1689. (XRE_IsParentProcess() && !presShell->GetRootScrollFrame());
  1690. // Add metrics if there are none in the layer tree with the id (create an id
  1691. // if there isn't one already) of the root scroll frame/root content.
  1692. bool ensureMetricsForRootId =
  1693. nsLayoutUtils::AsyncPanZoomEnabled(frame) &&
  1694. !gfxPrefs::LayoutUseContainersForRootFrames() &&
  1695. aBuilder->IsPaintingToWindow() &&
  1696. !presContext->GetParentPresContext();
  1697. nsIContent* content = nullptr;
  1698. nsIFrame* rootScrollFrame = presShell->GetRootScrollFrame();
  1699. if (rootScrollFrame) {
  1700. content = rootScrollFrame->GetContent();
  1701. } else {
  1702. // If there is no root scroll frame, pick the document element instead.
  1703. // The only case we don't want to do this is in non-APZ fennec, where
  1704. // we want the root xul document to get a null scroll id so that the root
  1705. // content document gets the first non-null scroll id.
  1706. content = document->GetDocumentElement();
  1707. }
  1708. if (ensureMetricsForRootId && content) {
  1709. ViewID scrollId = nsLayoutUtils::FindOrCreateIDFor(content);
  1710. if (nsLayoutUtils::ContainsMetricsWithId(root, scrollId)) {
  1711. ensureMetricsForRootId = false;
  1712. }
  1713. }
  1714. if (addMetrics || ensureMetricsForRootId) {
  1715. bool isRootContent = presContext->IsRootContentDocument();
  1716. nsRect viewport(aBuilder->ToReferenceFrame(frame), frame->GetSize());
  1717. root->SetScrollMetadata(
  1718. nsLayoutUtils::ComputeScrollMetadata(frame,
  1719. rootScrollFrame, content,
  1720. aBuilder->FindReferenceFrameFor(frame),
  1721. root, FrameMetrics::NULL_SCROLL_ID, viewport, Nothing(),
  1722. isRootContent, containerParameters));
  1723. }
  1724. // NS_WARNING is debug-only, so don't even bother checking the conditions in
  1725. // a release build.
  1726. #ifdef DEBUG
  1727. bool usingDisplayport = false;
  1728. if (nsIFrame* rootScrollFrame = presShell->GetRootScrollFrame()) {
  1729. nsIContent* content = rootScrollFrame->GetContent();
  1730. if (content) {
  1731. usingDisplayport = nsLayoutUtils::HasDisplayPort(content);
  1732. }
  1733. }
  1734. if (usingDisplayport &&
  1735. !(root->GetContentFlags() & Layer::CONTENT_OPAQUE) &&
  1736. SpammyLayoutWarningsEnabled()) {
  1737. // See bug 693938, attachment 567017
  1738. NS_WARNING("Transparent content with displayports can be expensive.");
  1739. }
  1740. #endif
  1741. layerManager->SetRoot(root);
  1742. layerBuilder->WillEndTransaction();
  1743. if (widgetTransaction ||
  1744. // SVG-as-an-image docs don't paint as part of the retained layer tree,
  1745. // but they still need the invalidation state bits cleared in order for
  1746. // invalidation for CSS/SMIL animation to work properly.
  1747. (document && document->IsBeingUsedAsImage())) {
  1748. frame->ClearInvalidationStateBits();
  1749. }
  1750. bool temp = aBuilder->SetIsCompositingCheap(layerManager->IsCompositingCheap());
  1751. LayerManager::EndTransactionFlags flags = LayerManager::END_DEFAULT;
  1752. if (layerManager->NeedsWidgetInvalidation()) {
  1753. if (aFlags & PAINT_NO_COMPOSITE) {
  1754. flags = LayerManager::END_NO_COMPOSITE;
  1755. }
  1756. } else {
  1757. // Client layer managers never composite directly, so
  1758. // we don't need to worry about END_NO_COMPOSITE.
  1759. if (aBuilder->WillComputePluginGeometry()) {
  1760. flags = LayerManager::END_NO_REMOTE_COMPOSITE;
  1761. }
  1762. }
  1763. // If this is the content process, we ship plugin geometry updates over with layer
  1764. // updates, so calculate that now before we call EndTransaction.
  1765. if (rootPresContext && XRE_IsContentProcess()) {
  1766. if (aBuilder->WillComputePluginGeometry()) {
  1767. rootPresContext->ComputePluginGeometryUpdates(aBuilder->RootReferenceFrame(), aBuilder, this);
  1768. }
  1769. // The layer system caches plugin configuration information for forwarding
  1770. // with layer updates which needs to get set during reflow. This must be
  1771. // called even if there are no windowed plugins in the page.
  1772. rootPresContext->CollectPluginGeometryUpdates(layerManager);
  1773. }
  1774. MaybeSetupTransactionIdAllocator(layerManager, view);
  1775. layerManager->EndTransaction(FrameLayerBuilder::DrawPaintedLayer,
  1776. aBuilder, flags);
  1777. aBuilder->SetIsCompositingCheap(temp);
  1778. layerBuilder->DidEndTransaction();
  1779. if (document && widgetTransaction) {
  1780. TriggerPendingAnimations(document, layerManager->GetAnimationReadyTime());
  1781. }
  1782. nsIntRegion invalid;
  1783. if (props) {
  1784. invalid = props->ComputeDifferences(root, computeInvalidFunc);
  1785. } else if (widgetTransaction) {
  1786. LayerProperties::ClearInvalidations(root);
  1787. }
  1788. bool shouldInvalidate = layerManager->NeedsWidgetInvalidation();
  1789. if (view) {
  1790. if (props) {
  1791. if (!invalid.IsEmpty()) {
  1792. nsIntRect bounds = invalid.GetBounds();
  1793. nsRect rect(presContext->DevPixelsToAppUnits(bounds.x),
  1794. presContext->DevPixelsToAppUnits(bounds.y),
  1795. presContext->DevPixelsToAppUnits(bounds.width),
  1796. presContext->DevPixelsToAppUnits(bounds.height));
  1797. if (shouldInvalidate) {
  1798. view->GetViewManager()->InvalidateViewNoSuppression(view, rect);
  1799. }
  1800. presContext->NotifyInvalidation(bounds, 0);
  1801. }
  1802. } else if (shouldInvalidate) {
  1803. view->GetViewManager()->InvalidateView(view);
  1804. }
  1805. }
  1806. layerManager->SetUserData(&gLayerManagerLayerBuilder, oldBuilder);
  1807. return layerManager.forget();
  1808. }
  1809. uint32_t nsDisplayList::Count() const {
  1810. uint32_t count = 0;
  1811. for (nsDisplayItem* i = GetBottom(); i; i = i->GetAbove()) {
  1812. ++count;
  1813. }
  1814. return count;
  1815. }
  1816. nsDisplayItem* nsDisplayList::RemoveBottom() {
  1817. nsDisplayItem* item = mSentinel.mAbove;
  1818. if (!item)
  1819. return nullptr;
  1820. mSentinel.mAbove = item->mAbove;
  1821. if (item == mTop) {
  1822. // must have been the only item
  1823. mTop = &mSentinel;
  1824. }
  1825. item->mAbove = nullptr;
  1826. return item;
  1827. }
  1828. void nsDisplayList::DeleteAll() {
  1829. nsDisplayItem* item;
  1830. while ((item = RemoveBottom()) != nullptr) {
  1831. item->~nsDisplayItem();
  1832. }
  1833. }
  1834. static bool
  1835. GetMouseThrough(const nsIFrame* aFrame)
  1836. {
  1837. if (!aFrame->IsXULBoxFrame())
  1838. return false;
  1839. const nsIFrame* frame = aFrame;
  1840. while (frame) {
  1841. if (frame->GetStateBits() & NS_FRAME_MOUSE_THROUGH_ALWAYS) {
  1842. return true;
  1843. } else if (frame->GetStateBits() & NS_FRAME_MOUSE_THROUGH_NEVER) {
  1844. return false;
  1845. }
  1846. frame = nsBox::GetParentXULBox(frame);
  1847. }
  1848. return false;
  1849. }
  1850. static bool
  1851. IsFrameReceivingPointerEvents(nsIFrame* aFrame)
  1852. {
  1853. return NS_STYLE_POINTER_EVENTS_NONE !=
  1854. aFrame->StyleUserInterface()->GetEffectivePointerEvents(aFrame);
  1855. }
  1856. // A list of frames, and their z depth. Used for sorting
  1857. // the results of hit testing.
  1858. struct FramesWithDepth
  1859. {
  1860. explicit FramesWithDepth(float aDepth) :
  1861. mDepth(aDepth)
  1862. {}
  1863. bool operator<(const FramesWithDepth& aOther) const {
  1864. if (!FuzzyEqual(mDepth, aOther.mDepth, 0.1f)) {
  1865. // We want to sort so that the shallowest item (highest depth value) is first
  1866. return mDepth > aOther.mDepth;
  1867. }
  1868. return this < &aOther;
  1869. }
  1870. bool operator==(const FramesWithDepth& aOther) const {
  1871. return this == &aOther;
  1872. }
  1873. float mDepth;
  1874. nsTArray<nsIFrame*> mFrames;
  1875. };
  1876. // Sort the frames by depth and then moves all the contained frames to the destination
  1877. void FlushFramesArray(nsTArray<FramesWithDepth>& aSource, nsTArray<nsIFrame*>* aDest)
  1878. {
  1879. if (aSource.IsEmpty()) {
  1880. return;
  1881. }
  1882. aSource.Sort();
  1883. uint32_t length = aSource.Length();
  1884. for (uint32_t i = 0; i < length; i++) {
  1885. aDest->AppendElements(Move(aSource[i].mFrames));
  1886. }
  1887. aSource.Clear();
  1888. }
  1889. void nsDisplayList::HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
  1890. nsDisplayItem::HitTestState* aState,
  1891. nsTArray<nsIFrame*> *aOutFrames) const {
  1892. nsDisplayItem* item;
  1893. if (aState->mInPreserves3D) {
  1894. // Collect leaves of the current 3D rendering context.
  1895. for (item = GetBottom(); item; item = item->GetAbove()) {
  1896. auto itemType = item->GetType();
  1897. if (itemType != nsDisplayItem::TYPE_TRANSFORM ||
  1898. !static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext()) {
  1899. item->HitTest(aBuilder, aRect, aState, aOutFrames);
  1900. } else {
  1901. // One of leaves in the current 3D rendering context.
  1902. aState->mItemBuffer.AppendElement(item);
  1903. }
  1904. }
  1905. return;
  1906. }
  1907. int32_t itemBufferStart = aState->mItemBuffer.Length();
  1908. for (item = GetBottom(); item; item = item->GetAbove()) {
  1909. aState->mItemBuffer.AppendElement(item);
  1910. }
  1911. AutoTArray<FramesWithDepth, 16> temp;
  1912. for (int32_t i = aState->mItemBuffer.Length() - 1; i >= itemBufferStart; --i) {
  1913. // Pop element off the end of the buffer. We want to shorten the buffer
  1914. // so that recursive calls to HitTest have more buffer space.
  1915. item = aState->mItemBuffer[i];
  1916. aState->mItemBuffer.SetLength(i);
  1917. bool snap;
  1918. nsRect r = item->GetBounds(aBuilder, &snap).Intersect(aRect);
  1919. auto itemType = item->GetType();
  1920. bool same3DContext =
  1921. (itemType == nsDisplayItem::TYPE_TRANSFORM &&
  1922. static_cast<nsDisplayTransform*>(item)->IsParticipating3DContext()) ||
  1923. (itemType == nsDisplayItem::TYPE_PERSPECTIVE &&
  1924. item->Frame()->Extend3DContext());
  1925. if (same3DContext &&
  1926. (itemType != nsDisplayItem::TYPE_TRANSFORM ||
  1927. !static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext())) {
  1928. if (!item->GetClip().MayIntersect(aRect)) {
  1929. continue;
  1930. }
  1931. AutoTArray<nsIFrame*, 1> neverUsed;
  1932. // Start gethering leaves of the 3D rendering context, and
  1933. // append leaves at the end of mItemBuffer. Leaves are
  1934. // processed at following iterations.
  1935. aState->mInPreserves3D = true;
  1936. item->HitTest(aBuilder, aRect, aState, &neverUsed);
  1937. aState->mInPreserves3D = false;
  1938. i = aState->mItemBuffer.Length();
  1939. continue;
  1940. }
  1941. if (same3DContext || item->GetClip().MayIntersect(r)) {
  1942. AutoTArray<nsIFrame*, 16> outFrames;
  1943. item->HitTest(aBuilder, aRect, aState, &outFrames);
  1944. // For 3d transforms with preserve-3d we add hit frames into the temp list
  1945. // so we can sort them later, otherwise we add them directly to the output list.
  1946. nsTArray<nsIFrame*> *writeFrames = aOutFrames;
  1947. if (item->GetType() == nsDisplayItem::TYPE_TRANSFORM &&
  1948. static_cast<nsDisplayTransform*>(item)->IsLeafOf3DContext()) {
  1949. if (outFrames.Length()) {
  1950. nsDisplayTransform *transform = static_cast<nsDisplayTransform*>(item);
  1951. nsPoint point = aRect.TopLeft();
  1952. // A 1x1 rect means a point, otherwise use the center of the rect
  1953. if (aRect.width != 1 || aRect.height != 1) {
  1954. point = aRect.Center();
  1955. }
  1956. temp.AppendElement(FramesWithDepth(transform->GetHitDepthAtPoint(aBuilder, point)));
  1957. writeFrames = &temp[temp.Length() - 1].mFrames;
  1958. }
  1959. } else {
  1960. // We may have just finished a run of consecutive preserve-3d transforms,
  1961. // so flush these into the destination array before processing our frame list.
  1962. FlushFramesArray(temp, aOutFrames);
  1963. }
  1964. for (uint32_t j = 0; j < outFrames.Length(); j++) {
  1965. nsIFrame *f = outFrames.ElementAt(j);
  1966. // Handle the XUL 'mousethrough' feature and 'pointer-events'.
  1967. if (!GetMouseThrough(f) && IsFrameReceivingPointerEvents(f)) {
  1968. writeFrames->AppendElement(f);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. // Clear any remaining preserve-3d transforms.
  1974. FlushFramesArray(temp, aOutFrames);
  1975. NS_ASSERTION(aState->mItemBuffer.Length() == uint32_t(itemBufferStart),
  1976. "How did we forget to pop some elements?");
  1977. }
  1978. static void Sort(nsDisplayList* aList, int32_t aCount, nsDisplayList::SortLEQ aCmp,
  1979. void* aClosure) {
  1980. if (aCount < 2)
  1981. return;
  1982. nsDisplayList list1;
  1983. nsDisplayList list2;
  1984. int i;
  1985. int32_t half = aCount/2;
  1986. bool sorted = true;
  1987. nsDisplayItem* prev = nullptr;
  1988. for (i = 0; i < aCount; ++i) {
  1989. nsDisplayItem* item = aList->RemoveBottom();
  1990. (i < half ? &list1 : &list2)->AppendToTop(item);
  1991. if (sorted && prev && !aCmp(prev, item, aClosure)) {
  1992. sorted = false;
  1993. }
  1994. prev = item;
  1995. }
  1996. if (sorted) {
  1997. aList->AppendToTop(&list1);
  1998. aList->AppendToTop(&list2);
  1999. return;
  2000. }
  2001. Sort(&list1, half, aCmp, aClosure);
  2002. Sort(&list2, aCount - half, aCmp, aClosure);
  2003. for (i = 0; i < aCount; ++i) {
  2004. if (list1.GetBottom() &&
  2005. (!list2.GetBottom() ||
  2006. aCmp(list1.GetBottom(), list2.GetBottom(), aClosure))) {
  2007. aList->AppendToTop(list1.RemoveBottom());
  2008. } else {
  2009. aList->AppendToTop(list2.RemoveBottom());
  2010. }
  2011. }
  2012. }
  2013. static nsIContent* FindContentInDocument(nsDisplayItem* aItem, nsIDocument* aDoc) {
  2014. nsIFrame* f = aItem->Frame();
  2015. while (f) {
  2016. nsPresContext* pc = f->PresContext();
  2017. if (pc->Document() == aDoc) {
  2018. return f->GetContent();
  2019. }
  2020. f = nsLayoutUtils::GetCrossDocParentFrame(pc->PresShell()->GetRootFrame());
  2021. }
  2022. return nullptr;
  2023. }
  2024. static bool IsContentLEQ(nsDisplayItem* aItem1, nsDisplayItem* aItem2,
  2025. void* aClosure) {
  2026. nsIContent* commonAncestor = static_cast<nsIContent*>(aClosure);
  2027. // It's possible that the nsIContent for aItem1 or aItem2 is in a subdocument
  2028. // of commonAncestor, because display items for subdocuments have been
  2029. // mixed into the same list. Ensure that we're looking at content
  2030. // in commonAncestor's document.
  2031. nsIDocument* commonAncestorDoc = commonAncestor->OwnerDoc();
  2032. nsIContent* content1 = FindContentInDocument(aItem1, commonAncestorDoc);
  2033. nsIContent* content2 = FindContentInDocument(aItem2, commonAncestorDoc);
  2034. if (!content1 || !content2) {
  2035. NS_ERROR("Document trees are mixed up!");
  2036. // Something weird going on
  2037. return true;
  2038. }
  2039. return nsLayoutUtils::CompareTreePosition(content1, content2, commonAncestor) <= 0;
  2040. }
  2041. static bool IsZOrderLEQ(nsDisplayItem* aItem1, nsDisplayItem* aItem2,
  2042. void* aClosure) {
  2043. // Note that we can't just take the difference of the two
  2044. // z-indices here, because that might overflow a 32-bit int.
  2045. return aItem1->ZIndex() <= aItem2->ZIndex();
  2046. }
  2047. void nsDisplayList::SortByZOrder() {
  2048. Sort(IsZOrderLEQ, nullptr);
  2049. }
  2050. void nsDisplayList::SortByContentOrder(nsIContent* aCommonAncestor) {
  2051. Sort(IsContentLEQ, aCommonAncestor);
  2052. }
  2053. void nsDisplayList::Sort(SortLEQ aCmp, void* aClosure) {
  2054. ::Sort(this, Count(), aCmp, aClosure);
  2055. }
  2056. nsDisplayItem::nsDisplayItem(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
  2057. : nsDisplayItem(aBuilder, aFrame, aBuilder->ClipState().GetCurrentInnermostScrollClip())
  2058. {}
  2059. nsDisplayItem::nsDisplayItem(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
  2060. const DisplayItemScrollClip* aScrollClip)
  2061. : mFrame(aFrame)
  2062. , mClip(aBuilder->ClipState().GetCurrentCombinedClip(aBuilder))
  2063. , mScrollClip(aScrollClip)
  2064. , mAnimatedGeometryRoot(nullptr)
  2065. , mForceNotVisible(aBuilder->IsBuildingInvisibleItems())
  2066. #ifdef MOZ_DUMP_PAINTING
  2067. , mPainted(false)
  2068. #endif
  2069. {
  2070. mReferenceFrame = aBuilder->FindReferenceFrameFor(aFrame, &mToReferenceFrame);
  2071. // This can return the wrong result if the item override ShouldFixToViewport(),
  2072. // the item needs to set it again in its constructor.
  2073. mAnimatedGeometryRoot = aBuilder->FindAnimatedGeometryRootFor(aFrame);
  2074. MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(aBuilder->RootReferenceFrame(),
  2075. *mAnimatedGeometryRoot), "Bad");
  2076. NS_ASSERTION(aBuilder->GetDirtyRect().width >= 0 ||
  2077. !aBuilder->IsForPainting(), "dirty rect not set");
  2078. // The dirty rect is for mCurrentFrame, so we have to use
  2079. // mCurrentOffsetToReferenceFrame
  2080. mVisibleRect = aBuilder->GetDirtyRect() +
  2081. aBuilder->GetCurrentFrameOffsetToReferenceFrame();
  2082. }
  2083. /* static */ bool
  2084. nsDisplayItem::ForceActiveLayers()
  2085. {
  2086. static bool sForce = false;
  2087. static bool sForceCached = false;
  2088. if (!sForceCached) {
  2089. Preferences::AddBoolVarCache(&sForce, "layers.force-active", false);
  2090. sForceCached = true;
  2091. }
  2092. return sForce;
  2093. }
  2094. static int32_t ZIndexForFrame(nsIFrame* aFrame)
  2095. {
  2096. if (!aFrame->IsAbsPosContainingBlock() && !aFrame->IsFlexOrGridItem())
  2097. return 0;
  2098. const nsStylePosition* position = aFrame->StylePosition();
  2099. if (position->mZIndex.GetUnit() == eStyleUnit_Integer)
  2100. return position->mZIndex.GetIntValue();
  2101. // sort the auto and 0 elements together
  2102. return 0;
  2103. }
  2104. int32_t
  2105. nsDisplayItem::ZIndex() const
  2106. {
  2107. return ZIndexForFrame(mFrame);
  2108. }
  2109. bool
  2110. nsDisplayItem::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  2111. nsRegion* aVisibleRegion)
  2112. {
  2113. return !mVisibleRect.IsEmpty() &&
  2114. !IsInvisibleInRect(aVisibleRegion->GetBounds());
  2115. }
  2116. bool
  2117. nsDisplayItem::RecomputeVisibility(nsDisplayListBuilder* aBuilder,
  2118. nsRegion* aVisibleRegion) {
  2119. if (mForceNotVisible && !GetSameCoordinateSystemChildren()) {
  2120. // mForceNotVisible wants to ensure that this display item doesn't render
  2121. // anything itself. If this item has contents, then we obviously want to
  2122. // render those, so we don't need this check in that case.
  2123. NS_ASSERTION(mVisibleRect.IsEmpty(),
  2124. "invisible items without children should have empty vis rect");
  2125. } else {
  2126. nsRect bounds = GetClippedBounds(aBuilder);
  2127. nsRegion itemVisible;
  2128. itemVisible.And(*aVisibleRegion, bounds);
  2129. mVisibleRect = itemVisible.GetBounds();
  2130. }
  2131. // When we recompute visibility within layers we don't need to
  2132. // expand the visible region for content behind plugins (the plugin
  2133. // is not in the layer).
  2134. if (!ComputeVisibility(aBuilder, aVisibleRegion)) {
  2135. mVisibleRect = nsRect();
  2136. return false;
  2137. }
  2138. nsRegion opaque = TreatAsOpaque(this, aBuilder);
  2139. aBuilder->SubtractFromVisibleRegion(aVisibleRegion, opaque);
  2140. return true;
  2141. }
  2142. nsRect
  2143. nsDisplayItem::GetClippedBounds(nsDisplayListBuilder* aBuilder)
  2144. {
  2145. bool snap;
  2146. nsRect r = GetBounds(aBuilder, &snap);
  2147. return GetClip().ApplyNonRoundedIntersection(r);
  2148. }
  2149. nsRect
  2150. nsDisplaySolidColor::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
  2151. {
  2152. *aSnap = true;
  2153. return mBounds;
  2154. }
  2155. void
  2156. nsDisplaySolidColor::Paint(nsDisplayListBuilder* aBuilder,
  2157. nsRenderingContext* aCtx)
  2158. {
  2159. int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  2160. DrawTarget* drawTarget = aCtx->GetDrawTarget();
  2161. Rect rect =
  2162. NSRectToSnappedRect(mVisibleRect, appUnitsPerDevPixel, *drawTarget);
  2163. drawTarget->FillRect(rect, ColorPattern(ToDeviceColor(mColor)));
  2164. }
  2165. void
  2166. nsDisplaySolidColor::WriteDebugInfo(std::stringstream& aStream)
  2167. {
  2168. aStream << " (rgba "
  2169. << (int)NS_GET_R(mColor) << ","
  2170. << (int)NS_GET_G(mColor) << ","
  2171. << (int)NS_GET_B(mColor) << ","
  2172. << (int)NS_GET_A(mColor) << ")";
  2173. }
  2174. nsRect
  2175. nsDisplaySolidColorRegion::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
  2176. {
  2177. *aSnap = true;
  2178. return mRegion.GetBounds();
  2179. }
  2180. void
  2181. nsDisplaySolidColorRegion::Paint(nsDisplayListBuilder* aBuilder,
  2182. nsRenderingContext* aCtx)
  2183. {
  2184. int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  2185. DrawTarget* drawTarget = aCtx->GetDrawTarget();
  2186. ColorPattern color(mColor);
  2187. for (auto iter = mRegion.RectIter(); !iter.Done(); iter.Next()) {
  2188. Rect rect =
  2189. NSRectToSnappedRect(iter.Get(), appUnitsPerDevPixel, *drawTarget);
  2190. drawTarget->FillRect(rect, color);
  2191. }
  2192. }
  2193. void
  2194. nsDisplaySolidColorRegion::WriteDebugInfo(std::stringstream& aStream)
  2195. {
  2196. aStream << " (rgba "
  2197. << int(mColor.r * 255) << ","
  2198. << int(mColor.g * 255) << ","
  2199. << int(mColor.b * 255) << ","
  2200. << mColor.a << ")";
  2201. }
  2202. static void
  2203. RegisterThemeGeometry(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
  2204. nsITheme::ThemeGeometryType aType)
  2205. {
  2206. if (aBuilder->IsInChromeDocumentOrPopup() && !aBuilder->IsInTransform()) {
  2207. nsIFrame* displayRoot = nsLayoutUtils::GetDisplayRootFrame(aFrame);
  2208. nsPoint offset = aBuilder->IsInSubdocument() ? aBuilder->ToReferenceFrame(aFrame)
  2209. : aFrame->GetOffsetTo(displayRoot);
  2210. nsRect borderBox = nsRect(offset, aFrame->GetSize());
  2211. aBuilder->RegisterThemeGeometry(aType,
  2212. LayoutDeviceIntRect::FromUnknownRect(
  2213. borderBox.ToNearestPixels(
  2214. aFrame->PresContext()->AppUnitsPerDevPixel())));
  2215. }
  2216. }
  2217. // Return the bounds of the viewport relative to |aFrame|'s reference frame.
  2218. // Returns Nothing() if transforming into |aFrame|'s coordinate space fails.
  2219. static Maybe<nsRect>
  2220. GetViewportRectRelativeToReferenceFrame(nsDisplayListBuilder* aBuilder,
  2221. nsIFrame* aFrame)
  2222. {
  2223. nsIFrame* rootFrame = aFrame->PresContext()->PresShell()->GetRootFrame();
  2224. nsRect rootRect = rootFrame->GetRectRelativeToSelf();
  2225. if (nsLayoutUtils::TransformRect(rootFrame, aFrame, rootRect) == nsLayoutUtils::TRANSFORM_SUCCEEDED) {
  2226. return Some(rootRect + aBuilder->ToReferenceFrame(aFrame));
  2227. }
  2228. return Nothing();
  2229. }
  2230. nsDisplayBackgroundImage::nsDisplayBackgroundImage(nsDisplayListBuilder* aBuilder,
  2231. nsIFrame* aFrame,
  2232. uint32_t aLayer,
  2233. const nsRect& aBackgroundRect,
  2234. const nsStyleBackground* aBackgroundStyle)
  2235. : nsDisplayImageContainer(aBuilder, aFrame)
  2236. , mBackgroundStyle(aBackgroundStyle)
  2237. , mBackgroundRect(aBackgroundRect)
  2238. , mLayer(aLayer)
  2239. , mIsRasterImage(false)
  2240. {
  2241. MOZ_COUNT_CTOR(nsDisplayBackgroundImage);
  2242. nsPresContext* presContext = mFrame->PresContext();
  2243. uint32_t flags = aBuilder->GetBackgroundPaintFlags();
  2244. const nsStyleImageLayers::Layer &layer = mBackgroundStyle->mImage.mLayers[mLayer];
  2245. bool isTransformedFixed;
  2246. nsBackgroundLayerState state =
  2247. nsCSSRendering::PrepareImageLayer(presContext, mFrame, flags,
  2248. mBackgroundRect, mBackgroundRect, layer,
  2249. &isTransformedFixed);
  2250. mShouldTreatAsFixed = ComputeShouldTreatAsFixed(isTransformedFixed);
  2251. mBounds = GetBoundsInternal(aBuilder);
  2252. if (ShouldFixToViewport(aBuilder)) {
  2253. mAnimatedGeometryRoot = aBuilder->FindAnimatedGeometryRootFor(this);
  2254. // Expand the item's visible rect to cover the entire bounds, limited to the
  2255. // viewport rect. This is necessary because the background's clip can move
  2256. // asynchronously.
  2257. if (Maybe<nsRect> viewportRect = GetViewportRectRelativeToReferenceFrame(aBuilder, mFrame)) {
  2258. mVisibleRect = mBounds.Intersect(*viewportRect);
  2259. }
  2260. }
  2261. mFillRect = state.mFillArea;
  2262. mDestRect = state.mDestArea;
  2263. nsImageRenderer* imageRenderer = &state.mImageRenderer;
  2264. // We only care about images here, not gradients.
  2265. if (imageRenderer->IsRasterImage()) {
  2266. mIsRasterImage = true;
  2267. mImage = imageRenderer->GetImage();
  2268. }
  2269. }
  2270. nsDisplayBackgroundImage::~nsDisplayBackgroundImage()
  2271. {
  2272. #ifdef NS_BUILD_REFCNT_LOGGING
  2273. MOZ_COUNT_DTOR(nsDisplayBackgroundImage);
  2274. #endif
  2275. }
  2276. static nsStyleContext* GetBackgroundStyleContext(nsIFrame* aFrame)
  2277. {
  2278. nsStyleContext *sc;
  2279. if (!nsCSSRendering::FindBackground(aFrame, &sc)) {
  2280. // We don't want to bail out if moz-appearance is set on a root
  2281. // node. If it has a parent content node, bail because it's not
  2282. // a root, other wise keep going in order to let the theme stuff
  2283. // draw the background. The canvas really should be drawing the
  2284. // bg, but there's no way to hook that up via css.
  2285. if (!aFrame->StyleDisplay()->mAppearance) {
  2286. return nullptr;
  2287. }
  2288. nsIContent* content = aFrame->GetContent();
  2289. if (!content || content->GetParent()) {
  2290. return nullptr;
  2291. }
  2292. sc = aFrame->StyleContext();
  2293. }
  2294. return sc;
  2295. }
  2296. /* static */ void
  2297. SetBackgroundClipRegion(DisplayListClipState::AutoSaveRestore& aClipState,
  2298. nsIFrame* aFrame, const nsStyleImageLayers::Layer& aLayer,
  2299. const nsRect& aBackgroundRect,
  2300. bool aWillPaintBorder)
  2301. {
  2302. nsCSSRendering::ImageLayerClipState clip;
  2303. nsCSSRendering::GetImageLayerClip(aLayer, aFrame, *aFrame->StyleBorder(),
  2304. aBackgroundRect, aBackgroundRect, aWillPaintBorder,
  2305. aFrame->PresContext()->AppUnitsPerDevPixel(),
  2306. &clip);
  2307. if (clip.mHasAdditionalBGClipArea) {
  2308. aClipState.ClipContentDescendants(clip.mAdditionalBGClipArea, clip.mBGClipArea,
  2309. clip.mHasRoundedCorners ? clip.mRadii : nullptr);
  2310. } else {
  2311. aClipState.ClipContentDescendants(clip.mBGClipArea, clip.mHasRoundedCorners ? clip.mRadii : nullptr);
  2312. }
  2313. }
  2314. /**
  2315. * This is used for the find bar highlighter overlay. It's only accessible
  2316. * through the AnonymousContent API, so it's not exposed to general web pages.
  2317. */
  2318. static bool
  2319. SpecialCutoutRegionCase(nsDisplayListBuilder* aBuilder,
  2320. nsIFrame* aFrame,
  2321. const nsRect& aBackgroundRect,
  2322. nsDisplayList* aList,
  2323. nscolor aColor)
  2324. {
  2325. nsIContent* content = aFrame->GetContent();
  2326. if (!content) {
  2327. return false;
  2328. }
  2329. void* cutoutRegion = content->GetProperty(nsGkAtoms::cutoutregion);
  2330. if (!cutoutRegion) {
  2331. return false;
  2332. }
  2333. if (NS_GET_A(aColor) == 0) {
  2334. return true;
  2335. }
  2336. nsRegion region;
  2337. region.Sub(aBackgroundRect, *static_cast<nsRegion*>(cutoutRegion));
  2338. region.MoveBy(aBuilder->ToReferenceFrame(aFrame));
  2339. aList->AppendNewToTop(
  2340. new (aBuilder) nsDisplaySolidColorRegion(aBuilder, aFrame, region, aColor));
  2341. return true;
  2342. }
  2343. /*static*/ bool
  2344. nsDisplayBackgroundImage::AppendBackgroundItemsToTop(nsDisplayListBuilder* aBuilder,
  2345. nsIFrame* aFrame,
  2346. const nsRect& aBackgroundRect,
  2347. nsDisplayList* aList,
  2348. bool aAllowWillPaintBorderOptimization,
  2349. nsStyleContext* aStyleContext,
  2350. const nsRect& aBackgroundOriginRect,
  2351. nsIFrame* aSecondaryReferenceFrame,
  2352. Maybe<nsDisplayListBuilder::AutoBuildingDisplayList>*
  2353. aAutoBuildingDisplayList)
  2354. {
  2355. nsStyleContext* bgSC = aStyleContext;
  2356. const nsStyleBackground* bg = nullptr;
  2357. nsRect bgRect = aBackgroundRect;
  2358. nsRect bgOriginRect = bgRect;
  2359. if (!aBackgroundOriginRect.IsEmpty()) {
  2360. bgOriginRect = aBackgroundOriginRect;
  2361. }
  2362. nsPresContext* presContext = aFrame->PresContext();
  2363. bool isThemed = aFrame->IsThemed();
  2364. if (!isThemed) {
  2365. if (!bgSC) {
  2366. bgSC = GetBackgroundStyleContext(aFrame);
  2367. }
  2368. if (bgSC) {
  2369. bg = bgSC->StyleBackground();
  2370. }
  2371. }
  2372. bool drawBackgroundColor = false;
  2373. // Dummy initialisation to keep Valgrind/Memcheck happy.
  2374. // See bug 1122375 comment 1.
  2375. nscolor color = NS_RGBA(0,0,0,0);
  2376. if (!nsCSSRendering::IsCanvasFrame(aFrame) && bg) {
  2377. bool drawBackgroundImage;
  2378. color =
  2379. nsCSSRendering::DetermineBackgroundColor(presContext, bgSC, aFrame,
  2380. drawBackgroundImage, drawBackgroundColor);
  2381. }
  2382. if (SpecialCutoutRegionCase(aBuilder, aFrame, aBackgroundRect, aList, color)) {
  2383. return false;
  2384. }
  2385. const nsStyleBorder* borderStyle = aFrame->StyleBorder();
  2386. const nsStyleEffects* effectsStyle = aFrame->StyleEffects();
  2387. bool hasInsetShadow = effectsStyle->mBoxShadow &&
  2388. effectsStyle->mBoxShadow->HasShadowWithInset(true);
  2389. bool willPaintBorder = aAllowWillPaintBorderOptimization &&
  2390. !isThemed && !hasInsetShadow &&
  2391. borderStyle->HasBorder();
  2392. // An auxiliary list is necessary in case we have background blending; if that
  2393. // is the case, background items need to be wrapped by a blend container to
  2394. // isolate blending to the background
  2395. nsDisplayList bgItemList;
  2396. // Even if we don't actually have a background color to paint, we may still need
  2397. // to create an item for hit testing.
  2398. if ((drawBackgroundColor && color != NS_RGBA(0,0,0,0)) ||
  2399. aBuilder->IsForEventDelivery()) {
  2400. if (aAutoBuildingDisplayList && !*aAutoBuildingDisplayList) {
  2401. aAutoBuildingDisplayList->emplace(aBuilder, aFrame);
  2402. }
  2403. DisplayListClipState::AutoSaveRestore clipState(aBuilder);
  2404. if (bg && !aBuilder->IsForEventDelivery()) {
  2405. // Disable the will-paint-border optimization for background
  2406. // colors with no border-radius. Enabling it for background colors
  2407. // doesn't help much (there are no tiling issues) and clipping the
  2408. // background breaks detection of the element's border-box being
  2409. // opaque. For nonzero border-radius we still need it because we
  2410. // want to inset the background if possible to avoid antialiasing
  2411. // artifacts along the rounded corners.
  2412. bool useWillPaintBorderOptimization = willPaintBorder &&
  2413. nsLayoutUtils::HasNonZeroCorner(borderStyle->mBorderRadius);
  2414. SetBackgroundClipRegion(clipState, aFrame,
  2415. bg->BottomLayer(), bgRect,
  2416. useWillPaintBorderOptimization);
  2417. }
  2418. if (aSecondaryReferenceFrame) {
  2419. bgItemList.AppendNewToTop(
  2420. new (aBuilder) nsDisplayTableBackgroundColor(aBuilder,
  2421. aSecondaryReferenceFrame,
  2422. bgRect,
  2423. bg,
  2424. drawBackgroundColor ? color : NS_RGBA(0, 0, 0, 0),
  2425. aFrame));
  2426. } else {
  2427. bgItemList.AppendNewToTop(
  2428. new (aBuilder) nsDisplayBackgroundColor(aBuilder,
  2429. aFrame,
  2430. bgRect,
  2431. bg,
  2432. drawBackgroundColor ? color : NS_RGBA(0, 0, 0, 0)));
  2433. }
  2434. }
  2435. if (isThemed) {
  2436. nsITheme* theme = presContext->GetTheme();
  2437. if (theme->NeedToClearBackgroundBehindWidget(aFrame, aFrame->StyleDisplay()->mAppearance) &&
  2438. aBuilder->IsInChromeDocumentOrPopup() && !aBuilder->IsInTransform()) {
  2439. bgItemList.AppendNewToTop(
  2440. new (aBuilder) nsDisplayClearBackground(aBuilder, aFrame));
  2441. }
  2442. nsDisplayThemedBackground* bgItem =
  2443. new (aBuilder) nsDisplayThemedBackground(aBuilder, aFrame, bgRect);
  2444. bgItemList.AppendNewToTop(bgItem);
  2445. aList->AppendToTop(&bgItemList);
  2446. return true;
  2447. }
  2448. if (!bg) {
  2449. aList->AppendToTop(&bgItemList);
  2450. return false;
  2451. }
  2452. const DisplayItemScrollClip* scrollClip =
  2453. aBuilder->ClipState().GetCurrentInnermostScrollClip();
  2454. bool needBlendContainer = false;
  2455. // Passing bg == nullptr in this macro will result in one iteration with
  2456. // i = 0.
  2457. NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, bg->mImage) {
  2458. if (bg->mImage.mLayers[i].mImage.IsEmpty()) {
  2459. continue;
  2460. }
  2461. if (aAutoBuildingDisplayList && !*aAutoBuildingDisplayList) {
  2462. aAutoBuildingDisplayList->emplace(aBuilder, aFrame);
  2463. }
  2464. if (bg->mImage.mLayers[i].mBlendMode != NS_STYLE_BLEND_NORMAL) {
  2465. needBlendContainer = true;
  2466. }
  2467. DisplayListClipState::AutoSaveRestore clipState(aBuilder);
  2468. if (!aBuilder->IsForEventDelivery()) {
  2469. const nsStyleImageLayers::Layer& layer = bg->mImage.mLayers[i];
  2470. SetBackgroundClipRegion(clipState, aFrame, layer, bgRect,
  2471. willPaintBorder);
  2472. }
  2473. nsDisplayList thisItemList;
  2474. nsDisplayBackgroundImage* bgItem;
  2475. if (aSecondaryReferenceFrame) {
  2476. bgItem =
  2477. new (aBuilder) nsDisplayTableBackgroundImage(aBuilder,
  2478. aFrame,
  2479. i,
  2480. bgOriginRect,
  2481. bg,
  2482. aSecondaryReferenceFrame);
  2483. } else {
  2484. bgItem =
  2485. new (aBuilder) nsDisplayBackgroundImage(aBuilder, aFrame, i, bgOriginRect, bg);
  2486. }
  2487. if (bgItem->ShouldFixToViewport(aBuilder)) {
  2488. if (aSecondaryReferenceFrame) {
  2489. thisItemList.AppendNewToTop(
  2490. nsDisplayTableFixedPosition::CreateForFixedBackground(aBuilder,
  2491. aSecondaryReferenceFrame,
  2492. bgItem,
  2493. i,
  2494. aFrame));
  2495. } else {
  2496. thisItemList.AppendNewToTop(
  2497. nsDisplayFixedPosition::CreateForFixedBackground(aBuilder, aFrame, bgItem, i));
  2498. }
  2499. } else {
  2500. thisItemList.AppendNewToTop(bgItem);
  2501. }
  2502. if (bg->mImage.mLayers[i].mBlendMode != NS_STYLE_BLEND_NORMAL) {
  2503. thisItemList.AppendNewToTop(
  2504. new (aBuilder) nsDisplayBlendMode(aBuilder, aFrame, &thisItemList,
  2505. bg->mImage.mLayers[i].mBlendMode,
  2506. scrollClip, i + 1));
  2507. }
  2508. bgItemList.AppendToTop(&thisItemList);
  2509. }
  2510. if (needBlendContainer) {
  2511. bgItemList.AppendNewToTop(
  2512. nsDisplayBlendContainer::CreateForBackgroundBlendMode(aBuilder, aFrame, &bgItemList, scrollClip));
  2513. }
  2514. aList->AppendToTop(&bgItemList);
  2515. return false;
  2516. }
  2517. // Check that the rounded border of aFrame, added to aToReferenceFrame,
  2518. // intersects aRect. Assumes that the unrounded border has already
  2519. // been checked for intersection.
  2520. static bool
  2521. RoundedBorderIntersectsRect(nsIFrame* aFrame,
  2522. const nsPoint& aFrameToReferenceFrame,
  2523. const nsRect& aTestRect)
  2524. {
  2525. if (!nsRect(aFrameToReferenceFrame, aFrame->GetSize()).Intersects(aTestRect))
  2526. return false;
  2527. nscoord radii[8];
  2528. return !aFrame->GetBorderRadii(radii) ||
  2529. nsLayoutUtils::RoundedRectIntersectsRect(nsRect(aFrameToReferenceFrame,
  2530. aFrame->GetSize()),
  2531. radii, aTestRect);
  2532. }
  2533. // Returns TRUE if aContainedRect is guaranteed to be contained in
  2534. // the rounded rect defined by aRoundedRect and aRadii. Complex cases are
  2535. // handled conservatively by returning FALSE in some situations where
  2536. // a more thorough analysis could return TRUE.
  2537. //
  2538. // See also RoundedRectIntersectsRect.
  2539. static bool RoundedRectContainsRect(const nsRect& aRoundedRect,
  2540. const nscoord aRadii[8],
  2541. const nsRect& aContainedRect) {
  2542. nsRegion rgn = nsLayoutUtils::RoundedRectIntersectRect(aRoundedRect, aRadii, aContainedRect);
  2543. return rgn.Contains(aContainedRect);
  2544. }
  2545. bool
  2546. nsDisplayBackgroundImage::ShouldTreatAsFixed() const
  2547. {
  2548. return mShouldTreatAsFixed;
  2549. }
  2550. bool
  2551. nsDisplayBackgroundImage::ComputeShouldTreatAsFixed(bool isTransformedFixed) const
  2552. {
  2553. if (!mBackgroundStyle)
  2554. return false;
  2555. const nsStyleImageLayers::Layer &layer = mBackgroundStyle->mImage.mLayers[mLayer];
  2556. if (layer.mAttachment != NS_STYLE_IMAGELAYER_ATTACHMENT_FIXED)
  2557. return false;
  2558. // background-attachment:fixed is treated as background-attachment:scroll
  2559. // if it's affected by a transform.
  2560. // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=17521.
  2561. return !isTransformedFixed;
  2562. }
  2563. bool
  2564. nsDisplayBackgroundImage::IsNonEmptyFixedImage() const
  2565. {
  2566. return ShouldTreatAsFixed() &&
  2567. !mBackgroundStyle->mImage.mLayers[mLayer].mImage.IsEmpty();
  2568. }
  2569. bool
  2570. nsDisplayBackgroundImage::ShouldFixToViewport(nsDisplayListBuilder* aBuilder)
  2571. {
  2572. // APZ needs background-attachment:fixed images layerized for correctness.
  2573. RefPtr<LayerManager> layerManager = aBuilder->GetWidgetLayerManager();
  2574. if (!nsLayoutUtils::UsesAsyncScrolling(mFrame) &&
  2575. layerManager && layerManager->ShouldAvoidComponentAlphaLayers()) {
  2576. return false;
  2577. }
  2578. // Put background-attachment:fixed background images in their own
  2579. // compositing layer.
  2580. return IsNonEmptyFixedImage();
  2581. }
  2582. bool
  2583. nsDisplayBackgroundImage::CanOptimizeToImageLayer(LayerManager* aManager,
  2584. nsDisplayListBuilder* aBuilder)
  2585. {
  2586. if (!mBackgroundStyle) {
  2587. return false;
  2588. }
  2589. // We currently can't handle tiled backgrounds.
  2590. if (!mDestRect.Contains(mFillRect)) {
  2591. return false;
  2592. }
  2593. // For 'contain' and 'cover', we allow any pixel of the image to be sampled
  2594. // because there isn't going to be any spriting/atlasing going on.
  2595. const nsStyleImageLayers::Layer &layer = mBackgroundStyle->mImage.mLayers[mLayer];
  2596. bool allowPartialImages =
  2597. (layer.mSize.mWidthType == nsStyleImageLayers::Size::eContain ||
  2598. layer.mSize.mWidthType == nsStyleImageLayers::Size::eCover);
  2599. if (!allowPartialImages && !mFillRect.Contains(mDestRect)) {
  2600. return false;
  2601. }
  2602. return nsDisplayImageContainer::CanOptimizeToImageLayer(aManager, aBuilder);
  2603. }
  2604. nsRect
  2605. nsDisplayBackgroundImage::GetDestRect()
  2606. {
  2607. return mDestRect;
  2608. }
  2609. already_AddRefed<imgIContainer>
  2610. nsDisplayBackgroundImage::GetImage()
  2611. {
  2612. nsCOMPtr<imgIContainer> image = mImage;
  2613. return image.forget();
  2614. }
  2615. nsDisplayBackgroundImage::ImageLayerization
  2616. nsDisplayBackgroundImage::ShouldCreateOwnLayer(nsDisplayListBuilder* aBuilder,
  2617. LayerManager* aManager)
  2618. {
  2619. nsIFrame* backgroundStyleFrame = nsCSSRendering::FindBackgroundStyleFrame(StyleFrame());
  2620. if (ActiveLayerTracker::IsBackgroundPositionAnimated(aBuilder,
  2621. backgroundStyleFrame)) {
  2622. return WHENEVER_POSSIBLE;
  2623. }
  2624. if (nsLayoutUtils::AnimatedImageLayersEnabled() && mBackgroundStyle) {
  2625. const nsStyleImageLayers::Layer &layer = mBackgroundStyle->mImage.mLayers[mLayer];
  2626. const nsStyleImage* image = &layer.mImage;
  2627. if (image->GetType() == eStyleImageType_Image) {
  2628. imgIRequest* imgreq = image->GetImageData();
  2629. nsCOMPtr<imgIContainer> image;
  2630. if (imgreq &&
  2631. NS_SUCCEEDED(imgreq->GetImage(getter_AddRefs(image))) &&
  2632. image) {
  2633. bool animated = false;
  2634. if (NS_SUCCEEDED(image->GetAnimated(&animated)) && animated) {
  2635. return WHENEVER_POSSIBLE;
  2636. }
  2637. }
  2638. }
  2639. }
  2640. if (nsLayoutUtils::GPUImageScalingEnabled() &&
  2641. aManager->IsCompositingCheap()) {
  2642. return ONLY_FOR_SCALING;
  2643. }
  2644. return NO_LAYER_NEEDED;
  2645. }
  2646. LayerState
  2647. nsDisplayBackgroundImage::GetLayerState(nsDisplayListBuilder* aBuilder,
  2648. LayerManager* aManager,
  2649. const ContainerLayerParameters& aParameters)
  2650. {
  2651. ImageLayerization shouldLayerize = ShouldCreateOwnLayer(aBuilder, aManager);
  2652. if (shouldLayerize == NO_LAYER_NEEDED) {
  2653. // We can skip the call to CanOptimizeToImageLayer if we don't want a
  2654. // layer anyway.
  2655. return LAYER_NONE;
  2656. }
  2657. if (CanOptimizeToImageLayer(aManager, aBuilder)) {
  2658. if (shouldLayerize == WHENEVER_POSSIBLE) {
  2659. return LAYER_ACTIVE;
  2660. }
  2661. MOZ_ASSERT(shouldLayerize == ONLY_FOR_SCALING, "unhandled ImageLayerization value?");
  2662. MOZ_ASSERT(mImage);
  2663. int32_t imageWidth;
  2664. int32_t imageHeight;
  2665. mImage->GetWidth(&imageWidth);
  2666. mImage->GetHeight(&imageHeight);
  2667. NS_ASSERTION(imageWidth != 0 && imageHeight != 0, "Invalid image size!");
  2668. int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  2669. LayoutDeviceRect destRect = LayoutDeviceRect::FromAppUnits(GetDestRect(), appUnitsPerDevPixel);
  2670. const LayerRect destLayerRect = destRect * aParameters.Scale();
  2671. // Calculate the scaling factor for the frame.
  2672. const gfxSize scale = gfxSize(destLayerRect.width / imageWidth,
  2673. destLayerRect.height / imageHeight);
  2674. if ((scale.width != 1.0f || scale.height != 1.0f) &&
  2675. (destLayerRect.width * destLayerRect.height >= 64 * 64)) {
  2676. // Separate this image into a layer.
  2677. // There's no point in doing this if we are not scaling at all or if the
  2678. // target size is pretty small.
  2679. return LAYER_ACTIVE;
  2680. }
  2681. }
  2682. return LAYER_NONE;
  2683. }
  2684. already_AddRefed<Layer>
  2685. nsDisplayBackgroundImage::BuildLayer(nsDisplayListBuilder* aBuilder,
  2686. LayerManager* aManager,
  2687. const ContainerLayerParameters& aParameters)
  2688. {
  2689. RefPtr<ImageLayer> layer = static_cast<ImageLayer*>
  2690. (aManager->GetLayerBuilder()->GetLeafLayerFor(aBuilder, this));
  2691. if (!layer) {
  2692. layer = aManager->CreateImageLayer();
  2693. if (!layer)
  2694. return nullptr;
  2695. }
  2696. RefPtr<ImageContainer> imageContainer = GetContainer(aManager, aBuilder);
  2697. layer->SetContainer(imageContainer);
  2698. ConfigureLayer(layer, aParameters);
  2699. return layer.forget();
  2700. }
  2701. void
  2702. nsDisplayBackgroundImage::HitTest(nsDisplayListBuilder* aBuilder,
  2703. const nsRect& aRect,
  2704. HitTestState* aState,
  2705. nsTArray<nsIFrame*> *aOutFrames)
  2706. {
  2707. if (RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
  2708. aOutFrames->AppendElement(mFrame);
  2709. }
  2710. }
  2711. bool
  2712. nsDisplayBackgroundImage::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  2713. nsRegion* aVisibleRegion)
  2714. {
  2715. if (!nsDisplayItem::ComputeVisibility(aBuilder, aVisibleRegion)) {
  2716. return false;
  2717. }
  2718. // Return false if the background was propagated away from this
  2719. // frame. We don't want this display item to show up and confuse
  2720. // anything.
  2721. return mBackgroundStyle;
  2722. }
  2723. /* static */ nsRegion
  2724. nsDisplayBackgroundImage::GetInsideClipRegion(nsDisplayItem* aItem,
  2725. StyleGeometryBox aClip,
  2726. const nsRect& aRect,
  2727. const nsRect& aBackgroundRect)
  2728. {
  2729. nsRegion result;
  2730. if (aRect.IsEmpty())
  2731. return result;
  2732. nsIFrame *frame = aItem->Frame();
  2733. nsRect clipRect = aBackgroundRect;
  2734. if (frame->GetType() == nsGkAtoms::canvasFrame) {
  2735. nsCanvasFrame* canvasFrame = static_cast<nsCanvasFrame*>(frame);
  2736. clipRect = canvasFrame->CanvasArea() + aItem->ToReferenceFrame();
  2737. } else if (aClip == StyleGeometryBox::Padding ||
  2738. aClip == StyleGeometryBox::Content) {
  2739. nsMargin border = frame->GetUsedBorder();
  2740. if (aClip == StyleGeometryBox::Content) {
  2741. border += frame->GetUsedPadding();
  2742. }
  2743. border.ApplySkipSides(frame->GetSkipSides());
  2744. clipRect.Deflate(border);
  2745. }
  2746. return clipRect.Intersect(aRect);
  2747. }
  2748. nsRegion
  2749. nsDisplayBackgroundImage::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
  2750. bool* aSnap) {
  2751. nsRegion result;
  2752. *aSnap = false;
  2753. if (!mBackgroundStyle)
  2754. return result;
  2755. *aSnap = true;
  2756. // For StyleBoxDecorationBreak::Slice, don't try to optimize here, since
  2757. // this could easily lead to O(N^2) behavior inside InlineBackgroundData,
  2758. // which expects frames to be sent to it in content order, not reverse
  2759. // content order which we'll produce here.
  2760. // Of course, if there's only one frame in the flow, it doesn't matter.
  2761. if (mFrame->StyleBorder()->mBoxDecorationBreak ==
  2762. StyleBoxDecorationBreak::Clone ||
  2763. (!mFrame->GetPrevContinuation() && !mFrame->GetNextContinuation())) {
  2764. const nsStyleImageLayers::Layer& layer = mBackgroundStyle->mImage.mLayers[mLayer];
  2765. if (layer.mImage.IsOpaque() && layer.mBlendMode == NS_STYLE_BLEND_NORMAL &&
  2766. layer.mRepeat.mXRepeat != NS_STYLE_IMAGELAYER_REPEAT_SPACE &&
  2767. layer.mRepeat.mYRepeat != NS_STYLE_IMAGELAYER_REPEAT_SPACE &&
  2768. layer.mClip != StyleGeometryBox::Text) {
  2769. result = GetInsideClipRegion(this, layer.mClip, mBounds, mBackgroundRect);
  2770. }
  2771. }
  2772. return result;
  2773. }
  2774. Maybe<nscolor>
  2775. nsDisplayBackgroundImage::IsUniform(nsDisplayListBuilder* aBuilder) {
  2776. if (!mBackgroundStyle) {
  2777. return Some(NS_RGBA(0,0,0,0));
  2778. }
  2779. return Nothing();
  2780. }
  2781. nsRect
  2782. nsDisplayBackgroundImage::GetPositioningArea()
  2783. {
  2784. if (!mBackgroundStyle) {
  2785. return nsRect();
  2786. }
  2787. nsIFrame* attachedToFrame;
  2788. bool transformedFixed;
  2789. return nsCSSRendering::ComputeImageLayerPositioningArea(
  2790. mFrame->PresContext(), mFrame,
  2791. mBackgroundRect,
  2792. mBackgroundStyle->mImage.mLayers[mLayer],
  2793. &attachedToFrame,
  2794. &transformedFixed) + ToReferenceFrame();
  2795. }
  2796. bool
  2797. nsDisplayBackgroundImage::RenderingMightDependOnPositioningAreaSizeChange()
  2798. {
  2799. if (!mBackgroundStyle)
  2800. return false;
  2801. nscoord radii[8];
  2802. if (mFrame->GetBorderRadii(radii)) {
  2803. // A change in the size of the positioning area might change the position
  2804. // of the rounded corners.
  2805. return true;
  2806. }
  2807. const nsStyleImageLayers::Layer &layer = mBackgroundStyle->mImage.mLayers[mLayer];
  2808. if (layer.RenderingMightDependOnPositioningAreaSizeChange()) {
  2809. return true;
  2810. }
  2811. return false;
  2812. }
  2813. static void CheckForBorderItem(nsDisplayItem *aItem, uint32_t& aFlags)
  2814. {
  2815. nsDisplayItem* nextItem = aItem->GetAbove();
  2816. while (nextItem && nextItem->GetType() == nsDisplayItem::TYPE_BACKGROUND) {
  2817. nextItem = nextItem->GetAbove();
  2818. }
  2819. if (nextItem &&
  2820. nextItem->Frame() == aItem->Frame() &&
  2821. nextItem->GetType() == nsDisplayItem::TYPE_BORDER) {
  2822. aFlags |= nsCSSRendering::PAINTBG_WILL_PAINT_BORDER;
  2823. }
  2824. }
  2825. void
  2826. nsDisplayBackgroundImage::Paint(nsDisplayListBuilder* aBuilder,
  2827. nsRenderingContext* aCtx) {
  2828. PaintInternal(aBuilder, aCtx, mVisibleRect, &mBounds);
  2829. }
  2830. void
  2831. nsDisplayBackgroundImage::PaintInternal(nsDisplayListBuilder* aBuilder,
  2832. nsRenderingContext* aCtx, const nsRect& aBounds,
  2833. nsRect* aClipRect) {
  2834. uint32_t flags = aBuilder->GetBackgroundPaintFlags();
  2835. CheckForBorderItem(this, flags);
  2836. gfxContext* ctx = aCtx->ThebesContext();
  2837. StyleGeometryBox clip = mBackgroundStyle->mImage.mLayers[mLayer].mClip;
  2838. if (clip == StyleGeometryBox::Text) {
  2839. if (!GenerateAndPushTextMask(StyleFrame(), aCtx, mBackgroundRect, aBuilder)) {
  2840. return;
  2841. }
  2842. }
  2843. nsCSSRendering::PaintBGParams params =
  2844. nsCSSRendering::PaintBGParams::ForSingleLayer(*StyleFrame()->PresContext(),
  2845. *aCtx,
  2846. aBounds, mBackgroundRect,
  2847. StyleFrame(), flags, mLayer,
  2848. CompositionOp::OP_OVER);
  2849. params.bgClipRect = aClipRect;
  2850. image::DrawResult result =
  2851. nsCSSRendering::PaintBackground(params);
  2852. if (clip == StyleGeometryBox::Text) {
  2853. ctx->PopGroupAndBlend();
  2854. }
  2855. nsDisplayBackgroundGeometry::UpdateDrawResult(this, result);
  2856. }
  2857. void nsDisplayBackgroundImage::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  2858. const nsDisplayItemGeometry* aGeometry,
  2859. nsRegion* aInvalidRegion)
  2860. {
  2861. if (!mBackgroundStyle) {
  2862. return;
  2863. }
  2864. const nsDisplayBackgroundGeometry* geometry = static_cast<const nsDisplayBackgroundGeometry*>(aGeometry);
  2865. bool snap;
  2866. nsRect bounds = GetBounds(aBuilder, &snap);
  2867. nsRect positioningArea = GetPositioningArea();
  2868. if (positioningArea.TopLeft() != geometry->mPositioningArea.TopLeft() ||
  2869. (positioningArea.Size() != geometry->mPositioningArea.Size() &&
  2870. RenderingMightDependOnPositioningAreaSizeChange())) {
  2871. // Positioning area changed in a way that could cause everything to change,
  2872. // so invalidate everything (both old and new painting areas).
  2873. aInvalidRegion->Or(bounds, geometry->mBounds);
  2874. if (positioningArea.Size() != geometry->mPositioningArea.Size()) {
  2875. NotifyRenderingChanged();
  2876. }
  2877. return;
  2878. }
  2879. if (!mDestRect.IsEqualInterior(geometry->mDestRect)) {
  2880. // Dest area changed in a way that could cause everything to change,
  2881. // so invalidate everything (both old and new painting areas).
  2882. aInvalidRegion->Or(bounds, geometry->mBounds);
  2883. NotifyRenderingChanged();
  2884. return;
  2885. }
  2886. if (aBuilder->ShouldSyncDecodeImages()) {
  2887. const nsStyleImage& image = mBackgroundStyle->mImage.mLayers[mLayer].mImage;
  2888. if (image.GetType() == eStyleImageType_Image &&
  2889. geometry->ShouldInvalidateToSyncDecodeImages()) {
  2890. aInvalidRegion->Or(*aInvalidRegion, bounds);
  2891. NotifyRenderingChanged();
  2892. }
  2893. }
  2894. if (!bounds.IsEqualInterior(geometry->mBounds)) {
  2895. // Positioning area is unchanged, so invalidate just the change in the
  2896. // painting area.
  2897. aInvalidRegion->Xor(bounds, geometry->mBounds);
  2898. NotifyRenderingChanged();
  2899. }
  2900. }
  2901. nsRect
  2902. nsDisplayBackgroundImage::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) {
  2903. *aSnap = true;
  2904. return mBounds;
  2905. }
  2906. nsRect
  2907. nsDisplayBackgroundImage::GetBoundsInternal(nsDisplayListBuilder* aBuilder) {
  2908. nsPresContext* presContext = mFrame->PresContext();
  2909. if (!mBackgroundStyle) {
  2910. return nsRect();
  2911. }
  2912. nsRect clipRect = mBackgroundRect;
  2913. if (mFrame->GetType() == nsGkAtoms::canvasFrame) {
  2914. nsCanvasFrame* frame = static_cast<nsCanvasFrame*>(mFrame);
  2915. clipRect = frame->CanvasArea() + ToReferenceFrame();
  2916. } else if (nsLayoutUtils::UsesAsyncScrolling(mFrame) && IsNonEmptyFixedImage()) {
  2917. // If this is a background-attachment:fixed image, and APZ is enabled,
  2918. // async scrolling could reveal additional areas of the image, so don't
  2919. // clip it beyond clipping to the document's viewport.
  2920. if (Maybe<nsRect> viewportRect = GetViewportRectRelativeToReferenceFrame(aBuilder, mFrame)) {
  2921. clipRect = clipRect.Union(*viewportRect);
  2922. }
  2923. }
  2924. const nsStyleImageLayers::Layer& layer = mBackgroundStyle->mImage.mLayers[mLayer];
  2925. return nsCSSRendering::GetBackgroundLayerRect(presContext, mFrame,
  2926. mBackgroundRect, clipRect, layer,
  2927. aBuilder->GetBackgroundPaintFlags());
  2928. }
  2929. uint32_t
  2930. nsDisplayBackgroundImage::GetPerFrameKey()
  2931. {
  2932. return (mLayer << nsDisplayItem::TYPE_BITS) |
  2933. nsDisplayItem::GetPerFrameKey();
  2934. }
  2935. nsDisplayTableBackgroundImage::nsDisplayTableBackgroundImage(nsDisplayListBuilder* aBuilder,
  2936. nsIFrame* aFrame,
  2937. uint32_t aLayer,
  2938. const nsRect& aBackgroundRect,
  2939. const nsStyleBackground* aBackgroundStyle,
  2940. nsIFrame* aCellFrame)
  2941. : nsDisplayBackgroundImage(aBuilder, aFrame, aLayer, aBackgroundRect, aBackgroundStyle)
  2942. , mStyleFrame(aFrame)
  2943. , mTableType(GetTableTypeFromFrame(mStyleFrame))
  2944. {
  2945. mFrame = aCellFrame;
  2946. }
  2947. bool
  2948. nsDisplayTableBackgroundImage::IsInvalid(nsRect& aRect)
  2949. {
  2950. bool result = mStyleFrame ? mStyleFrame->IsInvalid(aRect) : false;
  2951. aRect += ToReferenceFrame();
  2952. return result;
  2953. }
  2954. nsDisplayThemedBackground::nsDisplayThemedBackground(nsDisplayListBuilder* aBuilder,
  2955. nsIFrame* aFrame,
  2956. const nsRect& aBackgroundRect)
  2957. : nsDisplayItem(aBuilder, aFrame)
  2958. , mBackgroundRect(aBackgroundRect)
  2959. {
  2960. MOZ_COUNT_CTOR(nsDisplayThemedBackground);
  2961. const nsStyleDisplay* disp = mFrame->StyleDisplay();
  2962. mAppearance = disp->mAppearance;
  2963. mFrame->IsThemed(disp, &mThemeTransparency);
  2964. // Perform necessary RegisterThemeGeometry
  2965. nsITheme* theme = mFrame->PresContext()->GetTheme();
  2966. nsITheme::ThemeGeometryType type =
  2967. theme->ThemeGeometryTypeForWidget(mFrame, disp->mAppearance);
  2968. if (type != nsITheme::eThemeGeometryTypeUnknown) {
  2969. RegisterThemeGeometry(aBuilder, aFrame, type);
  2970. }
  2971. if (disp->mAppearance == NS_THEME_WIN_BORDERLESS_GLASS ||
  2972. disp->mAppearance == NS_THEME_WIN_GLASS) {
  2973. aBuilder->SetGlassDisplayItem(this);
  2974. }
  2975. mBounds = GetBoundsInternal();
  2976. }
  2977. nsDisplayThemedBackground::~nsDisplayThemedBackground()
  2978. {
  2979. #ifdef NS_BUILD_REFCNT_LOGGING
  2980. MOZ_COUNT_DTOR(nsDisplayThemedBackground);
  2981. #endif
  2982. }
  2983. void
  2984. nsDisplayThemedBackground::WriteDebugInfo(std::stringstream& aStream)
  2985. {
  2986. aStream << " (themed, appearance:" << (int)mAppearance << ")";
  2987. }
  2988. void
  2989. nsDisplayThemedBackground::HitTest(nsDisplayListBuilder* aBuilder,
  2990. const nsRect& aRect,
  2991. HitTestState* aState,
  2992. nsTArray<nsIFrame*> *aOutFrames)
  2993. {
  2994. // Assume that any point in our background rect is a hit.
  2995. if (mBackgroundRect.Intersects(aRect)) {
  2996. aOutFrames->AppendElement(mFrame);
  2997. }
  2998. }
  2999. nsRegion
  3000. nsDisplayThemedBackground::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
  3001. bool* aSnap) {
  3002. nsRegion result;
  3003. *aSnap = false;
  3004. if (mThemeTransparency == nsITheme::eOpaque) {
  3005. result = mBackgroundRect;
  3006. }
  3007. return result;
  3008. }
  3009. Maybe<nscolor>
  3010. nsDisplayThemedBackground::IsUniform(nsDisplayListBuilder* aBuilder) {
  3011. if (mAppearance == NS_THEME_WIN_BORDERLESS_GLASS ||
  3012. mAppearance == NS_THEME_WIN_GLASS) {
  3013. return Some(NS_RGBA(0,0,0,0));
  3014. }
  3015. return Nothing();
  3016. }
  3017. bool
  3018. nsDisplayThemedBackground::ProvidesFontSmoothingBackgroundColor(nscolor* aColor)
  3019. {
  3020. nsITheme* theme = mFrame->PresContext()->GetTheme();
  3021. return theme->WidgetProvidesFontSmoothingBackgroundColor(mFrame, mAppearance, aColor);
  3022. }
  3023. nsRect
  3024. nsDisplayThemedBackground::GetPositioningArea()
  3025. {
  3026. return mBackgroundRect;
  3027. }
  3028. void
  3029. nsDisplayThemedBackground::Paint(nsDisplayListBuilder* aBuilder,
  3030. nsRenderingContext* aCtx)
  3031. {
  3032. PaintInternal(aBuilder, aCtx, mVisibleRect, nullptr);
  3033. }
  3034. void
  3035. nsDisplayThemedBackground::PaintInternal(nsDisplayListBuilder* aBuilder,
  3036. nsRenderingContext* aCtx, const nsRect& aBounds,
  3037. nsRect* aClipRect)
  3038. {
  3039. // XXXzw this ignores aClipRect.
  3040. nsPresContext* presContext = mFrame->PresContext();
  3041. nsITheme *theme = presContext->GetTheme();
  3042. nsRect drawing(mBackgroundRect);
  3043. theme->GetWidgetOverflow(presContext->DeviceContext(), mFrame, mAppearance,
  3044. &drawing);
  3045. drawing.IntersectRect(drawing, aBounds);
  3046. theme->DrawWidgetBackground(aCtx, mFrame, mAppearance, mBackgroundRect, drawing);
  3047. }
  3048. bool nsDisplayThemedBackground::IsWindowActive()
  3049. {
  3050. EventStates docState = mFrame->GetContent()->OwnerDoc()->GetDocumentState();
  3051. return !docState.HasState(NS_DOCUMENT_STATE_WINDOW_INACTIVE);
  3052. }
  3053. void nsDisplayThemedBackground::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  3054. const nsDisplayItemGeometry* aGeometry,
  3055. nsRegion* aInvalidRegion)
  3056. {
  3057. const nsDisplayThemedBackgroundGeometry* geometry = static_cast<const nsDisplayThemedBackgroundGeometry*>(aGeometry);
  3058. bool snap;
  3059. nsRect bounds = GetBounds(aBuilder, &snap);
  3060. nsRect positioningArea = GetPositioningArea();
  3061. if (!positioningArea.IsEqualInterior(geometry->mPositioningArea)) {
  3062. // Invalidate everything (both old and new painting areas).
  3063. aInvalidRegion->Or(bounds, geometry->mBounds);
  3064. return;
  3065. }
  3066. if (!bounds.IsEqualInterior(geometry->mBounds)) {
  3067. // Positioning area is unchanged, so invalidate just the change in the
  3068. // painting area.
  3069. aInvalidRegion->Xor(bounds, geometry->mBounds);
  3070. }
  3071. nsITheme* theme = mFrame->PresContext()->GetTheme();
  3072. if (theme->WidgetAppearanceDependsOnWindowFocus(mAppearance) &&
  3073. IsWindowActive() != geometry->mWindowIsActive) {
  3074. aInvalidRegion->Or(*aInvalidRegion, bounds);
  3075. }
  3076. }
  3077. nsRect
  3078. nsDisplayThemedBackground::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) {
  3079. *aSnap = true;
  3080. return mBounds;
  3081. }
  3082. nsRect
  3083. nsDisplayThemedBackground::GetBoundsInternal() {
  3084. nsPresContext* presContext = mFrame->PresContext();
  3085. nsRect r = mBackgroundRect - ToReferenceFrame();
  3086. presContext->GetTheme()->
  3087. GetWidgetOverflow(presContext->DeviceContext(), mFrame,
  3088. mFrame->StyleDisplay()->mAppearance, &r);
  3089. return r + ToReferenceFrame();
  3090. }
  3091. void
  3092. nsDisplayImageContainer::ConfigureLayer(ImageLayer* aLayer,
  3093. const ContainerLayerParameters& aParameters)
  3094. {
  3095. aLayer->SetSamplingFilter(nsLayoutUtils::GetSamplingFilterForFrame(mFrame));
  3096. nsCOMPtr<imgIContainer> image = GetImage();
  3097. MOZ_ASSERT(image);
  3098. int32_t imageWidth;
  3099. int32_t imageHeight;
  3100. image->GetWidth(&imageWidth);
  3101. image->GetHeight(&imageHeight);
  3102. NS_ASSERTION(imageWidth != 0 && imageHeight != 0, "Invalid image size!");
  3103. if (imageWidth > 0 && imageHeight > 0) {
  3104. // We're actually using the ImageContainer. Let our frame know that it
  3105. // should consider itself to have painted successfully.
  3106. nsDisplayBackgroundGeometry::UpdateDrawResult(this,
  3107. image::DrawResult::SUCCESS);
  3108. }
  3109. // XXX(seth): Right now we ignore aParameters.Scale() and
  3110. // aParameters.Offset(), because FrameLayerBuilder already applies
  3111. // aParameters.Scale() via the layer's post-transform, and
  3112. // aParameters.Offset() is always zero.
  3113. MOZ_ASSERT(aParameters.Offset() == LayerIntPoint(0,0));
  3114. // It's possible (for example, due to downscale-during-decode) that the
  3115. // ImageContainer this ImageLayer is holding has a different size from the
  3116. // intrinsic size of the image. For this reason we compute the transform using
  3117. // the ImageContainer's size rather than the image's intrinsic size.
  3118. // XXX(seth): In reality, since the size of the ImageContainer may change
  3119. // asynchronously, this is not enough. Bug 1183378 will provide a more
  3120. // complete fix, but this solution is safe in more cases than simply relying
  3121. // on the intrinsic size.
  3122. IntSize containerSize = aLayer->GetContainer()
  3123. ? aLayer->GetContainer()->GetCurrentSize()
  3124. : IntSize(imageWidth, imageHeight);
  3125. const int32_t factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  3126. const LayoutDeviceRect destRect =
  3127. LayoutDeviceRect::FromAppUnits(GetDestRect(), factor);
  3128. const LayoutDevicePoint p = destRect.TopLeft();
  3129. Matrix transform = Matrix::Translation(p.x, p.y);
  3130. transform.PreScale(destRect.width / containerSize.width,
  3131. destRect.height / containerSize.height);
  3132. aLayer->SetBaseTransform(gfx::Matrix4x4::From2D(transform));
  3133. }
  3134. already_AddRefed<ImageContainer>
  3135. nsDisplayImageContainer::GetContainer(LayerManager* aManager,
  3136. nsDisplayListBuilder *aBuilder)
  3137. {
  3138. nsCOMPtr<imgIContainer> image = GetImage();
  3139. if (!image) {
  3140. MOZ_ASSERT_UNREACHABLE("Must call CanOptimizeToImage() and get true "
  3141. "before calling GetContainer()");
  3142. return nullptr;
  3143. }
  3144. uint32_t flags = aBuilder->ShouldSyncDecodeImages()
  3145. ? imgIContainer::FLAG_SYNC_DECODE
  3146. : imgIContainer::FLAG_NONE;
  3147. return image->GetImageContainer(aManager, flags);
  3148. }
  3149. bool
  3150. nsDisplayImageContainer::CanOptimizeToImageLayer(LayerManager* aManager,
  3151. nsDisplayListBuilder* aBuilder)
  3152. {
  3153. uint32_t flags = aBuilder->ShouldSyncDecodeImages()
  3154. ? imgIContainer::FLAG_SYNC_DECODE
  3155. : imgIContainer::FLAG_NONE;
  3156. nsCOMPtr<imgIContainer> image = GetImage();
  3157. if (!image) {
  3158. return false;
  3159. }
  3160. if (!image->IsImageContainerAvailable(aManager, flags)) {
  3161. return false;
  3162. }
  3163. int32_t imageWidth;
  3164. int32_t imageHeight;
  3165. image->GetWidth(&imageWidth);
  3166. image->GetHeight(&imageHeight);
  3167. if (imageWidth == 0 || imageHeight == 0) {
  3168. NS_ASSERTION(false, "invalid image size");
  3169. return false;
  3170. }
  3171. if (gfxPrefs::ImageLayerizeAlways()) {
  3172. // If the user decides to trade off quality for performance, so be it!
  3173. return true;
  3174. }
  3175. const int32_t factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  3176. const LayoutDeviceRect destRect =
  3177. LayoutDeviceRect::FromAppUnits(GetDestRect(), factor);
  3178. // Calculate the scaling factor for the frame.
  3179. const gfxSize scale = gfxSize(destRect.width / imageWidth,
  3180. destRect.height / imageHeight);
  3181. if (scale.width < 0.34 || scale.height < 0.34) {
  3182. // This would look awful as long as we can't use high-quality downscaling
  3183. // for image layers (bug 803703), so don't turn this into an image layer.
  3184. return false;
  3185. }
  3186. return true;
  3187. }
  3188. void
  3189. nsDisplayBackgroundColor::ApplyOpacity(nsDisplayListBuilder* aBuilder,
  3190. float aOpacity,
  3191. const DisplayItemClip* aClip)
  3192. {
  3193. NS_ASSERTION(CanApplyOpacity(), "ApplyOpacity should be allowed");
  3194. mColor.a = mColor.a * aOpacity;
  3195. if (aClip) {
  3196. IntersectClip(aBuilder, *aClip);
  3197. }
  3198. }
  3199. bool
  3200. nsDisplayBackgroundColor::CanApplyOpacity() const
  3201. {
  3202. return true;
  3203. }
  3204. void
  3205. nsDisplayBackgroundColor::Paint(nsDisplayListBuilder* aBuilder,
  3206. nsRenderingContext* aCtx)
  3207. {
  3208. if (mColor == Color()) {
  3209. return;
  3210. }
  3211. #if 0
  3212. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1148418#c21 for why this
  3213. // results in a precision induced rounding issue that makes the rect one
  3214. // pixel shorter in rare cases. Disabled in favor of the old code for now.
  3215. // Note that the pref layout.css.devPixelsPerPx needs to be set to 1 to
  3216. // reproduce the bug.
  3217. //
  3218. // TODO:
  3219. // This new path does not include support for background-clip:text; need to
  3220. // be fixed if/when we switch to this new code path.
  3221. DrawTarget& aDrawTarget = *aCtx->GetDrawTarget();
  3222. Rect rect = NSRectToSnappedRect(mBackgroundRect,
  3223. mFrame->PresContext()->AppUnitsPerDevPixel(),
  3224. aDrawTarget);
  3225. ColorPattern color(ToDeviceColor(mColor));
  3226. aDrawTarget.FillRect(rect, color);
  3227. #else
  3228. gfxContext* ctx = aCtx->ThebesContext();
  3229. gfxRect bounds =
  3230. nsLayoutUtils::RectToGfxRect(mBackgroundRect,
  3231. mFrame->PresContext()->AppUnitsPerDevPixel());
  3232. StyleGeometryBox clip = mBackgroundStyle->mImage.mLayers[0].mClip;
  3233. if (clip == StyleGeometryBox::Text) {
  3234. if (!GenerateAndPushTextMask(mFrame, aCtx, mBackgroundRect, aBuilder)) {
  3235. return;
  3236. }
  3237. ctx->SetColor(mColor);
  3238. ctx->Rectangle(bounds, true);
  3239. ctx->Fill();
  3240. ctx->PopGroupAndBlend();
  3241. return;
  3242. }
  3243. ctx->SetColor(mColor);
  3244. ctx->NewPath();
  3245. ctx->Rectangle(bounds, true);
  3246. ctx->Fill();
  3247. #endif
  3248. }
  3249. nsRegion
  3250. nsDisplayBackgroundColor::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
  3251. bool* aSnap)
  3252. {
  3253. *aSnap = false;
  3254. if (mColor.a != 1) {
  3255. return nsRegion();
  3256. }
  3257. if (!mBackgroundStyle)
  3258. return nsRegion();
  3259. const nsStyleImageLayers::Layer& bottomLayer = mBackgroundStyle->BottomLayer();
  3260. if (bottomLayer.mClip == StyleGeometryBox::Text) {
  3261. return nsRegion();
  3262. }
  3263. *aSnap = true;
  3264. return nsDisplayBackgroundImage::GetInsideClipRegion(this, bottomLayer.mClip,
  3265. mBackgroundRect, mBackgroundRect);
  3266. }
  3267. Maybe<nscolor>
  3268. nsDisplayBackgroundColor::IsUniform(nsDisplayListBuilder* aBuilder)
  3269. {
  3270. return Some(mColor.ToABGR());
  3271. }
  3272. void
  3273. nsDisplayBackgroundColor::HitTest(nsDisplayListBuilder* aBuilder,
  3274. const nsRect& aRect,
  3275. HitTestState* aState,
  3276. nsTArray<nsIFrame*> *aOutFrames)
  3277. {
  3278. if (!RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
  3279. // aRect doesn't intersect our border-radius curve.
  3280. return;
  3281. }
  3282. aOutFrames->AppendElement(mFrame);
  3283. }
  3284. void
  3285. nsDisplayBackgroundColor::WriteDebugInfo(std::stringstream& aStream)
  3286. {
  3287. aStream << " (rgba " << mColor.r << "," << mColor.g << ","
  3288. << mColor.b << "," << mColor.a << ")";
  3289. }
  3290. already_AddRefed<Layer>
  3291. nsDisplayClearBackground::BuildLayer(nsDisplayListBuilder* aBuilder,
  3292. LayerManager* aManager,
  3293. const ContainerLayerParameters& aParameters)
  3294. {
  3295. RefPtr<ColorLayer> layer = static_cast<ColorLayer*>
  3296. (aManager->GetLayerBuilder()->GetLeafLayerFor(aBuilder, this));
  3297. if (!layer) {
  3298. layer = aManager->CreateColorLayer();
  3299. if (!layer)
  3300. return nullptr;
  3301. }
  3302. layer->SetColor(Color());
  3303. layer->SetMixBlendMode(gfx::CompositionOp::OP_SOURCE);
  3304. bool snap;
  3305. nsRect bounds = GetBounds(aBuilder, &snap);
  3306. int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  3307. layer->SetBounds(bounds.ToNearestPixels(appUnitsPerDevPixel)); // XXX Do we need to respect the parent layer's scale here?
  3308. return layer.forget();
  3309. }
  3310. nsRect
  3311. nsDisplayOutline::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) {
  3312. *aSnap = false;
  3313. return mFrame->GetVisualOverflowRectRelativeToSelf() + ToReferenceFrame();
  3314. }
  3315. void
  3316. nsDisplayOutline::Paint(nsDisplayListBuilder* aBuilder,
  3317. nsRenderingContext* aCtx) {
  3318. // TODO join outlines together
  3319. nsPoint offset = ToReferenceFrame();
  3320. nsCSSRendering::PaintOutline(mFrame->PresContext(), *aCtx, mFrame,
  3321. mVisibleRect,
  3322. nsRect(offset, mFrame->GetSize()),
  3323. mFrame->StyleContext());
  3324. }
  3325. bool
  3326. nsDisplayOutline::IsInvisibleInRect(const nsRect& aRect)
  3327. {
  3328. const nsStyleOutline* outline = mFrame->StyleOutline();
  3329. nsRect borderBox(ToReferenceFrame(), mFrame->GetSize());
  3330. if (borderBox.Contains(aRect) &&
  3331. !nsLayoutUtils::HasNonZeroCorner(outline->mOutlineRadius)) {
  3332. if (outline->mOutlineOffset >= 0) {
  3333. // aRect is entirely inside the border-rect, and the outline isn't
  3334. // rendered inside the border-rect, so the outline is not visible.
  3335. return true;
  3336. }
  3337. }
  3338. return false;
  3339. }
  3340. void
  3341. nsDisplayEventReceiver::HitTest(nsDisplayListBuilder* aBuilder,
  3342. const nsRect& aRect,
  3343. HitTestState* aState,
  3344. nsTArray<nsIFrame*> *aOutFrames)
  3345. {
  3346. if (!RoundedBorderIntersectsRect(mFrame, ToReferenceFrame(), aRect)) {
  3347. // aRect doesn't intersect our border-radius curve.
  3348. return;
  3349. }
  3350. aOutFrames->AppendElement(mFrame);
  3351. }
  3352. void
  3353. nsDisplayLayerEventRegions::AddFrame(nsDisplayListBuilder* aBuilder,
  3354. nsIFrame* aFrame)
  3355. {
  3356. NS_ASSERTION(aBuilder->FindReferenceFrameFor(aFrame) == aBuilder->FindReferenceFrameFor(mFrame),
  3357. "Reference frame mismatch");
  3358. if (aBuilder->IsInsidePointerEventsNoneDoc()) {
  3359. // Somewhere up the parent document chain is a subdocument with pointer-
  3360. // events:none set on it.
  3361. return;
  3362. }
  3363. if (!aFrame->GetParent()) {
  3364. MOZ_ASSERT(aFrame->GetType() == nsGkAtoms::viewportFrame);
  3365. // Viewport frames are never event targets, other frames, like canvas frames,
  3366. // are the event targets for any regions viewport frames may cover.
  3367. return;
  3368. }
  3369. uint8_t pointerEvents =
  3370. aFrame->StyleUserInterface()->GetEffectivePointerEvents(aFrame);
  3371. if (pointerEvents == NS_STYLE_POINTER_EVENTS_NONE) {
  3372. return;
  3373. }
  3374. bool simpleRegions = aFrame->HasAnyStateBits(NS_FRAME_SIMPLE_EVENT_REGIONS);
  3375. if (!simpleRegions) {
  3376. if (!aFrame->StyleVisibility()->IsVisible()) {
  3377. return;
  3378. }
  3379. }
  3380. // XXX handle other pointerEvents values for SVG
  3381. // XXX Do something clever here for the common case where the border box
  3382. // is obviously entirely inside mHitRegion.
  3383. nsRect borderBox;
  3384. if (nsLayoutUtils::GetScrollableFrameFor(aFrame)) {
  3385. // If the frame is content of a scrollframe, then we need to pick up the
  3386. // area corresponding to the overflow rect as well. Otherwise the parts of
  3387. // the overflow that are not occupied by descendants get skipped and the
  3388. // APZ code sends touch events to the content underneath instead.
  3389. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1127773#c15.
  3390. borderBox = aFrame->GetScrollableOverflowRect();
  3391. } else {
  3392. borderBox = nsRect(nsPoint(0, 0), aFrame->GetSize());
  3393. }
  3394. borderBox += aBuilder->ToReferenceFrame(aFrame);
  3395. bool borderBoxHasRoundedCorners = false;
  3396. if (!simpleRegions) {
  3397. if (nsLayoutUtils::HasNonZeroCorner(aFrame->StyleBorder()->mBorderRadius)) {
  3398. borderBoxHasRoundedCorners = true;
  3399. } else {
  3400. aFrame->AddStateBits(NS_FRAME_SIMPLE_EVENT_REGIONS);
  3401. }
  3402. }
  3403. const DisplayItemClip* clip = aBuilder->ClipState().GetCurrentCombinedClip(aBuilder);
  3404. if (clip) {
  3405. borderBox = clip->ApplyNonRoundedIntersection(borderBox);
  3406. if (clip->GetRoundedRectCount() > 0) {
  3407. borderBoxHasRoundedCorners = true;
  3408. }
  3409. }
  3410. if (borderBoxHasRoundedCorners ||
  3411. (aFrame->GetStateBits() & NS_FRAME_SVG_LAYOUT)) {
  3412. mMaybeHitRegion.Or(mMaybeHitRegion, borderBox);
  3413. // Avoid quadratic performance as a result of the region growing to include
  3414. // an arbitrarily large number of rects, which can happen on some pages.
  3415. mMaybeHitRegion.SimplifyOutward(8);
  3416. } else {
  3417. mHitRegion.Or(mHitRegion, borderBox);
  3418. }
  3419. if (aBuilder->IsBuildingNonLayerizedScrollbar() ||
  3420. aBuilder->GetAncestorHasApzAwareEventHandler())
  3421. {
  3422. // Scrollbars may be painted into a layer below the actual layer they will
  3423. // scroll, and therefore wheel events may be dispatched to the outer frame
  3424. // instead of the intended scrollframe. To address this, we force a d-t-c
  3425. // region on scrollbar frames that won't be placed in their own layer. See
  3426. // bug 1213324 for details.
  3427. mDispatchToContentHitRegion.Or(mDispatchToContentHitRegion, borderBox);
  3428. mDispatchToContentHitRegion.SimplifyOutward(8);
  3429. } else if (aFrame->GetType() == nsGkAtoms::objectFrame) {
  3430. // If the frame is a plugin frame and wants to handle wheel events as
  3431. // default action, we should add the frame to dispatch-to-content region.
  3432. nsPluginFrame* pluginFrame = do_QueryFrame(aFrame);
  3433. if (pluginFrame && pluginFrame->WantsToHandleWheelEventAsDefaultAction()) {
  3434. mDispatchToContentHitRegion.Or(mDispatchToContentHitRegion, borderBox);
  3435. mDispatchToContentHitRegion.SimplifyOutward(8);
  3436. }
  3437. }
  3438. // Touch action region
  3439. nsIFrame* touchActionFrame = aFrame;
  3440. nsIScrollableFrame* scrollFrame = nsLayoutUtils::GetScrollableFrameFor(aFrame);
  3441. if (scrollFrame) {
  3442. touchActionFrame = do_QueryFrame(scrollFrame);
  3443. }
  3444. uint32_t touchAction = nsLayoutUtils::GetTouchActionFromFrame(touchActionFrame);
  3445. if (touchAction != NS_STYLE_TOUCH_ACTION_AUTO) {
  3446. // If this frame has touch-action areas, and there were already
  3447. // touch-action areas from some other element on this same event regions,
  3448. // then all we know is that there are multiple elements with touch-action
  3449. // properties. In particular, we don't know what the relationship is
  3450. // between those elements in terms of DOM ancestry, and so we don't know
  3451. // how to combine the regions properly. Instead, we just add all the areas
  3452. // to the dispatch-to-content region, so that the APZ knows to check with
  3453. // the main thread. XXX we need to come up with a better way to do this,
  3454. // see bug 1287829.
  3455. bool alreadyHadRegions = !mNoActionRegion.IsEmpty() ||
  3456. !mHorizontalPanRegion.IsEmpty() ||
  3457. !mVerticalPanRegion.IsEmpty();
  3458. if (touchAction & NS_STYLE_TOUCH_ACTION_NONE) {
  3459. mNoActionRegion.OrWith(borderBox);
  3460. } else {
  3461. if ((touchAction & NS_STYLE_TOUCH_ACTION_PAN_X)) {
  3462. mHorizontalPanRegion.OrWith(borderBox);
  3463. }
  3464. if ((touchAction & NS_STYLE_TOUCH_ACTION_PAN_Y)) {
  3465. mVerticalPanRegion.OrWith(borderBox);
  3466. }
  3467. }
  3468. if (alreadyHadRegions) {
  3469. mDispatchToContentHitRegion.OrWith(CombinedTouchActionRegion());
  3470. mDispatchToContentHitRegion.SimplifyOutward(8);
  3471. }
  3472. }
  3473. }
  3474. void
  3475. nsDisplayLayerEventRegions::AddInactiveScrollPort(const nsRect& aRect)
  3476. {
  3477. mHitRegion.Or(mHitRegion, aRect);
  3478. mDispatchToContentHitRegion.Or(mDispatchToContentHitRegion, aRect);
  3479. mDispatchToContentHitRegion.SimplifyOutward(8);
  3480. }
  3481. bool
  3482. nsDisplayLayerEventRegions::IsEmpty() const
  3483. {
  3484. // If the hit region and maybe-hit region are empty, then the rest
  3485. // must be empty too.
  3486. if (mHitRegion.IsEmpty() && mMaybeHitRegion.IsEmpty()) {
  3487. MOZ_ASSERT(mDispatchToContentHitRegion.IsEmpty());
  3488. MOZ_ASSERT(mNoActionRegion.IsEmpty());
  3489. MOZ_ASSERT(mHorizontalPanRegion.IsEmpty());
  3490. MOZ_ASSERT(mVerticalPanRegion.IsEmpty());
  3491. return true;
  3492. }
  3493. return false;
  3494. }
  3495. nsRegion
  3496. nsDisplayLayerEventRegions::CombinedTouchActionRegion()
  3497. {
  3498. nsRegion result;
  3499. result.Or(mHorizontalPanRegion, mVerticalPanRegion);
  3500. result.OrWith(mNoActionRegion);
  3501. return result;
  3502. }
  3503. int32_t
  3504. nsDisplayLayerEventRegions::ZIndex() const
  3505. {
  3506. return mOverrideZIndex ? *mOverrideZIndex : nsDisplayItem::ZIndex();
  3507. }
  3508. void
  3509. nsDisplayLayerEventRegions::SetOverrideZIndex(int32_t aZIndex)
  3510. {
  3511. mOverrideZIndex = Some(aZIndex);
  3512. }
  3513. void
  3514. nsDisplayLayerEventRegions::WriteDebugInfo(std::stringstream& aStream)
  3515. {
  3516. if (!mHitRegion.IsEmpty()) {
  3517. AppendToString(aStream, mHitRegion, " (hitRegion ", ")");
  3518. }
  3519. if (!mMaybeHitRegion.IsEmpty()) {
  3520. AppendToString(aStream, mMaybeHitRegion, " (maybeHitRegion ", ")");
  3521. }
  3522. if (!mDispatchToContentHitRegion.IsEmpty()) {
  3523. AppendToString(aStream, mDispatchToContentHitRegion, " (dispatchToContentRegion ", ")");
  3524. }
  3525. if (!mNoActionRegion.IsEmpty()) {
  3526. AppendToString(aStream, mNoActionRegion, " (noActionRegion ", ")");
  3527. }
  3528. if (!mHorizontalPanRegion.IsEmpty()) {
  3529. AppendToString(aStream, mHorizontalPanRegion, " (horizPanRegion ", ")");
  3530. }
  3531. if (!mVerticalPanRegion.IsEmpty()) {
  3532. AppendToString(aStream, mVerticalPanRegion, " (vertPanRegion ", ")");
  3533. }
  3534. }
  3535. nsDisplayCaret::nsDisplayCaret(nsDisplayListBuilder* aBuilder,
  3536. nsIFrame* aCaretFrame)
  3537. : nsDisplayItem(aBuilder, aCaretFrame)
  3538. , mCaret(aBuilder->GetCaret())
  3539. , mBounds(aBuilder->GetCaretRect() + ToReferenceFrame())
  3540. {
  3541. MOZ_COUNT_CTOR(nsDisplayCaret);
  3542. }
  3543. #ifdef NS_BUILD_REFCNT_LOGGING
  3544. nsDisplayCaret::~nsDisplayCaret()
  3545. {
  3546. MOZ_COUNT_DTOR(nsDisplayCaret);
  3547. }
  3548. #endif
  3549. nsRect
  3550. nsDisplayCaret::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
  3551. {
  3552. *aSnap = true;
  3553. // The caret returns a rect in the coordinates of mFrame.
  3554. return mBounds;
  3555. }
  3556. void
  3557. nsDisplayCaret::Paint(nsDisplayListBuilder* aBuilder,
  3558. nsRenderingContext* aCtx) {
  3559. // Note: Because we exist, we know that the caret is visible, so we don't
  3560. // need to check for the caret's visibility.
  3561. mCaret->PaintCaret(*aCtx->GetDrawTarget(), mFrame, ToReferenceFrame());
  3562. }
  3563. nsDisplayBorder::nsDisplayBorder(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
  3564. : nsDisplayItem(aBuilder, aFrame)
  3565. {
  3566. MOZ_COUNT_CTOR(nsDisplayBorder);
  3567. mBounds = CalculateBounds(*mFrame->StyleBorder());
  3568. }
  3569. bool
  3570. nsDisplayBorder::IsInvisibleInRect(const nsRect& aRect)
  3571. {
  3572. nsRect paddingRect = mFrame->GetPaddingRect() - mFrame->GetPosition() +
  3573. ToReferenceFrame();
  3574. const nsStyleBorder *styleBorder;
  3575. if (paddingRect.Contains(aRect) &&
  3576. !(styleBorder = mFrame->StyleBorder())->IsBorderImageLoaded() &&
  3577. !nsLayoutUtils::HasNonZeroCorner(styleBorder->mBorderRadius)) {
  3578. // aRect is entirely inside the content rect, and no part
  3579. // of the border is rendered inside the content rect, so we are not
  3580. // visible
  3581. // Skip this if there's a border-image (which draws a background
  3582. // too) or if there is a border-radius (which makes the border draw
  3583. // further in).
  3584. return true;
  3585. }
  3586. return false;
  3587. }
  3588. nsDisplayItemGeometry*
  3589. nsDisplayBorder::AllocateGeometry(nsDisplayListBuilder* aBuilder)
  3590. {
  3591. return new nsDisplayBorderGeometry(this, aBuilder);
  3592. }
  3593. void
  3594. nsDisplayBorder::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  3595. const nsDisplayItemGeometry* aGeometry,
  3596. nsRegion* aInvalidRegion)
  3597. {
  3598. const nsDisplayBorderGeometry* geometry = static_cast<const nsDisplayBorderGeometry*>(aGeometry);
  3599. bool snap;
  3600. if (!geometry->mBounds.IsEqualInterior(GetBounds(aBuilder, &snap)) ||
  3601. !geometry->mContentRect.IsEqualInterior(GetContentRect())) {
  3602. // We can probably get away with only invalidating the difference
  3603. // between the border and padding rects, but the XUL ui at least
  3604. // is apparently painting a background with this?
  3605. aInvalidRegion->Or(GetBounds(aBuilder, &snap), geometry->mBounds);
  3606. }
  3607. if (aBuilder->ShouldSyncDecodeImages() &&
  3608. geometry->ShouldInvalidateToSyncDecodeImages()) {
  3609. aInvalidRegion->Or(*aInvalidRegion, GetBounds(aBuilder, &snap));
  3610. }
  3611. }
  3612. void
  3613. nsDisplayBorder::Paint(nsDisplayListBuilder* aBuilder,
  3614. nsRenderingContext* aCtx) {
  3615. nsPoint offset = ToReferenceFrame();
  3616. PaintBorderFlags flags = aBuilder->ShouldSyncDecodeImages()
  3617. ? PaintBorderFlags::SYNC_DECODE_IMAGES
  3618. : PaintBorderFlags();
  3619. image::DrawResult result =
  3620. nsCSSRendering::PaintBorder(mFrame->PresContext(), *aCtx, mFrame,
  3621. mVisibleRect,
  3622. nsRect(offset, mFrame->GetSize()),
  3623. mFrame->StyleContext(),
  3624. flags,
  3625. mFrame->GetSkipSides());
  3626. nsDisplayBorderGeometry::UpdateDrawResult(this, result);
  3627. }
  3628. nsRect
  3629. nsDisplayBorder::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
  3630. {
  3631. *aSnap = true;
  3632. return mBounds;
  3633. }
  3634. nsRect
  3635. nsDisplayBorder::CalculateBounds(const nsStyleBorder& aStyleBorder)
  3636. {
  3637. nsRect borderBounds(ToReferenceFrame(), mFrame->GetSize());
  3638. if (aStyleBorder.IsBorderImageLoaded()) {
  3639. borderBounds.Inflate(aStyleBorder.GetImageOutset());
  3640. return borderBounds;
  3641. } else {
  3642. nsMargin border = aStyleBorder.GetComputedBorder();
  3643. nsRect result;
  3644. if (border.top > 0) {
  3645. result = nsRect(borderBounds.X(), borderBounds.Y(), borderBounds.Width(), border.top);
  3646. }
  3647. if (border.right > 0) {
  3648. result.UnionRect(result, nsRect(borderBounds.XMost() - border.right, borderBounds.Y(), border.right, borderBounds.Height()));
  3649. }
  3650. if (border.bottom > 0) {
  3651. result.UnionRect(result, nsRect(borderBounds.X(), borderBounds.YMost() - border.bottom, borderBounds.Width(), border.bottom));
  3652. }
  3653. if (border.left > 0) {
  3654. result.UnionRect(result, nsRect(borderBounds.X(), borderBounds.Y(), border.left, borderBounds.Height()));
  3655. }
  3656. nscoord radii[8];
  3657. if (mFrame->GetBorderRadii(radii)) {
  3658. if (border.left > 0 || border.top > 0) {
  3659. nsSize cornerSize(radii[NS_CORNER_TOP_LEFT_X], radii[NS_CORNER_TOP_LEFT_Y]);
  3660. result.UnionRect(result, nsRect(borderBounds.TopLeft(), cornerSize));
  3661. }
  3662. if (border.top > 0 || border.right > 0) {
  3663. nsSize cornerSize(radii[NS_CORNER_TOP_RIGHT_X], radii[NS_CORNER_TOP_RIGHT_Y]);
  3664. result.UnionRect(result, nsRect(borderBounds.TopRight() - nsPoint(cornerSize.width, 0), cornerSize));
  3665. }
  3666. if (border.right > 0 || border.bottom > 0) {
  3667. nsSize cornerSize(radii[NS_CORNER_BOTTOM_RIGHT_X], radii[NS_CORNER_BOTTOM_RIGHT_Y]);
  3668. result.UnionRect(result, nsRect(borderBounds.BottomRight() - nsPoint(cornerSize.width, cornerSize.height), cornerSize));
  3669. }
  3670. if (border.bottom > 0 || border.left > 0) {
  3671. nsSize cornerSize(radii[NS_CORNER_BOTTOM_LEFT_X], radii[NS_CORNER_BOTTOM_LEFT_Y]);
  3672. result.UnionRect(result, nsRect(borderBounds.BottomLeft() - nsPoint(0, cornerSize.height), cornerSize));
  3673. }
  3674. }
  3675. return result;
  3676. }
  3677. }
  3678. // Given a region, compute a conservative approximation to it as a list
  3679. // of rectangles that aren't vertically adjacent (i.e., vertically
  3680. // adjacent or overlapping rectangles are combined).
  3681. // Right now this is only approximate, some vertically overlapping rectangles
  3682. // aren't guaranteed to be combined.
  3683. static void
  3684. ComputeDisjointRectangles(const nsRegion& aRegion,
  3685. nsTArray<nsRect>* aRects) {
  3686. nscoord accumulationMargin = nsPresContext::CSSPixelsToAppUnits(25);
  3687. nsRect accumulated;
  3688. for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
  3689. const nsRect& r = iter.Get();
  3690. if (accumulated.IsEmpty()) {
  3691. accumulated = r;
  3692. continue;
  3693. }
  3694. if (accumulated.YMost() >= r.y - accumulationMargin) {
  3695. accumulated.UnionRect(accumulated, r);
  3696. } else {
  3697. aRects->AppendElement(accumulated);
  3698. accumulated = r;
  3699. }
  3700. }
  3701. // Finish the in-flight rectangle, if there is one.
  3702. if (!accumulated.IsEmpty()) {
  3703. aRects->AppendElement(accumulated);
  3704. }
  3705. }
  3706. void
  3707. nsDisplayBoxShadowOuter::Paint(nsDisplayListBuilder* aBuilder,
  3708. nsRenderingContext* aCtx) {
  3709. nsPoint offset = ToReferenceFrame();
  3710. nsRect borderRect = mFrame->VisualBorderRectRelativeToSelf() + offset;
  3711. nsPresContext* presContext = mFrame->PresContext();
  3712. AutoTArray<nsRect,10> rects;
  3713. ComputeDisjointRectangles(mVisibleRegion, &rects);
  3714. PROFILER_LABEL("nsDisplayBoxShadowOuter", "Paint",
  3715. js::ProfileEntry::Category::GRAPHICS);
  3716. for (uint32_t i = 0; i < rects.Length(); ++i) {
  3717. nsCSSRendering::PaintBoxShadowOuter(presContext, *aCtx, mFrame,
  3718. borderRect, rects[i], mOpacity);
  3719. }
  3720. }
  3721. nsRect
  3722. nsDisplayBoxShadowOuter::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) {
  3723. *aSnap = false;
  3724. return mBounds;
  3725. }
  3726. nsRect
  3727. nsDisplayBoxShadowOuter::GetBoundsInternal() {
  3728. return nsLayoutUtils::GetBoxShadowRectForFrame(mFrame, mFrame->GetSize()) +
  3729. ToReferenceFrame();
  3730. }
  3731. bool
  3732. nsDisplayBoxShadowOuter::IsInvisibleInRect(const nsRect& aRect)
  3733. {
  3734. nsPoint origin = ToReferenceFrame();
  3735. nsRect frameRect(origin, mFrame->GetSize());
  3736. if (!frameRect.Contains(aRect))
  3737. return false;
  3738. // the visible region is entirely inside the border-rect, and box shadows
  3739. // never render within the border-rect (unless there's a border radius).
  3740. nscoord twipsRadii[8];
  3741. bool hasBorderRadii = mFrame->GetBorderRadii(twipsRadii);
  3742. if (!hasBorderRadii)
  3743. return true;
  3744. return RoundedRectContainsRect(frameRect, twipsRadii, aRect);
  3745. }
  3746. bool
  3747. nsDisplayBoxShadowOuter::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  3748. nsRegion* aVisibleRegion) {
  3749. if (!nsDisplayItem::ComputeVisibility(aBuilder, aVisibleRegion)) {
  3750. return false;
  3751. }
  3752. // Store the actual visible region
  3753. mVisibleRegion.And(*aVisibleRegion, mVisibleRect);
  3754. return true;
  3755. }
  3756. void
  3757. nsDisplayBoxShadowOuter::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  3758. const nsDisplayItemGeometry* aGeometry,
  3759. nsRegion* aInvalidRegion)
  3760. {
  3761. const nsDisplayBoxShadowOuterGeometry* geometry =
  3762. static_cast<const nsDisplayBoxShadowOuterGeometry*>(aGeometry);
  3763. bool snap;
  3764. if (!geometry->mBounds.IsEqualInterior(GetBounds(aBuilder, &snap)) ||
  3765. !geometry->mBorderRect.IsEqualInterior(GetBorderRect()) ||
  3766. mOpacity != geometry->mOpacity) {
  3767. nsRegion oldShadow, newShadow;
  3768. nscoord dontCare[8];
  3769. bool hasBorderRadius = mFrame->GetBorderRadii(dontCare);
  3770. if (hasBorderRadius) {
  3771. // If we have rounded corners then we need to invalidate the frame area
  3772. // too since we paint into it.
  3773. oldShadow = geometry->mBounds;
  3774. newShadow = GetBounds(aBuilder, &snap);
  3775. } else {
  3776. oldShadow.Sub(geometry->mBounds, geometry->mBorderRect);
  3777. newShadow.Sub(GetBounds(aBuilder, &snap), GetBorderRect());
  3778. }
  3779. aInvalidRegion->Or(oldShadow, newShadow);
  3780. }
  3781. }
  3782. void
  3783. nsDisplayBoxShadowInner::Paint(nsDisplayListBuilder* aBuilder,
  3784. nsRenderingContext* aCtx) {
  3785. nsPoint offset = ToReferenceFrame();
  3786. nsRect borderRect = nsRect(offset, mFrame->GetSize());
  3787. nsPresContext* presContext = mFrame->PresContext();
  3788. AutoTArray<nsRect,10> rects;
  3789. ComputeDisjointRectangles(mVisibleRegion, &rects);
  3790. PROFILER_LABEL("nsDisplayBoxShadowInner", "Paint",
  3791. js::ProfileEntry::Category::GRAPHICS);
  3792. DrawTarget* drawTarget = aCtx->GetDrawTarget();
  3793. gfxContext* gfx = aCtx->ThebesContext();
  3794. int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  3795. for (uint32_t i = 0; i < rects.Length(); ++i) {
  3796. gfx->Save();
  3797. gfx->Clip(NSRectToSnappedRect(rects[i], appUnitsPerDevPixel, *drawTarget));
  3798. nsCSSRendering::PaintBoxShadowInner(presContext, *aCtx, mFrame, borderRect);
  3799. gfx->Restore();
  3800. }
  3801. }
  3802. bool
  3803. nsDisplayBoxShadowInner::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  3804. nsRegion* aVisibleRegion) {
  3805. if (!nsDisplayItem::ComputeVisibility(aBuilder, aVisibleRegion)) {
  3806. return false;
  3807. }
  3808. // Store the actual visible region
  3809. mVisibleRegion.And(*aVisibleRegion, mVisibleRect);
  3810. return true;
  3811. }
  3812. nsDisplayWrapList::nsDisplayWrapList(nsDisplayListBuilder* aBuilder,
  3813. nsIFrame* aFrame, nsDisplayList* aList)
  3814. : nsDisplayWrapList(aBuilder, aFrame, aList,
  3815. aBuilder->ClipState().GetCurrentInnermostScrollClip())
  3816. {}
  3817. nsDisplayWrapList::nsDisplayWrapList(nsDisplayListBuilder* aBuilder,
  3818. nsIFrame* aFrame, nsDisplayList* aList,
  3819. const DisplayItemScrollClip* aScrollClip)
  3820. : nsDisplayItem(aBuilder, aFrame, aScrollClip)
  3821. , mOverrideZIndex(0)
  3822. , mHasZIndexOverride(false)
  3823. {
  3824. MOZ_COUNT_CTOR(nsDisplayWrapList);
  3825. mBaseVisibleRect = mVisibleRect;
  3826. mList.AppendToTop(aList);
  3827. UpdateBounds(aBuilder);
  3828. if (!aFrame || !aFrame->IsTransformed()) {
  3829. return;
  3830. }
  3831. // If we're a transformed frame, then we need to find out if we're inside
  3832. // the nsDisplayTransform or outside of it. Frames inside the transform
  3833. // need mReferenceFrame == mFrame, outside needs the next ancestor
  3834. // reference frame.
  3835. // If we're inside the transform, then the nsDisplayItem constructor
  3836. // will have done the right thing.
  3837. // If we're outside the transform, then we should have only one child
  3838. // (since nsDisplayTransform wraps all actual content), and that child
  3839. // will have the correct reference frame set (since nsDisplayTransform
  3840. // handles this explictly).
  3841. nsDisplayItem *i = mList.GetBottom();
  3842. if (i && (!i->GetAbove() || i->GetType() == TYPE_TRANSFORM) &&
  3843. i->Frame() == mFrame) {
  3844. mReferenceFrame = i->ReferenceFrame();
  3845. mToReferenceFrame = i->ToReferenceFrame();
  3846. }
  3847. mVisibleRect = aBuilder->GetDirtyRect() +
  3848. aBuilder->GetCurrentFrameOffsetToReferenceFrame();
  3849. }
  3850. nsDisplayWrapList::nsDisplayWrapList(nsDisplayListBuilder* aBuilder,
  3851. nsIFrame* aFrame, nsDisplayItem* aItem)
  3852. : nsDisplayItem(aBuilder, aFrame)
  3853. , mOverrideZIndex(0)
  3854. , mHasZIndexOverride(false)
  3855. {
  3856. MOZ_COUNT_CTOR(nsDisplayWrapList);
  3857. mBaseVisibleRect = mVisibleRect;
  3858. mList.AppendToTop(aItem);
  3859. UpdateBounds(aBuilder);
  3860. if (!aFrame || !aFrame->IsTransformed()) {
  3861. return;
  3862. }
  3863. // See the previous nsDisplayWrapList constructor
  3864. if (aItem->Frame() == aFrame) {
  3865. mReferenceFrame = aItem->ReferenceFrame();
  3866. mToReferenceFrame = aItem->ToReferenceFrame();
  3867. }
  3868. mVisibleRect = aBuilder->GetDirtyRect() +
  3869. aBuilder->GetCurrentFrameOffsetToReferenceFrame();
  3870. }
  3871. nsDisplayWrapList::~nsDisplayWrapList() {
  3872. mList.DeleteAll();
  3873. MOZ_COUNT_DTOR(nsDisplayWrapList);
  3874. }
  3875. void
  3876. nsDisplayWrapList::HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
  3877. HitTestState* aState, nsTArray<nsIFrame*> *aOutFrames) {
  3878. mList.HitTest(aBuilder, aRect, aState, aOutFrames);
  3879. }
  3880. nsRect
  3881. nsDisplayWrapList::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) {
  3882. *aSnap = false;
  3883. return mBounds;
  3884. }
  3885. bool
  3886. nsDisplayWrapList::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  3887. nsRegion* aVisibleRegion) {
  3888. // Convert the passed in visible region to our appunits.
  3889. nsRegion visibleRegion;
  3890. // mVisibleRect has been clipped to GetClippedBounds
  3891. visibleRegion.And(*aVisibleRegion, mVisibleRect);
  3892. nsRegion originalVisibleRegion = visibleRegion;
  3893. bool retval =
  3894. mList.ComputeVisibilityForSublist(aBuilder, &visibleRegion, mVisibleRect);
  3895. nsRegion removed;
  3896. // removed = originalVisibleRegion - visibleRegion
  3897. removed.Sub(originalVisibleRegion, visibleRegion);
  3898. // aVisibleRegion = aVisibleRegion - removed (modulo any simplifications
  3899. // SubtractFromVisibleRegion does)
  3900. aBuilder->SubtractFromVisibleRegion(aVisibleRegion, removed);
  3901. return retval;
  3902. }
  3903. nsRegion
  3904. nsDisplayWrapList::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
  3905. bool* aSnap) {
  3906. *aSnap = false;
  3907. nsRegion result;
  3908. if (mList.IsOpaque()) {
  3909. // Everything within GetBounds that's visible is opaque.
  3910. result = GetBounds(aBuilder, aSnap);
  3911. }
  3912. return result;
  3913. }
  3914. Maybe<nscolor>
  3915. nsDisplayWrapList::IsUniform(nsDisplayListBuilder* aBuilder) {
  3916. // We could try to do something but let's conservatively just return Nothing.
  3917. return Nothing();
  3918. }
  3919. void nsDisplayWrapList::Paint(nsDisplayListBuilder* aBuilder,
  3920. nsRenderingContext* aCtx) {
  3921. NS_ERROR("nsDisplayWrapList should have been flattened away for painting");
  3922. }
  3923. /**
  3924. * Returns true if all descendant display items can be placed in the same
  3925. * PaintedLayer --- GetLayerState returns LAYER_INACTIVE or LAYER_NONE,
  3926. * and they all have the expected animated geometry root.
  3927. */
  3928. static LayerState
  3929. RequiredLayerStateForChildren(nsDisplayListBuilder* aBuilder,
  3930. LayerManager* aManager,
  3931. const ContainerLayerParameters& aParameters,
  3932. const nsDisplayList& aList,
  3933. AnimatedGeometryRoot* aExpectedAnimatedGeometryRootForChildren)
  3934. {
  3935. LayerState result = LAYER_INACTIVE;
  3936. for (nsDisplayItem* i = aList.GetBottom(); i; i = i->GetAbove()) {
  3937. if (result == LAYER_INACTIVE &&
  3938. i->GetAnimatedGeometryRoot() != aExpectedAnimatedGeometryRootForChildren) {
  3939. result = LAYER_ACTIVE;
  3940. }
  3941. LayerState state = i->GetLayerState(aBuilder, aManager, aParameters);
  3942. if (state == LAYER_ACTIVE && i->GetType() == nsDisplayItem::TYPE_BLEND_MODE) {
  3943. // nsDisplayBlendMode always returns LAYER_ACTIVE to ensure that the
  3944. // blending operation happens in the intermediate surface of its parent
  3945. // display item (usually an nsDisplayBlendContainer). But this does not
  3946. // mean that it needs all its ancestor display items to become active.
  3947. // So we ignore its layer state and look at its children instead.
  3948. state = RequiredLayerStateForChildren(aBuilder, aManager, aParameters,
  3949. *i->GetSameCoordinateSystemChildren(), i->GetAnimatedGeometryRoot());
  3950. }
  3951. if ((state == LAYER_ACTIVE || state == LAYER_ACTIVE_FORCE) &&
  3952. state > result) {
  3953. result = state;
  3954. }
  3955. if (state == LAYER_ACTIVE_EMPTY && state > result) {
  3956. result = LAYER_ACTIVE_FORCE;
  3957. }
  3958. if (state == LAYER_NONE) {
  3959. nsDisplayList* list = i->GetSameCoordinateSystemChildren();
  3960. if (list) {
  3961. LayerState childState =
  3962. RequiredLayerStateForChildren(aBuilder, aManager, aParameters, *list,
  3963. aExpectedAnimatedGeometryRootForChildren);
  3964. if (childState > result) {
  3965. result = childState;
  3966. }
  3967. }
  3968. }
  3969. }
  3970. return result;
  3971. }
  3972. nsRect nsDisplayWrapList::GetComponentAlphaBounds(nsDisplayListBuilder* aBuilder)
  3973. {
  3974. nsRect bounds;
  3975. for (nsDisplayItem* i = mList.GetBottom(); i; i = i->GetAbove()) {
  3976. bounds.UnionRect(bounds, i->GetComponentAlphaBounds(aBuilder));
  3977. }
  3978. return bounds;
  3979. }
  3980. void
  3981. nsDisplayWrapList::SetVisibleRect(const nsRect& aRect)
  3982. {
  3983. mVisibleRect = aRect;
  3984. }
  3985. void
  3986. nsDisplayWrapList::SetReferenceFrame(const nsIFrame* aFrame)
  3987. {
  3988. mReferenceFrame = aFrame;
  3989. mToReferenceFrame = mFrame->GetOffsetToCrossDoc(mReferenceFrame);
  3990. }
  3991. static nsresult
  3992. WrapDisplayList(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
  3993. nsDisplayList* aList, nsDisplayWrapper* aWrapper) {
  3994. if (!aList->GetTop())
  3995. return NS_OK;
  3996. nsDisplayItem* item = aWrapper->WrapList(aBuilder, aFrame, aList);
  3997. if (!item)
  3998. return NS_ERROR_OUT_OF_MEMORY;
  3999. // aList was emptied
  4000. aList->AppendToTop(item);
  4001. return NS_OK;
  4002. }
  4003. static nsresult
  4004. WrapEachDisplayItem(nsDisplayListBuilder* aBuilder,
  4005. nsDisplayList* aList, nsDisplayWrapper* aWrapper) {
  4006. nsDisplayList newList;
  4007. nsDisplayItem* item;
  4008. while ((item = aList->RemoveBottom())) {
  4009. item = aWrapper->WrapItem(aBuilder, item);
  4010. if (!item)
  4011. return NS_ERROR_OUT_OF_MEMORY;
  4012. newList.AppendToTop(item);
  4013. }
  4014. // aList was emptied
  4015. aList->AppendToTop(&newList);
  4016. return NS_OK;
  4017. }
  4018. nsresult nsDisplayWrapper::WrapLists(nsDisplayListBuilder* aBuilder,
  4019. nsIFrame* aFrame, const nsDisplayListSet& aIn, const nsDisplayListSet& aOut)
  4020. {
  4021. nsresult rv = WrapListsInPlace(aBuilder, aFrame, aIn);
  4022. NS_ENSURE_SUCCESS(rv, rv);
  4023. if (&aOut == &aIn)
  4024. return NS_OK;
  4025. aOut.BorderBackground()->AppendToTop(aIn.BorderBackground());
  4026. aOut.BlockBorderBackgrounds()->AppendToTop(aIn.BlockBorderBackgrounds());
  4027. aOut.Floats()->AppendToTop(aIn.Floats());
  4028. aOut.Content()->AppendToTop(aIn.Content());
  4029. aOut.PositionedDescendants()->AppendToTop(aIn.PositionedDescendants());
  4030. aOut.Outlines()->AppendToTop(aIn.Outlines());
  4031. return NS_OK;
  4032. }
  4033. nsresult nsDisplayWrapper::WrapListsInPlace(nsDisplayListBuilder* aBuilder,
  4034. nsIFrame* aFrame, const nsDisplayListSet& aLists)
  4035. {
  4036. nsresult rv;
  4037. if (WrapBorderBackground()) {
  4038. // Our border-backgrounds are in-flow
  4039. rv = WrapDisplayList(aBuilder, aFrame, aLists.BorderBackground(), this);
  4040. NS_ENSURE_SUCCESS(rv, rv);
  4041. }
  4042. // Our block border-backgrounds are in-flow
  4043. rv = WrapDisplayList(aBuilder, aFrame, aLists.BlockBorderBackgrounds(), this);
  4044. NS_ENSURE_SUCCESS(rv, rv);
  4045. // The floats are not in flow
  4046. rv = WrapEachDisplayItem(aBuilder, aLists.Floats(), this);
  4047. NS_ENSURE_SUCCESS(rv, rv);
  4048. // Our child content is in flow
  4049. rv = WrapDisplayList(aBuilder, aFrame, aLists.Content(), this);
  4050. NS_ENSURE_SUCCESS(rv, rv);
  4051. // The positioned descendants may not be in-flow
  4052. rv = WrapEachDisplayItem(aBuilder, aLists.PositionedDescendants(), this);
  4053. NS_ENSURE_SUCCESS(rv, rv);
  4054. // The outlines may not be in-flow
  4055. return WrapEachDisplayItem(aBuilder, aLists.Outlines(), this);
  4056. }
  4057. nsDisplayOpacity::nsDisplayOpacity(nsDisplayListBuilder* aBuilder,
  4058. nsIFrame* aFrame, nsDisplayList* aList,
  4059. const DisplayItemScrollClip* aScrollClip,
  4060. bool aForEventsAndPluginsOnly)
  4061. : nsDisplayWrapList(aBuilder, aFrame, aList, aScrollClip)
  4062. , mOpacity(aFrame->StyleEffects()->mOpacity)
  4063. , mForEventsAndPluginsOnly(aForEventsAndPluginsOnly)
  4064. {
  4065. MOZ_COUNT_CTOR(nsDisplayOpacity);
  4066. }
  4067. #ifdef NS_BUILD_REFCNT_LOGGING
  4068. nsDisplayOpacity::~nsDisplayOpacity() {
  4069. MOZ_COUNT_DTOR(nsDisplayOpacity);
  4070. }
  4071. #endif
  4072. nsRegion nsDisplayOpacity::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
  4073. bool* aSnap) {
  4074. *aSnap = false;
  4075. // The only time where mOpacity == 1.0 should be when we have will-change.
  4076. // We could report this as opaque then but when the will-change value starts
  4077. // animating the element would become non opaque and could cause repaints.
  4078. return nsRegion();
  4079. }
  4080. // nsDisplayOpacity uses layers for rendering
  4081. already_AddRefed<Layer>
  4082. nsDisplayOpacity::BuildLayer(nsDisplayListBuilder* aBuilder,
  4083. LayerManager* aManager,
  4084. const ContainerLayerParameters& aContainerParameters) {
  4085. ContainerLayerParameters params = aContainerParameters;
  4086. params.mForEventsAndPluginsOnly = mForEventsAndPluginsOnly;
  4087. RefPtr<Layer> container = aManager->GetLayerBuilder()->
  4088. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, &mList,
  4089. params, nullptr,
  4090. FrameLayerBuilder::CONTAINER_ALLOW_PULL_BACKGROUND_COLOR);
  4091. if (!container)
  4092. return nullptr;
  4093. container->SetOpacity(mOpacity);
  4094. nsDisplayListBuilder::AddAnimationsAndTransitionsToLayer(container, aBuilder,
  4095. this, mFrame,
  4096. eCSSProperty_opacity);
  4097. return container.forget();
  4098. }
  4099. /**
  4100. * This doesn't take into account layer scaling --- the layer may be
  4101. * rendered at a higher (or lower) resolution, affecting the retained layer
  4102. * size --- but this should be good enough.
  4103. */
  4104. static bool
  4105. IsItemTooSmallForActiveLayer(nsIFrame* aFrame)
  4106. {
  4107. nsIntRect visibleDevPixels = aFrame->GetVisualOverflowRectRelativeToSelf().ToOutsidePixels(
  4108. aFrame->PresContext()->AppUnitsPerDevPixel());
  4109. static const int MIN_ACTIVE_LAYER_SIZE_DEV_PIXELS = 16;
  4110. return visibleDevPixels.Size() <
  4111. nsIntSize(MIN_ACTIVE_LAYER_SIZE_DEV_PIXELS, MIN_ACTIVE_LAYER_SIZE_DEV_PIXELS);
  4112. }
  4113. static void
  4114. SetAnimationPerformanceWarningForTooSmallItem(nsIFrame* aFrame,
  4115. nsCSSPropertyID aProperty)
  4116. {
  4117. // We use ToNearestPixels() here since ToOutsidePixels causes some sort of
  4118. // errors. See https://bugzilla.mozilla.org/show_bug.cgi?id=1258904#c19
  4119. nsIntRect visibleDevPixels = aFrame->GetVisualOverflowRectRelativeToSelf().ToNearestPixels(
  4120. aFrame->PresContext()->AppUnitsPerDevPixel());
  4121. // Set performance warning only if the visible dev pixels is not empty
  4122. // because dev pixels is empty if the frame has 'preserve-3d' style.
  4123. if (visibleDevPixels.IsEmpty()) {
  4124. return;
  4125. }
  4126. EffectCompositor::SetPerformanceWarning(aFrame, aProperty,
  4127. AnimationPerformanceWarning(
  4128. AnimationPerformanceWarning::Type::ContentTooSmall,
  4129. { visibleDevPixels.Width(), visibleDevPixels.Height() }));
  4130. }
  4131. /* static */ bool
  4132. nsDisplayOpacity::NeedsActiveLayer(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
  4133. {
  4134. if (ActiveLayerTracker::IsStyleAnimated(aBuilder, aFrame,
  4135. eCSSProperty_opacity) ||
  4136. EffectCompositor::HasAnimationsForCompositor(aFrame,
  4137. eCSSProperty_opacity)) {
  4138. if (!IsItemTooSmallForActiveLayer(aFrame)) {
  4139. return true;
  4140. }
  4141. SetAnimationPerformanceWarningForTooSmallItem(aFrame, eCSSProperty_opacity);
  4142. }
  4143. return false;
  4144. }
  4145. void
  4146. nsDisplayOpacity::ApplyOpacity(nsDisplayListBuilder* aBuilder,
  4147. float aOpacity,
  4148. const DisplayItemClip* aClip)
  4149. {
  4150. NS_ASSERTION(CanApplyOpacity(), "ApplyOpacity should be allowed");
  4151. mOpacity = mOpacity * aOpacity;
  4152. if (aClip) {
  4153. IntersectClip(aBuilder, *aClip);
  4154. }
  4155. }
  4156. bool
  4157. nsDisplayOpacity::CanApplyOpacity() const
  4158. {
  4159. return true;
  4160. }
  4161. bool
  4162. nsDisplayOpacity::ShouldFlattenAway(nsDisplayListBuilder* aBuilder)
  4163. {
  4164. if (NeedsActiveLayer(aBuilder, mFrame) || mOpacity == 0.0) {
  4165. // If our opacity is zero then we'll discard all descendant display items
  4166. // except for layer event regions, so there's no point in doing this
  4167. // optimization (and if we do do it, then invalidations of those descendants
  4168. // might trigger repainting).
  4169. return false;
  4170. }
  4171. nsDisplayItem* child = mList.GetBottom();
  4172. // Only try folding our opacity down if we have at most three children
  4173. // that don't overlap and can all apply the opacity to themselves.
  4174. if (!child) {
  4175. return false;
  4176. }
  4177. struct {
  4178. nsDisplayItem* item;
  4179. nsRect bounds;
  4180. } children[3];
  4181. bool snap;
  4182. uint32_t numChildren = 0;
  4183. for (; numChildren < ArrayLength(children) && child; numChildren++, child = child->GetAbove()) {
  4184. if (child->GetType() == nsDisplayItem::TYPE_LAYER_EVENT_REGIONS) {
  4185. numChildren--;
  4186. continue;
  4187. }
  4188. if (!child->CanApplyOpacity()) {
  4189. return false;
  4190. }
  4191. children[numChildren].item = child;
  4192. children[numChildren].bounds = child->GetBounds(aBuilder, &snap);
  4193. }
  4194. if (child) {
  4195. // we have a fourth (or more) child
  4196. return false;
  4197. }
  4198. for (uint32_t i = 0; i < numChildren; i++) {
  4199. for (uint32_t j = i+1; j < numChildren; j++) {
  4200. if (children[i].bounds.Intersects(children[j].bounds)) {
  4201. return false;
  4202. }
  4203. }
  4204. }
  4205. for (uint32_t i = 0; i < numChildren; i++) {
  4206. children[i].item->ApplyOpacity(aBuilder, mOpacity, mClip);
  4207. }
  4208. return true;
  4209. }
  4210. nsDisplayItem::LayerState
  4211. nsDisplayOpacity::GetLayerState(nsDisplayListBuilder* aBuilder,
  4212. LayerManager* aManager,
  4213. const ContainerLayerParameters& aParameters) {
  4214. // If we only created this item so that we'd get correct nsDisplayEventRegions for child
  4215. // frames, then force us to inactive to avoid unnecessary layerization changes for content
  4216. // that won't ever be painted.
  4217. if (mForEventsAndPluginsOnly) {
  4218. MOZ_ASSERT(mOpacity == 0);
  4219. return LAYER_INACTIVE;
  4220. }
  4221. if (NeedsActiveLayer(aBuilder, mFrame)) {
  4222. // Returns LAYER_ACTIVE_FORCE to avoid flatterning the layer for async
  4223. // animations.
  4224. return LAYER_ACTIVE_FORCE;
  4225. }
  4226. return RequiredLayerStateForChildren(aBuilder, aManager, aParameters, mList, GetAnimatedGeometryRoot());
  4227. }
  4228. bool
  4229. nsDisplayOpacity::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  4230. nsRegion* aVisibleRegion) {
  4231. // Our children are translucent so we should not allow them to subtract
  4232. // area from aVisibleRegion. We do need to find out what is visible under
  4233. // our children in the temporary compositing buffer, because if our children
  4234. // paint our entire bounds opaquely then we don't need an alpha channel in
  4235. // the temporary compositing buffer.
  4236. nsRect bounds = GetClippedBounds(aBuilder);
  4237. nsRegion visibleUnderChildren;
  4238. visibleUnderChildren.And(*aVisibleRegion, bounds);
  4239. return
  4240. nsDisplayWrapList::ComputeVisibility(aBuilder, &visibleUnderChildren);
  4241. }
  4242. bool nsDisplayOpacity::TryMerge(nsDisplayItem* aItem) {
  4243. if (aItem->GetType() != TYPE_OPACITY)
  4244. return false;
  4245. // items for the same content element should be merged into a single
  4246. // compositing group
  4247. // aItem->GetUnderlyingFrame() returns non-null because it's nsDisplayOpacity
  4248. if (aItem->Frame()->GetContent() != mFrame->GetContent())
  4249. return false;
  4250. if (aItem->GetClip() != GetClip())
  4251. return false;
  4252. if (aItem->ScrollClip() != ScrollClip())
  4253. return false;
  4254. MergeFromTrackingMergedFrames(static_cast<nsDisplayOpacity*>(aItem));
  4255. return true;
  4256. }
  4257. void
  4258. nsDisplayOpacity::WriteDebugInfo(std::stringstream& aStream)
  4259. {
  4260. aStream << " (opacity " << mOpacity << ")";
  4261. }
  4262. nsDisplayBlendMode::nsDisplayBlendMode(nsDisplayListBuilder* aBuilder,
  4263. nsIFrame* aFrame, nsDisplayList* aList,
  4264. uint8_t aBlendMode,
  4265. const DisplayItemScrollClip* aScrollClip,
  4266. uint32_t aIndex)
  4267. : nsDisplayWrapList(aBuilder, aFrame, aList, aScrollClip)
  4268. , mBlendMode(aBlendMode)
  4269. , mIndex(aIndex)
  4270. {
  4271. MOZ_COUNT_CTOR(nsDisplayBlendMode);
  4272. }
  4273. #ifdef NS_BUILD_REFCNT_LOGGING
  4274. nsDisplayBlendMode::~nsDisplayBlendMode() {
  4275. MOZ_COUNT_DTOR(nsDisplayBlendMode);
  4276. }
  4277. #endif
  4278. nsRegion nsDisplayBlendMode::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
  4279. bool* aSnap) {
  4280. *aSnap = false;
  4281. // We are never considered opaque
  4282. return nsRegion();
  4283. }
  4284. LayerState
  4285. nsDisplayBlendMode::GetLayerState(nsDisplayListBuilder* aBuilder,
  4286. LayerManager* aManager,
  4287. const ContainerLayerParameters& aParameters)
  4288. {
  4289. return LAYER_ACTIVE;
  4290. }
  4291. // nsDisplayBlendMode uses layers for rendering
  4292. already_AddRefed<Layer>
  4293. nsDisplayBlendMode::BuildLayer(nsDisplayListBuilder* aBuilder,
  4294. LayerManager* aManager,
  4295. const ContainerLayerParameters& aContainerParameters) {
  4296. ContainerLayerParameters newContainerParameters = aContainerParameters;
  4297. newContainerParameters.mDisableSubpixelAntialiasingInDescendants = true;
  4298. RefPtr<Layer> container = aManager->GetLayerBuilder()->
  4299. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, &mList,
  4300. newContainerParameters, nullptr);
  4301. if (!container) {
  4302. return nullptr;
  4303. }
  4304. container->SetMixBlendMode(nsCSSRendering::GetGFXBlendMode(mBlendMode));
  4305. return container.forget();
  4306. }
  4307. bool nsDisplayBlendMode::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  4308. nsRegion* aVisibleRegion) {
  4309. // Our children are need their backdrop so we should not allow them to subtract
  4310. // area from aVisibleRegion. We do need to find out what is visible under
  4311. // our children in the temporary compositing buffer, because if our children
  4312. // paint our entire bounds opaquely then we don't need an alpha channel in
  4313. // the temporary compositing buffer.
  4314. nsRect bounds = GetClippedBounds(aBuilder);
  4315. nsRegion visibleUnderChildren;
  4316. visibleUnderChildren.And(*aVisibleRegion, bounds);
  4317. return nsDisplayWrapList::ComputeVisibility(aBuilder, &visibleUnderChildren);
  4318. }
  4319. bool nsDisplayBlendMode::TryMerge(nsDisplayItem* aItem) {
  4320. if (aItem->GetType() != TYPE_BLEND_MODE)
  4321. return false;
  4322. nsDisplayBlendMode* item = static_cast<nsDisplayBlendMode*>(aItem);
  4323. // items for the same content element should be merged into a single
  4324. // compositing group
  4325. if (item->Frame()->GetContent() != mFrame->GetContent())
  4326. return false;
  4327. if (item->mIndex != 0 || mIndex != 0)
  4328. return false; // don't merge background-blend-mode items
  4329. if (item->GetClip() != GetClip())
  4330. return false;
  4331. if (item->ScrollClip() != ScrollClip())
  4332. return false;
  4333. MergeFromTrackingMergedFrames(item);
  4334. return true;
  4335. }
  4336. /* static */ nsDisplayBlendContainer*
  4337. nsDisplayBlendContainer::CreateForMixBlendMode(nsDisplayListBuilder* aBuilder,
  4338. nsIFrame* aFrame, nsDisplayList* aList,
  4339. const DisplayItemScrollClip* aScrollClip)
  4340. {
  4341. return new (aBuilder) nsDisplayBlendContainer(aBuilder, aFrame, aList, aScrollClip, false);
  4342. }
  4343. /* static */ nsDisplayBlendContainer*
  4344. nsDisplayBlendContainer::CreateForBackgroundBlendMode(nsDisplayListBuilder* aBuilder,
  4345. nsIFrame* aFrame, nsDisplayList* aList,
  4346. const DisplayItemScrollClip* aScrollClip)
  4347. {
  4348. return new (aBuilder) nsDisplayBlendContainer(aBuilder, aFrame, aList, aScrollClip, true);
  4349. }
  4350. nsDisplayBlendContainer::nsDisplayBlendContainer(nsDisplayListBuilder* aBuilder,
  4351. nsIFrame* aFrame, nsDisplayList* aList,
  4352. const DisplayItemScrollClip* aScrollClip,
  4353. bool aIsForBackground)
  4354. : nsDisplayWrapList(aBuilder, aFrame, aList, aScrollClip)
  4355. , mIsForBackground(aIsForBackground)
  4356. {
  4357. MOZ_COUNT_CTOR(nsDisplayBlendContainer);
  4358. }
  4359. #ifdef NS_BUILD_REFCNT_LOGGING
  4360. nsDisplayBlendContainer::~nsDisplayBlendContainer() {
  4361. MOZ_COUNT_DTOR(nsDisplayBlendContainer);
  4362. }
  4363. #endif
  4364. // nsDisplayBlendContainer uses layers for rendering
  4365. already_AddRefed<Layer>
  4366. nsDisplayBlendContainer::BuildLayer(nsDisplayListBuilder* aBuilder,
  4367. LayerManager* aManager,
  4368. const ContainerLayerParameters& aContainerParameters) {
  4369. // turn off anti-aliasing in the parent stacking context because it changes
  4370. // how the group is initialized.
  4371. ContainerLayerParameters newContainerParameters = aContainerParameters;
  4372. newContainerParameters.mDisableSubpixelAntialiasingInDescendants = true;
  4373. RefPtr<Layer> container = aManager->GetLayerBuilder()->
  4374. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, &mList,
  4375. newContainerParameters, nullptr);
  4376. if (!container) {
  4377. return nullptr;
  4378. }
  4379. container->SetForceIsolatedGroup(true);
  4380. return container.forget();
  4381. }
  4382. LayerState
  4383. nsDisplayBlendContainer::GetLayerState(nsDisplayListBuilder* aBuilder,
  4384. LayerManager* aManager,
  4385. const ContainerLayerParameters& aParameters)
  4386. {
  4387. return RequiredLayerStateForChildren(aBuilder, aManager, aParameters, mList, GetAnimatedGeometryRoot());
  4388. }
  4389. bool nsDisplayBlendContainer::TryMerge(nsDisplayItem* aItem) {
  4390. if (aItem->GetType() != TYPE_BLEND_CONTAINER)
  4391. return false;
  4392. // items for the same content element should be merged into a single
  4393. // compositing group
  4394. // aItem->GetUnderlyingFrame() returns non-null because it's nsDisplayOpacity
  4395. if (aItem->Frame()->GetContent() != mFrame->GetContent())
  4396. return false;
  4397. if (aItem->GetClip() != GetClip())
  4398. return false;
  4399. if (aItem->ScrollClip() != ScrollClip())
  4400. return false;
  4401. MergeFromTrackingMergedFrames(static_cast<nsDisplayBlendContainer*>(aItem));
  4402. return true;
  4403. }
  4404. nsDisplayOwnLayer::nsDisplayOwnLayer(nsDisplayListBuilder* aBuilder,
  4405. nsIFrame* aFrame, nsDisplayList* aList,
  4406. uint32_t aFlags, ViewID aScrollTarget,
  4407. float aScrollbarThumbRatio,
  4408. bool aForceActive)
  4409. : nsDisplayWrapList(aBuilder, aFrame, aList)
  4410. , mFlags(aFlags)
  4411. , mScrollTarget(aScrollTarget)
  4412. , mScrollbarThumbRatio(aScrollbarThumbRatio)
  4413. , mForceActive(aForceActive)
  4414. {
  4415. MOZ_COUNT_CTOR(nsDisplayOwnLayer);
  4416. }
  4417. #ifdef NS_BUILD_REFCNT_LOGGING
  4418. nsDisplayOwnLayer::~nsDisplayOwnLayer() {
  4419. MOZ_COUNT_DTOR(nsDisplayOwnLayer);
  4420. }
  4421. #endif
  4422. LayerState
  4423. nsDisplayOwnLayer::GetLayerState(nsDisplayListBuilder* aBuilder,
  4424. LayerManager* aManager,
  4425. const ContainerLayerParameters& aParameters)
  4426. {
  4427. if (mForceActive) {
  4428. return mozilla::LAYER_ACTIVE_FORCE;
  4429. }
  4430. return RequiredLayerStateForChildren(aBuilder, aManager, aParameters, mList, mAnimatedGeometryRoot);
  4431. }
  4432. // nsDisplayOpacity uses layers for rendering
  4433. already_AddRefed<Layer>
  4434. nsDisplayOwnLayer::BuildLayer(nsDisplayListBuilder* aBuilder,
  4435. LayerManager* aManager,
  4436. const ContainerLayerParameters& aContainerParameters)
  4437. {
  4438. RefPtr<ContainerLayer> layer = aManager->GetLayerBuilder()->
  4439. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, &mList,
  4440. aContainerParameters, nullptr,
  4441. FrameLayerBuilder::CONTAINER_ALLOW_PULL_BACKGROUND_COLOR);
  4442. if (mFlags & VERTICAL_SCROLLBAR) {
  4443. layer->SetScrollbarData(mScrollTarget, Layer::ScrollDirection::VERTICAL, mScrollbarThumbRatio);
  4444. }
  4445. if (mFlags & HORIZONTAL_SCROLLBAR) {
  4446. layer->SetScrollbarData(mScrollTarget, Layer::ScrollDirection::HORIZONTAL, mScrollbarThumbRatio);
  4447. }
  4448. if (mFlags & SCROLLBAR_CONTAINER) {
  4449. layer->SetIsScrollbarContainer();
  4450. }
  4451. if (mFlags & GENERATE_SUBDOC_INVALIDATIONS) {
  4452. mFrame->PresContext()->SetNotifySubDocInvalidationData(layer);
  4453. }
  4454. return layer.forget();
  4455. }
  4456. nsDisplaySubDocument::nsDisplaySubDocument(nsDisplayListBuilder* aBuilder,
  4457. nsIFrame* aFrame, nsDisplayList* aList,
  4458. uint32_t aFlags)
  4459. : nsDisplayOwnLayer(aBuilder, aFrame, aList, aFlags)
  4460. , mScrollParentId(aBuilder->GetCurrentScrollParentId())
  4461. {
  4462. MOZ_COUNT_CTOR(nsDisplaySubDocument);
  4463. mForceDispatchToContentRegion =
  4464. aBuilder->IsBuildingLayerEventRegions() &&
  4465. nsLayoutUtils::HasDocumentLevelListenersForApzAwareEvents(aFrame->PresContext()->PresShell());
  4466. }
  4467. #ifdef NS_BUILD_REFCNT_LOGGING
  4468. nsDisplaySubDocument::~nsDisplaySubDocument() {
  4469. MOZ_COUNT_DTOR(nsDisplaySubDocument);
  4470. }
  4471. #endif
  4472. already_AddRefed<Layer>
  4473. nsDisplaySubDocument::BuildLayer(nsDisplayListBuilder* aBuilder,
  4474. LayerManager* aManager,
  4475. const ContainerLayerParameters& aContainerParameters) {
  4476. nsPresContext* presContext = mFrame->PresContext();
  4477. nsIFrame* rootScrollFrame = presContext->PresShell()->GetRootScrollFrame();
  4478. ContainerLayerParameters params = aContainerParameters;
  4479. if ((mFlags & GENERATE_SCROLLABLE_LAYER) &&
  4480. rootScrollFrame->GetContent() &&
  4481. nsLayoutUtils::HasCriticalDisplayPort(rootScrollFrame->GetContent())) {
  4482. params.mInLowPrecisionDisplayPort = true;
  4483. }
  4484. RefPtr<Layer> layer = nsDisplayOwnLayer::BuildLayer(aBuilder, aManager, params);
  4485. layer->AsContainerLayer()->SetEventRegionsOverride(mForceDispatchToContentRegion
  4486. ? EventRegionsOverride::ForceDispatchToContent
  4487. : EventRegionsOverride::NoOverride);
  4488. return layer.forget();
  4489. }
  4490. UniquePtr<ScrollMetadata>
  4491. nsDisplaySubDocument::ComputeScrollMetadata(Layer* aLayer,
  4492. const ContainerLayerParameters& aContainerParameters)
  4493. {
  4494. if (!(mFlags & GENERATE_SCROLLABLE_LAYER)) {
  4495. return UniquePtr<ScrollMetadata>(nullptr);
  4496. }
  4497. nsPresContext* presContext = mFrame->PresContext();
  4498. nsIFrame* rootScrollFrame = presContext->PresShell()->GetRootScrollFrame();
  4499. bool isRootContentDocument = presContext->IsRootContentDocument();
  4500. nsIPresShell* presShell = presContext->PresShell();
  4501. ContainerLayerParameters params(
  4502. aContainerParameters.mXScale * presShell->GetResolution(),
  4503. aContainerParameters.mYScale * presShell->GetResolution(),
  4504. nsIntPoint(), aContainerParameters);
  4505. if ((mFlags & GENERATE_SCROLLABLE_LAYER) &&
  4506. rootScrollFrame->GetContent() &&
  4507. nsLayoutUtils::HasCriticalDisplayPort(rootScrollFrame->GetContent())) {
  4508. params.mInLowPrecisionDisplayPort = true;
  4509. }
  4510. nsRect viewport = mFrame->GetRect() -
  4511. mFrame->GetPosition() +
  4512. mFrame->GetOffsetToCrossDoc(ReferenceFrame());
  4513. return MakeUnique<ScrollMetadata>(
  4514. nsLayoutUtils::ComputeScrollMetadata(
  4515. mFrame, rootScrollFrame, rootScrollFrame->GetContent(), ReferenceFrame(),
  4516. aLayer, mScrollParentId, viewport, Nothing(),
  4517. isRootContentDocument, params));
  4518. }
  4519. static bool
  4520. UseDisplayPortForViewport(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
  4521. {
  4522. return aBuilder->IsPaintingToWindow() &&
  4523. nsLayoutUtils::ViewportHasDisplayPort(aFrame->PresContext());
  4524. }
  4525. nsRect
  4526. nsDisplaySubDocument::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
  4527. {
  4528. bool usingDisplayPort = UseDisplayPortForViewport(aBuilder, mFrame);
  4529. if ((mFlags & GENERATE_SCROLLABLE_LAYER) && usingDisplayPort) {
  4530. *aSnap = false;
  4531. return mFrame->GetRect() + aBuilder->ToReferenceFrame(mFrame);
  4532. }
  4533. return nsDisplayOwnLayer::GetBounds(aBuilder, aSnap);
  4534. }
  4535. bool
  4536. nsDisplaySubDocument::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  4537. nsRegion* aVisibleRegion)
  4538. {
  4539. bool usingDisplayPort = UseDisplayPortForViewport(aBuilder, mFrame);
  4540. if (!(mFlags & GENERATE_SCROLLABLE_LAYER) || !usingDisplayPort) {
  4541. return nsDisplayWrapList::ComputeVisibility(aBuilder, aVisibleRegion);
  4542. }
  4543. nsRect displayport;
  4544. nsIFrame* rootScrollFrame = mFrame->PresContext()->PresShell()->GetRootScrollFrame();
  4545. MOZ_ASSERT(rootScrollFrame);
  4546. Unused << nsLayoutUtils::GetDisplayPort(rootScrollFrame->GetContent(), &displayport,
  4547. RelativeTo::ScrollFrame);
  4548. nsRegion childVisibleRegion;
  4549. // The visible region for the children may be much bigger than the hole we
  4550. // are viewing the children from, so that the compositor process has enough
  4551. // content to asynchronously pan while content is being refreshed.
  4552. childVisibleRegion = displayport + mFrame->GetOffsetToCrossDoc(ReferenceFrame());
  4553. nsRect boundedRect =
  4554. childVisibleRegion.GetBounds().Intersect(mList.GetBounds(aBuilder));
  4555. bool visible = mList.ComputeVisibilityForSublist(
  4556. aBuilder, &childVisibleRegion, boundedRect);
  4557. // If APZ is enabled then don't allow this computation to influence
  4558. // aVisibleRegion, on the assumption that the layer can be asynchronously
  4559. // scrolled so we'll definitely need all the content under it.
  4560. if (!nsLayoutUtils::UsesAsyncScrolling(mFrame)) {
  4561. bool snap;
  4562. nsRect bounds = GetBounds(aBuilder, &snap);
  4563. nsRegion removed;
  4564. removed.Sub(bounds, childVisibleRegion);
  4565. aBuilder->SubtractFromVisibleRegion(aVisibleRegion, removed);
  4566. }
  4567. return visible;
  4568. }
  4569. bool
  4570. nsDisplaySubDocument::ShouldBuildLayerEvenIfInvisible(nsDisplayListBuilder* aBuilder)
  4571. {
  4572. bool usingDisplayPort = UseDisplayPortForViewport(aBuilder, mFrame);
  4573. if ((mFlags & GENERATE_SCROLLABLE_LAYER) && usingDisplayPort) {
  4574. return true;
  4575. }
  4576. return nsDisplayOwnLayer::ShouldBuildLayerEvenIfInvisible(aBuilder);
  4577. }
  4578. nsRegion
  4579. nsDisplaySubDocument::GetOpaqueRegion(nsDisplayListBuilder* aBuilder, bool* aSnap)
  4580. {
  4581. bool usingDisplayPort = UseDisplayPortForViewport(aBuilder, mFrame);
  4582. if ((mFlags & GENERATE_SCROLLABLE_LAYER) && usingDisplayPort) {
  4583. *aSnap = false;
  4584. return nsRegion();
  4585. }
  4586. return nsDisplayOwnLayer::GetOpaqueRegion(aBuilder, aSnap);
  4587. }
  4588. nsDisplayResolution::nsDisplayResolution(nsDisplayListBuilder* aBuilder,
  4589. nsIFrame* aFrame, nsDisplayList* aList,
  4590. uint32_t aFlags)
  4591. : nsDisplaySubDocument(aBuilder, aFrame, aList, aFlags) {
  4592. MOZ_COUNT_CTOR(nsDisplayResolution);
  4593. }
  4594. #ifdef NS_BUILD_REFCNT_LOGGING
  4595. nsDisplayResolution::~nsDisplayResolution() {
  4596. MOZ_COUNT_DTOR(nsDisplayResolution);
  4597. }
  4598. #endif
  4599. void
  4600. nsDisplayResolution::HitTest(nsDisplayListBuilder* aBuilder,
  4601. const nsRect& aRect,
  4602. HitTestState* aState,
  4603. nsTArray<nsIFrame*> *aOutFrames)
  4604. {
  4605. nsIPresShell* presShell = mFrame->PresContext()->PresShell();
  4606. nsRect rect = aRect.RemoveResolution(presShell->ScaleToResolution() ? presShell->GetResolution () : 1.0f);
  4607. mList.HitTest(aBuilder, rect, aState, aOutFrames);
  4608. }
  4609. already_AddRefed<Layer>
  4610. nsDisplayResolution::BuildLayer(nsDisplayListBuilder* aBuilder,
  4611. LayerManager* aManager,
  4612. const ContainerLayerParameters& aContainerParameters) {
  4613. nsIPresShell* presShell = mFrame->PresContext()->PresShell();
  4614. ContainerLayerParameters containerParameters(
  4615. presShell->GetResolution(), presShell->GetResolution(), nsIntPoint(),
  4616. aContainerParameters);
  4617. RefPtr<Layer> layer = nsDisplaySubDocument::BuildLayer(
  4618. aBuilder, aManager, containerParameters);
  4619. layer->SetPostScale(1.0f / presShell->GetResolution(),
  4620. 1.0f / presShell->GetResolution());
  4621. layer->AsContainerLayer()->SetScaleToResolution(
  4622. presShell->ScaleToResolution(), presShell->GetResolution());
  4623. return layer.forget();
  4624. }
  4625. nsDisplayFixedPosition::nsDisplayFixedPosition(nsDisplayListBuilder* aBuilder,
  4626. nsIFrame* aFrame,
  4627. nsDisplayList* aList)
  4628. : nsDisplayOwnLayer(aBuilder, aFrame, aList)
  4629. , mIndex(0)
  4630. , mIsFixedBackground(false)
  4631. {
  4632. MOZ_COUNT_CTOR(nsDisplayFixedPosition);
  4633. Init(aBuilder);
  4634. }
  4635. nsDisplayFixedPosition::nsDisplayFixedPosition(nsDisplayListBuilder* aBuilder,
  4636. nsIFrame* aFrame,
  4637. nsDisplayList* aList,
  4638. uint32_t aIndex)
  4639. : nsDisplayOwnLayer(aBuilder, aFrame, aList)
  4640. , mIndex(aIndex)
  4641. , mIsFixedBackground(true)
  4642. {
  4643. MOZ_COUNT_CTOR(nsDisplayFixedPosition);
  4644. Init(aBuilder);
  4645. }
  4646. void
  4647. nsDisplayFixedPosition::Init(nsDisplayListBuilder* aBuilder)
  4648. {
  4649. mAnimatedGeometryRootForScrollMetadata = mAnimatedGeometryRoot;
  4650. if (ShouldFixToViewport(aBuilder)) {
  4651. mAnimatedGeometryRoot = aBuilder->FindAnimatedGeometryRootFor(this);
  4652. }
  4653. }
  4654. /* static */ nsDisplayFixedPosition*
  4655. nsDisplayFixedPosition::CreateForFixedBackground(nsDisplayListBuilder* aBuilder,
  4656. nsIFrame* aFrame,
  4657. nsDisplayBackgroundImage* aImage,
  4658. uint32_t aIndex)
  4659. {
  4660. // Clear clipping on the child item, since we will apply it to the
  4661. // fixed position item as well.
  4662. aImage->SetClip(aBuilder, DisplayItemClip());
  4663. aImage->SetScrollClip(nullptr);
  4664. nsDisplayList temp;
  4665. temp.AppendToTop(aImage);
  4666. return new (aBuilder) nsDisplayFixedPosition(aBuilder, aFrame, &temp, aIndex + 1);
  4667. }
  4668. #ifdef NS_BUILD_REFCNT_LOGGING
  4669. nsDisplayFixedPosition::~nsDisplayFixedPosition() {
  4670. MOZ_COUNT_DTOR(nsDisplayFixedPosition);
  4671. }
  4672. #endif
  4673. already_AddRefed<Layer>
  4674. nsDisplayFixedPosition::BuildLayer(nsDisplayListBuilder* aBuilder,
  4675. LayerManager* aManager,
  4676. const ContainerLayerParameters& aContainerParameters) {
  4677. RefPtr<Layer> layer =
  4678. nsDisplayOwnLayer::BuildLayer(aBuilder, aManager, aContainerParameters);
  4679. layer->SetIsFixedPosition(true);
  4680. nsPresContext* presContext = mFrame->PresContext();
  4681. nsIFrame* fixedFrame = mIsFixedBackground ? presContext->PresShell()->GetRootFrame() : mFrame;
  4682. const nsIFrame* viewportFrame = fixedFrame->GetParent();
  4683. // anchorRect will be in the container's coordinate system (aLayer's parent layer).
  4684. // This is the same as the display items' reference frame.
  4685. nsRect anchorRect;
  4686. if (viewportFrame) {
  4687. // Fixed position frames are reflowed into the scroll-port size if one has
  4688. // been set.
  4689. if (presContext->PresShell()->IsScrollPositionClampingScrollPortSizeSet()) {
  4690. anchorRect.SizeTo(presContext->PresShell()->GetScrollPositionClampingScrollPortSize());
  4691. } else {
  4692. anchorRect.SizeTo(viewportFrame->GetSize());
  4693. }
  4694. } else {
  4695. // A display item directly attached to the viewport.
  4696. // For background-attachment:fixed items, the anchor point is always the
  4697. // top-left of the viewport currently.
  4698. viewportFrame = fixedFrame;
  4699. }
  4700. // The anchorRect top-left is always the viewport top-left.
  4701. anchorRect.MoveTo(viewportFrame->GetOffsetToCrossDoc(ReferenceFrame()));
  4702. nsLayoutUtils::SetFixedPositionLayerData(layer,
  4703. viewportFrame, anchorRect, fixedFrame, presContext, aContainerParameters);
  4704. return layer.forget();
  4705. }
  4706. bool nsDisplayFixedPosition::TryMerge(nsDisplayItem* aItem) {
  4707. if (aItem->GetType() != TYPE_FIXED_POSITION)
  4708. return false;
  4709. // Items with the same fixed position frame can be merged.
  4710. nsDisplayFixedPosition* other = static_cast<nsDisplayFixedPosition*>(aItem);
  4711. if (other->mFrame != mFrame)
  4712. return false;
  4713. if (aItem->GetClip() != GetClip())
  4714. return false;
  4715. MergeFromTrackingMergedFrames(other);
  4716. return true;
  4717. }
  4718. TableType
  4719. GetTableTypeFromFrame(nsIFrame* aFrame)
  4720. {
  4721. nsIAtom* type = aFrame->GetType();
  4722. if (type == nsGkAtoms::tableFrame) {
  4723. return TableType::TABLE;
  4724. } else if (type == nsGkAtoms::tableColFrame) {
  4725. return TableType::TABLE_COL;
  4726. } else if (type == nsGkAtoms::tableColGroupFrame) {
  4727. return TableType::TABLE_COL_GROUP;
  4728. } else if (type == nsGkAtoms::tableRowFrame) {
  4729. return TableType::TABLE_ROW;
  4730. } else if (type == nsGkAtoms::tableRowGroupFrame) {
  4731. return TableType::TABLE_ROW_GROUP;
  4732. } else if (type == nsGkAtoms::tableCellFrame) {
  4733. return TableType::TABLE_CELL;
  4734. } else {
  4735. MOZ_ASSERT_UNREACHABLE("Invalid frame.");
  4736. return TableType::TABLE;
  4737. }
  4738. }
  4739. nsDisplayTableFixedPosition::nsDisplayTableFixedPosition(nsDisplayListBuilder* aBuilder,
  4740. nsIFrame* aFrame,
  4741. nsDisplayList* aList,
  4742. uint32_t aIndex,
  4743. nsIFrame* aAncestorFrame)
  4744. : nsDisplayFixedPosition(aBuilder, aFrame, aList, aIndex)
  4745. , mTableType(GetTableTypeFromFrame(aAncestorFrame))
  4746. {
  4747. }
  4748. /* static */ nsDisplayTableFixedPosition*
  4749. nsDisplayTableFixedPosition::CreateForFixedBackground(nsDisplayListBuilder* aBuilder,
  4750. nsIFrame* aFrame,
  4751. nsDisplayBackgroundImage* aImage,
  4752. uint32_t aIndex,
  4753. nsIFrame* aAncestorFrame)
  4754. {
  4755. nsDisplayList temp;
  4756. temp.AppendToTop(aImage);
  4757. return new (aBuilder) nsDisplayTableFixedPosition(aBuilder, aFrame, &temp, aIndex + 1, aAncestorFrame);
  4758. }
  4759. nsDisplayStickyPosition::nsDisplayStickyPosition(nsDisplayListBuilder* aBuilder,
  4760. nsIFrame* aFrame,
  4761. nsDisplayList* aList)
  4762. : nsDisplayOwnLayer(aBuilder, aFrame, aList)
  4763. {
  4764. MOZ_COUNT_CTOR(nsDisplayStickyPosition);
  4765. }
  4766. #ifdef NS_BUILD_REFCNT_LOGGING
  4767. nsDisplayStickyPosition::~nsDisplayStickyPosition() {
  4768. MOZ_COUNT_DTOR(nsDisplayStickyPosition);
  4769. }
  4770. #endif
  4771. already_AddRefed<Layer>
  4772. nsDisplayStickyPosition::BuildLayer(nsDisplayListBuilder* aBuilder,
  4773. LayerManager* aManager,
  4774. const ContainerLayerParameters& aContainerParameters) {
  4775. RefPtr<Layer> layer =
  4776. nsDisplayOwnLayer::BuildLayer(aBuilder, aManager, aContainerParameters);
  4777. StickyScrollContainer* stickyScrollContainer = StickyScrollContainer::
  4778. GetStickyScrollContainerForFrame(mFrame);
  4779. if (!stickyScrollContainer) {
  4780. return layer.forget();
  4781. }
  4782. nsIFrame* scrollFrame = do_QueryFrame(stickyScrollContainer->ScrollFrame());
  4783. nsPresContext* presContext = scrollFrame->PresContext();
  4784. // Sticky position frames whose scroll frame is the root scroll frame are
  4785. // reflowed into the scroll-port size if one has been set.
  4786. nsSize scrollFrameSize = scrollFrame->GetSize();
  4787. if (scrollFrame == presContext->PresShell()->GetRootScrollFrame() &&
  4788. presContext->PresShell()->IsScrollPositionClampingScrollPortSizeSet()) {
  4789. scrollFrameSize = presContext->PresShell()->
  4790. GetScrollPositionClampingScrollPortSize();
  4791. }
  4792. nsLayoutUtils::SetFixedPositionLayerData(layer, scrollFrame,
  4793. nsRect(scrollFrame->GetOffsetToCrossDoc(ReferenceFrame()), scrollFrameSize),
  4794. mFrame, presContext, aContainerParameters);
  4795. ViewID scrollId = nsLayoutUtils::FindOrCreateIDFor(
  4796. stickyScrollContainer->ScrollFrame()->GetScrolledFrame()->GetContent());
  4797. float factor = presContext->AppUnitsPerDevPixel();
  4798. nsRect outer;
  4799. nsRect inner;
  4800. stickyScrollContainer->GetScrollRanges(mFrame, &outer, &inner);
  4801. LayerRect stickyOuter(NSAppUnitsToFloatPixels(outer.x, factor) *
  4802. aContainerParameters.mXScale,
  4803. NSAppUnitsToFloatPixels(outer.y, factor) *
  4804. aContainerParameters.mYScale,
  4805. NSAppUnitsToFloatPixels(outer.width, factor) *
  4806. aContainerParameters.mXScale,
  4807. NSAppUnitsToFloatPixels(outer.height, factor) *
  4808. aContainerParameters.mYScale);
  4809. LayerRect stickyInner(NSAppUnitsToFloatPixels(inner.x, factor) *
  4810. aContainerParameters.mXScale,
  4811. NSAppUnitsToFloatPixels(inner.y, factor) *
  4812. aContainerParameters.mYScale,
  4813. NSAppUnitsToFloatPixels(inner.width, factor) *
  4814. aContainerParameters.mXScale,
  4815. NSAppUnitsToFloatPixels(inner.height, factor) *
  4816. aContainerParameters.mYScale);
  4817. layer->SetStickyPositionData(scrollId, stickyOuter, stickyInner);
  4818. return layer.forget();
  4819. }
  4820. bool nsDisplayStickyPosition::TryMerge(nsDisplayItem* aItem) {
  4821. if (aItem->GetType() != TYPE_STICKY_POSITION)
  4822. return false;
  4823. // Items with the same fixed position frame can be merged.
  4824. nsDisplayStickyPosition* other = static_cast<nsDisplayStickyPosition*>(aItem);
  4825. if (other->mFrame != mFrame)
  4826. return false;
  4827. if (aItem->GetClip() != GetClip())
  4828. return false;
  4829. if (aItem->ScrollClip() != ScrollClip())
  4830. return false;
  4831. MergeFromTrackingMergedFrames(other);
  4832. return true;
  4833. }
  4834. nsDisplayScrollInfoLayer::nsDisplayScrollInfoLayer(
  4835. nsDisplayListBuilder* aBuilder,
  4836. nsIFrame* aScrolledFrame,
  4837. nsIFrame* aScrollFrame)
  4838. : nsDisplayWrapList(aBuilder, aScrollFrame)
  4839. , mScrollFrame(aScrollFrame)
  4840. , mScrolledFrame(aScrolledFrame)
  4841. , mScrollParentId(aBuilder->GetCurrentScrollParentId())
  4842. {
  4843. #ifdef NS_BUILD_REFCNT_LOGGING
  4844. MOZ_COUNT_CTOR(nsDisplayScrollInfoLayer);
  4845. #endif
  4846. }
  4847. #ifdef NS_BUILD_REFCNT_LOGGING
  4848. nsDisplayScrollInfoLayer::~nsDisplayScrollInfoLayer()
  4849. {
  4850. MOZ_COUNT_DTOR(nsDisplayScrollInfoLayer);
  4851. }
  4852. #endif
  4853. already_AddRefed<Layer>
  4854. nsDisplayScrollInfoLayer::BuildLayer(nsDisplayListBuilder* aBuilder,
  4855. LayerManager* aManager,
  4856. const ContainerLayerParameters& aContainerParameters)
  4857. {
  4858. // In general for APZ with event-regions we no longer have a need for
  4859. // scrollinfo layers. However, in some cases, there might be content that
  4860. // cannot be layerized, and so needs to scroll synchronously. To handle those
  4861. // cases, we still want to generate scrollinfo layers.
  4862. ContainerLayerParameters params = aContainerParameters;
  4863. if (mScrolledFrame->GetContent() &&
  4864. nsLayoutUtils::HasCriticalDisplayPort(mScrolledFrame->GetContent())) {
  4865. params.mInLowPrecisionDisplayPort = true;
  4866. }
  4867. return aManager->GetLayerBuilder()->
  4868. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, &mList,
  4869. params, nullptr,
  4870. FrameLayerBuilder::CONTAINER_ALLOW_PULL_BACKGROUND_COLOR);
  4871. }
  4872. LayerState
  4873. nsDisplayScrollInfoLayer::GetLayerState(nsDisplayListBuilder* aBuilder,
  4874. LayerManager* aManager,
  4875. const ContainerLayerParameters& aParameters)
  4876. {
  4877. return LAYER_ACTIVE_EMPTY;
  4878. }
  4879. UniquePtr<ScrollMetadata>
  4880. nsDisplayScrollInfoLayer::ComputeScrollMetadata(Layer* aLayer,
  4881. const ContainerLayerParameters& aContainerParameters)
  4882. {
  4883. ContainerLayerParameters params = aContainerParameters;
  4884. if (mScrolledFrame->GetContent() &&
  4885. nsLayoutUtils::HasCriticalDisplayPort(mScrolledFrame->GetContent())) {
  4886. params.mInLowPrecisionDisplayPort = true;
  4887. }
  4888. nsRect viewport = mScrollFrame->GetRect() -
  4889. mScrollFrame->GetPosition() +
  4890. mScrollFrame->GetOffsetToCrossDoc(ReferenceFrame());
  4891. ScrollMetadata metadata = nsLayoutUtils::ComputeScrollMetadata(
  4892. mScrolledFrame, mScrollFrame, mScrollFrame->GetContent(),
  4893. ReferenceFrame(), aLayer,
  4894. mScrollParentId, viewport, Nothing(), false, params);
  4895. metadata.GetMetrics().SetIsScrollInfoLayer(true);
  4896. return UniquePtr<ScrollMetadata>(new ScrollMetadata(metadata));
  4897. }
  4898. void
  4899. nsDisplayScrollInfoLayer::WriteDebugInfo(std::stringstream& aStream)
  4900. {
  4901. aStream << " (scrollframe " << mScrollFrame
  4902. << " scrolledFrame " << mScrolledFrame << ")";
  4903. }
  4904. nsDisplayZoom::nsDisplayZoom(nsDisplayListBuilder* aBuilder,
  4905. nsIFrame* aFrame, nsDisplayList* aList,
  4906. int32_t aAPD, int32_t aParentAPD,
  4907. uint32_t aFlags)
  4908. : nsDisplaySubDocument(aBuilder, aFrame, aList, aFlags)
  4909. , mAPD(aAPD), mParentAPD(aParentAPD) {
  4910. MOZ_COUNT_CTOR(nsDisplayZoom);
  4911. }
  4912. #ifdef NS_BUILD_REFCNT_LOGGING
  4913. nsDisplayZoom::~nsDisplayZoom() {
  4914. MOZ_COUNT_DTOR(nsDisplayZoom);
  4915. }
  4916. #endif
  4917. nsRect nsDisplayZoom::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
  4918. {
  4919. nsRect bounds = nsDisplaySubDocument::GetBounds(aBuilder, aSnap);
  4920. *aSnap = false;
  4921. return bounds.ScaleToOtherAppUnitsRoundOut(mAPD, mParentAPD);
  4922. }
  4923. void nsDisplayZoom::HitTest(nsDisplayListBuilder *aBuilder,
  4924. const nsRect& aRect,
  4925. HitTestState *aState,
  4926. nsTArray<nsIFrame*> *aOutFrames)
  4927. {
  4928. nsRect rect;
  4929. // A 1x1 rect indicates we are just hit testing a point, so pass down a 1x1
  4930. // rect as well instead of possibly rounding the width or height to zero.
  4931. if (aRect.width == 1 && aRect.height == 1) {
  4932. rect.MoveTo(aRect.TopLeft().ScaleToOtherAppUnits(mParentAPD, mAPD));
  4933. rect.width = rect.height = 1;
  4934. } else {
  4935. rect = aRect.ScaleToOtherAppUnitsRoundOut(mParentAPD, mAPD);
  4936. }
  4937. mList.HitTest(aBuilder, rect, aState, aOutFrames);
  4938. }
  4939. bool nsDisplayZoom::ComputeVisibility(nsDisplayListBuilder *aBuilder,
  4940. nsRegion *aVisibleRegion)
  4941. {
  4942. // Convert the passed in visible region to our appunits.
  4943. nsRegion visibleRegion;
  4944. // mVisibleRect has been clipped to GetClippedBounds
  4945. visibleRegion.And(*aVisibleRegion, mVisibleRect);
  4946. visibleRegion = visibleRegion.ScaleToOtherAppUnitsRoundOut(mParentAPD, mAPD);
  4947. nsRegion originalVisibleRegion = visibleRegion;
  4948. nsRect transformedVisibleRect =
  4949. mVisibleRect.ScaleToOtherAppUnitsRoundOut(mParentAPD, mAPD);
  4950. bool retval;
  4951. // If we are to generate a scrollable layer we call
  4952. // nsDisplaySubDocument::ComputeVisibility to make the necessary adjustments
  4953. // for ComputeVisibility, it does all it's calculations in the child APD.
  4954. bool usingDisplayPort = UseDisplayPortForViewport(aBuilder, mFrame);
  4955. if (!(mFlags & GENERATE_SCROLLABLE_LAYER) || !usingDisplayPort) {
  4956. retval =
  4957. mList.ComputeVisibilityForSublist(aBuilder, &visibleRegion,
  4958. transformedVisibleRect);
  4959. } else {
  4960. retval =
  4961. nsDisplaySubDocument::ComputeVisibility(aBuilder, &visibleRegion);
  4962. }
  4963. nsRegion removed;
  4964. // removed = originalVisibleRegion - visibleRegion
  4965. removed.Sub(originalVisibleRegion, visibleRegion);
  4966. // Convert removed region to parent appunits.
  4967. removed = removed.ScaleToOtherAppUnitsRoundIn(mAPD, mParentAPD);
  4968. // aVisibleRegion = aVisibleRegion - removed (modulo any simplifications
  4969. // SubtractFromVisibleRegion does)
  4970. aBuilder->SubtractFromVisibleRegion(aVisibleRegion, removed);
  4971. return retval;
  4972. }
  4973. ///////////////////////////////////////////////////
  4974. // nsDisplayTransform Implementation
  4975. //
  4976. // Write #define UNIFIED_CONTINUATIONS here and in
  4977. // TransformReferenceBox::Initialize to have the transform property try
  4978. // to transform content with continuations as one unified block instead of
  4979. // several smaller ones. This is currently disabled because it doesn't work
  4980. // correctly, since when the frames are initially being reflowed, their
  4981. // continuations all compute their bounding rects independently of each other
  4982. // and consequently get the wrong value. Write #define DEBUG_HIT here to have
  4983. // the nsDisplayTransform class dump out a bunch of information about hit
  4984. // detection.
  4985. #undef UNIFIED_CONTINUATIONS
  4986. #undef DEBUG_HIT
  4987. nsDisplayTransform::nsDisplayTransform(nsDisplayListBuilder* aBuilder,
  4988. nsIFrame *aFrame, nsDisplayList *aList,
  4989. const nsRect& aChildrenVisibleRect,
  4990. ComputeTransformFunction aTransformGetter,
  4991. uint32_t aIndex)
  4992. : nsDisplayItem(aBuilder, aFrame)
  4993. , mStoredList(aBuilder, aFrame, aList)
  4994. , mTransformGetter(aTransformGetter)
  4995. , mAnimatedGeometryRootForChildren(mAnimatedGeometryRoot)
  4996. , mAnimatedGeometryRootForScrollMetadata(mAnimatedGeometryRoot)
  4997. , mChildrenVisibleRect(aChildrenVisibleRect)
  4998. , mIndex(aIndex)
  4999. , mNoExtendContext(false)
  5000. , mIsTransformSeparator(false)
  5001. , mTransformPreserves3DInited(false)
  5002. , mIsFullyVisible(false)
  5003. {
  5004. MOZ_COUNT_CTOR(nsDisplayTransform);
  5005. MOZ_ASSERT(aFrame, "Must have a frame!");
  5006. Init(aBuilder);
  5007. }
  5008. void
  5009. nsDisplayTransform::SetReferenceFrameToAncestor(nsDisplayListBuilder* aBuilder)
  5010. {
  5011. if (mFrame == aBuilder->RootReferenceFrame()) {
  5012. return;
  5013. }
  5014. nsIFrame *outerFrame = nsLayoutUtils::GetCrossDocParentFrame(mFrame);
  5015. mReferenceFrame =
  5016. aBuilder->FindReferenceFrameFor(outerFrame);
  5017. mToReferenceFrame = mFrame->GetOffsetToCrossDoc(mReferenceFrame);
  5018. if (nsLayoutUtils::IsFixedPosFrameInDisplayPort(mFrame)) {
  5019. // This is an odd special case. If we are both IsFixedPosFrameInDisplayPort
  5020. // and transformed that we are our own AGR parent.
  5021. // We want our frame to be our AGR because FrameLayerBuilder uses our AGR to
  5022. // determine if we are inside a fixed pos subtree. If we use the outer AGR
  5023. // from outside the fixed pos subtree FLB can't tell that we are fixed pos.
  5024. mAnimatedGeometryRoot = mAnimatedGeometryRootForChildren;
  5025. } else if (mFrame->StyleDisplay()->mPosition == NS_STYLE_POSITION_STICKY &&
  5026. IsStickyFrameActive(aBuilder, mFrame, nullptr)) {
  5027. // Similar to the IsFixedPosFrameInDisplayPort case we are our own AGR.
  5028. // We are inside the sticky position, so our AGR is the sticky positioned
  5029. // frame, which is our AGR, not the parent AGR.
  5030. mAnimatedGeometryRoot = mAnimatedGeometryRootForChildren;
  5031. } else if (mAnimatedGeometryRoot->mParentAGR) {
  5032. mAnimatedGeometryRootForScrollMetadata = mAnimatedGeometryRoot->mParentAGR;
  5033. if (!MayBeAnimated(aBuilder)) {
  5034. // If we're an animated transform then we want the same AGR as our children
  5035. // so that FrameLayerBuilder knows that this layer moves with the transform
  5036. // and won't compute occlusions. If we're not animated then use our parent
  5037. // AGR so that inactive transform layers can go in the same PaintedLayer as
  5038. // surrounding content.
  5039. mAnimatedGeometryRoot = mAnimatedGeometryRoot->mParentAGR;
  5040. }
  5041. }
  5042. mVisibleRect = aBuilder->GetDirtyRect() + mToReferenceFrame;
  5043. }
  5044. void
  5045. nsDisplayTransform::Init(nsDisplayListBuilder* aBuilder)
  5046. {
  5047. mHasBounds = false;
  5048. mStoredList.SetClip(aBuilder, DisplayItemClip::NoClip());
  5049. mStoredList.SetVisibleRect(mChildrenVisibleRect);
  5050. }
  5051. nsDisplayTransform::nsDisplayTransform(nsDisplayListBuilder* aBuilder,
  5052. nsIFrame *aFrame, nsDisplayList *aList,
  5053. const nsRect& aChildrenVisibleRect,
  5054. uint32_t aIndex,
  5055. bool aIsFullyVisible)
  5056. : nsDisplayItem(aBuilder, aFrame)
  5057. , mStoredList(aBuilder, aFrame, aList)
  5058. , mTransformGetter(nullptr)
  5059. , mAnimatedGeometryRootForChildren(mAnimatedGeometryRoot)
  5060. , mAnimatedGeometryRootForScrollMetadata(mAnimatedGeometryRoot)
  5061. , mChildrenVisibleRect(aChildrenVisibleRect)
  5062. , mIndex(aIndex)
  5063. , mNoExtendContext(false)
  5064. , mIsTransformSeparator(false)
  5065. , mTransformPreserves3DInited(false)
  5066. , mIsFullyVisible(aIsFullyVisible)
  5067. {
  5068. MOZ_COUNT_CTOR(nsDisplayTransform);
  5069. MOZ_ASSERT(aFrame, "Must have a frame!");
  5070. SetReferenceFrameToAncestor(aBuilder);
  5071. Init(aBuilder);
  5072. UpdateBoundsFor3D(aBuilder);
  5073. }
  5074. nsDisplayTransform::nsDisplayTransform(nsDisplayListBuilder* aBuilder,
  5075. nsIFrame *aFrame, nsDisplayItem *aItem,
  5076. const nsRect& aChildrenVisibleRect,
  5077. uint32_t aIndex)
  5078. : nsDisplayItem(aBuilder, aFrame)
  5079. , mStoredList(aBuilder, aFrame, aItem)
  5080. , mTransformGetter(nullptr)
  5081. , mAnimatedGeometryRootForChildren(mAnimatedGeometryRoot)
  5082. , mAnimatedGeometryRootForScrollMetadata(mAnimatedGeometryRoot)
  5083. , mChildrenVisibleRect(aChildrenVisibleRect)
  5084. , mIndex(aIndex)
  5085. , mNoExtendContext(false)
  5086. , mIsTransformSeparator(false)
  5087. , mTransformPreserves3DInited(false)
  5088. , mIsFullyVisible(false)
  5089. {
  5090. MOZ_COUNT_CTOR(nsDisplayTransform);
  5091. MOZ_ASSERT(aFrame, "Must have a frame!");
  5092. SetReferenceFrameToAncestor(aBuilder);
  5093. Init(aBuilder);
  5094. }
  5095. nsDisplayTransform::nsDisplayTransform(nsDisplayListBuilder* aBuilder,
  5096. nsIFrame *aFrame, nsDisplayList *aList,
  5097. const nsRect& aChildrenVisibleRect,
  5098. const Matrix4x4& aTransform,
  5099. uint32_t aIndex)
  5100. : nsDisplayItem(aBuilder, aFrame)
  5101. , mStoredList(aBuilder, aFrame, aList)
  5102. , mTransform(aTransform)
  5103. , mTransformGetter(nullptr)
  5104. , mAnimatedGeometryRootForChildren(mAnimatedGeometryRoot)
  5105. , mAnimatedGeometryRootForScrollMetadata(mAnimatedGeometryRoot)
  5106. , mChildrenVisibleRect(aChildrenVisibleRect)
  5107. , mIndex(aIndex)
  5108. , mNoExtendContext(false)
  5109. , mIsTransformSeparator(true)
  5110. , mTransformPreserves3DInited(false)
  5111. , mIsFullyVisible(false)
  5112. {
  5113. MOZ_COUNT_CTOR(nsDisplayTransform);
  5114. MOZ_ASSERT(aFrame, "Must have a frame!");
  5115. Init(aBuilder);
  5116. UpdateBoundsFor3D(aBuilder);
  5117. }
  5118. /* Returns the delta specified by the transform-origin property.
  5119. * This is a positive delta, meaning that it indicates the direction to move
  5120. * to get from (0, 0) of the frame to the transform origin. This function is
  5121. * called off the main thread.
  5122. */
  5123. /* static */ Point3D
  5124. nsDisplayTransform::GetDeltaToTransformOrigin(const nsIFrame* aFrame,
  5125. float aAppUnitsPerPixel,
  5126. const nsRect* aBoundsOverride)
  5127. {
  5128. NS_PRECONDITION(aFrame, "Can't get delta for a null frame!");
  5129. NS_PRECONDITION(aFrame->IsTransformed() ||
  5130. aFrame->BackfaceIsHidden() ||
  5131. aFrame->Combines3DTransformWithAncestors(),
  5132. "Shouldn't get a delta for an untransformed frame!");
  5133. if (!aFrame->IsTransformed()) {
  5134. return Point3D();
  5135. }
  5136. /* For both of the coordinates, if the value of transform is a
  5137. * percentage, it's relative to the size of the frame. Otherwise, if it's
  5138. * a distance, it's already computed for us!
  5139. */
  5140. const nsStyleDisplay* display = aFrame->StyleDisplay();
  5141. // We don't use aBoundsOverride for SVG since we need to account for
  5142. // refBox.X/Y(). This happens to work because ReflowSVG sets the frame's
  5143. // mRect before calling FinishAndStoreOverflow so we don't need the override.
  5144. TransformReferenceBox refBox;
  5145. if (aBoundsOverride &&
  5146. !(aFrame->GetStateBits() & NS_FRAME_SVG_LAYOUT)) {
  5147. refBox.Init(aBoundsOverride->Size());
  5148. } else {
  5149. refBox.Init(aFrame);
  5150. }
  5151. /* Allows us to access dimension getters by index. */
  5152. float transformOrigin[2];
  5153. TransformReferenceBox::DimensionGetter dimensionGetter[] =
  5154. { &TransformReferenceBox::Width, &TransformReferenceBox::Height };
  5155. TransformReferenceBox::DimensionGetter offsetGetter[] =
  5156. { &TransformReferenceBox::X, &TransformReferenceBox::Y };
  5157. for (uint8_t index = 0; index < 2; ++index) {
  5158. /* If the transform-origin specifies a percentage, take the percentage
  5159. * of the size of the box.
  5160. */
  5161. const nsStyleCoord &originValue = display->mTransformOrigin[index];
  5162. if (originValue.GetUnit() == eStyleUnit_Calc) {
  5163. const nsStyleCoord::Calc *calc = originValue.GetCalcValue();
  5164. transformOrigin[index] =
  5165. NSAppUnitsToFloatPixels((refBox.*dimensionGetter[index])(), aAppUnitsPerPixel) *
  5166. calc->mPercent +
  5167. NSAppUnitsToFloatPixels(calc->mLength, aAppUnitsPerPixel);
  5168. } else if (originValue.GetUnit() == eStyleUnit_Percent) {
  5169. transformOrigin[index] =
  5170. NSAppUnitsToFloatPixels((refBox.*dimensionGetter[index])(), aAppUnitsPerPixel) *
  5171. originValue.GetPercentValue();
  5172. } else {
  5173. MOZ_ASSERT(originValue.GetUnit() == eStyleUnit_Coord, "unexpected unit");
  5174. transformOrigin[index] =
  5175. NSAppUnitsToFloatPixels(originValue.GetCoordValue(), aAppUnitsPerPixel);
  5176. }
  5177. if (aFrame->GetStateBits() & NS_FRAME_SVG_LAYOUT) {
  5178. // SVG frames (unlike other frames) have a reference box that can be (and
  5179. // typically is) offset from the TopLeft() of the frame. We need to
  5180. // account for that here.
  5181. transformOrigin[index] +=
  5182. NSAppUnitsToFloatPixels((refBox.*offsetGetter[index])(), aAppUnitsPerPixel);
  5183. }
  5184. }
  5185. return Point3D(transformOrigin[0], transformOrigin[1],
  5186. NSAppUnitsToFloatPixels(display->mTransformOrigin[2].GetCoordValue(),
  5187. aAppUnitsPerPixel));
  5188. }
  5189. /* static */ bool
  5190. nsDisplayTransform::ComputePerspectiveMatrix(const nsIFrame* aFrame,
  5191. float aAppUnitsPerPixel,
  5192. Matrix4x4& aOutMatrix)
  5193. {
  5194. NS_PRECONDITION(aFrame, "Can't get delta for a null frame!");
  5195. NS_PRECONDITION(aFrame->IsTransformed() ||
  5196. aFrame->BackfaceIsHidden() ||
  5197. aFrame->Combines3DTransformWithAncestors(),
  5198. "Shouldn't get a delta for an untransformed frame!");
  5199. NS_PRECONDITION(aOutMatrix.IsIdentity(), "Must have a blank output matrix");
  5200. if (!aFrame->IsTransformed()) {
  5201. return false;
  5202. }
  5203. /* Find our containing block, which is the element that provides the
  5204. * value for perspective we need to use
  5205. */
  5206. //TODO: Is it possible that the cbFrame's bounds haven't been set correctly yet
  5207. // (similar to the aBoundsOverride case for GetResultingTransformMatrix)?
  5208. nsIFrame* cbFrame = aFrame->GetContainingBlock(nsIFrame::SKIP_SCROLLED_FRAME);
  5209. if (!cbFrame) {
  5210. return false;
  5211. }
  5212. /* Grab the values for perspective and perspective-origin (if present) */
  5213. const nsStyleDisplay* cbDisplay = cbFrame->StyleDisplay();
  5214. if (cbDisplay->mChildPerspective.GetUnit() != eStyleUnit_Coord) {
  5215. return false;
  5216. }
  5217. nscoord perspective = cbDisplay->mChildPerspective.GetCoordValue();
  5218. if (perspective < 0) {
  5219. return true;
  5220. }
  5221. TransformReferenceBox refBox(cbFrame);
  5222. /* Allows us to access named variables by index. */
  5223. Point3D perspectiveOrigin;
  5224. gfx::Float* coords[2] = {&perspectiveOrigin.x, &perspectiveOrigin.y};
  5225. TransformReferenceBox::DimensionGetter dimensionGetter[] =
  5226. { &TransformReferenceBox::Width, &TransformReferenceBox::Height };
  5227. /* For both of the coordinates, if the value of perspective-origin is a
  5228. * percentage, it's relative to the size of the frame. Otherwise, if it's
  5229. * a distance, it's already computed for us!
  5230. */
  5231. for (uint8_t index = 0; index < 2; ++index) {
  5232. /* If the -transform-origin specifies a percentage, take the percentage
  5233. * of the size of the box.
  5234. */
  5235. const nsStyleCoord &coord = cbDisplay->mPerspectiveOrigin[index];
  5236. if (coord.GetUnit() == eStyleUnit_Calc) {
  5237. const nsStyleCoord::Calc *calc = coord.GetCalcValue();
  5238. *coords[index] =
  5239. NSAppUnitsToFloatPixels((refBox.*dimensionGetter[index])(), aAppUnitsPerPixel) *
  5240. calc->mPercent +
  5241. NSAppUnitsToFloatPixels(calc->mLength, aAppUnitsPerPixel);
  5242. } else if (coord.GetUnit() == eStyleUnit_Percent) {
  5243. *coords[index] =
  5244. NSAppUnitsToFloatPixels((refBox.*dimensionGetter[index])(), aAppUnitsPerPixel) *
  5245. coord.GetPercentValue();
  5246. } else {
  5247. MOZ_ASSERT(coord.GetUnit() == eStyleUnit_Coord, "unexpected unit");
  5248. *coords[index] =
  5249. NSAppUnitsToFloatPixels(coord.GetCoordValue(), aAppUnitsPerPixel);
  5250. }
  5251. }
  5252. /* GetOffsetTo computes the offset required to move from 0,0 in cbFrame to 0,0
  5253. * in aFrame. Although we actually want the inverse of this, it's faster to
  5254. * compute this way.
  5255. */
  5256. nsPoint frameToCbOffset = -aFrame->GetOffsetTo(cbFrame);
  5257. Point3D frameToCbGfxOffset(
  5258. NSAppUnitsToFloatPixels(frameToCbOffset.x, aAppUnitsPerPixel),
  5259. NSAppUnitsToFloatPixels(frameToCbOffset.y, aAppUnitsPerPixel),
  5260. 0.0f);
  5261. /* Move the perspective origin to be relative to aFrame, instead of relative
  5262. * to the containing block which is how it was specified in the style system.
  5263. */
  5264. perspectiveOrigin += frameToCbGfxOffset;
  5265. Float perspectivePx = std::max(NSAppUnitsToFloatPixels(perspective,
  5266. aAppUnitsPerPixel),
  5267. std::numeric_limits<Float>::epsilon());
  5268. aOutMatrix._34 = -1.0 / perspectivePx;
  5269. aOutMatrix.ChangeBasis(perspectiveOrigin);
  5270. return true;
  5271. }
  5272. nsDisplayTransform::FrameTransformProperties::FrameTransformProperties(const nsIFrame* aFrame,
  5273. float aAppUnitsPerPixel,
  5274. const nsRect* aBoundsOverride)
  5275. : mFrame(aFrame)
  5276. , mTransformList(aFrame->StyleDisplay()->mSpecifiedTransform)
  5277. , mToTransformOrigin(GetDeltaToTransformOrigin(aFrame, aAppUnitsPerPixel, aBoundsOverride))
  5278. {
  5279. }
  5280. /* Wraps up the transform matrix in a change-of-basis matrix pair that
  5281. * translates from local coordinate space to transform coordinate space, then
  5282. * hands it back.
  5283. */
  5284. Matrix4x4
  5285. nsDisplayTransform::GetResultingTransformMatrix(const FrameTransformProperties& aProperties,
  5286. const nsPoint& aOrigin,
  5287. float aAppUnitsPerPixel,
  5288. uint32_t aFlags,
  5289. const nsRect* aBoundsOverride)
  5290. {
  5291. return GetResultingTransformMatrixInternal(aProperties, aOrigin, aAppUnitsPerPixel,
  5292. aFlags, aBoundsOverride);
  5293. }
  5294. Matrix4x4
  5295. nsDisplayTransform::GetResultingTransformMatrix(const nsIFrame* aFrame,
  5296. const nsPoint& aOrigin,
  5297. float aAppUnitsPerPixel,
  5298. uint32_t aFlags,
  5299. const nsRect* aBoundsOverride)
  5300. {
  5301. FrameTransformProperties props(aFrame,
  5302. aAppUnitsPerPixel,
  5303. aBoundsOverride);
  5304. return GetResultingTransformMatrixInternal(props, aOrigin, aAppUnitsPerPixel,
  5305. aFlags, aBoundsOverride);
  5306. }
  5307. Matrix4x4
  5308. nsDisplayTransform::GetResultingTransformMatrixInternal(const FrameTransformProperties& aProperties,
  5309. const nsPoint& aOrigin,
  5310. float aAppUnitsPerPixel,
  5311. uint32_t aFlags,
  5312. const nsRect* aBoundsOverride)
  5313. {
  5314. const nsIFrame *frame = aProperties.mFrame;
  5315. NS_ASSERTION(frame || !(aFlags & INCLUDE_PERSPECTIVE), "Must have a frame to compute perspective!");
  5316. // Get the underlying transform matrix:
  5317. // We don't use aBoundsOverride for SVG since we need to account for
  5318. // refBox.X/Y(). This happens to work because ReflowSVG sets the frame's
  5319. // mRect before calling FinishAndStoreOverflow so we don't need the override.
  5320. TransformReferenceBox refBox;
  5321. if (aBoundsOverride &&
  5322. (!frame || !(frame->GetStateBits() & NS_FRAME_SVG_LAYOUT))) {
  5323. refBox.Init(aBoundsOverride->Size());
  5324. } else {
  5325. refBox.Init(frame);
  5326. }
  5327. /* Get the matrix, then change its basis to factor in the origin. */
  5328. RuleNodeCacheConditions dummy;
  5329. bool dummyBool;
  5330. Matrix4x4 result;
  5331. // Call IsSVGTransformed() regardless of the value of
  5332. // disp->mSpecifiedTransform, since we still need any transformFromSVGParent.
  5333. Matrix svgTransform, transformFromSVGParent;
  5334. bool hasSVGTransforms =
  5335. frame && frame->IsSVGTransformed(&svgTransform, &transformFromSVGParent);
  5336. bool hasTransformFromSVGParent =
  5337. hasSVGTransforms && !transformFromSVGParent.IsIdentity();
  5338. bool shouldRound = true;
  5339. // An SVG frame should not have its translation rounded.
  5340. // Note it's possible that the SVG frame doesn't have an SVG
  5341. // transform but only has a CSS transform.
  5342. if (frame && frame->HasAnyStateBits(NS_FRAME_SVG_LAYOUT) &&
  5343. !(frame->GetType() == nsGkAtoms::svgOuterSVGAnonChildFrame)) {
  5344. shouldRound = false;
  5345. }
  5346. /* Transformed frames always have a transform, or are preserving 3d (and might still have perspective!) */
  5347. if (aProperties.mTransformList) {
  5348. result = nsStyleTransformMatrix::ReadTransforms(aProperties.mTransformList->mHead,
  5349. frame ? frame->StyleContext() : nullptr,
  5350. frame ? frame->PresContext() : nullptr,
  5351. dummy, refBox, aAppUnitsPerPixel,
  5352. &dummyBool);
  5353. } else if (hasSVGTransforms) {
  5354. // Correct the translation components for zoom:
  5355. float pixelsPerCSSPx = frame->PresContext()->AppUnitsPerCSSPixel() /
  5356. aAppUnitsPerPixel;
  5357. svgTransform._31 *= pixelsPerCSSPx;
  5358. svgTransform._32 *= pixelsPerCSSPx;
  5359. result = Matrix4x4::From2D(svgTransform);
  5360. }
  5361. Matrix4x4 perspectiveMatrix;
  5362. bool hasPerspective = aFlags & INCLUDE_PERSPECTIVE;
  5363. if (hasPerspective) {
  5364. hasPerspective = ComputePerspectiveMatrix(frame, aAppUnitsPerPixel,
  5365. perspectiveMatrix);
  5366. }
  5367. if (!hasSVGTransforms || !hasTransformFromSVGParent) {
  5368. // This is a simplification of the following |else| block, the
  5369. // simplification being possible because we don't need to apply
  5370. // mToTransformOrigin between two transforms.
  5371. result.ChangeBasis(aProperties.mToTransformOrigin);
  5372. } else {
  5373. Point3D refBoxOffset(NSAppUnitsToFloatPixels(refBox.X(), aAppUnitsPerPixel),
  5374. NSAppUnitsToFloatPixels(refBox.Y(), aAppUnitsPerPixel),
  5375. 0);
  5376. // We have both a transform and children-only transform. The
  5377. // 'transform-origin' must apply between the two, so we need to apply it
  5378. // now before we apply transformFromSVGParent. Since mToTransformOrigin is
  5379. // relative to the frame's TopLeft(), we need to convert it to SVG user
  5380. // space by subtracting refBoxOffset. (Then after applying
  5381. // transformFromSVGParent we have to reapply refBoxOffset below.)
  5382. result.ChangeBasis(aProperties.mToTransformOrigin - refBoxOffset);
  5383. // Now apply the children-only transforms, converting the translation
  5384. // components to device pixels:
  5385. float pixelsPerCSSPx =
  5386. frame->PresContext()->AppUnitsPerCSSPixel() / aAppUnitsPerPixel;
  5387. transformFromSVGParent._31 *= pixelsPerCSSPx;
  5388. transformFromSVGParent._32 *= pixelsPerCSSPx;
  5389. result = result * Matrix4x4::From2D(transformFromSVGParent);
  5390. // Similar to the code in the |if| block above, but since we've accounted
  5391. // for mToTransformOrigin so we don't include that. We also need to reapply
  5392. // refBoxOffset.
  5393. result.ChangeBasis(refBoxOffset);
  5394. }
  5395. if (hasPerspective) {
  5396. result = result * perspectiveMatrix;
  5397. }
  5398. if ((aFlags & INCLUDE_PRESERVE3D_ANCESTORS) &&
  5399. frame && frame->Combines3DTransformWithAncestors()) {
  5400. // Include the transform set on our parent
  5401. NS_ASSERTION(frame->GetParent() &&
  5402. frame->GetParent()->IsTransformed() &&
  5403. frame->GetParent()->Extend3DContext(),
  5404. "Preserve3D mismatch!");
  5405. FrameTransformProperties props(frame->GetParent(),
  5406. aAppUnitsPerPixel,
  5407. nullptr);
  5408. uint32_t flags = aFlags & (INCLUDE_PRESERVE3D_ANCESTORS|INCLUDE_PERSPECTIVE);
  5409. // If this frame isn't transformed (but we exist for backface-visibility),
  5410. // then we're not a reference frame so no offset to origin will be added.
  5411. // Otherwise we need to manually translate into our parent's coordinate
  5412. // space.
  5413. if (frame->IsTransformed()) {
  5414. nsLayoutUtils::PostTranslate(result, frame->GetPosition(), aAppUnitsPerPixel, shouldRound);
  5415. }
  5416. Matrix4x4 parent =
  5417. GetResultingTransformMatrixInternal(props,
  5418. nsPoint(0, 0),
  5419. aAppUnitsPerPixel, flags,
  5420. nullptr);
  5421. result = result * parent;
  5422. }
  5423. if (aFlags & OFFSET_BY_ORIGIN) {
  5424. nsLayoutUtils::PostTranslate(result, aOrigin, aAppUnitsPerPixel, shouldRound);
  5425. }
  5426. return result;
  5427. }
  5428. bool
  5429. nsDisplayOpacity::CanUseAsyncAnimations(nsDisplayListBuilder* aBuilder)
  5430. {
  5431. if (ActiveLayerTracker::IsStyleAnimated(aBuilder, mFrame, eCSSProperty_opacity)) {
  5432. return true;
  5433. }
  5434. EffectCompositor::SetPerformanceWarning(
  5435. mFrame, eCSSProperty_opacity,
  5436. AnimationPerformanceWarning(
  5437. AnimationPerformanceWarning::Type::OpacityFrameInactive));
  5438. return false;
  5439. }
  5440. bool
  5441. nsDisplayTransform::CanUseAsyncAnimations(nsDisplayListBuilder* aBuilder)
  5442. {
  5443. return mIsFullyVisible;
  5444. }
  5445. /* static */ bool
  5446. nsDisplayTransform::ShouldPrerenderTransformedContent(nsDisplayListBuilder* aBuilder,
  5447. nsIFrame* aFrame)
  5448. {
  5449. // Elements whose transform has been modified recently, or which
  5450. // have a compositor-animated transform, can be prerendered. An element
  5451. // might have only just had its transform animated in which case
  5452. // the ActiveLayerManager may not have been notified yet.
  5453. if (!ActiveLayerTracker::IsStyleMaybeAnimated(aFrame, eCSSProperty_transform) &&
  5454. !EffectCompositor::HasAnimationsForCompositor(aFrame,
  5455. eCSSProperty_transform)) {
  5456. EffectCompositor::SetPerformanceWarning(
  5457. aFrame, eCSSProperty_transform,
  5458. AnimationPerformanceWarning(
  5459. AnimationPerformanceWarning::Type::TransformFrameInactive));
  5460. return false;
  5461. }
  5462. nsSize refSize = aBuilder->RootReferenceFrame()->GetSize();
  5463. // Only prerender if the transformed frame's size is <= the
  5464. // reference frame size (~viewport), allowing a 1/8th fuzz factor
  5465. // for shadows, borders, etc.
  5466. refSize += nsSize(refSize.width / 8, refSize.height / 8);
  5467. gfxSize scale = nsLayoutUtils::GetTransformToAncestorScale(aFrame);
  5468. nsSize frameSize = nsSize(
  5469. aFrame->GetVisualOverflowRectRelativeToSelf().Size().width * scale.width,
  5470. aFrame->GetVisualOverflowRectRelativeToSelf().Size().height * scale.height);
  5471. nscoord maxInAppUnits = nscoord_MAX;
  5472. if (frameSize <= refSize) {
  5473. maxInAppUnits = aFrame->PresContext()->DevPixelsToAppUnits(4096);
  5474. if (frameSize <= nsSize(maxInAppUnits, maxInAppUnits)) {
  5475. return true;
  5476. }
  5477. }
  5478. nsRect visual = aFrame->GetVisualOverflowRect();
  5479. EffectCompositor::SetPerformanceWarning(
  5480. aFrame, eCSSProperty_transform,
  5481. AnimationPerformanceWarning(
  5482. AnimationPerformanceWarning::Type::ContentTooLarge,
  5483. {
  5484. nsPresContext::AppUnitsToIntCSSPixels(frameSize.width),
  5485. nsPresContext::AppUnitsToIntCSSPixels(frameSize.height),
  5486. nsPresContext::AppUnitsToIntCSSPixels(refSize.width),
  5487. nsPresContext::AppUnitsToIntCSSPixels(refSize.height),
  5488. nsPresContext::AppUnitsToIntCSSPixels(visual.width),
  5489. nsPresContext::AppUnitsToIntCSSPixels(visual.height),
  5490. nsPresContext::AppUnitsToIntCSSPixels(maxInAppUnits)
  5491. }));
  5492. return false;
  5493. }
  5494. /* If the matrix is singular, or a hidden backface is shown, the frame won't be visible or hit. */
  5495. static bool IsFrameVisible(nsIFrame* aFrame, const Matrix4x4& aMatrix)
  5496. {
  5497. if (aMatrix.IsSingular()) {
  5498. return false;
  5499. }
  5500. if (aFrame->BackfaceIsHidden() && aMatrix.IsBackfaceVisible()) {
  5501. return false;
  5502. }
  5503. return true;
  5504. }
  5505. const Matrix4x4&
  5506. nsDisplayTransform::GetTransform()
  5507. {
  5508. if (mTransform.IsIdentity()) {
  5509. float scale = mFrame->PresContext()->AppUnitsPerDevPixel();
  5510. Point3D newOrigin =
  5511. Point3D(NSAppUnitsToFloatPixels(mToReferenceFrame.x, scale),
  5512. NSAppUnitsToFloatPixels(mToReferenceFrame.y, scale),
  5513. 0.0f);
  5514. if (mTransformGetter) {
  5515. mTransform = mTransformGetter(mFrame, scale);
  5516. mTransform.ChangeBasis(newOrigin.x, newOrigin.y, newOrigin.z);
  5517. } else if (!mIsTransformSeparator) {
  5518. DebugOnly<bool> isReference =
  5519. mFrame->IsTransformed() ||
  5520. mFrame->Combines3DTransformWithAncestors() || mFrame->Extend3DContext();
  5521. MOZ_ASSERT(isReference);
  5522. mTransform =
  5523. GetResultingTransformMatrix(mFrame, ToReferenceFrame(),
  5524. scale, INCLUDE_PERSPECTIVE|OFFSET_BY_ORIGIN);
  5525. }
  5526. }
  5527. return mTransform;
  5528. }
  5529. Matrix4x4
  5530. nsDisplayTransform::GetTransformForRendering()
  5531. {
  5532. if (!mFrame->HasPerspective() || mTransformGetter || mIsTransformSeparator) {
  5533. return GetTransform();
  5534. }
  5535. MOZ_ASSERT(!mTransformGetter);
  5536. float scale = mFrame->PresContext()->AppUnitsPerDevPixel();
  5537. // Don't include perspective transform, or the offset to origin, since
  5538. // nsDisplayPerspective will handle both of those.
  5539. return GetResultingTransformMatrix(mFrame, ToReferenceFrame(), scale, 0);
  5540. }
  5541. const Matrix4x4&
  5542. nsDisplayTransform::GetAccumulatedPreserved3DTransform(nsDisplayListBuilder* aBuilder)
  5543. {
  5544. MOZ_ASSERT(!mFrame->Extend3DContext() || IsLeafOf3DContext());
  5545. // XXX: should go back to fix mTransformGetter.
  5546. if (!mTransformPreserves3DInited) {
  5547. mTransformPreserves3DInited = true;
  5548. if (!IsLeafOf3DContext()) {
  5549. mTransformPreserves3D = GetTransform();
  5550. return mTransformPreserves3D;
  5551. }
  5552. const nsIFrame* establisher; // Establisher of the 3D rendering context.
  5553. for (establisher = mFrame;
  5554. establisher && establisher->Combines3DTransformWithAncestors();
  5555. establisher = nsLayoutUtils::GetCrossDocParentFrame(establisher)) {
  5556. }
  5557. const nsIFrame* establisherReference =
  5558. aBuilder->FindReferenceFrameFor(nsLayoutUtils::GetCrossDocParentFrame(establisher));
  5559. nsPoint offset = establisher->GetOffsetToCrossDoc(establisherReference);
  5560. float scale = mFrame->PresContext()->AppUnitsPerDevPixel();
  5561. uint32_t flags = INCLUDE_PRESERVE3D_ANCESTORS|INCLUDE_PERSPECTIVE|OFFSET_BY_ORIGIN;
  5562. mTransformPreserves3D =
  5563. GetResultingTransformMatrix(mFrame, offset, scale, flags);
  5564. }
  5565. return mTransformPreserves3D;
  5566. }
  5567. bool
  5568. nsDisplayTransform::ShouldBuildLayerEvenIfInvisible(nsDisplayListBuilder* aBuilder)
  5569. {
  5570. // The visible rect of a Preserves-3D frame is just an intermediate
  5571. // result. It should always build a layer to make sure it is
  5572. // rendering correctly.
  5573. return MayBeAnimated(aBuilder) || mFrame->Combines3DTransformWithAncestors();
  5574. }
  5575. already_AddRefed<Layer> nsDisplayTransform::BuildLayer(nsDisplayListBuilder *aBuilder,
  5576. LayerManager *aManager,
  5577. const ContainerLayerParameters& aContainerParameters)
  5578. {
  5579. // While generating a glyph mask, the transform vector of the root frame had
  5580. // been applied into the target context, so stop applying it again here.
  5581. const bool shouldSkipTransform =
  5582. (aBuilder->RootReferenceFrame() == mFrame) &&
  5583. (aBuilder->IsForGenerateGlyphMask() || aBuilder->IsForPaintingSelectionBG());
  5584. /* For frames without transform, it would not be removed for
  5585. * backface hidden here. But, it would be removed by the init
  5586. * function of nsDisplayTransform.
  5587. */
  5588. const Matrix4x4& newTransformMatrix =
  5589. shouldSkipTransform ? Matrix4x4(): GetTransformForRendering();
  5590. uint32_t flags = FrameLayerBuilder::CONTAINER_ALLOW_PULL_BACKGROUND_COLOR;
  5591. RefPtr<ContainerLayer> container = aManager->GetLayerBuilder()->
  5592. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, mStoredList.GetChildren(),
  5593. aContainerParameters, &newTransformMatrix, flags);
  5594. if (!container) {
  5595. return nullptr;
  5596. }
  5597. // Add the preserve-3d flag for this layer, BuildContainerLayerFor clears all flags,
  5598. // so we never need to explicitely unset this flag.
  5599. if (mFrame->Extend3DContext() && !mNoExtendContext) {
  5600. container->SetContentFlags(container->GetContentFlags() | Layer::CONTENT_EXTEND_3D_CONTEXT);
  5601. } else {
  5602. container->SetContentFlags(container->GetContentFlags() & ~Layer::CONTENT_EXTEND_3D_CONTEXT);
  5603. }
  5604. nsDisplayListBuilder::AddAnimationsAndTransitionsToLayer(container, aBuilder,
  5605. this, mFrame,
  5606. eCSSProperty_transform);
  5607. if (mIsFullyVisible && MayBeAnimated(aBuilder)) {
  5608. // Only allow async updates to the transform if we're an animated layer, since that's what
  5609. // triggers us to set the correct AGR in the constructor and makes sure FrameLayerBuilder
  5610. // won't compute occlusions for this layer.
  5611. container->SetUserData(nsIFrame::LayerIsPrerenderedDataKey(),
  5612. /*the value is irrelevant*/nullptr);
  5613. container->SetContentFlags(container->GetContentFlags() | Layer::CONTENT_MAY_CHANGE_TRANSFORM);
  5614. } else {
  5615. container->RemoveUserData(nsIFrame::LayerIsPrerenderedDataKey());
  5616. container->SetContentFlags(container->GetContentFlags() & ~Layer::CONTENT_MAY_CHANGE_TRANSFORM);
  5617. }
  5618. return container.forget();
  5619. }
  5620. bool
  5621. nsDisplayTransform::MayBeAnimated(nsDisplayListBuilder* aBuilder)
  5622. {
  5623. // Here we check if the *post-transform* bounds of this item are big enough
  5624. // to justify an active layer.
  5625. if (ActiveLayerTracker::IsStyleAnimated(aBuilder,
  5626. mFrame,
  5627. eCSSProperty_transform) ||
  5628. EffectCompositor::HasAnimationsForCompositor(mFrame,
  5629. eCSSProperty_transform)) {
  5630. if (!IsItemTooSmallForActiveLayer(mFrame)) {
  5631. return true;
  5632. }
  5633. SetAnimationPerformanceWarningForTooSmallItem(mFrame, eCSSProperty_transform);
  5634. }
  5635. return false;
  5636. }
  5637. nsDisplayItem::LayerState
  5638. nsDisplayTransform::GetLayerState(nsDisplayListBuilder* aBuilder,
  5639. LayerManager* aManager,
  5640. const ContainerLayerParameters& aParameters) {
  5641. // If the transform is 3d, the layer takes part in preserve-3d
  5642. // sorting, or the layer is a separator then we *always* want this
  5643. // to be an active layer.
  5644. if (!GetTransform().Is2D() || mFrame->Combines3DTransformWithAncestors() ||
  5645. mIsTransformSeparator) {
  5646. return LAYER_ACTIVE_FORCE;
  5647. }
  5648. if (MayBeAnimated(aBuilder)) {
  5649. // Returns LAYER_ACTIVE_FORCE to avoid flatterning the layer for async
  5650. // animations.
  5651. return LAYER_ACTIVE_FORCE;
  5652. }
  5653. // Expect the child display items to have this frame as their animated
  5654. // geometry root (since it will be their reference frame). If they have a
  5655. // different animated geometry root, we'll make this an active layer so the
  5656. // animation can be accelerated.
  5657. return RequiredLayerStateForChildren(aBuilder, aManager, aParameters,
  5658. *mStoredList.GetChildren(), mAnimatedGeometryRootForChildren);
  5659. }
  5660. bool nsDisplayTransform::ComputeVisibility(nsDisplayListBuilder *aBuilder,
  5661. nsRegion *aVisibleRegion)
  5662. {
  5663. /* As we do this, we need to be sure to
  5664. * untransform the visible rect, since we want everything that's painting to
  5665. * think that it's painting in its original rectangular coordinate space.
  5666. * If we can't untransform, take the entire overflow rect */
  5667. nsRect untransformedVisibleRect;
  5668. if (!UntransformVisibleRect(aBuilder, &untransformedVisibleRect))
  5669. {
  5670. untransformedVisibleRect = mFrame->GetVisualOverflowRectRelativeToSelf();
  5671. }
  5672. nsRegion untransformedVisible = untransformedVisibleRect;
  5673. // Call RecomputeVisiblity instead of ComputeVisibility since
  5674. // nsDisplayItem::ComputeVisibility should only be called from
  5675. // nsDisplayList::ComputeVisibility (which sets mVisibleRect on the item)
  5676. mStoredList.RecomputeVisibility(aBuilder, &untransformedVisible);
  5677. return true;
  5678. }
  5679. #ifdef DEBUG_HIT
  5680. #include <time.h>
  5681. #endif
  5682. /* HitTest does some fun stuff with matrix transforms to obtain the answer. */
  5683. void nsDisplayTransform::HitTest(nsDisplayListBuilder *aBuilder,
  5684. const nsRect& aRect,
  5685. HitTestState *aState,
  5686. nsTArray<nsIFrame*> *aOutFrames)
  5687. {
  5688. if (aState->mInPreserves3D) {
  5689. mStoredList.HitTest(aBuilder, aRect, aState, aOutFrames);
  5690. return;
  5691. }
  5692. /* Here's how this works:
  5693. * 1. Get the matrix. If it's singular, abort (clearly we didn't hit
  5694. * anything).
  5695. * 2. Invert the matrix.
  5696. * 3. Use it to transform the rect into the correct space.
  5697. * 4. Pass that rect down through to the list's version of HitTest.
  5698. */
  5699. // GetTransform always operates in dev pixels.
  5700. float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  5701. Matrix4x4 matrix = GetAccumulatedPreserved3DTransform(aBuilder);
  5702. if (!IsFrameVisible(mFrame, matrix)) {
  5703. return;
  5704. }
  5705. /* We want to go from transformed-space to regular space.
  5706. * Thus we have to invert the matrix, which normally does
  5707. * the reverse operation (e.g. regular->transformed)
  5708. */
  5709. /* Now, apply the transform and pass it down the channel. */
  5710. matrix.Invert();
  5711. nsRect resultingRect;
  5712. if (aRect.width == 1 && aRect.height == 1) {
  5713. // Magic width/height indicating we're hit testing a point, not a rect
  5714. Point4D point = matrix.ProjectPoint(Point(NSAppUnitsToFloatPixels(aRect.x, factor),
  5715. NSAppUnitsToFloatPixels(aRect.y, factor)));
  5716. if (!point.HasPositiveWCoord()) {
  5717. return;
  5718. }
  5719. Point point2d = point.As2DPoint();
  5720. resultingRect = nsRect(NSFloatPixelsToAppUnits(float(point2d.x), factor),
  5721. NSFloatPixelsToAppUnits(float(point2d.y), factor),
  5722. 1, 1);
  5723. } else {
  5724. Rect originalRect(NSAppUnitsToFloatPixels(aRect.x, factor),
  5725. NSAppUnitsToFloatPixels(aRect.y, factor),
  5726. NSAppUnitsToFloatPixels(aRect.width, factor),
  5727. NSAppUnitsToFloatPixels(aRect.height, factor));
  5728. bool snap;
  5729. nsRect childBounds = mStoredList.GetBounds(aBuilder, &snap);
  5730. Rect childGfxBounds(NSAppUnitsToFloatPixels(childBounds.x, factor),
  5731. NSAppUnitsToFloatPixels(childBounds.y, factor),
  5732. NSAppUnitsToFloatPixels(childBounds.width, factor),
  5733. NSAppUnitsToFloatPixels(childBounds.height, factor));
  5734. Rect rect = matrix.ProjectRectBounds(originalRect, childGfxBounds);
  5735. resultingRect = nsRect(NSFloatPixelsToAppUnits(float(rect.X()), factor),
  5736. NSFloatPixelsToAppUnits(float(rect.Y()), factor),
  5737. NSFloatPixelsToAppUnits(float(rect.Width()), factor),
  5738. NSFloatPixelsToAppUnits(float(rect.Height()), factor));
  5739. }
  5740. if (resultingRect.IsEmpty()) {
  5741. return;
  5742. }
  5743. #ifdef DEBUG_HIT
  5744. printf("Frame: %p\n", dynamic_cast<void *>(mFrame));
  5745. printf(" Untransformed point: (%f, %f)\n", resultingRect.X(), resultingRect.Y());
  5746. uint32_t originalFrameCount = aOutFrames.Length();
  5747. #endif
  5748. mStoredList.HitTest(aBuilder, resultingRect, aState, aOutFrames);
  5749. #ifdef DEBUG_HIT
  5750. if (originalFrameCount != aOutFrames.Length())
  5751. printf(" Hit! Time: %f, first frame: %p\n", static_cast<double>(clock()),
  5752. dynamic_cast<void *>(aOutFrames.ElementAt(0)));
  5753. printf("=== end of hit test ===\n");
  5754. #endif
  5755. }
  5756. float
  5757. nsDisplayTransform::GetHitDepthAtPoint(nsDisplayListBuilder* aBuilder, const nsPoint& aPoint)
  5758. {
  5759. // GetTransform always operates in dev pixels.
  5760. float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  5761. Matrix4x4 matrix = GetAccumulatedPreserved3DTransform(aBuilder);
  5762. NS_ASSERTION(IsFrameVisible(mFrame, matrix),
  5763. "We can't have hit a frame that isn't visible!");
  5764. Matrix4x4 inverse = matrix;
  5765. inverse.Invert();
  5766. Point4D point = inverse.ProjectPoint(Point(NSAppUnitsToFloatPixels(aPoint.x, factor),
  5767. NSAppUnitsToFloatPixels(aPoint.y, factor)));
  5768. Point point2d = point.As2DPoint();
  5769. Point3D transformed = matrix.TransformPoint(Point3D(point2d.x, point2d.y, 0));
  5770. return transformed.z;
  5771. }
  5772. /* The bounding rectangle for the object is the overflow rectangle translated
  5773. * by the reference point.
  5774. */
  5775. nsRect
  5776. nsDisplayTransform::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
  5777. {
  5778. *aSnap = false;
  5779. if (mHasBounds) {
  5780. return mBounds;
  5781. }
  5782. if (mFrame->Extend3DContext() && !mIsTransformSeparator) {
  5783. return nsRect();
  5784. }
  5785. nsRect untransformedBounds = mStoredList.GetBounds(aBuilder, aSnap);
  5786. // GetTransform always operates in dev pixels.
  5787. float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  5788. mBounds = nsLayoutUtils::MatrixTransformRect(untransformedBounds,
  5789. GetTransform(),
  5790. factor);
  5791. mHasBounds = true;
  5792. return mBounds;
  5793. }
  5794. void
  5795. nsDisplayTransform::ComputeBounds(nsDisplayListBuilder* aBuilder)
  5796. {
  5797. MOZ_ASSERT(mFrame->Extend3DContext() || IsLeafOf3DContext());
  5798. /* For some cases, the transform would make an empty bounds, but it
  5799. * may be turned back again to get a non-empty bounds. We should
  5800. * not depend on transforming bounds level by level.
  5801. *
  5802. * Here, it applies accumulated transforms on the leaf frames of the
  5803. * 3d rendering context, and track and accmulate bounds at
  5804. * nsDisplayListBuilder.
  5805. */
  5806. nsDisplayListBuilder::AutoAccumulateTransform accTransform(aBuilder);
  5807. accTransform.Accumulate(GetTransform());
  5808. if (!IsLeafOf3DContext()) {
  5809. // Do not dive into another 3D context.
  5810. mStoredList.DoUpdateBoundsPreserves3D(aBuilder);
  5811. }
  5812. /* For Preserves3D, it is bounds of only children as leaf frames.
  5813. * For non-leaf frames, their bounds are accumulated and kept at
  5814. * nsDisplayListBuilder.
  5815. */
  5816. bool snap;
  5817. nsRect untransformedBounds = mStoredList.GetBounds(aBuilder, &snap);
  5818. // GetTransform always operates in dev pixels.
  5819. float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  5820. nsRect rect =
  5821. nsLayoutUtils::MatrixTransformRect(untransformedBounds,
  5822. accTransform.GetCurrentTransform(),
  5823. factor);
  5824. aBuilder->AccumulateRect(rect);
  5825. }
  5826. /* The transform is opaque iff the transform consists solely of scales and
  5827. * translations and if the underlying content is opaque. Thus if the transform
  5828. * is of the form
  5829. *
  5830. * |a c e|
  5831. * |b d f|
  5832. * |0 0 1|
  5833. *
  5834. * We need b and c to be zero.
  5835. *
  5836. * We also need to check whether the underlying opaque content completely fills
  5837. * our visible rect. We use UntransformRect which expands to the axis-aligned
  5838. * bounding rect, but that's OK since if
  5839. * mStoredList.GetVisibleRect().Contains(untransformedVisible), then it
  5840. * certainly contains the actual (non-axis-aligned) untransformed rect.
  5841. */
  5842. nsRegion nsDisplayTransform::GetOpaqueRegion(nsDisplayListBuilder *aBuilder,
  5843. bool* aSnap)
  5844. {
  5845. *aSnap = false;
  5846. nsRect untransformedVisible;
  5847. if (!UntransformVisibleRect(aBuilder, &untransformedVisible)) {
  5848. return nsRegion();
  5849. }
  5850. const Matrix4x4& matrix = GetTransform();
  5851. nsRegion result;
  5852. Matrix matrix2d;
  5853. bool tmpSnap;
  5854. if (matrix.Is2D(&matrix2d) &&
  5855. matrix2d.PreservesAxisAlignedRectangles() &&
  5856. mStoredList.GetOpaqueRegion(aBuilder, &tmpSnap).Contains(untransformedVisible)) {
  5857. result = mVisibleRect.Intersect(GetBounds(aBuilder, &tmpSnap));
  5858. }
  5859. return result;
  5860. }
  5861. /* The transform is uniform if it fills the entire bounding rect and the
  5862. * wrapped list is uniform. See GetOpaqueRegion for discussion of why this
  5863. * works.
  5864. */
  5865. Maybe<nscolor>
  5866. nsDisplayTransform::IsUniform(nsDisplayListBuilder *aBuilder)
  5867. {
  5868. nsRect untransformedVisible;
  5869. if (!UntransformVisibleRect(aBuilder, &untransformedVisible)) {
  5870. return Nothing();
  5871. }
  5872. const Matrix4x4& matrix = GetTransform();
  5873. Matrix matrix2d;
  5874. if (matrix.Is2D(&matrix2d) &&
  5875. matrix2d.PreservesAxisAlignedRectangles() &&
  5876. mStoredList.GetVisibleRect().Contains(untransformedVisible)) {
  5877. return mStoredList.IsUniform(aBuilder);
  5878. }
  5879. return Nothing();
  5880. }
  5881. /* If UNIFIED_CONTINUATIONS is defined, we can merge two display lists that
  5882. * share the same underlying content. Otherwise, doing so results in graphical
  5883. * glitches.
  5884. */
  5885. #ifndef UNIFIED_CONTINUATIONS
  5886. bool
  5887. nsDisplayTransform::TryMerge(nsDisplayItem *aItem)
  5888. {
  5889. return false;
  5890. }
  5891. #else
  5892. bool
  5893. nsDisplayTransform::TryMerge(nsDisplayItem *aItem)
  5894. {
  5895. NS_PRECONDITION(aItem, "Why did you try merging with a null item?");
  5896. /* Make sure that we're dealing with two transforms. */
  5897. if (aItem->GetType() != TYPE_TRANSFORM)
  5898. return false;
  5899. /* Check to see that both frames are part of the same content. */
  5900. if (aItem->Frame()->GetContent() != mFrame->GetContent())
  5901. return false;
  5902. if (aItem->GetClip() != GetClip())
  5903. return false;
  5904. if (aItem->ScrollClip() != ScrollClip())
  5905. return false;
  5906. /* Now, move everything over to this frame and signal that
  5907. * we merged things!
  5908. */
  5909. mStoredList.MergeFromTrackingMergedFrames(&static_cast<nsDisplayTransform*>(aItem)->mStoredList);
  5910. return true;
  5911. }
  5912. #endif
  5913. /* TransformRect takes in as parameters a rectangle (in app space) and returns
  5914. * the smallest rectangle (in app space) containing the transformed image of
  5915. * that rectangle. That is, it takes the four corners of the rectangle,
  5916. * transforms them according to the matrix associated with the specified frame,
  5917. * then returns the smallest rectangle containing the four transformed points.
  5918. *
  5919. * @param aUntransformedBounds The rectangle (in app units) to transform.
  5920. * @param aFrame The frame whose transformation should be applied.
  5921. * @param aOrigin The delta from the frame origin to the coordinate space origin
  5922. * @param aBoundsOverride (optional) Force the frame bounds to be the
  5923. * specified bounds.
  5924. * @return The smallest rectangle containing the image of the transformed
  5925. * rectangle.
  5926. */
  5927. nsRect nsDisplayTransform::TransformRect(const nsRect &aUntransformedBounds,
  5928. const nsIFrame* aFrame,
  5929. const nsRect* aBoundsOverride)
  5930. {
  5931. NS_PRECONDITION(aFrame, "Can't take the transform based on a null frame!");
  5932. float factor = aFrame->PresContext()->AppUnitsPerDevPixel();
  5933. uint32_t flags = INCLUDE_PERSPECTIVE|OFFSET_BY_ORIGIN|INCLUDE_PRESERVE3D_ANCESTORS;
  5934. return nsLayoutUtils::MatrixTransformRect
  5935. (aUntransformedBounds,
  5936. GetResultingTransformMatrix(aFrame, nsPoint(0, 0), factor, flags, aBoundsOverride),
  5937. factor);
  5938. }
  5939. bool nsDisplayTransform::UntransformRect(const nsRect &aTransformedBounds,
  5940. const nsRect &aChildBounds,
  5941. const nsIFrame* aFrame,
  5942. nsRect *aOutRect)
  5943. {
  5944. NS_PRECONDITION(aFrame, "Can't take the transform based on a null frame!");
  5945. float factor = aFrame->PresContext()->AppUnitsPerDevPixel();
  5946. uint32_t flags = INCLUDE_PERSPECTIVE|OFFSET_BY_ORIGIN|INCLUDE_PRESERVE3D_ANCESTORS;
  5947. Matrix4x4 transform = GetResultingTransformMatrix(aFrame, nsPoint(0, 0), factor, flags);
  5948. if (transform.IsSingular()) {
  5949. return false;
  5950. }
  5951. RectDouble result(NSAppUnitsToFloatPixels(aTransformedBounds.x, factor),
  5952. NSAppUnitsToFloatPixels(aTransformedBounds.y, factor),
  5953. NSAppUnitsToFloatPixels(aTransformedBounds.width, factor),
  5954. NSAppUnitsToFloatPixels(aTransformedBounds.height, factor));
  5955. RectDouble childGfxBounds(NSAppUnitsToFloatPixels(aChildBounds.x, factor),
  5956. NSAppUnitsToFloatPixels(aChildBounds.y, factor),
  5957. NSAppUnitsToFloatPixels(aChildBounds.width, factor),
  5958. NSAppUnitsToFloatPixels(aChildBounds.height, factor));
  5959. result = transform.Inverse().ProjectRectBounds(result, childGfxBounds);
  5960. *aOutRect = nsLayoutUtils::RoundGfxRectToAppRect(ThebesRect(result), factor);
  5961. return true;
  5962. }
  5963. bool nsDisplayTransform::UntransformVisibleRect(nsDisplayListBuilder* aBuilder,
  5964. nsRect *aOutRect)
  5965. {
  5966. const Matrix4x4& matrix = GetTransform();
  5967. if (matrix.IsSingular())
  5968. return false;
  5969. // GetTransform always operates in dev pixels.
  5970. float factor = mFrame->PresContext()->AppUnitsPerDevPixel();
  5971. RectDouble result(NSAppUnitsToFloatPixels(mVisibleRect.x, factor),
  5972. NSAppUnitsToFloatPixels(mVisibleRect.y, factor),
  5973. NSAppUnitsToFloatPixels(mVisibleRect.width, factor),
  5974. NSAppUnitsToFloatPixels(mVisibleRect.height, factor));
  5975. bool snap;
  5976. nsRect childBounds = mStoredList.GetBounds(aBuilder, &snap);
  5977. RectDouble childGfxBounds(NSAppUnitsToFloatPixels(childBounds.x, factor),
  5978. NSAppUnitsToFloatPixels(childBounds.y, factor),
  5979. NSAppUnitsToFloatPixels(childBounds.width, factor),
  5980. NSAppUnitsToFloatPixels(childBounds.height, factor));
  5981. /* We want to untransform the matrix, so invert the transformation first! */
  5982. result = matrix.Inverse().ProjectRectBounds(result, childGfxBounds);
  5983. *aOutRect = nsLayoutUtils::RoundGfxRectToAppRect(ThebesRect(result), factor);
  5984. return true;
  5985. }
  5986. void
  5987. nsDisplayTransform::WriteDebugInfo(std::stringstream& aStream)
  5988. {
  5989. AppendToString(aStream, GetTransform());
  5990. if (IsTransformSeparator()) {
  5991. aStream << " transform-separator";
  5992. }
  5993. if (IsLeafOf3DContext()) {
  5994. aStream << " 3d-context-leaf";
  5995. }
  5996. if (mFrame->Extend3DContext()) {
  5997. aStream << " extends-3d-context";
  5998. }
  5999. if (mFrame->Combines3DTransformWithAncestors()) {
  6000. aStream << " combines-3d-with-ancestors";
  6001. }
  6002. }
  6003. nsDisplayPerspective::nsDisplayPerspective(nsDisplayListBuilder* aBuilder,
  6004. nsIFrame* aTransformFrame,
  6005. nsIFrame* aPerspectiveFrame,
  6006. nsDisplayList* aList)
  6007. : nsDisplayItem(aBuilder, aPerspectiveFrame)
  6008. , mList(aBuilder, aPerspectiveFrame, aList)
  6009. , mTransformFrame(aTransformFrame)
  6010. , mIndex(aBuilder->AllocatePerspectiveItemIndex())
  6011. {
  6012. MOZ_ASSERT(mList.GetChildren()->Count() == 1);
  6013. MOZ_ASSERT(mList.GetChildren()->GetTop()->GetType() == TYPE_TRANSFORM);
  6014. }
  6015. already_AddRefed<Layer>
  6016. nsDisplayPerspective::BuildLayer(nsDisplayListBuilder *aBuilder,
  6017. LayerManager *aManager,
  6018. const ContainerLayerParameters& aContainerParameters)
  6019. {
  6020. float appUnitsPerPixel = mFrame->PresContext()->AppUnitsPerDevPixel();
  6021. Matrix4x4 perspectiveMatrix;
  6022. DebugOnly<bool> hasPerspective =
  6023. nsDisplayTransform::ComputePerspectiveMatrix(mTransformFrame, appUnitsPerPixel,
  6024. perspectiveMatrix);
  6025. MOZ_ASSERT(hasPerspective, "Why did we create nsDisplayPerspective?");
  6026. /*
  6027. * ClipListToRange can remove our child after we were created.
  6028. */
  6029. if (!mList.GetChildren()->GetTop()) {
  6030. return nullptr;
  6031. }
  6032. /*
  6033. * The resulting matrix is still in the coordinate space of the transformed
  6034. * frame. Append a translation to the reference frame coordinates.
  6035. */
  6036. nsDisplayTransform* transform =
  6037. static_cast<nsDisplayTransform*>(mList.GetChildren()->GetTop());
  6038. Point3D newOrigin =
  6039. Point3D(NSAppUnitsToFloatPixels(transform->ToReferenceFrame().x, appUnitsPerPixel),
  6040. NSAppUnitsToFloatPixels(transform->ToReferenceFrame().y, appUnitsPerPixel),
  6041. 0.0f);
  6042. Point3D roundedOrigin(NS_round(newOrigin.x),
  6043. NS_round(newOrigin.y),
  6044. 0);
  6045. perspectiveMatrix.PostTranslate(roundedOrigin);
  6046. RefPtr<ContainerLayer> container = aManager->GetLayerBuilder()->
  6047. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, mList.GetChildren(),
  6048. aContainerParameters, &perspectiveMatrix, 0);
  6049. if (!container) {
  6050. return nullptr;
  6051. }
  6052. // Sort of a lie, but we want to pretend that the perspective layer extends a 3d context
  6053. // so that it gets its transform combined with children. Might need a better name that reflects
  6054. // this use case and isn't specific to preserve-3d.
  6055. container->SetContentFlags(container->GetContentFlags() | Layer::CONTENT_EXTEND_3D_CONTEXT);
  6056. container->SetTransformIsPerspective(true);
  6057. return container.forget();
  6058. }
  6059. LayerState
  6060. nsDisplayPerspective::GetLayerState(nsDisplayListBuilder* aBuilder,
  6061. LayerManager* aManager,
  6062. const ContainerLayerParameters& aParameters)
  6063. {
  6064. return LAYER_ACTIVE_FORCE;
  6065. }
  6066. int32_t
  6067. nsDisplayPerspective::ZIndex() const
  6068. {
  6069. return ZIndexForFrame(mTransformFrame);
  6070. }
  6071. nsDisplayItemGeometry*
  6072. nsCharClipDisplayItem::AllocateGeometry(nsDisplayListBuilder* aBuilder)
  6073. {
  6074. return new nsCharClipGeometry(this, aBuilder);
  6075. }
  6076. void
  6077. nsCharClipDisplayItem::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  6078. const nsDisplayItemGeometry* aGeometry,
  6079. nsRegion* aInvalidRegion)
  6080. {
  6081. const nsCharClipGeometry* geometry = static_cast<const nsCharClipGeometry*>(aGeometry);
  6082. bool snap;
  6083. nsRect newRect = geometry->mBounds;
  6084. nsRect oldRect = GetBounds(aBuilder, &snap);
  6085. if (mVisIStartEdge != geometry->mVisIStartEdge ||
  6086. mVisIEndEdge != geometry->mVisIEndEdge ||
  6087. !oldRect.IsEqualInterior(newRect) ||
  6088. !geometry->mBorderRect.IsEqualInterior(GetBorderRect())) {
  6089. aInvalidRegion->Or(oldRect, newRect);
  6090. }
  6091. }
  6092. nsDisplaySVGEffects::nsDisplaySVGEffects(nsDisplayListBuilder* aBuilder,
  6093. nsIFrame* aFrame, nsDisplayList* aList,
  6094. bool aHandleOpacity,
  6095. const DisplayItemScrollClip* aScrollClip)
  6096. : nsDisplayWrapList(aBuilder, aFrame, aList, aScrollClip)
  6097. , mEffectsBounds(aFrame->GetVisualOverflowRectRelativeToSelf())
  6098. , mHandleOpacity(aHandleOpacity)
  6099. {
  6100. MOZ_COUNT_CTOR(nsDisplaySVGEffects);
  6101. }
  6102. nsDisplaySVGEffects::nsDisplaySVGEffects(nsDisplayListBuilder* aBuilder,
  6103. nsIFrame* aFrame, nsDisplayList* aList,
  6104. bool aHandleOpacity)
  6105. : nsDisplayWrapList(aBuilder, aFrame, aList)
  6106. , mEffectsBounds(aFrame->GetVisualOverflowRectRelativeToSelf())
  6107. , mHandleOpacity(aHandleOpacity)
  6108. {
  6109. MOZ_COUNT_CTOR(nsDisplaySVGEffects);
  6110. }
  6111. #ifdef NS_BUILD_REFCNT_LOGGING
  6112. nsDisplaySVGEffects::~nsDisplaySVGEffects()
  6113. {
  6114. MOZ_COUNT_DTOR(nsDisplaySVGEffects);
  6115. }
  6116. #endif
  6117. nsRegion nsDisplaySVGEffects::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
  6118. bool* aSnap)
  6119. {
  6120. *aSnap = false;
  6121. return nsRegion();
  6122. }
  6123. void
  6124. nsDisplaySVGEffects::HitTest(nsDisplayListBuilder* aBuilder, const nsRect& aRect,
  6125. HitTestState* aState, nsTArray<nsIFrame*> *aOutFrames)
  6126. {
  6127. nsPoint rectCenter(aRect.x + aRect.width / 2, aRect.y + aRect.height / 2);
  6128. if (nsSVGIntegrationUtils::HitTestFrameForEffects(mFrame,
  6129. rectCenter - ToReferenceFrame())) {
  6130. mList.HitTest(aBuilder, aRect, aState, aOutFrames);
  6131. }
  6132. }
  6133. gfxRect
  6134. nsDisplaySVGEffects::BBoxInUserSpace() const
  6135. {
  6136. return nsSVGUtils::GetBBox(mFrame);
  6137. }
  6138. gfxPoint
  6139. nsDisplaySVGEffects::UserSpaceOffset() const
  6140. {
  6141. return nsSVGUtils::FrameSpaceInCSSPxToUserSpaceOffset(mFrame);
  6142. }
  6143. void
  6144. nsDisplaySVGEffects::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  6145. const nsDisplayItemGeometry* aGeometry,
  6146. nsRegion* aInvalidRegion)
  6147. {
  6148. const nsDisplaySVGEffectGeometry* geometry =
  6149. static_cast<const nsDisplaySVGEffectGeometry*>(aGeometry);
  6150. bool snap;
  6151. nsRect bounds = GetBounds(aBuilder, &snap);
  6152. if (geometry->mFrameOffsetToReferenceFrame != ToReferenceFrame() ||
  6153. geometry->mUserSpaceOffset != UserSpaceOffset() ||
  6154. !geometry->mBBox.IsEqualInterior(BBoxInUserSpace())) {
  6155. // Filter and mask output can depend on the location of the frame's user
  6156. // space and on the frame's BBox. We need to invalidate if either of these
  6157. // change relative to the reference frame.
  6158. // Invalidations from our inactive layer manager are not enough to catch
  6159. // some of these cases because filters can produce output even if there's
  6160. // nothing in the filter input.
  6161. aInvalidRegion->Or(bounds, geometry->mBounds);
  6162. }
  6163. }
  6164. bool nsDisplaySVGEffects::ValidateSVGFrame()
  6165. {
  6166. const nsIContent* content = mFrame->GetContent();
  6167. bool hasSVGLayout = (mFrame->GetStateBits() & NS_FRAME_SVG_LAYOUT);
  6168. if (hasSVGLayout) {
  6169. nsISVGChildFrame *svgChildFrame = do_QueryFrame(mFrame);
  6170. if (!svgChildFrame || !mFrame->GetContent()->IsSVGElement()) {
  6171. NS_ASSERTION(false, "why?");
  6172. return false;
  6173. }
  6174. if (!static_cast<const nsSVGElement*>(content)->HasValidDimensions()) {
  6175. return false; // The SVG spec says not to draw filters for this
  6176. }
  6177. }
  6178. return true;
  6179. }
  6180. static IntRect
  6181. ComputeClipExtsInDeviceSpace(gfxContext& aCtx)
  6182. {
  6183. gfxContextMatrixAutoSaveRestore matRestore(&aCtx);
  6184. // Get the clip extents in device space.
  6185. aCtx.SetMatrix(gfxMatrix());
  6186. gfxRect clippedFrameSurfaceRect = aCtx.GetClipExtents();
  6187. clippedFrameSurfaceRect.RoundOut();
  6188. IntRect result;
  6189. ToRect(clippedFrameSurfaceRect).ToIntRect(&result);
  6190. return mozilla::gfx::Factory::CheckSurfaceSize(result.Size()) ? result
  6191. : IntRect();
  6192. }
  6193. typedef nsSVGIntegrationUtils::PaintFramesParams PaintFramesParams;
  6194. static nsPoint
  6195. ComputeOffsetToUserSpace(const PaintFramesParams& aParams)
  6196. {
  6197. nsIFrame* frame = aParams.frame;
  6198. nsPoint offsetToBoundingBox = aParams.builder->ToReferenceFrame(frame) -
  6199. nsSVGIntegrationUtils::GetOffsetToBoundingBox(frame);
  6200. if (!frame->IsFrameOfType(nsIFrame::eSVG)) {
  6201. // Snap the offset if the reference frame is not a SVG frame, since other
  6202. // frames will be snapped to pixel when rendering.
  6203. offsetToBoundingBox = nsPoint(
  6204. frame->PresContext()->RoundAppUnitsToNearestDevPixels(offsetToBoundingBox.x),
  6205. frame->PresContext()->RoundAppUnitsToNearestDevPixels(offsetToBoundingBox.y));
  6206. }
  6207. // After applying only "offsetToBoundingBox", aParams.ctx would have its
  6208. // origin at the top left corner of frame's bounding box (over all
  6209. // continuations).
  6210. // However, SVG painting needs the origin to be located at the origin of the
  6211. // SVG frame's "user space", i.e. the space in which, for example, the
  6212. // frame's BBox lives.
  6213. // SVG geometry frames and foreignObject frames apply their own offsets, so
  6214. // their position is relative to their user space. So for these frame types,
  6215. // if we want aCtx to be in user space, we first need to subtract the
  6216. // frame's position so that SVG painting can later add it again and the
  6217. // frame is painted in the right place.
  6218. gfxPoint toUserSpaceGfx = nsSVGUtils::FrameSpaceInCSSPxToUserSpaceOffset(frame);
  6219. nsPoint toUserSpace =
  6220. nsPoint(nsPresContext::CSSPixelsToAppUnits(float(toUserSpaceGfx.x)),
  6221. nsPresContext::CSSPixelsToAppUnits(float(toUserSpaceGfx.y)));
  6222. return (offsetToBoundingBox - toUserSpace);
  6223. }
  6224. static void
  6225. ComputeMaskGeometry(PaintFramesParams& aParams)
  6226. {
  6227. // Properties are added lazily and may have been removed by a restyle, so
  6228. // make sure all applicable ones are set again.
  6229. nsIFrame* firstFrame =
  6230. nsLayoutUtils::FirstContinuationOrIBSplitSibling(aParams.frame);
  6231. const nsStyleSVGReset *svgReset = firstFrame->StyleSVGReset();
  6232. nsSVGEffects::EffectProperties effectProperties =
  6233. nsSVGEffects::GetEffectProperties(firstFrame);
  6234. nsTArray<nsSVGMaskFrame *> maskFrames = effectProperties.GetMaskFrames();
  6235. if (maskFrames.Length() == 0) {
  6236. return;
  6237. }
  6238. gfxContext& ctx = aParams.ctx;
  6239. nsIFrame* frame = aParams.frame;
  6240. nsPoint offsetToUserSpace = ComputeOffsetToUserSpace(aParams);
  6241. gfxPoint devPixelOffsetToUserSpace =
  6242. nsLayoutUtils::PointToGfxPoint(offsetToUserSpace,
  6243. frame->PresContext()->AppUnitsPerDevPixel());
  6244. gfxContextMatrixAutoSaveRestore matSR(&ctx);
  6245. ctx.SetMatrix(ctx.CurrentMatrix().Translate(devPixelOffsetToUserSpace));
  6246. // Convert boaderArea and dirtyRect to user space.
  6247. int32_t appUnitsPerDevPixel = frame->PresContext()->AppUnitsPerDevPixel();
  6248. nsRect userSpaceBorderArea = aParams.borderArea - offsetToUserSpace;
  6249. nsRect userSpaceDirtyRect = aParams.dirtyRect - offsetToUserSpace;
  6250. // Union all mask layer rectangles in user space.
  6251. gfxRect maskInUserSpace;
  6252. for (size_t i = 0; i < maskFrames.Length() ; i++) {
  6253. nsSVGMaskFrame* maskFrame = maskFrames[i];
  6254. gfxRect currentMaskSurfaceRect;
  6255. if (maskFrame) {
  6256. currentMaskSurfaceRect = maskFrame->GetMaskArea(aParams.frame);
  6257. } else {
  6258. nsCSSRendering::ImageLayerClipState clipState;
  6259. nsCSSRendering::GetImageLayerClip(svgReset->mMask.mLayers[i],
  6260. frame,
  6261. *frame->StyleBorder(),
  6262. userSpaceBorderArea,
  6263. userSpaceDirtyRect,
  6264. false, /* aWillPaintBorder */
  6265. appUnitsPerDevPixel,
  6266. &clipState);
  6267. currentMaskSurfaceRect = clipState.mDirtyRectGfx;
  6268. }
  6269. maskInUserSpace = maskInUserSpace.Union(currentMaskSurfaceRect);
  6270. }
  6271. ctx.Save();
  6272. if (!maskInUserSpace.IsEmpty()) {
  6273. ctx.Clip(maskInUserSpace);
  6274. }
  6275. IntRect result = ComputeClipExtsInDeviceSpace(ctx);
  6276. ctx.Restore();
  6277. aParams.maskRect = result;
  6278. }
  6279. nsDisplayMask::nsDisplayMask(nsDisplayListBuilder* aBuilder,
  6280. nsIFrame* aFrame, nsDisplayList* aList,
  6281. bool aHandleOpacity,
  6282. const DisplayItemScrollClip* aScrollClip)
  6283. : nsDisplaySVGEffects(aBuilder, aFrame, aList, aHandleOpacity, aScrollClip)
  6284. {
  6285. MOZ_COUNT_CTOR(nsDisplayMask);
  6286. nsPresContext* presContext = mFrame->PresContext();
  6287. uint32_t flags = aBuilder->GetBackgroundPaintFlags() |
  6288. nsCSSRendering::PAINTBG_MASK_IMAGE;
  6289. const nsStyleSVGReset *svgReset = aFrame->StyleSVGReset();
  6290. NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, svgReset->mMask) {
  6291. bool isTransformedFixed;
  6292. nsBackgroundLayerState state =
  6293. nsCSSRendering::PrepareImageLayer(presContext, aFrame, flags,
  6294. mFrame->GetRectRelativeToSelf(),
  6295. mFrame->GetRectRelativeToSelf(),
  6296. svgReset->mMask.mLayers[i],
  6297. &isTransformedFixed);
  6298. mDestRects.AppendElement(state.mDestArea);
  6299. }
  6300. }
  6301. #ifdef NS_BUILD_REFCNT_LOGGING
  6302. nsDisplayMask::~nsDisplayMask()
  6303. {
  6304. MOZ_COUNT_DTOR(nsDisplayMask);
  6305. }
  6306. #endif
  6307. bool nsDisplayMask::TryMerge(nsDisplayItem* aItem)
  6308. {
  6309. if (aItem->GetType() != TYPE_MASK)
  6310. return false;
  6311. // items for the same content element should be merged into a single
  6312. // compositing group
  6313. // aItem->GetUnderlyingFrame() returns non-null because it's nsDisplaySVGEffects
  6314. if (aItem->Frame()->GetContent() != mFrame->GetContent()) {
  6315. return false;
  6316. }
  6317. if (aItem->GetClip() != GetClip()) {
  6318. return false;
  6319. }
  6320. if (aItem->ScrollClip() != ScrollClip()) {
  6321. return false;
  6322. }
  6323. // Do not merge if mFrame has mask. Continuation frames should apply mask
  6324. // independently(just like nsDisplayBackgroundImage).
  6325. const nsStyleSVGReset *style = mFrame->StyleSVGReset();
  6326. if (style->mMask.HasLayerWithImage()) {
  6327. return false;
  6328. }
  6329. nsDisplayMask* other = static_cast<nsDisplayMask*>(aItem);
  6330. MergeFromTrackingMergedFrames(other);
  6331. mEffectsBounds.UnionRect(mEffectsBounds,
  6332. other->mEffectsBounds + other->mFrame->GetOffsetTo(mFrame));
  6333. return true;
  6334. }
  6335. already_AddRefed<Layer>
  6336. nsDisplayMask::BuildLayer(nsDisplayListBuilder* aBuilder,
  6337. LayerManager* aManager,
  6338. const ContainerLayerParameters& aContainerParameters)
  6339. {
  6340. if (!ValidateSVGFrame()) {
  6341. return nullptr;
  6342. }
  6343. if (mFrame->StyleEffects()->mOpacity == 0.0f && mHandleOpacity) {
  6344. return nullptr;
  6345. }
  6346. nsIFrame* firstFrame =
  6347. nsLayoutUtils::FirstContinuationOrIBSplitSibling(mFrame);
  6348. nsSVGEffects::EffectProperties effectProperties =
  6349. nsSVGEffects::GetEffectProperties(firstFrame);
  6350. bool isOK = effectProperties.HasNoFilterOrHasValidFilter();
  6351. effectProperties.GetClipPathFrame(&isOK);
  6352. if (!isOK) {
  6353. return nullptr;
  6354. }
  6355. RefPtr<ContainerLayer> container = aManager->GetLayerBuilder()->
  6356. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, &mList,
  6357. aContainerParameters, nullptr);
  6358. return container.forget();
  6359. }
  6360. bool
  6361. nsDisplayMask::PaintMask(nsDisplayListBuilder* aBuilder,
  6362. gfxContext* aMaskContext)
  6363. {
  6364. MOZ_ASSERT(aMaskContext->GetDrawTarget()->GetFormat() == SurfaceFormat::A8);
  6365. nsRect borderArea = nsRect(ToReferenceFrame(), mFrame->GetSize());
  6366. nsSVGIntegrationUtils::PaintFramesParams params(*aMaskContext,
  6367. mFrame, mVisibleRect,
  6368. borderArea, aBuilder,
  6369. nullptr,
  6370. mHandleOpacity);
  6371. ComputeMaskGeometry(params);
  6372. image::DrawResult result = nsSVGIntegrationUtils::PaintMask(params);
  6373. nsDisplayMaskGeometry::UpdateDrawResult(this, result);
  6374. return (result == image::DrawResult::SUCCESS) ? true : false;
  6375. }
  6376. LayerState
  6377. nsDisplayMask::GetLayerState(nsDisplayListBuilder* aBuilder,
  6378. LayerManager* aManager,
  6379. const ContainerLayerParameters& aParameters)
  6380. {
  6381. if (ShouldPaintOnMaskLayer(aManager)) {
  6382. return RequiredLayerStateForChildren(aBuilder, aManager, aParameters,
  6383. mList, GetAnimatedGeometryRoot());
  6384. }
  6385. return LAYER_SVG_EFFECTS;
  6386. }
  6387. bool nsDisplayMask::ShouldPaintOnMaskLayer(LayerManager* aManager)
  6388. {
  6389. if (!aManager->IsCompositingCheap()) {
  6390. return false;
  6391. }
  6392. nsSVGUtils::MaskUsage maskUsage;
  6393. nsSVGUtils::DetermineMaskUsage(mFrame, mHandleOpacity, maskUsage);
  6394. if (!maskUsage.shouldGenerateMaskLayer ||
  6395. maskUsage.opacity != 1.0 || maskUsage.shouldApplyClipPath ||
  6396. maskUsage.shouldApplyBasicShape ||
  6397. maskUsage.shouldGenerateClipMaskLayer) {
  6398. return false;
  6399. }
  6400. if (!nsSVGIntegrationUtils::IsMaskResourceReady(mFrame)) {
  6401. return false;
  6402. }
  6403. // XXX temporary disable drawing SVG mask onto mask layer before bug 1313877
  6404. // been fixed.
  6405. nsIFrame* firstFrame =
  6406. nsLayoutUtils::FirstContinuationOrIBSplitSibling(mFrame);
  6407. nsSVGEffects::EffectProperties effectProperties =
  6408. nsSVGEffects::GetEffectProperties(firstFrame);
  6409. nsTArray<nsSVGMaskFrame *> maskFrames = effectProperties.GetMaskFrames();
  6410. for (size_t i = 0; i < maskFrames.Length() ; i++) {
  6411. nsSVGMaskFrame *maskFrame = maskFrames[i];
  6412. if (maskFrame) {
  6413. return false; // Found SVG mask.
  6414. }
  6415. }
  6416. if (gfxPrefs::DrawMaskLayer()) {
  6417. return false;
  6418. }
  6419. return true;
  6420. }
  6421. bool nsDisplayMask::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  6422. nsRegion* aVisibleRegion)
  6423. {
  6424. // Our children may be made translucent or arbitrarily deformed so we should
  6425. // not allow them to subtract area from aVisibleRegion.
  6426. nsRegion childrenVisible(mVisibleRect);
  6427. nsRect r = mVisibleRect.Intersect(mList.GetBounds(aBuilder));
  6428. mList.ComputeVisibilityForSublist(aBuilder, &childrenVisible, r);
  6429. return true;
  6430. }
  6431. void
  6432. nsDisplayMask::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  6433. const nsDisplayItemGeometry* aGeometry,
  6434. nsRegion* aInvalidRegion)
  6435. {
  6436. nsDisplaySVGEffects::ComputeInvalidationRegion(aBuilder, aGeometry,
  6437. aInvalidRegion);
  6438. const nsDisplayMaskGeometry* geometry =
  6439. static_cast<const nsDisplayMaskGeometry*>(aGeometry);
  6440. bool snap;
  6441. nsRect bounds = GetBounds(aBuilder, &snap);
  6442. if (mDestRects.Length() != geometry->mDestRects.Length()) {
  6443. aInvalidRegion->Or(bounds, geometry->mBounds);
  6444. } else {
  6445. for (size_t i = 0; i < mDestRects.Length(); i++) {
  6446. if (!mDestRects[i].IsEqualInterior(geometry->mDestRects[i])) {
  6447. aInvalidRegion->Or(bounds, geometry->mBounds);
  6448. break;
  6449. }
  6450. }
  6451. }
  6452. if (aBuilder->ShouldSyncDecodeImages() &&
  6453. geometry->ShouldInvalidateToSyncDecodeImages()) {
  6454. const nsStyleSVGReset *svgReset = mFrame->StyleSVGReset();
  6455. NS_FOR_VISIBLE_IMAGE_LAYERS_BACK_TO_FRONT(i, svgReset->mMask) {
  6456. const nsStyleImage& image = svgReset->mMask.mLayers[i].mImage;
  6457. if (image.GetType() == eStyleImageType_Image ) {
  6458. aInvalidRegion->Or(*aInvalidRegion, bounds);
  6459. break;
  6460. }
  6461. }
  6462. }
  6463. }
  6464. void
  6465. nsDisplayMask::PaintAsLayer(nsDisplayListBuilder* aBuilder,
  6466. nsRenderingContext* aCtx,
  6467. LayerManager* aManager)
  6468. {
  6469. MOZ_ASSERT(!ShouldPaintOnMaskLayer(aManager));
  6470. nsRect borderArea = nsRect(ToReferenceFrame(), mFrame->GetSize());
  6471. nsSVGIntegrationUtils::PaintFramesParams params(*aCtx->ThebesContext(),
  6472. mFrame, mVisibleRect,
  6473. borderArea, aBuilder,
  6474. aManager,
  6475. mHandleOpacity);
  6476. // Clip the drawing target by mVisibleRect, which contains the visible
  6477. // region of the target frame and its out-of-flow and inflow descendants.
  6478. gfxContext* context = aCtx->ThebesContext();
  6479. Rect bounds =
  6480. NSRectToRect(mVisibleRect, mFrame->PresContext()->AppUnitsPerDevPixel());
  6481. bounds.RoundOut();
  6482. context->Clip(bounds);
  6483. ComputeMaskGeometry(params);
  6484. image::DrawResult result =
  6485. nsSVGIntegrationUtils::PaintMaskAndClipPath(params);
  6486. context->PopClip();
  6487. nsDisplayMaskGeometry::UpdateDrawResult(this, result);
  6488. }
  6489. #ifdef MOZ_DUMP_PAINTING
  6490. void
  6491. nsDisplayMask::PrintEffects(nsACString& aTo)
  6492. {
  6493. nsIFrame* firstFrame =
  6494. nsLayoutUtils::FirstContinuationOrIBSplitSibling(mFrame);
  6495. nsSVGEffects::EffectProperties effectProperties =
  6496. nsSVGEffects::GetEffectProperties(firstFrame);
  6497. bool isOK = true;
  6498. nsSVGClipPathFrame *clipPathFrame = effectProperties.GetClipPathFrame(&isOK);
  6499. bool first = true;
  6500. aTo += " effects=(";
  6501. if (mFrame->StyleEffects()->mOpacity != 1.0f && mHandleOpacity) {
  6502. first = false;
  6503. aTo += nsPrintfCString("opacity(%f)", mFrame->StyleEffects()->mOpacity);
  6504. }
  6505. if (clipPathFrame) {
  6506. if (!first) {
  6507. aTo += ", ";
  6508. }
  6509. aTo += nsPrintfCString("clip(%s)", clipPathFrame->IsTrivial() ? "trivial" : "non-trivial");
  6510. first = false;
  6511. }
  6512. const nsStyleSVGReset *style = mFrame->StyleSVGReset();
  6513. if (style->HasClipPath() && !clipPathFrame) {
  6514. if (!first) {
  6515. aTo += ", ";
  6516. }
  6517. aTo += "clip(basic-shape)";
  6518. first = false;
  6519. }
  6520. if (effectProperties.GetFirstMaskFrame()) {
  6521. if (!first) {
  6522. aTo += ", ";
  6523. }
  6524. aTo += "mask";
  6525. }
  6526. aTo += ")";
  6527. }
  6528. #endif
  6529. nsDisplayFilter::nsDisplayFilter(nsDisplayListBuilder* aBuilder,
  6530. nsIFrame* aFrame, nsDisplayList* aList,
  6531. bool aHandleOpacity)
  6532. : nsDisplaySVGEffects(aBuilder, aFrame, aList, aHandleOpacity)
  6533. {
  6534. MOZ_COUNT_CTOR(nsDisplayFilter);
  6535. }
  6536. #ifdef NS_BUILD_REFCNT_LOGGING
  6537. nsDisplayFilter::~nsDisplayFilter()
  6538. {
  6539. MOZ_COUNT_DTOR(nsDisplayFilter);
  6540. }
  6541. #endif
  6542. already_AddRefed<Layer>
  6543. nsDisplayFilter::BuildLayer(nsDisplayListBuilder* aBuilder,
  6544. LayerManager* aManager,
  6545. const ContainerLayerParameters& aContainerParameters)
  6546. {
  6547. if (!ValidateSVGFrame()) {
  6548. return nullptr;
  6549. }
  6550. if (mFrame->StyleEffects()->mOpacity == 0.0f && mHandleOpacity) {
  6551. return nullptr;
  6552. }
  6553. nsIFrame* firstFrame =
  6554. nsLayoutUtils::FirstContinuationOrIBSplitSibling(mFrame);
  6555. nsSVGEffects::EffectProperties effectProperties =
  6556. nsSVGEffects::GetEffectProperties(firstFrame);
  6557. ContainerLayerParameters newContainerParameters = aContainerParameters;
  6558. if (effectProperties.HasValidFilter()) {
  6559. newContainerParameters.mDisableSubpixelAntialiasingInDescendants = true;
  6560. }
  6561. RefPtr<ContainerLayer> container = aManager->GetLayerBuilder()->
  6562. BuildContainerLayerFor(aBuilder, aManager, mFrame, this, &mList,
  6563. newContainerParameters, nullptr);
  6564. return container.forget();
  6565. }
  6566. bool nsDisplayFilter::TryMerge(nsDisplayItem* aItem)
  6567. {
  6568. if (aItem->GetType() != TYPE_FILTER) {
  6569. return false;
  6570. }
  6571. // items for the same content element should be merged into a single
  6572. // compositing group.
  6573. // aItem->Frame() returns non-null because it's nsDisplayFilter
  6574. if (aItem->Frame()->GetContent() != mFrame->GetContent()) {
  6575. return false;
  6576. }
  6577. if (aItem->GetClip() != GetClip()) {
  6578. return false;
  6579. }
  6580. if (aItem->ScrollClip() != ScrollClip()) {
  6581. return false;
  6582. }
  6583. nsDisplayFilter* other = static_cast<nsDisplayFilter*>(aItem);
  6584. MergeFromTrackingMergedFrames(other);
  6585. mEffectsBounds.UnionRect(mEffectsBounds,
  6586. other->mEffectsBounds + other->mFrame->GetOffsetTo(mFrame));
  6587. return true;
  6588. }
  6589. LayerState
  6590. nsDisplayFilter::GetLayerState(nsDisplayListBuilder* aBuilder,
  6591. LayerManager* aManager,
  6592. const ContainerLayerParameters& aParameters)
  6593. {
  6594. return LAYER_SVG_EFFECTS;
  6595. }
  6596. bool nsDisplayFilter::ComputeVisibility(nsDisplayListBuilder* aBuilder,
  6597. nsRegion* aVisibleRegion)
  6598. {
  6599. nsPoint offset = ToReferenceFrame();
  6600. nsRect dirtyRect =
  6601. nsSVGIntegrationUtils::GetRequiredSourceForInvalidArea(mFrame,
  6602. mVisibleRect - offset) +
  6603. offset;
  6604. // Our children may be made translucent or arbitrarily deformed so we should
  6605. // not allow them to subtract area from aVisibleRegion.
  6606. nsRegion childrenVisible(dirtyRect);
  6607. nsRect r = dirtyRect.Intersect(mList.GetBounds(aBuilder));
  6608. mList.ComputeVisibilityForSublist(aBuilder, &childrenVisible, r);
  6609. return true;
  6610. }
  6611. void
  6612. nsDisplayFilter::ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
  6613. const nsDisplayItemGeometry* aGeometry,
  6614. nsRegion* aInvalidRegion)
  6615. {
  6616. nsDisplaySVGEffects::ComputeInvalidationRegion(aBuilder, aGeometry,
  6617. aInvalidRegion);
  6618. const nsDisplayFilterGeometry* geometry =
  6619. static_cast<const nsDisplayFilterGeometry*>(aGeometry);
  6620. if (aBuilder->ShouldSyncDecodeImages() &&
  6621. geometry->ShouldInvalidateToSyncDecodeImages()) {
  6622. bool snap;
  6623. nsRect bounds = GetBounds(aBuilder, &snap);
  6624. aInvalidRegion->Or(*aInvalidRegion, bounds);
  6625. }
  6626. }
  6627. void
  6628. nsDisplayFilter::PaintAsLayer(nsDisplayListBuilder* aBuilder,
  6629. nsRenderingContext* aCtx,
  6630. LayerManager* aManager)
  6631. {
  6632. nsRect borderArea = nsRect(ToReferenceFrame(), mFrame->GetSize());
  6633. nsSVGIntegrationUtils::PaintFramesParams params(*aCtx->ThebesContext(),
  6634. mFrame, mVisibleRect,
  6635. borderArea, aBuilder,
  6636. aManager,
  6637. mHandleOpacity);
  6638. image::DrawResult result = nsSVGIntegrationUtils::PaintFilter(params);
  6639. nsDisplayFilterGeometry::UpdateDrawResult(this, result);
  6640. }
  6641. #ifdef MOZ_DUMP_PAINTING
  6642. void
  6643. nsDisplayFilter::PrintEffects(nsACString& aTo)
  6644. {
  6645. nsIFrame* firstFrame =
  6646. nsLayoutUtils::FirstContinuationOrIBSplitSibling(mFrame);
  6647. nsSVGEffects::EffectProperties effectProperties =
  6648. nsSVGEffects::GetEffectProperties(firstFrame);
  6649. bool first = true;
  6650. aTo += " effects=(";
  6651. if (mFrame->StyleEffects()->mOpacity != 1.0f && mHandleOpacity) {
  6652. first = false;
  6653. aTo += nsPrintfCString("opacity(%f)", mFrame->StyleEffects()->mOpacity);
  6654. }
  6655. if (effectProperties.HasValidFilter()) {
  6656. if (!first) {
  6657. aTo += ", ";
  6658. }
  6659. aTo += "filter";
  6660. }
  6661. aTo += ")";
  6662. }
  6663. #endif