display_server_windows.cpp 234 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409
  1. /**************************************************************************/
  2. /* display_server_windows.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "display_server_windows.h"
  31. #include "drop_target_windows.h"
  32. #include "os_windows.h"
  33. #include "scene/main/window.h"
  34. #include "wgl_detect_version.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/io/marshalls.h"
  37. #include "core/io/xml_parser.h"
  38. #include "core/version.h"
  39. #include "drivers/png/png_driver_common.h"
  40. #include "main/main.h"
  41. #include "scene/resources/texture.h"
  42. #include "servers/rendering/dummy/rasterizer_dummy.h"
  43. #if defined(VULKAN_ENABLED)
  44. #include "rendering_context_driver_vulkan_windows.h"
  45. #endif
  46. #if defined(D3D12_ENABLED)
  47. #include "drivers/d3d12/rendering_context_driver_d3d12.h"
  48. #endif
  49. #if defined(GLES3_ENABLED)
  50. #include "drivers/gles3/rasterizer_gles3.h"
  51. #endif
  52. #if defined(ACCESSKIT_ENABLED)
  53. #include "drivers/accesskit/accessibility_driver_accesskit.h"
  54. #endif
  55. #include <avrt.h>
  56. #include <dwmapi.h>
  57. #include <propkey.h>
  58. #include <propvarutil.h>
  59. #include <shellapi.h>
  60. #include <shellscalingapi.h>
  61. #include <shlwapi.h>
  62. #include <shobjidl.h>
  63. #include <wbemcli.h>
  64. #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
  65. #define DWMWA_USE_IMMERSIVE_DARK_MODE 20
  66. #endif
  67. #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1
  68. #define DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 19
  69. #endif
  70. #ifndef DWMWA_WINDOW_CORNER_PREFERENCE
  71. #define DWMWA_WINDOW_CORNER_PREFERENCE 33
  72. #endif
  73. #ifndef DWMWCP_DEFAULT
  74. #define DWMWCP_DEFAULT 0
  75. #endif
  76. #ifndef DWMWCP_DONOTROUND
  77. #define DWMWCP_DONOTROUND 1
  78. #endif
  79. #define WM_INDICATOR_CALLBACK_MESSAGE (WM_USER + 1)
  80. int constexpr FS_TRANSP_BORDER = 2;
  81. static String format_error_message(DWORD id) {
  82. LPWSTR messageBuffer = nullptr;
  83. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  84. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  85. String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
  86. LocalFree(messageBuffer);
  87. return msg;
  88. }
  89. static void track_mouse_leave_event(HWND hWnd) {
  90. TRACKMOUSEEVENT tme;
  91. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  92. tme.dwFlags = TME_LEAVE;
  93. tme.hwndTrack = hWnd;
  94. tme.dwHoverTime = HOVER_DEFAULT;
  95. TrackMouseEvent(&tme);
  96. }
  97. bool DisplayServerWindows::has_feature(Feature p_feature) const {
  98. switch (p_feature) {
  99. #ifndef DISABLE_DEPRECATED
  100. case FEATURE_GLOBAL_MENU: {
  101. return (native_menu && native_menu->has_feature(NativeMenu::FEATURE_GLOBAL_MENU));
  102. } break;
  103. #endif
  104. case FEATURE_SUBWINDOWS:
  105. case FEATURE_TOUCHSCREEN:
  106. case FEATURE_MOUSE:
  107. case FEATURE_MOUSE_WARP:
  108. case FEATURE_CLIPBOARD:
  109. case FEATURE_CURSOR_SHAPE:
  110. case FEATURE_CUSTOM_CURSOR_SHAPE:
  111. case FEATURE_IME:
  112. case FEATURE_WINDOW_TRANSPARENCY:
  113. case FEATURE_HIDPI:
  114. case FEATURE_ICON:
  115. case FEATURE_NATIVE_ICON:
  116. case FEATURE_NATIVE_DIALOG:
  117. case FEATURE_NATIVE_DIALOG_INPUT:
  118. case FEATURE_NATIVE_DIALOG_FILE:
  119. case FEATURE_NATIVE_DIALOG_FILE_EXTRA:
  120. //case FEATURE_NATIVE_DIALOG_FILE_MIME:
  121. case FEATURE_SWAP_BUFFERS:
  122. case FEATURE_KEEP_SCREEN_ON:
  123. case FEATURE_TEXT_TO_SPEECH:
  124. case FEATURE_SCREEN_CAPTURE:
  125. case FEATURE_STATUS_INDICATOR:
  126. case FEATURE_WINDOW_EMBEDDING:
  127. case FEATURE_WINDOW_DRAG:
  128. case FEATURE_SCREEN_EXCLUDE_FROM_CAPTURE:
  129. return true;
  130. case FEATURE_EMOJI_AND_SYMBOL_PICKER:
  131. return (os_ver.dwBuildNumber >= 17134); // Windows 10 Redstone 4 (1803)+ only.
  132. #ifdef ACCESSKIT_ENABLED
  133. case FEATURE_ACCESSIBILITY_SCREEN_READER: {
  134. return (accessibility_driver != nullptr);
  135. } break;
  136. #endif
  137. default:
  138. return false;
  139. }
  140. }
  141. String DisplayServerWindows::get_name() const {
  142. return "Windows";
  143. }
  144. void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) {
  145. if (p_mode == MOUSE_MODE_HIDDEN || p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  146. // Hide cursor before moving.
  147. if (hCursor == nullptr) {
  148. hCursor = SetCursor(nullptr);
  149. } else {
  150. SetCursor(nullptr);
  151. }
  152. }
  153. if (windows.has(MAIN_WINDOW_ID) && (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN)) {
  154. // Mouse is grabbed (captured or confined).
  155. WindowID window_id = _get_focused_window_or_popup();
  156. if (!windows.has(window_id)) {
  157. window_id = MAIN_WINDOW_ID;
  158. }
  159. WindowData &wd = windows[window_id];
  160. int off_x = (wd.multiwindow_fs || (!wd.fullscreen && wd.borderless && wd.maximized)) ? FS_TRANSP_BORDER : 0;
  161. RECT clipRect;
  162. GetClientRect(wd.hWnd, &clipRect);
  163. clipRect.right -= off_x;
  164. ClientToScreen(wd.hWnd, (POINT *)&clipRect.left);
  165. ClientToScreen(wd.hWnd, (POINT *)&clipRect.right);
  166. ClipCursor(&clipRect);
  167. if (p_mode == MOUSE_MODE_CAPTURED) {
  168. center = window_get_size() / 2;
  169. POINT pos = { (int)center.x, (int)center.y };
  170. ClientToScreen(wd.hWnd, &pos);
  171. SetCursorPos(pos.x, pos.y);
  172. SetCapture(wd.hWnd);
  173. _register_raw_input_devices(window_id);
  174. }
  175. } else {
  176. // Mouse is free to move around (not captured or confined).
  177. // When the user is moving a window, it's important to not ReleaseCapture because it will cause
  178. // the window movement to stop and if the user tries to move the Windows when it's not activated,
  179. // it will prevent the window movement. It's probably impossible to move the Window while it's captured anyway.
  180. if (!_has_moving_window()) {
  181. ReleaseCapture();
  182. }
  183. ClipCursor(nullptr);
  184. _register_raw_input_devices(INVALID_WINDOW_ID);
  185. }
  186. if (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED) {
  187. // Show cursor.
  188. CursorShape c = cursor_shape;
  189. cursor_shape = CURSOR_MAX;
  190. cursor_set_shape(c);
  191. }
  192. }
  193. DisplayServer::WindowID DisplayServerWindows::_get_focused_window_or_popup() const {
  194. const List<WindowID>::Element *E = popup_list.back();
  195. if (E) {
  196. return E->get();
  197. }
  198. return last_focused_window;
  199. }
  200. bool DisplayServerWindows::_has_moving_window() const {
  201. for (const KeyValue<WindowID, WindowData> &E : windows) {
  202. if (E.value.move_timer_id) {
  203. return true;
  204. }
  205. }
  206. return false;
  207. }
  208. void DisplayServerWindows::_register_raw_input_devices(WindowID p_target_window) {
  209. use_raw_input = true;
  210. RAWINPUTDEVICE rid[2] = {};
  211. rid[0].usUsagePage = 0x01; // HID_USAGE_PAGE_GENERIC
  212. rid[0].usUsage = 0x02; // HID_USAGE_GENERIC_MOUSE
  213. rid[0].dwFlags = 0;
  214. rid[1].usUsagePage = 0x01; // HID_USAGE_PAGE_GENERIC
  215. rid[1].usUsage = 0x06; // HID_USAGE_GENERIC_KEYBOARD
  216. rid[1].dwFlags = 0;
  217. if (p_target_window != INVALID_WINDOW_ID && windows.has(p_target_window)) {
  218. // Follow the defined window
  219. rid[0].hwndTarget = windows[p_target_window].hWnd;
  220. rid[1].hwndTarget = windows[p_target_window].hWnd;
  221. } else {
  222. // Follow the keyboard focus
  223. rid[0].hwndTarget = nullptr;
  224. rid[1].hwndTarget = nullptr;
  225. }
  226. if (RegisterRawInputDevices(rid, 2, sizeof(rid[0])) == FALSE) {
  227. // Registration failed.
  228. use_raw_input = false;
  229. }
  230. }
  231. void DisplayServerWindows::initialize_tts() const {
  232. const_cast<DisplayServerWindows *>(this)->tts = memnew(TTS_Windows);
  233. }
  234. bool DisplayServerWindows::tts_is_speaking() const {
  235. if (unlikely(!tts)) {
  236. initialize_tts();
  237. }
  238. ERR_FAIL_NULL_V(tts, false);
  239. return tts->is_speaking();
  240. }
  241. bool DisplayServerWindows::tts_is_paused() const {
  242. if (unlikely(!tts)) {
  243. initialize_tts();
  244. }
  245. ERR_FAIL_NULL_V(tts, false);
  246. return tts->is_paused();
  247. }
  248. TypedArray<Dictionary> DisplayServerWindows::tts_get_voices() const {
  249. if (unlikely(!tts)) {
  250. initialize_tts();
  251. }
  252. ERR_FAIL_NULL_V(tts, TypedArray<Dictionary>());
  253. return tts->get_voices();
  254. }
  255. void DisplayServerWindows::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
  256. if (unlikely(!tts)) {
  257. initialize_tts();
  258. }
  259. ERR_FAIL_NULL(tts);
  260. tts->speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
  261. }
  262. void DisplayServerWindows::tts_pause() {
  263. if (unlikely(!tts)) {
  264. initialize_tts();
  265. }
  266. ERR_FAIL_NULL(tts);
  267. tts->pause();
  268. }
  269. void DisplayServerWindows::tts_resume() {
  270. if (unlikely(!tts)) {
  271. initialize_tts();
  272. }
  273. ERR_FAIL_NULL(tts);
  274. tts->resume();
  275. }
  276. void DisplayServerWindows::tts_stop() {
  277. if (unlikely(!tts)) {
  278. initialize_tts();
  279. }
  280. ERR_FAIL_NULL(tts);
  281. tts->stop();
  282. }
  283. Error DisplayServerWindows::file_dialog_show(const String &p_title, const String &p_current_directory, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const Callable &p_callback, WindowID p_window_id) {
  284. return _file_dialog_with_options_show(p_title, p_current_directory, String(), p_filename, p_show_hidden, p_mode, p_filters, TypedArray<Dictionary>(), p_callback, false, p_window_id);
  285. }
  286. Error DisplayServerWindows::file_dialog_with_options_show(const String &p_title, const String &p_current_directory, const String &p_root, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const TypedArray<Dictionary> &p_options, const Callable &p_callback, WindowID p_window_id) {
  287. return _file_dialog_with_options_show(p_title, p_current_directory, p_root, p_filename, p_show_hidden, p_mode, p_filters, p_options, p_callback, true, p_window_id);
  288. }
  289. GODOT_GCC_WARNING_PUSH_AND_IGNORE("-Wnon-virtual-dtor") // Silence warning due to a COM API weirdness.
  290. class FileDialogEventHandler : public IFileDialogEvents, public IFileDialogControlEvents {
  291. LONG ref_count = 1;
  292. int ctl_id = 1;
  293. HashMap<int, String> ctls;
  294. Dictionary selected;
  295. String root;
  296. public:
  297. // IUnknown methods
  298. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv) {
  299. static const QITAB qit[] = {
  300. #ifdef __MINGW32__
  301. { &__uuidof(IFileDialogEvents), static_cast<decltype(qit[0].dwOffset)>(OFFSETOFCLASS(IFileDialogEvents, FileDialogEventHandler)) },
  302. { &__uuidof(IFileDialogControlEvents), static_cast<decltype(qit[0].dwOffset)>(OFFSETOFCLASS(IFileDialogControlEvents, FileDialogEventHandler)) },
  303. #else
  304. QITABENT(FileDialogEventHandler, IFileDialogEvents),
  305. QITABENT(FileDialogEventHandler, IFileDialogControlEvents),
  306. #endif
  307. { nullptr, 0 },
  308. };
  309. return QISearch(this, qit, riid, ppv);
  310. }
  311. ULONG STDMETHODCALLTYPE AddRef() {
  312. return InterlockedIncrement(&ref_count);
  313. }
  314. ULONG STDMETHODCALLTYPE Release() {
  315. long ref = InterlockedDecrement(&ref_count);
  316. if (!ref) {
  317. delete this;
  318. }
  319. return ref;
  320. }
  321. // IFileDialogEvents methods
  322. HRESULT STDMETHODCALLTYPE OnFileOk(IFileDialog *) { return S_OK; }
  323. HRESULT STDMETHODCALLTYPE OnFolderChange(IFileDialog *) { return S_OK; }
  324. HRESULT STDMETHODCALLTYPE OnFolderChanging(IFileDialog *p_pfd, IShellItem *p_item) {
  325. if (root.is_empty()) {
  326. return S_OK;
  327. }
  328. LPWSTR lpw_path = nullptr;
  329. p_item->GetDisplayName(SIGDN_FILESYSPATH, &lpw_path);
  330. if (!lpw_path) {
  331. return S_FALSE;
  332. }
  333. String path = String::utf16((const char16_t *)lpw_path).replace_char('\\', '/').trim_prefix(R"(\\?\)").simplify_path();
  334. if (!path.begins_with(root.simplify_path())) {
  335. return S_FALSE;
  336. }
  337. return S_OK;
  338. }
  339. HRESULT STDMETHODCALLTYPE OnHelp(IFileDialog *) { return S_OK; }
  340. HRESULT STDMETHODCALLTYPE OnSelectionChange(IFileDialog *) { return S_OK; }
  341. HRESULT STDMETHODCALLTYPE OnShareViolation(IFileDialog *, IShellItem *, FDE_SHAREVIOLATION_RESPONSE *) { return S_OK; }
  342. HRESULT STDMETHODCALLTYPE OnTypeChange(IFileDialog *pfd) { return S_OK; }
  343. HRESULT STDMETHODCALLTYPE OnOverwrite(IFileDialog *, IShellItem *, FDE_OVERWRITE_RESPONSE *) { return S_OK; }
  344. // IFileDialogControlEvents methods
  345. HRESULT STDMETHODCALLTYPE OnItemSelected(IFileDialogCustomize *p_pfdc, DWORD p_ctl_id, DWORD p_item_idx) {
  346. if (ctls.has(p_ctl_id)) {
  347. selected[ctls[p_ctl_id]] = (int)p_item_idx;
  348. }
  349. return S_OK;
  350. }
  351. HRESULT STDMETHODCALLTYPE OnButtonClicked(IFileDialogCustomize *, DWORD) { return S_OK; }
  352. HRESULT STDMETHODCALLTYPE OnCheckButtonToggled(IFileDialogCustomize *p_pfdc, DWORD p_ctl_id, BOOL p_checked) {
  353. if (ctls.has(p_ctl_id)) {
  354. selected[ctls[p_ctl_id]] = (bool)p_checked;
  355. }
  356. return S_OK;
  357. }
  358. HRESULT STDMETHODCALLTYPE OnControlActivating(IFileDialogCustomize *, DWORD) { return S_OK; }
  359. Dictionary get_selected() {
  360. return selected;
  361. }
  362. void set_root(const String &p_root) {
  363. root = p_root;
  364. }
  365. void add_option(IFileDialogCustomize *p_pfdc, const String &p_name, const Vector<String> &p_options, int p_default) {
  366. int gid = ctl_id++;
  367. int cid = ctl_id++;
  368. if (p_options.is_empty()) {
  369. // Add check box.
  370. p_pfdc->StartVisualGroup(gid, L"");
  371. p_pfdc->AddCheckButton(cid, (LPCWSTR)p_name.utf16().get_data(), p_default);
  372. p_pfdc->SetControlState(cid, CDCS_VISIBLE | CDCS_ENABLED);
  373. p_pfdc->EndVisualGroup();
  374. selected[p_name] = (bool)p_default;
  375. } else {
  376. // Add combo box.
  377. p_pfdc->StartVisualGroup(gid, (LPCWSTR)p_name.utf16().get_data());
  378. p_pfdc->AddComboBox(cid);
  379. p_pfdc->SetControlState(cid, CDCS_VISIBLE | CDCS_ENABLED);
  380. for (int i = 0; i < p_options.size(); i++) {
  381. p_pfdc->AddControlItem(cid, i, (LPCWSTR)p_options[i].utf16().get_data());
  382. }
  383. p_pfdc->SetSelectedControlItem(cid, p_default);
  384. p_pfdc->EndVisualGroup();
  385. selected[p_name] = p_default;
  386. }
  387. ctls[cid] = p_name;
  388. }
  389. virtual ~FileDialogEventHandler() {}
  390. };
  391. GODOT_GCC_WARNING_POP
  392. LRESULT CALLBACK WndProcFileDialog(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  393. DisplayServerWindows *ds_win = static_cast<DisplayServerWindows *>(DisplayServer::get_singleton());
  394. if (ds_win) {
  395. return ds_win->WndProcFileDialog(hWnd, uMsg, wParam, lParam);
  396. } else {
  397. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  398. }
  399. }
  400. LRESULT DisplayServerWindows::WndProcFileDialog(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  401. MutexLock lock(file_dialog_mutex);
  402. if (file_dialog_wnd.has(hWnd)) {
  403. if (file_dialog_wnd[hWnd]->close_requested.is_set()) {
  404. IPropertyStore *prop_store;
  405. HRESULT hr = SHGetPropertyStoreForWindow(hWnd, IID_IPropertyStore, (void **)&prop_store);
  406. if (hr == S_OK) {
  407. PROPVARIANT val;
  408. PropVariantInit(&val);
  409. prop_store->SetValue(PKEY_AppUserModel_ID, val);
  410. prop_store->Release();
  411. }
  412. DestroyWindow(hWnd);
  413. file_dialog_wnd.erase(hWnd);
  414. }
  415. }
  416. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  417. }
  418. void DisplayServerWindows::_thread_fd_monitor(void *p_ud) {
  419. DisplayServerWindows *ds = static_cast<DisplayServerWindows *>(get_singleton());
  420. FileDialogData *fd = (FileDialogData *)p_ud;
  421. if (fd->mode < 0 && fd->mode >= DisplayServer::FILE_DIALOG_MODE_SAVE_MAX) {
  422. fd->finished.set();
  423. return;
  424. }
  425. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  426. int64_t x = fd->wrect.position.x;
  427. int64_t y = fd->wrect.position.y;
  428. int64_t w = fd->wrect.size.x;
  429. int64_t h = fd->wrect.size.y;
  430. WNDCLASSW wc = {};
  431. wc.lpfnWndProc = (WNDPROC)::WndProcFileDialog;
  432. wc.hInstance = GetModuleHandle(nullptr);
  433. wc.lpszClassName = L"Engine File Dialog";
  434. RegisterClassW(&wc);
  435. HWND hwnd_dialog = CreateWindowExW(WS_EX_APPWINDOW, L"Engine File Dialog", L"", WS_OVERLAPPEDWINDOW, x, y, w, h, nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
  436. if (hwnd_dialog) {
  437. {
  438. MutexLock lock(ds->file_dialog_mutex);
  439. ds->file_dialog_wnd[hwnd_dialog] = fd;
  440. }
  441. HICON mainwindow_icon = (HICON)SendMessage(fd->hwnd_owner, WM_GETICON, ICON_SMALL, 0);
  442. if (mainwindow_icon) {
  443. SendMessage(hwnd_dialog, WM_SETICON, ICON_SMALL, (LPARAM)mainwindow_icon);
  444. }
  445. mainwindow_icon = (HICON)SendMessage(fd->hwnd_owner, WM_GETICON, ICON_BIG, 0);
  446. if (mainwindow_icon) {
  447. SendMessage(hwnd_dialog, WM_SETICON, ICON_BIG, (LPARAM)mainwindow_icon);
  448. }
  449. IPropertyStore *prop_store;
  450. HRESULT hr = SHGetPropertyStoreForWindow(hwnd_dialog, IID_IPropertyStore, (void **)&prop_store);
  451. if (hr == S_OK) {
  452. PROPVARIANT val;
  453. InitPropVariantFromString((PCWSTR)fd->appid.utf16().get_data(), &val);
  454. prop_store->SetValue(PKEY_AppUserModel_ID, val);
  455. prop_store->Release();
  456. }
  457. }
  458. SetCurrentProcessExplicitAppUserModelID((PCWSTR)fd->appid.utf16().get_data());
  459. Vector<Char16String> filter_names;
  460. Vector<Char16String> filter_exts;
  461. for (const String &E : fd->filters) {
  462. Vector<String> tokens = E.split(";");
  463. if (tokens.size() >= 1) {
  464. String flt = tokens[0].strip_edges();
  465. int filter_slice_count = flt.get_slice_count(",");
  466. Vector<String> exts;
  467. for (int j = 0; j < filter_slice_count; j++) {
  468. String str = (flt.get_slicec(',', j).strip_edges());
  469. if (!str.is_empty()) {
  470. exts.push_back(str);
  471. }
  472. }
  473. if (!exts.is_empty()) {
  474. String str = String(";").join(exts);
  475. filter_exts.push_back(str.utf16());
  476. if (tokens.size() == 2) {
  477. filter_names.push_back(tokens[1].strip_edges().utf16());
  478. } else {
  479. filter_names.push_back(str.utf16());
  480. }
  481. }
  482. }
  483. }
  484. if (filter_names.is_empty()) {
  485. filter_exts.push_back(String("*.*").utf16());
  486. filter_names.push_back((RTR("All Files") + " (*.*)").utf16());
  487. }
  488. Vector<COMDLG_FILTERSPEC> filters;
  489. for (int i = 0; i < filter_names.size(); i++) {
  490. filters.push_back({ (LPCWSTR)filter_names[i].ptr(), (LPCWSTR)filter_exts[i].ptr() });
  491. }
  492. HRESULT hr = S_OK;
  493. IFileDialog *pfd = nullptr;
  494. if (fd->mode == DisplayServer::FILE_DIALOG_MODE_SAVE_FILE) {
  495. hr = CoCreateInstance(CLSID_FileSaveDialog, nullptr, CLSCTX_INPROC_SERVER, IID_IFileSaveDialog, (void **)&pfd);
  496. } else {
  497. hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_IFileOpenDialog, (void **)&pfd);
  498. }
  499. if (SUCCEEDED(hr)) {
  500. IFileDialogEvents *pfde = nullptr;
  501. FileDialogEventHandler *event_handler = new FileDialogEventHandler();
  502. hr = event_handler->QueryInterface(IID_PPV_ARGS(&pfde));
  503. DWORD cookie = 0;
  504. hr = pfd->Advise(pfde, &cookie);
  505. IFileDialogCustomize *pfdc = nullptr;
  506. hr = pfd->QueryInterface(IID_PPV_ARGS(&pfdc));
  507. for (int i = 0; i < fd->options.size(); i++) {
  508. const Dictionary &item = fd->options[i];
  509. if (!item.has("name") || !item.has("values") || !item.has("default")) {
  510. continue;
  511. }
  512. event_handler->add_option(pfdc, item["name"], item["values"], item["default"]);
  513. }
  514. event_handler->set_root(fd->root);
  515. pfdc->Release();
  516. DWORD flags;
  517. pfd->GetOptions(&flags);
  518. if (fd->mode == DisplayServer::FILE_DIALOG_MODE_OPEN_FILES) {
  519. flags |= FOS_ALLOWMULTISELECT;
  520. }
  521. if (fd->mode == DisplayServer::FILE_DIALOG_MODE_OPEN_DIR) {
  522. flags |= FOS_PICKFOLDERS;
  523. }
  524. if (fd->show_hidden) {
  525. flags |= FOS_FORCESHOWHIDDEN;
  526. }
  527. pfd->SetOptions(flags | FOS_FORCEFILESYSTEM);
  528. pfd->SetTitle((LPCWSTR)fd->title.utf16().get_data());
  529. String dir = ProjectSettings::get_singleton()->globalize_path(fd->current_directory);
  530. if (dir == ".") {
  531. dir = OS::get_singleton()->get_executable_path().get_base_dir();
  532. }
  533. if (dir.is_relative_path() || dir == ".") {
  534. Char16String current_dir_name;
  535. size_t str_len = GetCurrentDirectoryW(0, nullptr);
  536. current_dir_name.resize(str_len + 1);
  537. GetCurrentDirectoryW(current_dir_name.size(), (LPWSTR)current_dir_name.ptrw());
  538. if (dir == ".") {
  539. dir = String::utf16((const char16_t *)current_dir_name.get_data()).trim_prefix(R"(\\?\)").replace_char('\\', '/');
  540. } else {
  541. dir = String::utf16((const char16_t *)current_dir_name.get_data()).trim_prefix(R"(\\?\)").replace_char('\\', '/').path_join(dir);
  542. }
  543. }
  544. dir = dir.simplify_path();
  545. dir = dir.trim_prefix(R"(\\?\)").replace_char('/', '\\');
  546. IShellItem *shellitem = nullptr;
  547. hr = SHCreateItemFromParsingName((LPCWSTR)dir.utf16().ptr(), nullptr, IID_IShellItem, (void **)&shellitem);
  548. if (SUCCEEDED(hr)) {
  549. pfd->SetDefaultFolder(shellitem);
  550. pfd->SetFolder(shellitem);
  551. }
  552. pfd->SetFileName((LPCWSTR)fd->filename.utf16().get_data());
  553. pfd->SetFileTypes(filters.size(), filters.ptr());
  554. pfd->SetFileTypeIndex(0);
  555. hr = pfd->Show(hwnd_dialog);
  556. pfd->Unadvise(cookie);
  557. Dictionary options = event_handler->get_selected();
  558. pfde->Release();
  559. event_handler->Release();
  560. UINT index = 0;
  561. pfd->GetFileTypeIndex(&index);
  562. if (index > 0) {
  563. index = index - 1;
  564. }
  565. if (SUCCEEDED(hr)) {
  566. Vector<String> file_names;
  567. if (fd->mode == DisplayServer::FILE_DIALOG_MODE_OPEN_FILES) {
  568. IShellItemArray *results;
  569. hr = static_cast<IFileOpenDialog *>(pfd)->GetResults(&results);
  570. if (SUCCEEDED(hr)) {
  571. DWORD count = 0;
  572. results->GetCount(&count);
  573. for (DWORD i = 0; i < count; i++) {
  574. IShellItem *result;
  575. results->GetItemAt(i, &result);
  576. PWSTR file_path = nullptr;
  577. hr = result->GetDisplayName(SIGDN_FILESYSPATH, &file_path);
  578. if (SUCCEEDED(hr)) {
  579. file_names.push_back(String::utf16((const char16_t *)file_path).replace_char('\\', '/').trim_prefix(R"(\\?\)"));
  580. CoTaskMemFree(file_path);
  581. }
  582. result->Release();
  583. }
  584. results->Release();
  585. }
  586. } else {
  587. IShellItem *result;
  588. hr = pfd->GetResult(&result);
  589. if (SUCCEEDED(hr)) {
  590. PWSTR file_path = nullptr;
  591. hr = result->GetDisplayName(SIGDN_FILESYSPATH, &file_path);
  592. if (SUCCEEDED(hr)) {
  593. file_names.push_back(String::utf16((const char16_t *)file_path).replace_char('\\', '/').trim_prefix(R"(\\?\)"));
  594. CoTaskMemFree(file_path);
  595. }
  596. result->Release();
  597. }
  598. }
  599. if (fd->callback.is_valid()) {
  600. MutexLock lock(ds->file_dialog_mutex);
  601. FileDialogCallback cb;
  602. cb.callback = fd->callback;
  603. cb.status = true;
  604. cb.files = file_names;
  605. cb.index = index;
  606. cb.options = options;
  607. cb.opt_in_cb = fd->options_in_cb;
  608. ds->pending_cbs.push_back(cb);
  609. }
  610. } else {
  611. if (fd->callback.is_valid()) {
  612. MutexLock lock(ds->file_dialog_mutex);
  613. FileDialogCallback cb;
  614. cb.callback = fd->callback;
  615. cb.status = false;
  616. cb.files = Vector<String>();
  617. cb.index = index;
  618. cb.options = options;
  619. cb.opt_in_cb = fd->options_in_cb;
  620. ds->pending_cbs.push_back(cb);
  621. }
  622. }
  623. pfd->Release();
  624. } else {
  625. if (fd->callback.is_valid()) {
  626. MutexLock lock(ds->file_dialog_mutex);
  627. FileDialogCallback cb;
  628. cb.callback = fd->callback;
  629. cb.status = false;
  630. cb.files = Vector<String>();
  631. cb.index = 0;
  632. cb.options = Dictionary();
  633. cb.opt_in_cb = fd->options_in_cb;
  634. ds->pending_cbs.push_back(cb);
  635. }
  636. }
  637. {
  638. MutexLock lock(ds->file_dialog_mutex);
  639. if (hwnd_dialog && ds->file_dialog_wnd.has(hwnd_dialog)) {
  640. IPropertyStore *prop_store;
  641. hr = SHGetPropertyStoreForWindow(hwnd_dialog, IID_IPropertyStore, (void **)&prop_store);
  642. if (hr == S_OK) {
  643. PROPVARIANT val;
  644. PropVariantInit(&val);
  645. prop_store->SetValue(PKEY_AppUserModel_ID, val);
  646. prop_store->Release();
  647. }
  648. DestroyWindow(hwnd_dialog);
  649. ds->file_dialog_wnd.erase(hwnd_dialog);
  650. }
  651. }
  652. UnregisterClassW(L"Engine File Dialog", GetModuleHandle(nullptr));
  653. CoUninitialize();
  654. fd->finished.set();
  655. if (fd->window_id != INVALID_WINDOW_ID) {
  656. callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(fd->window_id);
  657. }
  658. }
  659. Error DisplayServerWindows::_file_dialog_with_options_show(const String &p_title, const String &p_current_directory, const String &p_root, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const TypedArray<Dictionary> &p_options, const Callable &p_callback, bool p_options_in_cb, WindowID p_window_id) {
  660. _THREAD_SAFE_METHOD_
  661. ERR_FAIL_INDEX_V(int(p_mode), FILE_DIALOG_MODE_SAVE_MAX, FAILED);
  662. String appname;
  663. if (Engine::get_singleton()->is_editor_hint()) {
  664. appname = "Godot.GodotEditor." + String(GODOT_VERSION_BRANCH);
  665. } else {
  666. String name = GLOBAL_GET("application/config/name");
  667. String version = GLOBAL_GET("application/config/version");
  668. if (version.is_empty()) {
  669. version = "0";
  670. }
  671. String clean_app_name = name.to_pascal_case();
  672. for (int i = 0; i < clean_app_name.length(); i++) {
  673. if (!is_ascii_alphanumeric_char(clean_app_name[i]) && clean_app_name[i] != '_' && clean_app_name[i] != '.') {
  674. clean_app_name[i] = '_';
  675. }
  676. }
  677. clean_app_name = clean_app_name.substr(0, 120 - version.length()).trim_suffix(".");
  678. appname = "Godot." + clean_app_name + "." + version;
  679. }
  680. FileDialogData *fd = memnew(FileDialogData);
  681. if (windows.has(p_window_id) && !windows[p_window_id].is_popup) {
  682. fd->hwnd_owner = windows[p_window_id].hWnd;
  683. RECT crect;
  684. GetWindowRect(fd->hwnd_owner, &crect);
  685. fd->wrect = Rect2i(crect.left, crect.top, crect.right - crect.left, crect.bottom - crect.top);
  686. } else {
  687. fd->hwnd_owner = nullptr;
  688. fd->wrect = Rect2i(CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT);
  689. }
  690. fd->appid = appname;
  691. fd->title = p_title;
  692. fd->current_directory = p_current_directory;
  693. fd->root = p_root;
  694. fd->filename = p_filename;
  695. fd->show_hidden = p_show_hidden;
  696. fd->mode = p_mode;
  697. fd->window_id = p_window_id;
  698. fd->filters = p_filters;
  699. fd->options = p_options;
  700. fd->callback = p_callback;
  701. fd->options_in_cb = p_options_in_cb;
  702. fd->finished.clear();
  703. fd->close_requested.clear();
  704. fd->listener_thread.start(DisplayServerWindows::_thread_fd_monitor, fd);
  705. file_dialogs.push_back(fd);
  706. return OK;
  707. }
  708. void DisplayServerWindows::process_file_dialog_callbacks() {
  709. MutexLock lock(file_dialog_mutex);
  710. while (!pending_cbs.is_empty()) {
  711. FileDialogCallback cb = pending_cbs.front()->get();
  712. pending_cbs.pop_front();
  713. if (cb.opt_in_cb) {
  714. Variant ret;
  715. Callable::CallError ce;
  716. const Variant *args[4] = { &cb.status, &cb.files, &cb.index, &cb.options };
  717. cb.callback.callp(args, 4, ret, ce);
  718. if (ce.error != Callable::CallError::CALL_OK) {
  719. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(cb.callback, args, 4, ce)));
  720. }
  721. } else {
  722. Variant ret;
  723. Callable::CallError ce;
  724. const Variant *args[3] = { &cb.status, &cb.files, &cb.index };
  725. cb.callback.callp(args, 3, ret, ce);
  726. if (ce.error != Callable::CallError::CALL_OK) {
  727. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(cb.callback, args, 3, ce)));
  728. }
  729. }
  730. }
  731. }
  732. void DisplayServerWindows::beep() const {
  733. MessageBeep(MB_OK);
  734. }
  735. void DisplayServerWindows::_mouse_update_mode() {
  736. _THREAD_SAFE_METHOD_
  737. MouseMode wanted_mouse_mode = mouse_mode_override_enabled
  738. ? mouse_mode_override
  739. : mouse_mode_base;
  740. if (mouse_mode == wanted_mouse_mode) {
  741. // Already in the same mode; do nothing.
  742. return;
  743. }
  744. mouse_mode = wanted_mouse_mode;
  745. _set_mouse_mode_impl(wanted_mouse_mode);
  746. }
  747. void DisplayServerWindows::mouse_set_mode(MouseMode p_mode) {
  748. ERR_FAIL_INDEX(p_mode, MouseMode::MOUSE_MODE_MAX);
  749. if (p_mode == mouse_mode_base) {
  750. return;
  751. }
  752. mouse_mode_base = p_mode;
  753. _mouse_update_mode();
  754. }
  755. DisplayServer::MouseMode DisplayServerWindows::mouse_get_mode() const {
  756. return mouse_mode;
  757. }
  758. void DisplayServerWindows::mouse_set_mode_override(MouseMode p_mode) {
  759. ERR_FAIL_INDEX(p_mode, MouseMode::MOUSE_MODE_MAX);
  760. if (p_mode == mouse_mode_override) {
  761. return;
  762. }
  763. mouse_mode_override = p_mode;
  764. _mouse_update_mode();
  765. }
  766. DisplayServer::MouseMode DisplayServerWindows::mouse_get_mode_override() const {
  767. return mouse_mode_override;
  768. }
  769. void DisplayServerWindows::mouse_set_mode_override_enabled(bool p_override_enabled) {
  770. if (p_override_enabled == mouse_mode_override_enabled) {
  771. return;
  772. }
  773. mouse_mode_override_enabled = p_override_enabled;
  774. _mouse_update_mode();
  775. }
  776. bool DisplayServerWindows::mouse_is_mode_override_enabled() const {
  777. return mouse_mode_override_enabled;
  778. }
  779. void DisplayServerWindows::warp_mouse(const Point2i &p_position) {
  780. _THREAD_SAFE_METHOD_
  781. WindowID window_id = _get_focused_window_or_popup();
  782. if (!windows.has(window_id)) {
  783. return; // No focused window?
  784. }
  785. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  786. old_x = p_position.x;
  787. old_y = p_position.y;
  788. } else {
  789. POINT p;
  790. p.x = p_position.x;
  791. p.y = p_position.y;
  792. ClientToScreen(windows[window_id].hWnd, &p);
  793. SetCursorPos(p.x, p.y);
  794. }
  795. }
  796. Point2i DisplayServerWindows::mouse_get_position() const {
  797. POINT p;
  798. GetCursorPos(&p);
  799. return Point2i(p.x, p.y) - _get_screens_origin();
  800. }
  801. BitField<MouseButtonMask> DisplayServerWindows::mouse_get_button_state() const {
  802. BitField<MouseButtonMask> last_button_state = MouseButtonMask::NONE;
  803. if (GetKeyState(VK_LBUTTON) & (1 << 15)) {
  804. last_button_state.set_flag(MouseButtonMask::LEFT);
  805. }
  806. if (GetKeyState(VK_RBUTTON) & (1 << 15)) {
  807. last_button_state.set_flag(MouseButtonMask::RIGHT);
  808. }
  809. if (GetKeyState(VK_MBUTTON) & (1 << 15)) {
  810. last_button_state.set_flag(MouseButtonMask::MIDDLE);
  811. }
  812. if (GetKeyState(VK_XBUTTON1) & (1 << 15)) {
  813. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON1);
  814. }
  815. if (GetKeyState(VK_XBUTTON2) & (1 << 15)) {
  816. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON2);
  817. }
  818. return last_button_state;
  819. }
  820. void DisplayServerWindows::clipboard_set(const String &p_text) {
  821. _THREAD_SAFE_METHOD_
  822. if (!windows.has(MAIN_WINDOW_ID)) {
  823. return;
  824. }
  825. // Convert LF line endings to CRLF in clipboard content.
  826. // Otherwise, line endings won't be visible when pasted in other software.
  827. String text = p_text.replace("\r\n", "\n").replace("\n", "\r\n"); // Avoid \r\r\n.
  828. if (!OpenClipboard(windows[MAIN_WINDOW_ID].hWnd)) {
  829. ERR_FAIL_MSG("Unable to open clipboard.");
  830. }
  831. EmptyClipboard();
  832. Char16String utf16 = text.utf16();
  833. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (utf16.length() + 1) * sizeof(WCHAR));
  834. ERR_FAIL_NULL_MSG(mem, "Unable to allocate memory for clipboard contents.");
  835. LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
  836. memcpy(lptstrCopy, utf16.get_data(), (utf16.length() + 1) * sizeof(WCHAR));
  837. GlobalUnlock(mem);
  838. SetClipboardData(CF_UNICODETEXT, mem);
  839. // Set the CF_TEXT version (not needed?).
  840. CharString utf8 = text.utf8();
  841. mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
  842. ERR_FAIL_NULL_MSG(mem, "Unable to allocate memory for clipboard contents.");
  843. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  844. memcpy(ptr, utf8.get_data(), utf8.length());
  845. ptr[utf8.length()] = 0;
  846. GlobalUnlock(mem);
  847. SetClipboardData(CF_TEXT, mem);
  848. CloseClipboard();
  849. }
  850. String DisplayServerWindows::clipboard_get() const {
  851. _THREAD_SAFE_METHOD_
  852. if (!windows.has(MAIN_WINDOW_ID)) {
  853. return String();
  854. }
  855. String ret;
  856. if (!OpenClipboard(windows[MAIN_WINDOW_ID].hWnd)) {
  857. ERR_FAIL_V_MSG("", "Unable to open clipboard.");
  858. }
  859. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  860. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  861. if (mem != nullptr) {
  862. LPWSTR ptr = (LPWSTR)GlobalLock(mem);
  863. if (ptr != nullptr) {
  864. ret = String::utf16((const char16_t *)ptr);
  865. GlobalUnlock(mem);
  866. }
  867. }
  868. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  869. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  870. if (mem != nullptr) {
  871. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  872. if (ptr != nullptr) {
  873. ret.append_utf8((const char *)ptr);
  874. GlobalUnlock(mem);
  875. }
  876. }
  877. }
  878. CloseClipboard();
  879. return ret;
  880. }
  881. Ref<Image> DisplayServerWindows::clipboard_get_image() const {
  882. Ref<Image> image;
  883. if (!windows.has(last_focused_window)) {
  884. return image; // No focused window?
  885. }
  886. if (!OpenClipboard(windows[last_focused_window].hWnd)) {
  887. ERR_FAIL_V_MSG(image, "Unable to open clipboard.");
  888. }
  889. UINT png_format = RegisterClipboardFormatA("PNG");
  890. if (png_format && IsClipboardFormatAvailable(png_format)) {
  891. HANDLE png_handle = GetClipboardData(png_format);
  892. if (png_handle) {
  893. size_t png_size = GlobalSize(png_handle);
  894. uint8_t *png_data = (uint8_t *)GlobalLock(png_handle);
  895. image.instantiate();
  896. PNGDriverCommon::png_to_image(png_data, png_size, false, image);
  897. GlobalUnlock(png_handle);
  898. }
  899. } else if (IsClipboardFormatAvailable(CF_DIB)) {
  900. HGLOBAL mem = GetClipboardData(CF_DIB);
  901. if (mem != nullptr) {
  902. BITMAPINFO *ptr = static_cast<BITMAPINFO *>(GlobalLock(mem));
  903. if (ptr != nullptr) {
  904. BITMAPINFOHEADER *info = &ptr->bmiHeader;
  905. void *dib_bits = (void *)(ptr->bmiColors);
  906. // Draw DIB image to temporary DC surface and read it back as BGRA8.
  907. HDC dc = GetDC(nullptr);
  908. if (dc) {
  909. HDC hdc = CreateCompatibleDC(dc);
  910. if (hdc) {
  911. HBITMAP hbm = CreateCompatibleBitmap(dc, info->biWidth, std::abs(info->biHeight));
  912. if (hbm) {
  913. SelectObject(hdc, hbm);
  914. SetDIBitsToDevice(hdc, 0, 0, info->biWidth, std::abs(info->biHeight), 0, 0, 0, std::abs(info->biHeight), dib_bits, ptr, DIB_RGB_COLORS);
  915. BITMAPINFO bmp_info = {};
  916. bmp_info.bmiHeader.biSize = sizeof(bmp_info.bmiHeader);
  917. bmp_info.bmiHeader.biWidth = info->biWidth;
  918. bmp_info.bmiHeader.biHeight = -std::abs(info->biHeight);
  919. bmp_info.bmiHeader.biPlanes = 1;
  920. bmp_info.bmiHeader.biBitCount = 32;
  921. bmp_info.bmiHeader.biCompression = BI_RGB;
  922. Vector<uint8_t> img_data;
  923. img_data.resize(info->biWidth * std::abs(info->biHeight) * 4);
  924. GetDIBits(hdc, hbm, 0, std::abs(info->biHeight), img_data.ptrw(), &bmp_info, DIB_RGB_COLORS);
  925. uint8_t *wr = (uint8_t *)img_data.ptrw();
  926. for (int i = 0; i < info->biWidth * std::abs(info->biHeight); i++) {
  927. SWAP(wr[i * 4 + 0], wr[i * 4 + 2]); // Swap B and R.
  928. if (info->biBitCount != 32) {
  929. wr[i * 4 + 3] = 255; // Set A to solid if it's not in the source image.
  930. }
  931. }
  932. image = Image::create_from_data(info->biWidth, std::abs(info->biHeight), false, Image::Format::FORMAT_RGBA8, img_data);
  933. DeleteObject(hbm);
  934. }
  935. DeleteDC(hdc);
  936. }
  937. ReleaseDC(nullptr, dc);
  938. }
  939. GlobalUnlock(mem);
  940. }
  941. }
  942. }
  943. CloseClipboard();
  944. return image;
  945. }
  946. bool DisplayServerWindows::clipboard_has() const {
  947. return (IsClipboardFormatAvailable(CF_TEXT) ||
  948. IsClipboardFormatAvailable(CF_UNICODETEXT) ||
  949. IsClipboardFormatAvailable(CF_OEMTEXT));
  950. }
  951. bool DisplayServerWindows::clipboard_has_image() const {
  952. UINT png_format = RegisterClipboardFormatA("PNG");
  953. return ((png_format && IsClipboardFormatAvailable(png_format)) || IsClipboardFormatAvailable(CF_DIB));
  954. }
  955. typedef struct {
  956. int count;
  957. int screen;
  958. HMONITOR monitor;
  959. } EnumScreenData;
  960. static BOOL CALLBACK _MonitorEnumProcPrim(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  961. EnumScreenData *data = (EnumScreenData *)dwData;
  962. if ((lprcMonitor->left == 0) && (lprcMonitor->top == 0)) {
  963. data->screen = data->count;
  964. return FALSE;
  965. }
  966. data->count++;
  967. return TRUE;
  968. }
  969. static BOOL CALLBACK _MonitorEnumProcScreen(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  970. EnumScreenData *data = (EnumScreenData *)dwData;
  971. if (data->monitor == hMonitor) {
  972. data->screen = data->count;
  973. }
  974. data->count++;
  975. return TRUE;
  976. }
  977. static BOOL CALLBACK _MonitorEnumProcCount(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  978. int *data = (int *)dwData;
  979. (*data)++;
  980. return TRUE;
  981. }
  982. int DisplayServerWindows::get_screen_count() const {
  983. _THREAD_SAFE_METHOD_
  984. int data = 0;
  985. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcCount, (LPARAM)&data);
  986. return data;
  987. }
  988. int DisplayServerWindows::get_primary_screen() const {
  989. EnumScreenData data = { 0, 0, nullptr };
  990. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcPrim, (LPARAM)&data);
  991. return data.screen;
  992. }
  993. int DisplayServerWindows::get_keyboard_focus_screen() const {
  994. HWND hwnd = GetForegroundWindow();
  995. if (hwnd) {
  996. EnumScreenData data = { 0, 0, MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) };
  997. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcScreen, (LPARAM)&data);
  998. return data.screen;
  999. } else {
  1000. return get_primary_screen();
  1001. }
  1002. }
  1003. typedef struct {
  1004. int count;
  1005. int screen;
  1006. Point2 pos;
  1007. } EnumPosData;
  1008. static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1009. EnumPosData *data = (EnumPosData *)dwData;
  1010. if (data->count == data->screen) {
  1011. data->pos.x = lprcMonitor->left;
  1012. data->pos.y = lprcMonitor->top;
  1013. }
  1014. data->count++;
  1015. return TRUE;
  1016. }
  1017. static BOOL CALLBACK _MonitorEnumProcOrigin(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1018. EnumPosData *data = (EnumPosData *)dwData;
  1019. data->pos = data->pos.min(Point2(lprcMonitor->left, lprcMonitor->top));
  1020. return TRUE;
  1021. }
  1022. Point2i DisplayServerWindows::_get_screens_origin() const {
  1023. _THREAD_SAFE_METHOD_
  1024. EnumPosData data = { 0, 0, Point2() };
  1025. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcOrigin, (LPARAM)&data);
  1026. return data.pos;
  1027. }
  1028. Point2i DisplayServerWindows::screen_get_position(int p_screen) const {
  1029. _THREAD_SAFE_METHOD_
  1030. p_screen = _get_screen_index(p_screen);
  1031. int screen_count = get_screen_count();
  1032. ERR_FAIL_INDEX_V(p_screen, screen_count, Point2i());
  1033. EnumPosData data = { 0, p_screen, Point2() };
  1034. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcPos, (LPARAM)&data);
  1035. return data.pos - _get_screens_origin();
  1036. }
  1037. typedef struct {
  1038. int count;
  1039. int screen;
  1040. Size2 size;
  1041. } EnumSizeData;
  1042. typedef struct {
  1043. int count;
  1044. int screen;
  1045. Rect2i rect;
  1046. } EnumRectData;
  1047. typedef struct {
  1048. Vector<DISPLAYCONFIG_PATH_INFO> paths;
  1049. Vector<DISPLAYCONFIG_MODE_INFO> modes;
  1050. int count;
  1051. int screen;
  1052. float rate;
  1053. } EnumRefreshRateData;
  1054. static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1055. EnumSizeData *data = (EnumSizeData *)dwData;
  1056. if (data->count == data->screen) {
  1057. data->size.x = lprcMonitor->right - lprcMonitor->left;
  1058. data->size.y = lprcMonitor->bottom - lprcMonitor->top;
  1059. }
  1060. data->count++;
  1061. return TRUE;
  1062. }
  1063. Size2i DisplayServerWindows::screen_get_size(int p_screen) const {
  1064. _THREAD_SAFE_METHOD_
  1065. p_screen = _get_screen_index(p_screen);
  1066. int screen_count = get_screen_count();
  1067. ERR_FAIL_INDEX_V(p_screen, screen_count, Size2i());
  1068. EnumSizeData data = { 0, p_screen, Size2() };
  1069. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcSize, (LPARAM)&data);
  1070. return data.size;
  1071. }
  1072. static BOOL CALLBACK _MonitorEnumProcUsableSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1073. EnumRectData *data = (EnumRectData *)dwData;
  1074. if (data->count == data->screen) {
  1075. MONITORINFO minfo;
  1076. memset(&minfo, 0, sizeof(MONITORINFO));
  1077. minfo.cbSize = sizeof(MONITORINFO);
  1078. GetMonitorInfoA(hMonitor, &minfo);
  1079. data->rect.position.x = minfo.rcWork.left;
  1080. data->rect.position.y = minfo.rcWork.top;
  1081. data->rect.size.x = minfo.rcWork.right - minfo.rcWork.left;
  1082. data->rect.size.y = minfo.rcWork.bottom - minfo.rcWork.top;
  1083. }
  1084. data->count++;
  1085. return TRUE;
  1086. }
  1087. static BOOL CALLBACK _MonitorEnumProcRefreshRate(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1088. EnumRefreshRateData *data = (EnumRefreshRateData *)dwData;
  1089. if (data->count == data->screen) {
  1090. MONITORINFOEXW minfo;
  1091. memset(&minfo, 0, sizeof(minfo));
  1092. minfo.cbSize = sizeof(minfo);
  1093. GetMonitorInfoW(hMonitor, &minfo);
  1094. bool found = false;
  1095. for (const DISPLAYCONFIG_PATH_INFO &path : data->paths) {
  1096. DISPLAYCONFIG_SOURCE_DEVICE_NAME source_name;
  1097. memset(&source_name, 0, sizeof(source_name));
  1098. source_name.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
  1099. source_name.header.size = sizeof(source_name);
  1100. source_name.header.adapterId = path.sourceInfo.adapterId;
  1101. source_name.header.id = path.sourceInfo.id;
  1102. if (DisplayConfigGetDeviceInfo(&source_name.header) == ERROR_SUCCESS) {
  1103. if (wcscmp(minfo.szDevice, source_name.viewGdiDeviceName) == 0 && path.targetInfo.refreshRate.Numerator != 0 && path.targetInfo.refreshRate.Denominator != 0) {
  1104. data->rate = (double)path.targetInfo.refreshRate.Numerator / (double)path.targetInfo.refreshRate.Denominator;
  1105. found = true;
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. if (!found) {
  1111. DEVMODEW dm;
  1112. memset(&dm, 0, sizeof(dm));
  1113. dm.dmSize = sizeof(dm);
  1114. EnumDisplaySettingsW(minfo.szDevice, ENUM_CURRENT_SETTINGS, &dm);
  1115. data->rate = dm.dmDisplayFrequency;
  1116. }
  1117. }
  1118. data->count++;
  1119. return TRUE;
  1120. }
  1121. Rect2i DisplayServerWindows::screen_get_usable_rect(int p_screen) const {
  1122. _THREAD_SAFE_METHOD_
  1123. p_screen = _get_screen_index(p_screen);
  1124. int screen_count = get_screen_count();
  1125. ERR_FAIL_INDEX_V(p_screen, screen_count, Rect2i());
  1126. EnumRectData data = { 0, p_screen, Rect2i() };
  1127. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcUsableSize, (LPARAM)&data);
  1128. data.rect.position -= _get_screens_origin();
  1129. return data.rect;
  1130. }
  1131. typedef struct {
  1132. int count;
  1133. int screen;
  1134. int dpi;
  1135. } EnumDpiData;
  1136. static int QueryDpiForMonitor(HMONITOR hmon, MONITOR_DPI_TYPE dpiType = MDT_DEFAULT) {
  1137. int dpiX = 96, dpiY = 96;
  1138. UINT x = 0, y = 0;
  1139. if (hmon) {
  1140. HRESULT hr = GetDpiForMonitor(hmon, dpiType, &x, &y);
  1141. if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
  1142. dpiX = (int)x;
  1143. dpiY = (int)y;
  1144. }
  1145. } else {
  1146. static int overallX = 0, overallY = 0;
  1147. if (overallX <= 0 || overallY <= 0) {
  1148. HDC hdc = GetDC(nullptr);
  1149. if (hdc) {
  1150. overallX = GetDeviceCaps(hdc, LOGPIXELSX);
  1151. overallY = GetDeviceCaps(hdc, LOGPIXELSY);
  1152. ReleaseDC(nullptr, hdc);
  1153. }
  1154. }
  1155. if (overallX > 0 && overallY > 0) {
  1156. dpiX = overallX;
  1157. dpiY = overallY;
  1158. }
  1159. }
  1160. return (dpiX + dpiY) / 2;
  1161. }
  1162. static BOOL CALLBACK _MonitorEnumProcDpi(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1163. EnumDpiData *data = (EnumDpiData *)dwData;
  1164. if (data->count == data->screen) {
  1165. data->dpi = QueryDpiForMonitor(hMonitor);
  1166. }
  1167. data->count++;
  1168. return TRUE;
  1169. }
  1170. int DisplayServerWindows::screen_get_dpi(int p_screen) const {
  1171. _THREAD_SAFE_METHOD_
  1172. p_screen = _get_screen_index(p_screen);
  1173. int screen_count = get_screen_count();
  1174. ERR_FAIL_INDEX_V(p_screen, screen_count, 72);
  1175. EnumDpiData data = { 0, p_screen, 72 };
  1176. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcDpi, (LPARAM)&data);
  1177. return data.dpi;
  1178. }
  1179. Color DisplayServerWindows::screen_get_pixel(const Point2i &p_position) const {
  1180. Point2i pos = p_position + _get_screens_origin();
  1181. POINT p;
  1182. p.x = pos.x;
  1183. p.y = pos.y;
  1184. LogicalToPhysicalPointForPerMonitorDPI(nullptr, &p);
  1185. HDC dc = GetDC(nullptr);
  1186. if (dc) {
  1187. COLORREF col = GetPixel(dc, p.x, p.y);
  1188. if (col != CLR_INVALID) {
  1189. ReleaseDC(nullptr, dc);
  1190. return Color(float(col & 0x000000FF) / 255.0f, float((col & 0x0000FF00) >> 8) / 255.0f, float((col & 0x00FF0000) >> 16) / 255.0f, 1.0f);
  1191. }
  1192. ReleaseDC(nullptr, dc);
  1193. }
  1194. return Color();
  1195. }
  1196. Ref<Image> DisplayServerWindows::screen_get_image(int p_screen) const {
  1197. p_screen = _get_screen_index(p_screen);
  1198. int screen_count = get_screen_count();
  1199. ERR_FAIL_INDEX_V(p_screen, screen_count, Ref<Image>());
  1200. Point2i pos = screen_get_position(p_screen) + _get_screens_origin();
  1201. Size2i size = screen_get_size(p_screen);
  1202. POINT p1;
  1203. p1.x = pos.x;
  1204. p1.y = pos.y;
  1205. POINT p2;
  1206. p2.x = pos.x + size.x;
  1207. p2.y = pos.y + size.y;
  1208. LogicalToPhysicalPointForPerMonitorDPI(nullptr, &p1);
  1209. LogicalToPhysicalPointForPerMonitorDPI(nullptr, &p2);
  1210. Ref<Image> img;
  1211. HDC dc = GetDC(nullptr);
  1212. if (dc) {
  1213. HDC hdc = CreateCompatibleDC(dc);
  1214. int width = p2.x - p1.x;
  1215. int height = p2.y - p1.y;
  1216. if (hdc) {
  1217. HBITMAP hbm = CreateCompatibleBitmap(dc, width, height);
  1218. if (hbm) {
  1219. SelectObject(hdc, hbm);
  1220. BitBlt(hdc, 0, 0, width, height, dc, p1.x, p1.y, SRCCOPY);
  1221. BITMAPINFO bmp_info = {};
  1222. bmp_info.bmiHeader.biSize = sizeof(bmp_info.bmiHeader);
  1223. bmp_info.bmiHeader.biWidth = width;
  1224. bmp_info.bmiHeader.biHeight = -height;
  1225. bmp_info.bmiHeader.biPlanes = 1;
  1226. bmp_info.bmiHeader.biBitCount = 32;
  1227. bmp_info.bmiHeader.biCompression = BI_RGB;
  1228. Vector<uint8_t> img_data;
  1229. img_data.resize(width * height * 4);
  1230. GetDIBits(hdc, hbm, 0, height, img_data.ptrw(), &bmp_info, DIB_RGB_COLORS);
  1231. uint8_t *wr = (uint8_t *)img_data.ptrw();
  1232. for (int i = 0; i < width * height; i++) {
  1233. SWAP(wr[i * 4 + 0], wr[i * 4 + 2]); // Swap B and R.
  1234. }
  1235. img = Image::create_from_data(width, height, false, Image::FORMAT_RGBA8, img_data);
  1236. DeleteObject(hbm);
  1237. }
  1238. DeleteDC(hdc);
  1239. }
  1240. ReleaseDC(nullptr, dc);
  1241. }
  1242. return img;
  1243. }
  1244. Ref<Image> DisplayServerWindows::screen_get_image_rect(const Rect2i &p_rect) const {
  1245. Point2i pos = p_rect.position + _get_screens_origin();
  1246. Size2i size = p_rect.size;
  1247. POINT p1;
  1248. p1.x = pos.x;
  1249. p1.y = pos.y;
  1250. POINT p2;
  1251. p2.x = pos.x + size.x;
  1252. p2.y = pos.y + size.y;
  1253. LogicalToPhysicalPointForPerMonitorDPI(0, &p1);
  1254. LogicalToPhysicalPointForPerMonitorDPI(0, &p2);
  1255. Ref<Image> img;
  1256. HDC dc = GetDC(0);
  1257. if (dc) {
  1258. HDC hdc = CreateCompatibleDC(dc);
  1259. int width = p2.x - p1.x;
  1260. int height = p2.y - p1.y;
  1261. if (hdc) {
  1262. HBITMAP hbm = CreateCompatibleBitmap(dc, width, height);
  1263. if (hbm) {
  1264. SelectObject(hdc, hbm);
  1265. BitBlt(hdc, 0, 0, width, height, dc, p1.x, p1.y, SRCCOPY);
  1266. BITMAPINFO bmp_info = {};
  1267. bmp_info.bmiHeader.biSize = sizeof(bmp_info.bmiHeader);
  1268. bmp_info.bmiHeader.biWidth = width;
  1269. bmp_info.bmiHeader.biHeight = -height;
  1270. bmp_info.bmiHeader.biPlanes = 1;
  1271. bmp_info.bmiHeader.biBitCount = 32;
  1272. bmp_info.bmiHeader.biCompression = BI_RGB;
  1273. Vector<uint8_t> img_data;
  1274. img_data.resize(width * height * 4);
  1275. GetDIBits(hdc, hbm, 0, height, img_data.ptrw(), &bmp_info, DIB_RGB_COLORS);
  1276. uint8_t *wr = (uint8_t *)img_data.ptrw();
  1277. for (int i = 0; i < width * height; i++) {
  1278. SWAP(wr[i * 4 + 0], wr[i * 4 + 2]); // Swap B and R.
  1279. }
  1280. img = Image::create_from_data(width, height, false, Image::FORMAT_RGBA8, img_data);
  1281. DeleteObject(hbm);
  1282. }
  1283. DeleteDC(hdc);
  1284. }
  1285. ReleaseDC(NULL, dc);
  1286. }
  1287. return img;
  1288. }
  1289. float DisplayServerWindows::screen_get_refresh_rate(int p_screen) const {
  1290. _THREAD_SAFE_METHOD_
  1291. p_screen = _get_screen_index(p_screen);
  1292. int screen_count = get_screen_count();
  1293. ERR_FAIL_INDEX_V(p_screen, screen_count, SCREEN_REFRESH_RATE_FALLBACK);
  1294. EnumRefreshRateData data = { Vector<DISPLAYCONFIG_PATH_INFO>(), Vector<DISPLAYCONFIG_MODE_INFO>(), 0, p_screen, SCREEN_REFRESH_RATE_FALLBACK };
  1295. uint32_t path_count = 0;
  1296. uint32_t mode_count = 0;
  1297. if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &path_count, &mode_count) == ERROR_SUCCESS) {
  1298. data.paths.resize(path_count);
  1299. data.modes.resize(mode_count);
  1300. if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &path_count, data.paths.ptrw(), &mode_count, data.modes.ptrw(), nullptr) != ERROR_SUCCESS) {
  1301. data.paths.clear();
  1302. data.modes.clear();
  1303. }
  1304. }
  1305. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcRefreshRate, (LPARAM)&data);
  1306. return data.rate;
  1307. }
  1308. void DisplayServerWindows::screen_set_keep_on(bool p_enable) {
  1309. if (keep_screen_on == p_enable) {
  1310. return;
  1311. }
  1312. if (p_enable) {
  1313. const String reason = "Godot Engine running with display/window/energy_saving/keep_screen_on = true";
  1314. Char16String reason_utf16 = reason.utf16();
  1315. REASON_CONTEXT context;
  1316. context.Version = POWER_REQUEST_CONTEXT_VERSION;
  1317. context.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
  1318. context.Reason.SimpleReasonString = (LPWSTR)(reason_utf16.ptrw());
  1319. power_request = PowerCreateRequest(&context);
  1320. if (power_request == INVALID_HANDLE_VALUE) {
  1321. print_error("Failed to enable screen_keep_on.");
  1322. return;
  1323. }
  1324. if (PowerSetRequest(power_request, POWER_REQUEST_TYPE::PowerRequestSystemRequired) == 0) {
  1325. print_error("Failed to request system sleep override.");
  1326. return;
  1327. }
  1328. if (PowerSetRequest(power_request, POWER_REQUEST_TYPE::PowerRequestDisplayRequired) == 0) {
  1329. print_error("Failed to request display timeout override.");
  1330. return;
  1331. }
  1332. } else {
  1333. PowerClearRequest(power_request, POWER_REQUEST_TYPE::PowerRequestSystemRequired);
  1334. PowerClearRequest(power_request, POWER_REQUEST_TYPE::PowerRequestDisplayRequired);
  1335. CloseHandle(power_request);
  1336. power_request = nullptr;
  1337. }
  1338. keep_screen_on = p_enable;
  1339. }
  1340. bool DisplayServerWindows::screen_is_kept_on() const {
  1341. return keep_screen_on;
  1342. }
  1343. Vector<DisplayServer::WindowID> DisplayServerWindows::get_window_list() const {
  1344. _THREAD_SAFE_METHOD_
  1345. Vector<DisplayServer::WindowID> ret;
  1346. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1347. ret.push_back(E.key);
  1348. }
  1349. return ret;
  1350. }
  1351. DisplayServer::WindowID DisplayServerWindows::get_window_at_screen_position(const Point2i &p_position) const {
  1352. Point2i offset = _get_screens_origin();
  1353. POINT p;
  1354. p.x = p_position.x + offset.x;
  1355. p.y = p_position.y + offset.y;
  1356. HWND hwnd = WindowFromPoint(p);
  1357. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1358. if (E.value.hWnd == hwnd) {
  1359. return E.key;
  1360. }
  1361. }
  1362. return INVALID_WINDOW_ID;
  1363. }
  1364. DisplayServer::WindowID DisplayServerWindows::create_sub_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect, bool p_exclusive, WindowID p_transient_parent) {
  1365. _THREAD_SAFE_METHOD_
  1366. WindowID window_id = _create_window(p_mode, p_vsync_mode, p_flags, p_rect, p_exclusive, p_transient_parent, NULL);
  1367. ERR_FAIL_COND_V_MSG(window_id == INVALID_WINDOW_ID, INVALID_WINDOW_ID, "Failed to create sub window.");
  1368. WindowData &wd = windows[window_id];
  1369. if (p_flags & WINDOW_FLAG_RESIZE_DISABLED_BIT) {
  1370. wd.resizable = false;
  1371. }
  1372. if (p_flags & WINDOW_FLAG_MINIMIZE_DISABLED_BIT) {
  1373. wd.no_min_btn = true;
  1374. }
  1375. if (p_flags & WINDOW_FLAG_MAXIMIZE_DISABLED_BIT) {
  1376. wd.no_max_btn = true;
  1377. }
  1378. if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) {
  1379. wd.borderless = true;
  1380. }
  1381. if (p_flags & WINDOW_FLAG_ALWAYS_ON_TOP_BIT && p_mode != WINDOW_MODE_FULLSCREEN && p_mode != WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  1382. wd.always_on_top = true;
  1383. }
  1384. if (p_flags & WINDOW_FLAG_SHARP_CORNERS_BIT) {
  1385. wd.sharp_corners = true;
  1386. }
  1387. if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) {
  1388. wd.no_focus = true;
  1389. }
  1390. if (p_flags & WINDOW_FLAG_MOUSE_PASSTHROUGH_BIT) {
  1391. wd.mpass = true;
  1392. }
  1393. if (p_flags & WINDOW_FLAG_EXCLUDE_FROM_CAPTURE_BIT) {
  1394. wd.hide_from_capture = true;
  1395. if (os_ver.dwBuildNumber >= 19041) {
  1396. SetWindowDisplayAffinity(wd.hWnd, WDA_EXCLUDEFROMCAPTURE);
  1397. } else {
  1398. SetWindowDisplayAffinity(wd.hWnd, WDA_MONITOR);
  1399. }
  1400. }
  1401. if (p_flags & WINDOW_FLAG_POPUP_BIT) {
  1402. wd.is_popup = true;
  1403. }
  1404. if (p_flags & WINDOW_FLAG_TRANSPARENT_BIT) {
  1405. if (OS::get_singleton()->is_layered_allowed()) {
  1406. DWM_BLURBEHIND bb;
  1407. ZeroMemory(&bb, sizeof(bb));
  1408. HRGN hRgn = CreateRectRgn(0, 0, -1, -1);
  1409. bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
  1410. bb.hRgnBlur = hRgn;
  1411. bb.fEnable = TRUE;
  1412. DwmEnableBlurBehindWindow(wd.hWnd, &bb);
  1413. }
  1414. wd.layered_window = true;
  1415. }
  1416. // Inherit icons from MAIN_WINDOW for all sub windows.
  1417. HICON mainwindow_icon = (HICON)SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_GETICON, ICON_SMALL, 0);
  1418. if (mainwindow_icon) {
  1419. SendMessage(windows[window_id].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)mainwindow_icon);
  1420. }
  1421. mainwindow_icon = (HICON)SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_GETICON, ICON_BIG, 0);
  1422. if (mainwindow_icon) {
  1423. SendMessage(windows[window_id].hWnd, WM_SETICON, ICON_BIG, (LPARAM)mainwindow_icon);
  1424. }
  1425. #ifdef RD_ENABLED
  1426. if (rendering_device) {
  1427. rendering_device->screen_create(window_id);
  1428. }
  1429. #endif
  1430. return window_id;
  1431. }
  1432. bool DisplayServerWindows::_is_always_on_top_recursive(WindowID p_window) const {
  1433. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1434. const WindowData &wd = windows[p_window];
  1435. if (wd.always_on_top) {
  1436. return true;
  1437. }
  1438. if (wd.transient_parent != INVALID_WINDOW_ID) {
  1439. return _is_always_on_top_recursive(wd.transient_parent);
  1440. }
  1441. return false;
  1442. }
  1443. void DisplayServerWindows::show_window(WindowID p_id) {
  1444. ERR_FAIL_COND(!windows.has(p_id));
  1445. WindowData &wd = windows[p_id];
  1446. popup_open(p_id);
  1447. if (p_id != MAIN_WINDOW_ID) {
  1448. _update_window_style(p_id);
  1449. }
  1450. wd.initialized = true;
  1451. if (wd.maximized) {
  1452. ShowWindow(wd.hWnd, SW_SHOWMAXIMIZED);
  1453. SetForegroundWindow(wd.hWnd); // Slightly higher priority.
  1454. SetFocus(wd.hWnd); // Set keyboard focus.
  1455. } else if (wd.minimized) {
  1456. ShowWindow(wd.hWnd, SW_SHOWMINIMIZED);
  1457. } else if (wd.no_focus) {
  1458. // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
  1459. ShowWindow(wd.hWnd, SW_SHOWNA);
  1460. } else if (wd.is_popup) {
  1461. ShowWindow(wd.hWnd, SW_SHOWNA);
  1462. SetFocus(wd.hWnd); // Set keyboard focus.
  1463. } else {
  1464. ShowWindow(wd.hWnd, SW_SHOW);
  1465. SetForegroundWindow(wd.hWnd); // Slightly higher priority.
  1466. SetFocus(wd.hWnd); // Set keyboard focus.
  1467. }
  1468. if (_is_always_on_top_recursive(p_id)) {
  1469. SetWindowPos(wd.hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | ((wd.no_focus || wd.is_popup) ? SWP_NOACTIVATE : 0));
  1470. }
  1471. }
  1472. void DisplayServerWindows::delete_sub_window(WindowID p_window) {
  1473. _THREAD_SAFE_METHOD_
  1474. ERR_FAIL_COND(!windows.has(p_window));
  1475. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window cannot be deleted.");
  1476. popup_close(p_window);
  1477. WindowData &wd = windows[p_window];
  1478. IPropertyStore *prop_store;
  1479. HRESULT hr = SHGetPropertyStoreForWindow(wd.hWnd, IID_IPropertyStore, (void **)&prop_store);
  1480. if (hr == S_OK) {
  1481. PROPVARIANT val;
  1482. PropVariantInit(&val);
  1483. prop_store->SetValue(PKEY_AppUserModel_ID, val);
  1484. prop_store->Release();
  1485. }
  1486. while (wd.transient_children.size()) {
  1487. window_set_transient(*wd.transient_children.begin(), INVALID_WINDOW_ID);
  1488. }
  1489. if (wd.transient_parent != INVALID_WINDOW_ID) {
  1490. window_set_transient(p_window, INVALID_WINDOW_ID);
  1491. }
  1492. #ifdef RD_ENABLED
  1493. if (rendering_device) {
  1494. rendering_device->screen_free(p_window);
  1495. }
  1496. if (rendering_context) {
  1497. rendering_context->window_destroy(p_window);
  1498. }
  1499. #endif
  1500. #ifdef GLES3_ENABLED
  1501. if (gl_manager_angle) {
  1502. gl_manager_angle->window_destroy(p_window);
  1503. }
  1504. if (gl_manager_native) {
  1505. gl_manager_native->window_destroy(p_window);
  1506. }
  1507. #endif
  1508. if ((tablet_get_current_driver() == "wintab") && wintab_available && wd.wtctx) {
  1509. wintab_WTClose(wd.wtctx);
  1510. wd.wtctx = nullptr;
  1511. }
  1512. if (wd.drop_target != nullptr) {
  1513. RevokeDragDrop(wd.hWnd);
  1514. wd.drop_target->Release();
  1515. }
  1516. DestroyWindow(wd.hWnd);
  1517. windows.erase(p_window);
  1518. if (last_focused_window == p_window) {
  1519. last_focused_window = INVALID_WINDOW_ID;
  1520. }
  1521. }
  1522. void DisplayServerWindows::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  1523. #if defined(GLES3_ENABLED)
  1524. if (gl_manager_angle) {
  1525. gl_manager_angle->window_make_current(p_window_id);
  1526. }
  1527. if (gl_manager_native) {
  1528. gl_manager_native->window_make_current(p_window_id);
  1529. }
  1530. #endif
  1531. }
  1532. int64_t DisplayServerWindows::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
  1533. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  1534. switch (p_handle_type) {
  1535. case DISPLAY_HANDLE: {
  1536. return 0; // Not supported.
  1537. }
  1538. case WINDOW_HANDLE: {
  1539. return (int64_t)windows[p_window].hWnd;
  1540. }
  1541. #if defined(GLES3_ENABLED)
  1542. case WINDOW_VIEW: {
  1543. if (gl_manager_native) {
  1544. return (int64_t)gl_manager_native->get_hdc(p_window);
  1545. } else {
  1546. return (int64_t)GetDC(windows[p_window].hWnd);
  1547. }
  1548. }
  1549. case OPENGL_CONTEXT: {
  1550. if (gl_manager_native) {
  1551. return (int64_t)gl_manager_native->get_hglrc(p_window);
  1552. }
  1553. if (gl_manager_angle) {
  1554. return (int64_t)gl_manager_angle->get_context(p_window);
  1555. }
  1556. return 0;
  1557. }
  1558. case EGL_DISPLAY: {
  1559. if (gl_manager_angle) {
  1560. return (int64_t)gl_manager_angle->get_display(p_window);
  1561. }
  1562. return 0;
  1563. }
  1564. case EGL_CONFIG: {
  1565. if (gl_manager_angle) {
  1566. return (int64_t)gl_manager_angle->get_config(p_window);
  1567. }
  1568. return 0;
  1569. }
  1570. #endif
  1571. default: {
  1572. return 0;
  1573. }
  1574. }
  1575. }
  1576. void DisplayServerWindows::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  1577. _THREAD_SAFE_METHOD_
  1578. ERR_FAIL_COND(!windows.has(p_window));
  1579. windows[p_window].instance_id = p_instance;
  1580. }
  1581. ObjectID DisplayServerWindows::window_get_attached_instance_id(WindowID p_window) const {
  1582. _THREAD_SAFE_METHOD_
  1583. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  1584. return windows[p_window].instance_id;
  1585. }
  1586. void DisplayServerWindows::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  1587. _THREAD_SAFE_METHOD_
  1588. ERR_FAIL_COND(!windows.has(p_window));
  1589. windows[p_window].rect_changed_callback = p_callable;
  1590. }
  1591. void DisplayServerWindows::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  1592. _THREAD_SAFE_METHOD_
  1593. ERR_FAIL_COND(!windows.has(p_window));
  1594. windows[p_window].event_callback = p_callable;
  1595. }
  1596. void DisplayServerWindows::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  1597. _THREAD_SAFE_METHOD_
  1598. ERR_FAIL_COND(!windows.has(p_window));
  1599. windows[p_window].input_event_callback = p_callable;
  1600. }
  1601. void DisplayServerWindows::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  1602. _THREAD_SAFE_METHOD_
  1603. ERR_FAIL_COND(!windows.has(p_window));
  1604. windows[p_window].input_text_callback = p_callable;
  1605. }
  1606. void DisplayServerWindows::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  1607. _THREAD_SAFE_METHOD_
  1608. ERR_FAIL_COND(!windows.has(p_window));
  1609. WindowData &window_data = windows[p_window];
  1610. window_data.drop_files_callback = p_callable;
  1611. if (window_data.drop_target == nullptr) {
  1612. window_data.drop_target = memnew(DropTargetWindows(&window_data));
  1613. ERR_FAIL_COND(RegisterDragDrop(window_data.hWnd, window_data.drop_target) != S_OK);
  1614. }
  1615. }
  1616. void DisplayServerWindows::window_set_title(const String &p_title, WindowID p_window) {
  1617. _THREAD_SAFE_METHOD_
  1618. ERR_FAIL_COND(!windows.has(p_window));
  1619. SetWindowTextW(windows[p_window].hWnd, (LPCWSTR)(p_title.utf16().get_data()));
  1620. }
  1621. Size2i DisplayServerWindows::window_get_title_size(const String &p_title, WindowID p_window) const {
  1622. _THREAD_SAFE_METHOD_
  1623. Size2i size;
  1624. ERR_FAIL_COND_V(!windows.has(p_window), size);
  1625. const WindowData &wd = windows[p_window];
  1626. if (wd.fullscreen || wd.minimized || wd.borderless) {
  1627. return size;
  1628. }
  1629. HDC hdc = GetDCEx(wd.hWnd, nullptr, DCX_WINDOW);
  1630. if (hdc) {
  1631. Char16String s = p_title.utf16();
  1632. SIZE text_size;
  1633. if (GetTextExtentPoint32W(hdc, (LPCWSTR)(s.get_data()), s.length(), &text_size)) {
  1634. size.x = text_size.cx;
  1635. size.y = text_size.cy;
  1636. }
  1637. ReleaseDC(wd.hWnd, hdc);
  1638. }
  1639. RECT rect;
  1640. if (DwmGetWindowAttribute(wd.hWnd, DWMWA_CAPTION_BUTTON_BOUNDS, &rect, sizeof(RECT)) == S_OK) {
  1641. if (rect.right - rect.left > 0) {
  1642. ClientToScreen(wd.hWnd, (POINT *)&rect.left);
  1643. ClientToScreen(wd.hWnd, (POINT *)&rect.right);
  1644. PhysicalToLogicalPointForPerMonitorDPI(nullptr, (POINT *)&rect.left);
  1645. PhysicalToLogicalPointForPerMonitorDPI(nullptr, (POINT *)&rect.right);
  1646. size.x += (rect.right - rect.left);
  1647. size.y = MAX(size.y, rect.bottom - rect.top);
  1648. }
  1649. }
  1650. if (icon.is_valid()) {
  1651. size.x += 32;
  1652. } else {
  1653. size.x += 16;
  1654. }
  1655. return size;
  1656. }
  1657. void DisplayServerWindows::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  1658. _THREAD_SAFE_METHOD_
  1659. ERR_FAIL_COND(!windows.has(p_window));
  1660. windows[p_window].mpath = p_region;
  1661. _update_window_mouse_passthrough(p_window);
  1662. }
  1663. void DisplayServerWindows::_update_window_mouse_passthrough(WindowID p_window) {
  1664. ERR_FAIL_COND(!windows.has(p_window));
  1665. const WindowData &wd = windows[p_window];
  1666. bool clip_pixel = (wd.multiwindow_fs || (wd.borderless && wd.maximized));
  1667. bool pass_set = (wd.mpath.size() > 0);
  1668. if (!clip_pixel && !pass_set) {
  1669. SetWindowRgn(wd.hWnd, nullptr, TRUE);
  1670. } else {
  1671. HRGN region = nullptr;
  1672. if (pass_set) {
  1673. Vector<POINT> points;
  1674. points.resize(wd.mpath.size());
  1675. POINT *points_ptr = points.ptrw();
  1676. for (int i = 0; i < wd.mpath.size(); i++) {
  1677. if (wd.borderless) {
  1678. points_ptr[i].x = wd.mpath[i].x;
  1679. points_ptr[i].y = wd.mpath[i].y;
  1680. } else {
  1681. points_ptr[i].x = wd.mpath[i].x + GetSystemMetrics(SM_CXSIZEFRAME);
  1682. points_ptr[i].y = wd.mpath[i].y + GetSystemMetrics(SM_CYSIZEFRAME) + GetSystemMetrics(SM_CYCAPTION);
  1683. }
  1684. }
  1685. region = CreatePolygonRgn(points.ptr(), points.size(), ALTERNATE);
  1686. } else {
  1687. region = CreateRectRgn(0, 0, wd.width, wd.height);
  1688. }
  1689. if (clip_pixel) {
  1690. HRGN region_clip = CreateRectRgn(0, 0, wd.width, wd.height);
  1691. CombineRgn(region, region, region_clip, RGN_AND);
  1692. DeleteObject(region_clip);
  1693. }
  1694. SetWindowRgn(wd.hWnd, region, FALSE);
  1695. }
  1696. }
  1697. int DisplayServerWindows::window_get_current_screen(WindowID p_window) const {
  1698. _THREAD_SAFE_METHOD_
  1699. ERR_FAIL_COND_V(!windows.has(p_window), INVALID_SCREEN);
  1700. EnumScreenData data = { 0, 0, MonitorFromWindow(windows[p_window].hWnd, MONITOR_DEFAULTTONEAREST) };
  1701. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcScreen, (LPARAM)&data);
  1702. return data.screen;
  1703. }
  1704. void DisplayServerWindows::window_set_current_screen(int p_screen, WindowID p_window) {
  1705. _THREAD_SAFE_METHOD_
  1706. ERR_FAIL_COND(!windows.has(p_window));
  1707. p_screen = _get_screen_index(p_screen);
  1708. int screen_count = get_screen_count();
  1709. ERR_FAIL_INDEX(p_screen, screen_count);
  1710. if (window_get_current_screen(p_window) == p_screen) {
  1711. return;
  1712. }
  1713. const WindowData &wd = windows[p_window];
  1714. if (wd.parent_hwnd) {
  1715. print_line("Embedded window can't be moved to another screen.");
  1716. return;
  1717. }
  1718. if (wd.fullscreen) {
  1719. Point2 pos = screen_get_position(p_screen) + _get_screens_origin();
  1720. Size2 size = screen_get_size(p_screen);
  1721. int off_x = (wd.multiwindow_fs || (!wd.fullscreen && wd.borderless && wd.maximized)) ? FS_TRANSP_BORDER : 0;
  1722. MoveWindow(wd.hWnd, pos.x, pos.y, size.width + off_x, size.height, TRUE);
  1723. } else if (wd.maximized) {
  1724. Point2 pos = screen_get_position(p_screen) + _get_screens_origin();
  1725. Size2 size = screen_get_size(p_screen);
  1726. int off_x = (wd.multiwindow_fs || (!wd.fullscreen && wd.borderless && wd.maximized)) ? FS_TRANSP_BORDER : 0;
  1727. ShowWindow(wd.hWnd, SW_RESTORE);
  1728. MoveWindow(wd.hWnd, pos.x, pos.y, size.width + off_x, size.height, TRUE);
  1729. ShowWindow(wd.hWnd, SW_MAXIMIZE);
  1730. } else {
  1731. Rect2i srect = screen_get_usable_rect(p_screen);
  1732. Point2i wpos = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  1733. Size2i wsize = window_get_size(p_window);
  1734. wpos += srect.position;
  1735. wpos = wpos.clamp(srect.position, srect.position + srect.size - wsize / 3);
  1736. window_set_position(wpos, p_window);
  1737. }
  1738. }
  1739. Point2i DisplayServerWindows::window_get_position(WindowID p_window) const {
  1740. _THREAD_SAFE_METHOD_
  1741. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1742. const WindowData &wd = windows[p_window];
  1743. if (wd.minimized) {
  1744. return wd.last_pos;
  1745. }
  1746. POINT point;
  1747. point.x = 0;
  1748. point.y = 0;
  1749. ClientToScreen(wd.hWnd, &point);
  1750. return Point2i(point.x, point.y) - _get_screens_origin();
  1751. }
  1752. Point2i DisplayServerWindows::window_get_position_with_decorations(WindowID p_window) const {
  1753. _THREAD_SAFE_METHOD_
  1754. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1755. const WindowData &wd = windows[p_window];
  1756. if (wd.minimized) {
  1757. return wd.last_pos;
  1758. }
  1759. RECT r;
  1760. if (GetWindowRect(wd.hWnd, &r)) {
  1761. return Point2i(r.left, r.top) - _get_screens_origin();
  1762. }
  1763. return Point2i();
  1764. }
  1765. void DisplayServerWindows::_update_real_mouse_position(WindowID p_window) {
  1766. ERR_FAIL_COND(!windows.has(p_window));
  1767. POINT mouse_pos;
  1768. if (GetCursorPos(&mouse_pos) && ScreenToClient(windows[p_window].hWnd, &mouse_pos)) {
  1769. if (mouse_pos.x > 0 && mouse_pos.y > 0 && mouse_pos.x <= windows[p_window].width && mouse_pos.y <= windows[p_window].height) {
  1770. old_x = mouse_pos.x;
  1771. old_y = mouse_pos.y;
  1772. old_invalid = false;
  1773. Input::get_singleton()->set_mouse_position(Point2i(mouse_pos.x, mouse_pos.y));
  1774. }
  1775. }
  1776. }
  1777. void DisplayServerWindows::window_set_position(const Point2i &p_position, WindowID p_window) {
  1778. _THREAD_SAFE_METHOD_
  1779. ERR_FAIL_COND(!windows.has(p_window));
  1780. WindowData &wd = windows[p_window];
  1781. if (wd.parent_hwnd) {
  1782. print_line("Embedded window can't be moved.");
  1783. return;
  1784. }
  1785. if (wd.fullscreen || wd.maximized) {
  1786. return;
  1787. }
  1788. Point2i offset = _get_screens_origin();
  1789. RECT rc;
  1790. rc.left = p_position.x + offset.x;
  1791. rc.right = p_position.x + wd.width + offset.x;
  1792. rc.bottom = p_position.y + wd.height + offset.y;
  1793. rc.top = p_position.y + offset.y;
  1794. const DWORD style = GetWindowLongPtr(wd.hWnd, GWL_STYLE);
  1795. const DWORD exStyle = GetWindowLongPtr(wd.hWnd, GWL_EXSTYLE);
  1796. AdjustWindowRectEx(&rc, style, false, exStyle);
  1797. MoveWindow(wd.hWnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, TRUE);
  1798. wd.last_pos = p_position;
  1799. _update_real_mouse_position(p_window);
  1800. }
  1801. void DisplayServerWindows::window_set_exclusive(WindowID p_window, bool p_exclusive) {
  1802. _THREAD_SAFE_METHOD_
  1803. ERR_FAIL_COND(!windows.has(p_window));
  1804. WindowData &wd = windows[p_window];
  1805. if (wd.exclusive != p_exclusive) {
  1806. wd.exclusive = p_exclusive;
  1807. if (wd.transient_parent != INVALID_WINDOW_ID) {
  1808. if (wd.exclusive) {
  1809. WindowData &wd_parent = windows[wd.transient_parent];
  1810. SetWindowLongPtr(wd.hWnd, GWLP_HWNDPARENT, (LONG_PTR)wd_parent.hWnd);
  1811. } else {
  1812. SetWindowLongPtr(wd.hWnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr);
  1813. }
  1814. }
  1815. }
  1816. }
  1817. void DisplayServerWindows::window_set_transient(WindowID p_window, WindowID p_parent) {
  1818. _THREAD_SAFE_METHOD_
  1819. ERR_FAIL_COND(p_window == p_parent);
  1820. ERR_FAIL_COND(!windows.has(p_window));
  1821. WindowData &wd_window = windows[p_window];
  1822. ERR_FAIL_COND(wd_window.transient_parent == p_parent);
  1823. ERR_FAIL_COND_MSG(wd_window.always_on_top, "Windows with the 'on top' can't become transient.");
  1824. if (p_parent == INVALID_WINDOW_ID) {
  1825. // Remove transient.
  1826. ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
  1827. ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
  1828. WindowData &wd_parent = windows[wd_window.transient_parent];
  1829. wd_window.transient_parent = INVALID_WINDOW_ID;
  1830. wd_parent.transient_children.erase(p_window);
  1831. if (wd_window.exclusive) {
  1832. SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr);
  1833. }
  1834. } else {
  1835. ERR_FAIL_COND(!windows.has(p_parent));
  1836. ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  1837. WindowData &wd_parent = windows[p_parent];
  1838. wd_window.transient_parent = p_parent;
  1839. wd_parent.transient_children.insert(p_window);
  1840. if (wd_window.exclusive) {
  1841. SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, (LONG_PTR)wd_parent.hWnd);
  1842. }
  1843. }
  1844. }
  1845. void DisplayServerWindows::window_set_max_size(const Size2i p_size, WindowID p_window) {
  1846. _THREAD_SAFE_METHOD_
  1847. ERR_FAIL_COND(!windows.has(p_window));
  1848. WindowData &wd = windows[p_window];
  1849. if (wd.parent_hwnd) {
  1850. print_line("Embedded windows can't have a maximum size.");
  1851. return;
  1852. }
  1853. if ((p_size != Size2()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  1854. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1855. return;
  1856. }
  1857. wd.max_size = p_size;
  1858. }
  1859. Size2i DisplayServerWindows::window_get_max_size(WindowID p_window) const {
  1860. _THREAD_SAFE_METHOD_
  1861. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1862. const WindowData &wd = windows[p_window];
  1863. return wd.max_size;
  1864. }
  1865. void DisplayServerWindows::window_set_min_size(const Size2i p_size, WindowID p_window) {
  1866. _THREAD_SAFE_METHOD_
  1867. ERR_FAIL_COND(!windows.has(p_window));
  1868. WindowData &wd = windows[p_window];
  1869. if (wd.parent_hwnd) {
  1870. print_line("Embedded windows can't have a minimum size.");
  1871. return;
  1872. }
  1873. if ((p_size != Size2()) && (wd.max_size != Size2()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  1874. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1875. return;
  1876. }
  1877. wd.min_size = p_size;
  1878. }
  1879. Size2i DisplayServerWindows::window_get_min_size(WindowID p_window) const {
  1880. _THREAD_SAFE_METHOD_
  1881. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1882. const WindowData &wd = windows[p_window];
  1883. return wd.min_size;
  1884. }
  1885. void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_window) {
  1886. _THREAD_SAFE_METHOD_
  1887. ERR_FAIL_COND(!windows.has(p_window));
  1888. WindowData &wd = windows[p_window];
  1889. if (wd.parent_hwnd) {
  1890. print_line("Embedded window can't be resized.");
  1891. return;
  1892. }
  1893. if (wd.fullscreen || wd.maximized) {
  1894. return;
  1895. }
  1896. int w = p_size.width;
  1897. int h = p_size.height;
  1898. RECT rect;
  1899. GetWindowRect(wd.hWnd, &rect);
  1900. if (!wd.borderless) {
  1901. RECT crect;
  1902. GetClientRect(wd.hWnd, &crect);
  1903. w += (rect.right - rect.left) - (crect.right - crect.left);
  1904. h += (rect.bottom - rect.top) - (crect.bottom - crect.top);
  1905. }
  1906. MoveWindow(wd.hWnd, rect.left, rect.top, w, h, TRUE);
  1907. }
  1908. Size2i DisplayServerWindows::window_get_size(WindowID p_window) const {
  1909. _THREAD_SAFE_METHOD_
  1910. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1911. const WindowData &wd = windows[p_window];
  1912. // GetClientRect() returns a zero rect for a minimized window, so we need to get the size in another way.
  1913. if (wd.minimized) {
  1914. return Size2(wd.width, wd.height);
  1915. }
  1916. RECT r;
  1917. if (GetClientRect(wd.hWnd, &r)) { // Retrieves area inside of window border, including decoration.
  1918. int off_x = (wd.multiwindow_fs || (!wd.fullscreen && wd.borderless && wd.maximized)) ? FS_TRANSP_BORDER : 0;
  1919. return Size2(r.right - r.left - off_x, r.bottom - r.top);
  1920. }
  1921. return Size2();
  1922. }
  1923. Size2i DisplayServerWindows::window_get_size_with_decorations(WindowID p_window) const {
  1924. _THREAD_SAFE_METHOD_
  1925. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1926. const WindowData &wd = windows[p_window];
  1927. RECT r;
  1928. if (GetWindowRect(wd.hWnd, &r)) { // Retrieves area inside of window border, including decoration.
  1929. int off_x = (wd.multiwindow_fs || (!wd.fullscreen && wd.borderless && wd.maximized)) ? FS_TRANSP_BORDER : 0;
  1930. return Size2(r.right - r.left - off_x, r.bottom - r.top);
  1931. }
  1932. return Size2();
  1933. }
  1934. void DisplayServerWindows::_get_window_style(bool p_main_window, bool p_initialized, bool p_fullscreen, bool p_multiwindow_fs, bool p_borderless, bool p_resizable, bool p_no_min_btn, bool p_no_max_btn, bool p_minimized, bool p_maximized, bool p_maximized_fs, bool p_no_activate_focus, bool p_embed_child, DWORD &r_style, DWORD &r_style_ex) {
  1935. // Windows docs for window styles:
  1936. // https://docs.microsoft.com/en-us/windows/win32/winmsg/window-styles
  1937. // https://docs.microsoft.com/en-us/windows/win32/winmsg/extended-window-styles
  1938. r_style = 0;
  1939. r_style_ex = WS_EX_WINDOWEDGE;
  1940. if (p_main_window) {
  1941. // When embedded, we don't want the window to have WS_EX_APPWINDOW because it will
  1942. // show the embedded process in the taskbar and Alt-Tab.
  1943. if (!p_embed_child) {
  1944. r_style_ex |= WS_EX_APPWINDOW;
  1945. }
  1946. if (p_initialized) {
  1947. r_style |= WS_VISIBLE;
  1948. }
  1949. }
  1950. if (p_embed_child) {
  1951. r_style |= WS_POPUP;
  1952. } else if (p_fullscreen || p_borderless) {
  1953. r_style |= WS_POPUP; // p_borderless was WS_EX_TOOLWINDOW in the past.
  1954. if (p_minimized) {
  1955. r_style |= WS_MINIMIZE;
  1956. } else if (p_maximized) {
  1957. r_style |= WS_MAXIMIZE;
  1958. }
  1959. if (!p_fullscreen) {
  1960. r_style |= WS_SYSMENU;
  1961. if (!p_no_min_btn) {
  1962. r_style |= WS_MINIMIZEBOX;
  1963. }
  1964. if (!p_no_max_btn) {
  1965. r_style |= WS_MAXIMIZEBOX;
  1966. }
  1967. }
  1968. } else {
  1969. if (p_resizable) {
  1970. if (p_minimized) {
  1971. r_style = WS_OVERLAPPEDWINDOW | WS_MINIMIZE;
  1972. } else if (p_maximized) {
  1973. r_style = WS_OVERLAPPEDWINDOW | WS_MAXIMIZE;
  1974. } else {
  1975. r_style = WS_OVERLAPPEDWINDOW;
  1976. }
  1977. if (p_no_min_btn) {
  1978. r_style &= ~WS_MINIMIZEBOX;
  1979. }
  1980. if (p_no_max_btn) {
  1981. r_style &= ~WS_MAXIMIZEBOX;
  1982. }
  1983. } else {
  1984. if (p_minimized) {
  1985. r_style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZE;
  1986. } else {
  1987. r_style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU;
  1988. }
  1989. if (!p_no_min_btn) {
  1990. r_style |= WS_MINIMIZEBOX;
  1991. }
  1992. if (!p_no_max_btn) {
  1993. r_style |= WS_MAXIMIZEBOX;
  1994. }
  1995. }
  1996. }
  1997. if (p_no_activate_focus && !p_embed_child) {
  1998. r_style_ex |= WS_EX_TOPMOST | WS_EX_NOACTIVATE;
  1999. }
  2000. if (!p_borderless && !p_no_activate_focus && p_initialized) {
  2001. r_style |= WS_VISIBLE;
  2002. }
  2003. r_style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
  2004. r_style_ex |= WS_EX_ACCEPTFILES;
  2005. if (OS::get_singleton()->get_current_rendering_driver_name() == "d3d12") {
  2006. r_style_ex |= WS_EX_NOREDIRECTIONBITMAP;
  2007. }
  2008. }
  2009. void DisplayServerWindows::_update_window_style(WindowID p_window, bool p_repaint) {
  2010. _THREAD_SAFE_METHOD_
  2011. ERR_FAIL_COND(!windows.has(p_window));
  2012. WindowData &wd = windows[p_window];
  2013. DWORD style = 0;
  2014. DWORD style_ex = 0;
  2015. _get_window_style(p_window == MAIN_WINDOW_ID, wd.initialized, wd.fullscreen, wd.multiwindow_fs, wd.borderless, wd.resizable, wd.no_min_btn, wd.no_max_btn, wd.minimized, wd.maximized, wd.maximized_fs, wd.no_focus || wd.is_popup, wd.parent_hwnd, style, style_ex);
  2016. SetWindowLongPtr(wd.hWnd, GWL_STYLE, style);
  2017. SetWindowLongPtr(wd.hWnd, GWL_EXSTYLE, style_ex);
  2018. if (icon.is_valid()) {
  2019. set_icon(icon);
  2020. }
  2021. SetWindowPos(wd.hWnd, _is_always_on_top_recursive(p_window) ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | ((wd.no_focus || wd.is_popup) ? SWP_NOACTIVATE : 0));
  2022. if (p_repaint) {
  2023. RECT rect;
  2024. GetWindowRect(wd.hWnd, &rect);
  2025. int off_x = (wd.multiwindow_fs || (!wd.fullscreen && wd.borderless && wd.maximized)) ? FS_TRANSP_BORDER : 0;
  2026. MoveWindow(wd.hWnd, rect.left, rect.top, rect.right - rect.left + off_x, rect.bottom - rect.top, TRUE);
  2027. }
  2028. }
  2029. void DisplayServerWindows::window_set_mode(WindowMode p_mode, WindowID p_window) {
  2030. _THREAD_SAFE_METHOD_
  2031. ERR_FAIL_COND(!windows.has(p_window));
  2032. WindowData &wd = windows[p_window];
  2033. if (p_mode != WINDOW_MODE_WINDOWED && wd.parent_hwnd) {
  2034. print_line("Embedded window only supports Windowed mode.");
  2035. return;
  2036. }
  2037. bool was_fullscreen = wd.fullscreen;
  2038. wd.was_fullscreen_pre_min = false;
  2039. if (p_mode == WINDOW_MODE_MAXIMIZED && wd.borderless) {
  2040. int cs = window_get_current_screen(p_window);
  2041. Rect2i full = Rect2i(screen_get_position(cs), screen_get_size(cs));
  2042. Rect2i usable = screen_get_usable_rect(cs);
  2043. if (full == usable) {
  2044. p_mode = WINDOW_MODE_FULLSCREEN;
  2045. }
  2046. }
  2047. if (wd.fullscreen && p_mode != WINDOW_MODE_FULLSCREEN && p_mode != WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2048. RECT rect;
  2049. wd.fullscreen = false;
  2050. wd.multiwindow_fs = false;
  2051. // Restore previous maximized state.
  2052. wd.maximized = wd.was_maximized_pre_fs;
  2053. _update_window_style(p_window, false);
  2054. // Restore window rect after exiting fullscreen.
  2055. if (wd.pre_fs_valid) {
  2056. rect = wd.pre_fs_rect;
  2057. } else {
  2058. rect.left = 0;
  2059. rect.right = wd.width;
  2060. rect.top = 0;
  2061. rect.bottom = wd.height;
  2062. }
  2063. ShowWindow(wd.hWnd, SW_RESTORE);
  2064. MoveWindow(wd.hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  2065. if (restore_mouse_trails > 1) {
  2066. SystemParametersInfoA(SPI_SETMOUSETRAILS, restore_mouse_trails, nullptr, 0);
  2067. restore_mouse_trails = 0;
  2068. }
  2069. }
  2070. if (p_mode == WINDOW_MODE_WINDOWED) {
  2071. ShowWindow(wd.hWnd, SW_NORMAL);
  2072. wd.maximized = false;
  2073. wd.minimized = false;
  2074. }
  2075. if (p_mode == WINDOW_MODE_MAXIMIZED && !wd.borderless) {
  2076. ShowWindow(wd.hWnd, SW_MAXIMIZE);
  2077. wd.maximized = true;
  2078. wd.minimized = false;
  2079. }
  2080. if (p_mode == WINDOW_MODE_MAXIMIZED && wd.borderless) {
  2081. ShowWindow(wd.hWnd, SW_NORMAL);
  2082. wd.maximized = true;
  2083. wd.minimized = false;
  2084. int cs = window_get_current_screen(p_window);
  2085. Rect2i usable = screen_get_usable_rect(cs);
  2086. Point2 pos = usable.position + _get_screens_origin();
  2087. Size2 size = usable.size;
  2088. MoveWindow(wd.hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  2089. }
  2090. if (p_mode == WINDOW_MODE_MINIMIZED) {
  2091. ShowWindow(wd.hWnd, SW_MINIMIZE);
  2092. wd.maximized = false;
  2093. wd.minimized = true;
  2094. wd.was_fullscreen_pre_min = was_fullscreen;
  2095. }
  2096. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2097. wd.multiwindow_fs = false;
  2098. } else if (p_mode == WINDOW_MODE_FULLSCREEN) {
  2099. wd.multiwindow_fs = true;
  2100. }
  2101. _update_window_style(p_window, false);
  2102. if ((p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) && !wd.fullscreen) {
  2103. if (wd.minimized || wd.maximized) {
  2104. ShowWindow(wd.hWnd, SW_RESTORE);
  2105. }
  2106. // Save previous maximized stare.
  2107. wd.was_maximized_pre_fs = wd.maximized;
  2108. if (!was_fullscreen) {
  2109. // Save non-fullscreen rect before entering fullscreen.
  2110. GetWindowRect(wd.hWnd, &wd.pre_fs_rect);
  2111. wd.pre_fs_valid = true;
  2112. }
  2113. int cs = window_get_current_screen(p_window);
  2114. Point2 pos = screen_get_position(cs) + _get_screens_origin();
  2115. Size2 size = screen_get_size(cs);
  2116. wd.fullscreen = true;
  2117. wd.maximized = false;
  2118. wd.minimized = false;
  2119. _update_window_style(p_window, false);
  2120. int off_x = (wd.multiwindow_fs || (!wd.fullscreen && wd.borderless && wd.maximized)) ? FS_TRANSP_BORDER : 0;
  2121. MoveWindow(wd.hWnd, pos.x, pos.y, size.width + off_x, size.height, TRUE);
  2122. // If the user has mouse trails enabled in windows, then sometimes the cursor disappears in fullscreen mode.
  2123. // Save number of trails so we can restore when exiting, then turn off mouse trails
  2124. SystemParametersInfoA(SPI_GETMOUSETRAILS, 0, &restore_mouse_trails, 0);
  2125. if (restore_mouse_trails > 1) {
  2126. SystemParametersInfoA(SPI_SETMOUSETRAILS, 0, nullptr, 0);
  2127. }
  2128. }
  2129. _update_window_mouse_passthrough(p_window);
  2130. }
  2131. DisplayServer::WindowMode DisplayServerWindows::window_get_mode(WindowID p_window) const {
  2132. _THREAD_SAFE_METHOD_
  2133. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  2134. const WindowData &wd = windows[p_window];
  2135. if (wd.fullscreen) {
  2136. if (wd.multiwindow_fs) {
  2137. return WINDOW_MODE_FULLSCREEN;
  2138. } else {
  2139. return WINDOW_MODE_EXCLUSIVE_FULLSCREEN;
  2140. }
  2141. } else if (wd.minimized) {
  2142. return WINDOW_MODE_MINIMIZED;
  2143. } else if (wd.maximized) {
  2144. return WINDOW_MODE_MAXIMIZED;
  2145. } else {
  2146. return WINDOW_MODE_WINDOWED;
  2147. }
  2148. }
  2149. bool DisplayServerWindows::window_is_maximize_allowed(WindowID p_window) const {
  2150. _THREAD_SAFE_METHOD_
  2151. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2152. const WindowData &wd = windows[p_window];
  2153. const DWORD style = GetWindowLongPtr(wd.hWnd, GWL_STYLE);
  2154. return (style & WS_MAXIMIZEBOX) == WS_MAXIMIZEBOX;
  2155. }
  2156. void DisplayServerWindows::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  2157. _THREAD_SAFE_METHOD_
  2158. ERR_FAIL_COND(!windows.has(p_window));
  2159. WindowData &wd = windows[p_window];
  2160. switch (p_flag) {
  2161. case WINDOW_FLAG_MINIMIZE_DISABLED: {
  2162. wd.no_min_btn = p_enabled;
  2163. _update_window_style(p_window);
  2164. } break;
  2165. case WINDOW_FLAG_MAXIMIZE_DISABLED: {
  2166. wd.no_max_btn = p_enabled;
  2167. _update_window_style(p_window);
  2168. } break;
  2169. case WINDOW_FLAG_RESIZE_DISABLED: {
  2170. if (p_enabled && wd.parent_hwnd) {
  2171. print_line("Embedded window resize can't be disabled.");
  2172. return;
  2173. }
  2174. wd.resizable = !p_enabled;
  2175. _update_window_style(p_window);
  2176. } break;
  2177. case WINDOW_FLAG_BORDERLESS: {
  2178. wd.borderless = p_enabled;
  2179. _update_window_mouse_passthrough(p_window);
  2180. _update_window_style(p_window);
  2181. ShowWindow(wd.hWnd, (wd.no_focus || wd.is_popup) ? SW_SHOWNOACTIVATE : SW_SHOW); // Show the window.
  2182. } break;
  2183. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2184. ERR_FAIL_COND_MSG(wd.transient_parent != INVALID_WINDOW_ID && p_enabled, "Transient windows can't become on top.");
  2185. if (p_enabled && wd.parent_hwnd) {
  2186. print_line("Embedded window can't become on top.");
  2187. return;
  2188. }
  2189. wd.always_on_top = p_enabled;
  2190. _update_window_style(p_window);
  2191. } break;
  2192. case WINDOW_FLAG_SHARP_CORNERS: {
  2193. wd.sharp_corners = p_enabled;
  2194. DWORD value = wd.sharp_corners ? DWMWCP_DONOTROUND : DWMWCP_DEFAULT;
  2195. ::DwmSetWindowAttribute(wd.hWnd, DWMWA_WINDOW_CORNER_PREFERENCE, &value, sizeof(value));
  2196. _update_window_style(p_window);
  2197. } break;
  2198. case WINDOW_FLAG_TRANSPARENT: {
  2199. if (p_enabled) {
  2200. // Enable per-pixel alpha.
  2201. if (OS::get_singleton()->is_layered_allowed()) {
  2202. DWM_BLURBEHIND bb;
  2203. ZeroMemory(&bb, sizeof(bb));
  2204. HRGN hRgn = CreateRectRgn(0, 0, -1, -1);
  2205. bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
  2206. bb.hRgnBlur = hRgn;
  2207. bb.fEnable = TRUE;
  2208. DwmEnableBlurBehindWindow(wd.hWnd, &bb);
  2209. }
  2210. wd.layered_window = true;
  2211. } else {
  2212. // Disable per-pixel alpha.
  2213. wd.layered_window = false;
  2214. if (OS::get_singleton()->is_layered_allowed()) {
  2215. DWM_BLURBEHIND bb;
  2216. ZeroMemory(&bb, sizeof(bb));
  2217. HRGN hRgn = CreateRectRgn(0, 0, -1, -1);
  2218. bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
  2219. bb.hRgnBlur = hRgn;
  2220. bb.fEnable = FALSE;
  2221. DwmEnableBlurBehindWindow(wd.hWnd, &bb);
  2222. }
  2223. }
  2224. } break;
  2225. case WINDOW_FLAG_NO_FOCUS: {
  2226. wd.no_focus = p_enabled;
  2227. _update_window_style(p_window);
  2228. } break;
  2229. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2230. wd.mpass = p_enabled;
  2231. } break;
  2232. case WINDOW_FLAG_EXCLUDE_FROM_CAPTURE: {
  2233. wd.hide_from_capture = p_enabled;
  2234. if (p_enabled) {
  2235. if (os_ver.dwBuildNumber >= 19041) {
  2236. SetWindowDisplayAffinity(wd.hWnd, WDA_EXCLUDEFROMCAPTURE);
  2237. } else {
  2238. SetWindowDisplayAffinity(wd.hWnd, WDA_MONITOR);
  2239. }
  2240. } else {
  2241. SetWindowDisplayAffinity(wd.hWnd, WDA_NONE);
  2242. }
  2243. } break;
  2244. case WINDOW_FLAG_POPUP: {
  2245. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
  2246. ERR_FAIL_COND_MSG(IsWindowVisible(wd.hWnd) && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
  2247. if (p_enabled && wd.parent_hwnd) {
  2248. print_line("Embedded window can't be popup.");
  2249. return;
  2250. }
  2251. wd.is_popup = p_enabled;
  2252. } break;
  2253. default:
  2254. break;
  2255. }
  2256. }
  2257. bool DisplayServerWindows::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  2258. _THREAD_SAFE_METHOD_
  2259. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2260. const WindowData &wd = windows[p_window];
  2261. switch (p_flag) {
  2262. case WINDOW_FLAG_MAXIMIZE_DISABLED: {
  2263. return wd.no_max_btn;
  2264. } break;
  2265. case WINDOW_FLAG_MINIMIZE_DISABLED: {
  2266. return wd.no_min_btn;
  2267. } break;
  2268. case WINDOW_FLAG_RESIZE_DISABLED: {
  2269. return !wd.resizable;
  2270. } break;
  2271. case WINDOW_FLAG_BORDERLESS: {
  2272. return wd.borderless;
  2273. } break;
  2274. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2275. return wd.always_on_top;
  2276. } break;
  2277. case WINDOW_FLAG_SHARP_CORNERS: {
  2278. return wd.sharp_corners;
  2279. } break;
  2280. case WINDOW_FLAG_TRANSPARENT: {
  2281. return wd.layered_window;
  2282. } break;
  2283. case WINDOW_FLAG_NO_FOCUS: {
  2284. return wd.no_focus;
  2285. } break;
  2286. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2287. return wd.mpass;
  2288. } break;
  2289. case WINDOW_FLAG_EXCLUDE_FROM_CAPTURE: {
  2290. return wd.hide_from_capture;
  2291. } break;
  2292. case WINDOW_FLAG_POPUP: {
  2293. return wd.is_popup;
  2294. } break;
  2295. default:
  2296. break;
  2297. }
  2298. return false;
  2299. }
  2300. void DisplayServerWindows::window_request_attention(WindowID p_window) {
  2301. _THREAD_SAFE_METHOD_
  2302. ERR_FAIL_COND(!windows.has(p_window));
  2303. const WindowData &wd = windows[p_window];
  2304. FLASHWINFO info;
  2305. info.cbSize = sizeof(FLASHWINFO);
  2306. info.hwnd = wd.hWnd;
  2307. info.dwFlags = FLASHW_ALL;
  2308. info.dwTimeout = 0;
  2309. info.uCount = 2;
  2310. FlashWindowEx(&info);
  2311. }
  2312. void DisplayServerWindows::window_move_to_foreground(WindowID p_window) {
  2313. _THREAD_SAFE_METHOD_
  2314. ERR_FAIL_COND(!windows.has(p_window));
  2315. WindowData &wd = windows[p_window];
  2316. if (!wd.no_focus && !wd.is_popup) {
  2317. SetForegroundWindow(wd.hWnd);
  2318. }
  2319. }
  2320. bool DisplayServerWindows::window_is_focused(WindowID p_window) const {
  2321. _THREAD_SAFE_METHOD_
  2322. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2323. const WindowData &wd = windows[p_window];
  2324. return wd.window_focused;
  2325. }
  2326. DisplayServerWindows::WindowID DisplayServerWindows::get_focused_window() const {
  2327. return last_focused_window;
  2328. }
  2329. bool DisplayServerWindows::window_can_draw(WindowID p_window) const {
  2330. _THREAD_SAFE_METHOD_
  2331. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2332. const WindowData &wd = windows[p_window];
  2333. return !wd.minimized;
  2334. }
  2335. bool DisplayServerWindows::can_any_window_draw() const {
  2336. _THREAD_SAFE_METHOD_
  2337. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2338. if (!E.value.minimized) {
  2339. return true;
  2340. }
  2341. }
  2342. return false;
  2343. }
  2344. int DisplayServerWindows::accessibility_should_increase_contrast() const {
  2345. HIGHCONTRASTA hc;
  2346. hc.cbSize = sizeof(HIGHCONTRAST);
  2347. if (!SystemParametersInfoA(SPI_GETHIGHCONTRAST, sizeof(HIGHCONTRAST), &hc, 0)) {
  2348. return -1;
  2349. }
  2350. return (hc.dwFlags & HCF_HIGHCONTRASTON);
  2351. }
  2352. int DisplayServerWindows::accessibility_should_reduce_animation() const {
  2353. BOOL anim_enabled = false; // Note: this should be BOOL (WinAPI), not bool (C++), since SystemParametersInfoA expect variable with specific size.
  2354. if (!SystemParametersInfoA(SPI_GETCLIENTAREAANIMATION, 0, &anim_enabled, 0)) {
  2355. return -1;
  2356. }
  2357. return (!anim_enabled);
  2358. }
  2359. int DisplayServerWindows::accessibility_should_reduce_transparency() const {
  2360. BOOL tr_enabled = false; // Note: this should be BOOL (WinAPI), not bool (C++), since SystemParametersInfoA expect variable with specific size.
  2361. if (!SystemParametersInfoA(SPI_GETDISABLEOVERLAPPEDCONTENT, 0, &tr_enabled, 0)) {
  2362. return -1;
  2363. }
  2364. return tr_enabled;
  2365. }
  2366. int DisplayServerWindows::accessibility_screen_reader_active() const {
  2367. BOOL sr_enabled = false; // Note: this should be BOOL (WinAPI), not bool (C++), since SystemParametersInfoA expect variable with specific size.
  2368. if (SystemParametersInfoA(SPI_GETSCREENREADER, 0, &sr_enabled, 0) && sr_enabled) {
  2369. return true;
  2370. }
  2371. static const WCHAR *narrator_mutex_name = L"NarratorRunning";
  2372. HANDLE narrator_mutex = OpenMutexW(MUTEX_ALL_ACCESS, false, narrator_mutex_name);
  2373. if (narrator_mutex) {
  2374. CloseHandle(narrator_mutex);
  2375. return true;
  2376. }
  2377. return false;
  2378. }
  2379. Vector2i DisplayServerWindows::ime_get_selection() const {
  2380. _THREAD_SAFE_METHOD_
  2381. DisplayServer::WindowID window_id = _get_focused_window_or_popup();
  2382. const WindowData &wd = windows[window_id];
  2383. if (!wd.ime_active) {
  2384. return Vector2i();
  2385. }
  2386. int cursor = ImmGetCompositionStringW(wd.im_himc, GCS_CURSORPOS, nullptr, 0);
  2387. int32_t length = ImmGetCompositionStringW(wd.im_himc, GCS_COMPSTR, nullptr, 0);
  2388. wchar_t *string = reinterpret_cast<wchar_t *>(memalloc(length));
  2389. ImmGetCompositionStringW(wd.im_himc, GCS_COMPSTR, string, length);
  2390. int32_t utf32_cursor = 0;
  2391. for (int32_t i = 0; i < length / int32_t(sizeof(wchar_t)); i++) {
  2392. if ((string[i] & 0xfffffc00) == 0xd800) {
  2393. i++;
  2394. }
  2395. if (i < cursor) {
  2396. utf32_cursor++;
  2397. } else {
  2398. break;
  2399. }
  2400. }
  2401. memdelete(string);
  2402. return Vector2i(utf32_cursor, 0);
  2403. }
  2404. String DisplayServerWindows::ime_get_text() const {
  2405. _THREAD_SAFE_METHOD_
  2406. DisplayServer::WindowID window_id = _get_focused_window_or_popup();
  2407. const WindowData &wd = windows[window_id];
  2408. if (!wd.ime_active) {
  2409. return String();
  2410. }
  2411. String ret;
  2412. int32_t length = ImmGetCompositionStringW(wd.im_himc, GCS_COMPSTR, nullptr, 0);
  2413. wchar_t *string = reinterpret_cast<wchar_t *>(memalloc(length));
  2414. ImmGetCompositionStringW(wd.im_himc, GCS_COMPSTR, string, length);
  2415. ret.append_utf16((char16_t *)string, length / sizeof(wchar_t));
  2416. memdelete(string);
  2417. return ret;
  2418. }
  2419. void DisplayServerWindows::window_set_ime_active(const bool p_active, WindowID p_window) {
  2420. _THREAD_SAFE_METHOD_
  2421. ERR_FAIL_COND(!windows.has(p_window));
  2422. WindowData &wd = windows[p_window];
  2423. if (p_active) {
  2424. wd.ime_active = true;
  2425. ImmAssociateContext(wd.hWnd, wd.im_himc);
  2426. CreateCaret(wd.hWnd, nullptr, 1, 1);
  2427. window_set_ime_position(wd.im_position, p_window);
  2428. } else {
  2429. ImmAssociateContext(wd.hWnd, (HIMC) nullptr);
  2430. DestroyCaret();
  2431. wd.ime_active = false;
  2432. }
  2433. }
  2434. void DisplayServerWindows::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  2435. _THREAD_SAFE_METHOD_
  2436. ERR_FAIL_COND(!windows.has(p_window));
  2437. WindowData &wd = windows[p_window];
  2438. wd.im_position = p_pos;
  2439. HIMC himc = ImmGetContext(wd.hWnd);
  2440. if (himc == (HIMC) nullptr) {
  2441. return;
  2442. }
  2443. COMPOSITIONFORM cps;
  2444. cps.dwStyle = CFS_POINT;
  2445. cps.ptCurrentPos.x = wd.im_position.x;
  2446. cps.ptCurrentPos.y = wd.im_position.y;
  2447. ImmSetCompositionWindow(himc, &cps);
  2448. ImmReleaseContext(wd.hWnd, himc);
  2449. }
  2450. void DisplayServerWindows::cursor_set_shape(CursorShape p_shape) {
  2451. _THREAD_SAFE_METHOD_
  2452. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2453. if (cursor_shape == p_shape) {
  2454. return;
  2455. }
  2456. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  2457. cursor_shape = p_shape;
  2458. return;
  2459. }
  2460. static const LPCTSTR win_cursors[CURSOR_MAX] = {
  2461. IDC_ARROW,
  2462. IDC_IBEAM,
  2463. IDC_HAND, // Finger.
  2464. IDC_CROSS,
  2465. IDC_WAIT,
  2466. IDC_APPSTARTING,
  2467. IDC_SIZEALL,
  2468. IDC_ARROW,
  2469. IDC_NO,
  2470. IDC_SIZENS,
  2471. IDC_SIZEWE,
  2472. IDC_SIZENESW,
  2473. IDC_SIZENWSE,
  2474. IDC_SIZEALL,
  2475. IDC_SIZENS,
  2476. IDC_SIZEWE,
  2477. IDC_HELP
  2478. };
  2479. if (cursors_cache.has(p_shape)) {
  2480. SetCursor(cursors[p_shape]);
  2481. } else {
  2482. SetCursor(LoadCursor(hInstance, win_cursors[p_shape]));
  2483. }
  2484. cursor_shape = p_shape;
  2485. }
  2486. DisplayServer::CursorShape DisplayServerWindows::cursor_get_shape() const {
  2487. return cursor_shape;
  2488. }
  2489. void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2490. _THREAD_SAFE_METHOD_
  2491. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2492. if (p_cursor.is_valid()) {
  2493. RBMap<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape);
  2494. if (cursor_c) {
  2495. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  2496. cursor_set_shape(p_shape);
  2497. return;
  2498. }
  2499. cursors_cache.erase(p_shape);
  2500. }
  2501. Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot);
  2502. ERR_FAIL_COND(image.is_null());
  2503. Vector2i texture_size = image->get_size();
  2504. UINT image_size = texture_size.width * texture_size.height;
  2505. // Create the BITMAP with alpha channel.
  2506. COLORREF *buffer = nullptr;
  2507. BITMAPV5HEADER bi;
  2508. ZeroMemory(&bi, sizeof(bi));
  2509. bi.bV5Size = sizeof(bi);
  2510. bi.bV5Width = texture_size.width;
  2511. bi.bV5Height = -texture_size.height;
  2512. bi.bV5Planes = 1;
  2513. bi.bV5BitCount = 32;
  2514. bi.bV5Compression = BI_BITFIELDS;
  2515. bi.bV5RedMask = 0x00ff0000;
  2516. bi.bV5GreenMask = 0x0000ff00;
  2517. bi.bV5BlueMask = 0x000000ff;
  2518. bi.bV5AlphaMask = 0xff000000;
  2519. HDC dc = GetDC(nullptr);
  2520. HBITMAP bitmap = CreateDIBSection(dc, reinterpret_cast<BITMAPINFO *>(&bi), DIB_RGB_COLORS, reinterpret_cast<void **>(&buffer), nullptr, 0);
  2521. HBITMAP mask = CreateBitmap(texture_size.width, texture_size.height, 1, 1, nullptr);
  2522. bool fully_transparent = true;
  2523. for (UINT index = 0; index < image_size; index++) {
  2524. int row_index = std::floor(index / texture_size.width);
  2525. int column_index = index % int(texture_size.width);
  2526. const Color &c = image->get_pixel(column_index, row_index);
  2527. fully_transparent = fully_transparent && (c.a == 0.f);
  2528. *(buffer + index) = c.to_argb32();
  2529. }
  2530. // Finally, create the icon.
  2531. if (cursors[p_shape]) {
  2532. DestroyIcon(cursors[p_shape]);
  2533. }
  2534. if (fully_transparent) {
  2535. cursors[p_shape] = nullptr;
  2536. } else {
  2537. ICONINFO iconinfo;
  2538. iconinfo.fIcon = FALSE;
  2539. iconinfo.xHotspot = p_hotspot.x;
  2540. iconinfo.yHotspot = p_hotspot.y;
  2541. iconinfo.hbmMask = mask;
  2542. iconinfo.hbmColor = bitmap;
  2543. cursors[p_shape] = CreateIconIndirect(&iconinfo);
  2544. }
  2545. Vector<Variant> params;
  2546. params.push_back(p_cursor);
  2547. params.push_back(p_hotspot);
  2548. cursors_cache.insert(p_shape, params);
  2549. if (p_shape == cursor_shape) {
  2550. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2551. SetCursor(cursors[p_shape]);
  2552. }
  2553. }
  2554. DeleteObject(mask);
  2555. DeleteObject(bitmap);
  2556. ReleaseDC(nullptr, dc);
  2557. } else {
  2558. // Reset to default system cursor.
  2559. if (cursors[p_shape]) {
  2560. DestroyIcon(cursors[p_shape]);
  2561. }
  2562. cursors[p_shape] = nullptr;
  2563. cursors_cache.erase(p_shape);
  2564. CursorShape c = cursor_shape;
  2565. cursor_shape = CURSOR_MAX;
  2566. cursor_set_shape(c);
  2567. }
  2568. }
  2569. bool DisplayServerWindows::get_swap_cancel_ok() {
  2570. return true;
  2571. }
  2572. void DisplayServerWindows::enable_for_stealing_focus(OS::ProcessID pid) {
  2573. _THREAD_SAFE_METHOD_
  2574. AllowSetForegroundWindow(pid);
  2575. }
  2576. struct WindowEnumData {
  2577. DWORD process_id;
  2578. HWND parent_hWnd;
  2579. HWND hWnd;
  2580. };
  2581. static BOOL CALLBACK _enum_proc_find_window_from_process_id_callback(HWND hWnd, LPARAM lParam) {
  2582. WindowEnumData &ed = *(WindowEnumData *)lParam;
  2583. DWORD process_id = 0x0;
  2584. GetWindowThreadProcessId(hWnd, &process_id);
  2585. if (ed.process_id == process_id) {
  2586. if (GetParent(hWnd) != ed.parent_hWnd) {
  2587. return TRUE;
  2588. }
  2589. // Found it.
  2590. ed.hWnd = hWnd;
  2591. SetLastError(ERROR_SUCCESS);
  2592. return FALSE;
  2593. }
  2594. // Continue enumeration.
  2595. return TRUE;
  2596. }
  2597. HWND DisplayServerWindows::_find_window_from_process_id(OS::ProcessID p_pid, HWND p_current_hwnd) {
  2598. DWORD pid = p_pid;
  2599. WindowEnumData ed = { pid, p_current_hwnd, NULL };
  2600. // First, check our own child, maybe it's already embedded.
  2601. if (!EnumChildWindows(p_current_hwnd, _enum_proc_find_window_from_process_id_callback, (LPARAM)&ed) && (GetLastError() == ERROR_SUCCESS)) {
  2602. if (ed.hWnd) {
  2603. return ed.hWnd;
  2604. }
  2605. }
  2606. // Then check all the opened windows on the computer.
  2607. if (!EnumWindows(_enum_proc_find_window_from_process_id_callback, (LPARAM)&ed) && (GetLastError() == ERROR_SUCCESS)) {
  2608. return ed.hWnd;
  2609. }
  2610. return NULL;
  2611. }
  2612. Error DisplayServerWindows::embed_process(WindowID p_window, OS::ProcessID p_pid, const Rect2i &p_rect, bool p_visible, bool p_grab_focus) {
  2613. _THREAD_SAFE_METHOD_
  2614. ERR_FAIL_COND_V(!windows.has(p_window), FAILED);
  2615. const WindowData &wd = windows[p_window];
  2616. EmbeddedProcessData *ep = nullptr;
  2617. if (embedded_processes.has(p_pid)) {
  2618. ep = embedded_processes.get(p_pid);
  2619. } else {
  2620. // New process, trying to find the window.
  2621. HWND handle_to_embed = _find_window_from_process_id(p_pid, wd.hWnd);
  2622. if (!handle_to_embed) {
  2623. return ERR_DOES_NOT_EXIST;
  2624. }
  2625. const DWORD style = GetWindowLongPtr(handle_to_embed, GWL_STYLE);
  2626. ep = memnew(EmbeddedProcessData);
  2627. ep->window_handle = handle_to_embed;
  2628. ep->parent_window_handle = wd.hWnd;
  2629. ep->is_visible = (style & WS_VISIBLE) == WS_VISIBLE;
  2630. embedded_processes.insert(p_pid, ep);
  2631. }
  2632. if (p_rect.size.x <= 100 || p_rect.size.y <= 100) {
  2633. p_visible = false;
  2634. }
  2635. // In Godot, the window position is offset by the screen's origin coordinates.
  2636. // We need to adjust for this when a screen is positioned in the negative space
  2637. // (e.g., a screen to the left of the main screen).
  2638. const Rect2i adjusted_rect = Rect2i(p_rect.position + _get_screens_origin(), p_rect.size);
  2639. // Use HWND_BOTTOM to prevent reordering of the embedded window over another popup.
  2640. SetWindowPos(ep->window_handle, HWND_BOTTOM, adjusted_rect.position.x, adjusted_rect.position.y, adjusted_rect.size.x, adjusted_rect.size.y, SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
  2641. if (ep->is_visible != p_visible) {
  2642. if (p_visible) {
  2643. ShowWindow(ep->window_handle, SW_SHOWNA);
  2644. } else {
  2645. ShowWindow(ep->window_handle, SW_HIDE);
  2646. }
  2647. ep->is_visible = p_visible;
  2648. }
  2649. if (p_grab_focus) {
  2650. SetForegroundWindow(ep->window_handle);
  2651. SetFocus(ep->window_handle);
  2652. }
  2653. return OK;
  2654. }
  2655. Error DisplayServerWindows::request_close_embedded_process(OS::ProcessID p_pid) {
  2656. _THREAD_SAFE_METHOD_
  2657. if (!embedded_processes.has(p_pid)) {
  2658. return ERR_DOES_NOT_EXIST;
  2659. }
  2660. EmbeddedProcessData *ep = embedded_processes.get(p_pid);
  2661. // Send a close message to gracefully close the process.
  2662. PostMessage(ep->window_handle, WM_CLOSE, 0, 0);
  2663. return OK;
  2664. }
  2665. Error DisplayServerWindows::remove_embedded_process(OS::ProcessID p_pid) {
  2666. _THREAD_SAFE_METHOD_
  2667. if (!embedded_processes.has(p_pid)) {
  2668. return ERR_DOES_NOT_EXIST;
  2669. }
  2670. EmbeddedProcessData *ep = embedded_processes.get(p_pid);
  2671. request_close_embedded_process(p_pid);
  2672. // This is a workaround to ensure the parent window correctly regains focus after the
  2673. // embedded window is closed. When the embedded window is closed while it has focus,
  2674. // the parent window (the editor) does not become active. It appears focused but is not truly activated.
  2675. // Opening a new window and closing it forces Windows to set the focus and activation correctly.
  2676. DWORD style = WS_POPUP | WS_VISIBLE;
  2677. DWORD style_ex = WS_EX_TOPMOST;
  2678. WNDCLASSW wcTemp = {};
  2679. wcTemp.lpfnWndProc = DefWindowProcW;
  2680. wcTemp.hInstance = GetModuleHandle(nullptr);
  2681. wcTemp.lpszClassName = L"Engine temp window";
  2682. RegisterClassW(&wcTemp);
  2683. HWND hWnd = CreateWindowExW(
  2684. style_ex,
  2685. L"Engine temp window", L"",
  2686. style,
  2687. 0,
  2688. 0,
  2689. 1,
  2690. 1,
  2691. ep->parent_window_handle,
  2692. nullptr,
  2693. GetModuleHandle(nullptr),
  2694. nullptr);
  2695. SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
  2696. DestroyWindow(hWnd);
  2697. UnregisterClassW(L"Engine temp window", GetModuleHandle(nullptr));
  2698. SetForegroundWindow(ep->parent_window_handle);
  2699. embedded_processes.erase(p_pid);
  2700. memdelete(ep);
  2701. return OK;
  2702. }
  2703. OS::ProcessID DisplayServerWindows::get_focused_process_id() {
  2704. HWND hwnd = GetForegroundWindow();
  2705. if (!hwnd) {
  2706. return 0;
  2707. }
  2708. // Get the process ID of the window.
  2709. DWORD processID;
  2710. GetWindowThreadProcessId(hwnd, &processID);
  2711. return processID;
  2712. }
  2713. static HRESULT CALLBACK win32_task_dialog_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, LONG_PTR lpRefData) {
  2714. if (msg == TDN_CREATED) {
  2715. // To match the input text dialog.
  2716. SendMessageW(hwnd, WM_SETICON, ICON_BIG, 0);
  2717. SendMessageW(hwnd, WM_SETICON, ICON_SMALL, 0);
  2718. }
  2719. return 0;
  2720. }
  2721. Error DisplayServerWindows::dialog_show(String p_title, String p_description, Vector<String> p_buttons, const Callable &p_callback) {
  2722. _THREAD_SAFE_METHOD_
  2723. TASKDIALOGCONFIG config;
  2724. ZeroMemory(&config, sizeof(TASKDIALOGCONFIG));
  2725. config.cbSize = sizeof(TASKDIALOGCONFIG);
  2726. Char16String title = p_title.utf16();
  2727. Char16String message = p_description.utf16();
  2728. LocalVector<Char16String> buttons;
  2729. for (String s : p_buttons) {
  2730. buttons.push_back(s.utf16());
  2731. }
  2732. WindowID window_id = _get_focused_window_or_popup();
  2733. if (!windows.has(window_id)) {
  2734. window_id = MAIN_WINDOW_ID;
  2735. }
  2736. config.pszWindowTitle = (LPCWSTR)(title.get_data());
  2737. config.pszContent = (LPCWSTR)(message.get_data());
  2738. config.hwndParent = windows[window_id].hWnd;
  2739. const int button_count = buttons.size();
  2740. config.cButtons = button_count;
  2741. // No dynamic stack array size :(
  2742. TASKDIALOG_BUTTON *tbuttons = button_count != 0 ? (TASKDIALOG_BUTTON *)alloca(sizeof(TASKDIALOG_BUTTON) * button_count) : nullptr;
  2743. if (tbuttons) {
  2744. for (int i = 0; i < button_count; i++) {
  2745. tbuttons[i].nButtonID = i + 100;
  2746. tbuttons[i].pszButtonText = (LPCWSTR)(buttons[i].get_data());
  2747. }
  2748. }
  2749. config.pButtons = tbuttons;
  2750. config.pfCallback = win32_task_dialog_callback;
  2751. Error result = FAILED;
  2752. HMODULE comctl = LoadLibraryW(L"comctl32.dll");
  2753. if (comctl) {
  2754. typedef HRESULT(WINAPI * TaskDialogIndirectPtr)(const TASKDIALOGCONFIG *pTaskConfig, int *pnButton, int *pnRadioButton, BOOL *pfVerificationFlagChecked);
  2755. TaskDialogIndirectPtr task_dialog_indirect = (TaskDialogIndirectPtr)(void *)GetProcAddress(comctl, "TaskDialogIndirect");
  2756. int button_pressed;
  2757. if (task_dialog_indirect && SUCCEEDED(task_dialog_indirect(&config, &button_pressed, nullptr, nullptr))) {
  2758. if (p_callback.is_valid()) {
  2759. Variant button = button_pressed - 100;
  2760. const Variant *args[1] = { &button };
  2761. Variant ret;
  2762. Callable::CallError ce;
  2763. p_callback.callp(args, 1, ret, ce);
  2764. if (ce.error != Callable::CallError::CALL_OK) {
  2765. ERR_PRINT(vformat("Failed to execute dialog callback: %s.", Variant::get_callable_error_text(p_callback, args, 1, ce)));
  2766. }
  2767. }
  2768. result = OK;
  2769. }
  2770. FreeLibrary(comctl);
  2771. } else {
  2772. ERR_PRINT("Unable to create native dialog.");
  2773. }
  2774. return result;
  2775. }
  2776. struct Win32InputTextDialogInit {
  2777. const char16_t *title;
  2778. const char16_t *description;
  2779. const char16_t *partial;
  2780. const Callable &callback;
  2781. };
  2782. static int scale_with_dpi(int p_pos, int p_dpi) {
  2783. return IsProcessDPIAware() ? (p_pos * p_dpi / 96) : p_pos;
  2784. }
  2785. static INT_PTR input_text_dialog_init(HWND hWnd, UINT code, WPARAM wParam, LPARAM lParam) {
  2786. Win32InputTextDialogInit init = *(Win32InputTextDialogInit *)lParam;
  2787. SetWindowLongPtrW(hWnd, GWLP_USERDATA, (LONG_PTR)&init.callback); // Set dialog callback.
  2788. SetWindowTextW(hWnd, (LPCWSTR)init.title);
  2789. const int dpi = DisplayServerWindows::get_singleton()->screen_get_dpi();
  2790. const int margin = scale_with_dpi(7, dpi);
  2791. const SIZE dlg_size = { scale_with_dpi(300, dpi), scale_with_dpi(50, dpi) };
  2792. int str_len = lstrlenW((LPCWSTR)init.description);
  2793. SIZE str_size = { dlg_size.cx, 0 };
  2794. if (str_len > 0) {
  2795. HDC hdc = GetDC(nullptr);
  2796. RECT trect = { margin, margin, margin + dlg_size.cx, margin + dlg_size.cy };
  2797. SelectObject(hdc, (HFONT)SendMessageW(hWnd, WM_GETFONT, 0, 0));
  2798. // `+ margin` adds some space between the static text and the edit field.
  2799. // Don't scale this with DPI because DPI is already handled by DrawText.
  2800. str_size.cy = DrawTextW(hdc, (LPCWSTR)init.description, str_len, &trect, DT_LEFT | DT_WORDBREAK | DT_CALCRECT) + margin;
  2801. ReleaseDC(nullptr, hdc);
  2802. }
  2803. RECT crect, wrect;
  2804. GetClientRect(hWnd, &crect);
  2805. GetWindowRect(hWnd, &wrect);
  2806. int sw = GetSystemMetrics(SM_CXSCREEN);
  2807. int sh = GetSystemMetrics(SM_CYSCREEN);
  2808. int new_width = dlg_size.cx + margin * 2 + wrect.right - wrect.left - crect.right;
  2809. int new_height = dlg_size.cy + margin * 2 + wrect.bottom - wrect.top - crect.bottom + str_size.cy;
  2810. MoveWindow(hWnd, (sw - new_width) / 2, (sh - new_height) / 2, new_width, new_height, true);
  2811. HWND ok_button = GetDlgItem(hWnd, 1);
  2812. MoveWindow(ok_button,
  2813. dlg_size.cx + margin - scale_with_dpi(65, dpi),
  2814. dlg_size.cy + str_size.cy + margin - scale_with_dpi(20, dpi),
  2815. scale_with_dpi(65, dpi), scale_with_dpi(20, dpi), true);
  2816. HWND description = GetDlgItem(hWnd, 3);
  2817. MoveWindow(description, margin, margin, dlg_size.cx, str_size.cy, true);
  2818. SetWindowTextW(description, (LPCWSTR)init.description);
  2819. HWND text_edit = GetDlgItem(hWnd, 2);
  2820. MoveWindow(text_edit, margin, str_size.cy + margin, dlg_size.cx, scale_with_dpi(20, dpi), true);
  2821. SetWindowTextW(text_edit, (LPCWSTR)init.partial);
  2822. return TRUE;
  2823. }
  2824. static INT_PTR input_text_dialog_cmd_proc(HWND hWnd, UINT code, WPARAM wParam, LPARAM lParam) {
  2825. if (LOWORD(wParam) == 1) {
  2826. HWND text_edit = GetDlgItem(hWnd, 2);
  2827. ERR_FAIL_NULL_V(text_edit, false);
  2828. Char16String text;
  2829. text.resize(GetWindowTextLengthW(text_edit) + 1);
  2830. GetWindowTextW(text_edit, (LPWSTR)text.get_data(), text.size());
  2831. const Callable *callback = (const Callable *)GetWindowLongPtrW(hWnd, GWLP_USERDATA);
  2832. if (callback && callback->is_valid()) {
  2833. Variant v_result = String((const wchar_t *)text.get_data());
  2834. Variant ret;
  2835. Callable::CallError ce;
  2836. const Variant *args[1] = { &v_result };
  2837. callback->callp(args, 1, ret, ce);
  2838. if (ce.error != Callable::CallError::CALL_OK) {
  2839. ERR_PRINT(vformat("Failed to execute input dialog callback: %s.", Variant::get_callable_error_text(*callback, args, 1, ce)));
  2840. }
  2841. }
  2842. return EndDialog(hWnd, 0);
  2843. }
  2844. return false;
  2845. }
  2846. static INT_PTR CALLBACK input_text_dialog_proc(HWND hWnd, UINT code, WPARAM wParam, LPARAM lParam) {
  2847. switch (code) {
  2848. case WM_INITDIALOG:
  2849. return input_text_dialog_init(hWnd, code, wParam, lParam);
  2850. case WM_COMMAND:
  2851. return input_text_dialog_cmd_proc(hWnd, code, wParam, lParam);
  2852. default:
  2853. return FALSE;
  2854. }
  2855. }
  2856. Error DisplayServerWindows::dialog_input_text(String p_title, String p_description, String p_partial, const Callable &p_callback) {
  2857. #pragma pack(push, 1)
  2858. // NOTE: Use default/placeholder coordinates here. Windows uses its own coordinate system
  2859. // specifically for dialogs which relies on font sizes instead of pixels.
  2860. const struct {
  2861. WORD dlgVer; // must be 1
  2862. WORD signature; // must be 0xFFFF
  2863. DWORD helpID;
  2864. DWORD exStyle;
  2865. DWORD style;
  2866. WORD cDlgItems;
  2867. short x;
  2868. short y;
  2869. short cx;
  2870. short cy;
  2871. WCHAR menu[1]; // must be 0
  2872. WCHAR windowClass[7]; // must be "#32770" -- the default window class for dialogs
  2873. WCHAR title[1]; // must be 0
  2874. WORD pointsize;
  2875. WORD weight;
  2876. BYTE italic;
  2877. BYTE charset;
  2878. WCHAR font[13]; // must be "MS Shell Dlg"
  2879. } template_base = {
  2880. 1, 0xFFFF, 0, 0,
  2881. DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION,
  2882. 3, 0, 0, 20, 20, L"", L"#32770", L"", 8, FW_NORMAL, 0, DEFAULT_CHARSET, L"MS Shell Dlg"
  2883. };
  2884. const struct {
  2885. DWORD helpID;
  2886. DWORD exStyle;
  2887. DWORD style;
  2888. short x;
  2889. short y;
  2890. short cx;
  2891. short cy;
  2892. DWORD id;
  2893. WCHAR windowClass[7]; // must be "Button"
  2894. WCHAR title[3]; // must be "OK"
  2895. WORD extraCount;
  2896. } ok_button = {
  2897. 0, 0, WS_VISIBLE | BS_DEFPUSHBUTTON, 0, 0, 50, 14, 1, WC_BUTTONW, L"OK", 0
  2898. };
  2899. const struct {
  2900. DWORD helpID;
  2901. DWORD exStyle;
  2902. DWORD style;
  2903. short x;
  2904. short y;
  2905. short cx;
  2906. short cy;
  2907. DWORD id;
  2908. WCHAR windowClass[5]; // must be "Edit"
  2909. WCHAR title[1]; // must be 0
  2910. WORD extraCount;
  2911. } text_field = {
  2912. 0, 0, WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL, 0, 0, 250, 14, 2, WC_EDITW, L"", 0
  2913. };
  2914. const struct {
  2915. DWORD helpID;
  2916. DWORD exStyle;
  2917. DWORD style;
  2918. short x;
  2919. short y;
  2920. short cx;
  2921. short cy;
  2922. DWORD id;
  2923. WCHAR windowClass[7]; // must be "Static"
  2924. WCHAR title[1]; // must be 0
  2925. WORD extraCount;
  2926. } static_text = {
  2927. 0, 0, WS_VISIBLE, 0, 0, 250, 14, 3, WC_STATICW, L"", 0
  2928. };
  2929. #pragma pack(pop)
  2930. // Dialog template
  2931. const size_t data_size = sizeof(template_base) + (sizeof(template_base) % 4) +
  2932. sizeof(ok_button) + (sizeof(ok_button) % 4) +
  2933. sizeof(text_field) + (sizeof(text_field) % 4) +
  2934. sizeof(static_text) + (sizeof(static_text) % 4);
  2935. void *data_template = memalloc(data_size);
  2936. ERR_FAIL_NULL_V_MSG(data_template, FAILED, "Unable to allocate memory for the dialog template.");
  2937. ZeroMemory(data_template, data_size);
  2938. char *current_block = (char *)data_template;
  2939. CopyMemory(current_block, &template_base, sizeof(template_base));
  2940. current_block += sizeof(template_base) + (sizeof(template_base) % 4);
  2941. CopyMemory(current_block, &ok_button, sizeof(ok_button));
  2942. current_block += sizeof(ok_button) + (sizeof(ok_button) % 4);
  2943. CopyMemory(current_block, &text_field, sizeof(text_field));
  2944. current_block += sizeof(text_field) + (sizeof(text_field) % 4);
  2945. CopyMemory(current_block, &static_text, sizeof(static_text));
  2946. Char16String title16 = p_title.utf16();
  2947. Char16String description16 = p_description.utf16();
  2948. Char16String partial16 = p_partial.utf16();
  2949. Win32InputTextDialogInit init = {
  2950. title16.get_data(), description16.get_data(), partial16.get_data(), p_callback
  2951. };
  2952. // No modal dialogs for specific windows? Assume main window here.
  2953. INT_PTR ret = DialogBoxIndirectParamW(hInstance, (LPDLGTEMPLATEW)data_template, nullptr, (DLGPROC)input_text_dialog_proc, (LPARAM)(&init));
  2954. Error result = ret != -1 ? OK : FAILED;
  2955. memfree(data_template);
  2956. if (result == FAILED) {
  2957. ERR_PRINT("Unable to create native dialog.");
  2958. }
  2959. return result;
  2960. }
  2961. int DisplayServerWindows::keyboard_get_layout_count() const {
  2962. return GetKeyboardLayoutList(0, nullptr);
  2963. }
  2964. int DisplayServerWindows::keyboard_get_current_layout() const {
  2965. HKL cur_layout = GetKeyboardLayout(0);
  2966. int layout_count = GetKeyboardLayoutList(0, nullptr);
  2967. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  2968. GetKeyboardLayoutList(layout_count, layouts);
  2969. for (int i = 0; i < layout_count; i++) {
  2970. if (cur_layout == layouts[i]) {
  2971. memfree(layouts);
  2972. return i;
  2973. }
  2974. }
  2975. memfree(layouts);
  2976. return -1;
  2977. }
  2978. void DisplayServerWindows::keyboard_set_current_layout(int p_index) {
  2979. int layout_count = GetKeyboardLayoutList(0, nullptr);
  2980. ERR_FAIL_INDEX(p_index, layout_count);
  2981. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  2982. GetKeyboardLayoutList(layout_count, layouts);
  2983. ActivateKeyboardLayout(layouts[p_index], KLF_SETFORPROCESS);
  2984. memfree(layouts);
  2985. }
  2986. String DisplayServerWindows::keyboard_get_layout_language(int p_index) const {
  2987. int layout_count = GetKeyboardLayoutList(0, nullptr);
  2988. ERR_FAIL_INDEX_V(p_index, layout_count, "");
  2989. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  2990. GetKeyboardLayoutList(layout_count, layouts);
  2991. WCHAR buf[LOCALE_NAME_MAX_LENGTH];
  2992. memset(buf, 0, LOCALE_NAME_MAX_LENGTH * sizeof(WCHAR));
  2993. LCIDToLocaleName(MAKELCID(LOWORD(layouts[p_index]), SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
  2994. memfree(layouts);
  2995. return String::utf16((const char16_t *)buf).substr(0, 2);
  2996. }
  2997. Key DisplayServerWindows::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2998. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2999. Key keycode_no_mod = (Key)(p_keycode & KeyModifierMask::CODE_MASK);
  3000. if (keycode_no_mod == Key::PRINT ||
  3001. keycode_no_mod == Key::KP_ADD ||
  3002. keycode_no_mod == Key::KP_5 ||
  3003. (keycode_no_mod >= Key::KEY_0 && keycode_no_mod <= Key::KEY_9)) {
  3004. return p_keycode;
  3005. }
  3006. unsigned int scancode = KeyMappingWindows::get_scancode(keycode_no_mod);
  3007. if (scancode == 0) {
  3008. return p_keycode;
  3009. }
  3010. HKL current_layout = GetKeyboardLayout(0);
  3011. UINT vk = MapVirtualKeyEx(scancode, MAPVK_VSC_TO_VK, current_layout);
  3012. if (vk == 0) {
  3013. return p_keycode;
  3014. }
  3015. UINT char_code = MapVirtualKeyEx(vk, MAPVK_VK_TO_CHAR, current_layout) & 0x7FFF;
  3016. // Unlike a similar Linux/BSD check which matches full Latin-1 range,
  3017. // we limit these to ASCII to fix some layouts, including Arabic ones
  3018. if (char_code >= 32 && char_code <= 127) {
  3019. // Godot uses 'braces' instead of 'brackets'
  3020. if (char_code == (unsigned int)Key::BRACKETLEFT || char_code == (unsigned int)Key::BRACKETRIGHT) {
  3021. char_code += 32;
  3022. }
  3023. return (Key)(char_code | (unsigned int)modifiers);
  3024. }
  3025. return (Key)(KeyMappingWindows::get_keysym(vk) | modifiers);
  3026. }
  3027. Key DisplayServerWindows::keyboard_get_label_from_physical(Key p_keycode) const {
  3028. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  3029. Key keycode_no_mod = (Key)(p_keycode & KeyModifierMask::CODE_MASK);
  3030. if (keycode_no_mod == Key::PRINT ||
  3031. keycode_no_mod == Key::KP_ADD ||
  3032. keycode_no_mod == Key::KP_5 ||
  3033. (keycode_no_mod >= Key::KEY_0 && keycode_no_mod <= Key::KEY_9)) {
  3034. return p_keycode;
  3035. }
  3036. unsigned int scancode = KeyMappingWindows::get_scancode(keycode_no_mod);
  3037. if (scancode == 0) {
  3038. return p_keycode;
  3039. }
  3040. Key keycode = KeyMappingWindows::get_keysym(MapVirtualKey(scancode, MAPVK_VSC_TO_VK));
  3041. HKL current_layout = GetKeyboardLayout(0);
  3042. static BYTE keyboard_state[256];
  3043. memset(keyboard_state, 0, 256);
  3044. wchar_t chars[256] = {};
  3045. UINT extended_code = MapVirtualKey(scancode, MAPVK_VSC_TO_VK_EX);
  3046. if (ToUnicodeEx(extended_code, scancode, keyboard_state, chars, 255, 4, current_layout) > 0) {
  3047. String keysym = String::utf16((char16_t *)chars, 255);
  3048. if (!keysym.is_empty()) {
  3049. return fix_key_label(keysym[0], keycode) | modifiers;
  3050. }
  3051. }
  3052. return p_keycode;
  3053. }
  3054. void DisplayServerWindows::show_emoji_and_symbol_picker() const {
  3055. // Send Win + Period shortcut, there's no non-WinRT public API.
  3056. INPUT input[4] = {};
  3057. input[0].type = INPUT_KEYBOARD; // Win down.
  3058. input[0].ki.wVk = VK_LWIN;
  3059. input[1].type = INPUT_KEYBOARD; // Period down.
  3060. input[1].ki.wVk = VK_OEM_PERIOD;
  3061. input[2].type = INPUT_KEYBOARD; // Win up.
  3062. input[2].ki.wVk = VK_LWIN;
  3063. input[2].ki.dwFlags = KEYEVENTF_KEYUP;
  3064. input[3].type = INPUT_KEYBOARD; // Period up.
  3065. input[3].ki.wVk = VK_OEM_PERIOD;
  3066. input[3].ki.dwFlags = KEYEVENTF_KEYUP;
  3067. SendInput(4, input, sizeof(INPUT));
  3068. }
  3069. String DisplayServerWindows::_get_keyboard_layout_display_name(const String &p_klid) const {
  3070. String ret;
  3071. HKEY key;
  3072. if (RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts", &key) != ERROR_SUCCESS) {
  3073. return String();
  3074. }
  3075. WCHAR buffer[MAX_PATH] = {};
  3076. DWORD buffer_size = MAX_PATH;
  3077. if (RegGetValueW(key, (LPCWSTR)p_klid.utf16().get_data(), L"Layout Display Name", RRF_RT_REG_SZ, nullptr, buffer, &buffer_size) == ERROR_SUCCESS) {
  3078. if (SHLoadIndirectString(buffer, buffer, buffer_size, nullptr) == S_OK) {
  3079. ret = String::utf16((const char16_t *)buffer, buffer_size);
  3080. }
  3081. } else {
  3082. if (RegGetValueW(key, (LPCWSTR)p_klid.utf16().get_data(), L"Layout Text", RRF_RT_REG_SZ, nullptr, buffer, &buffer_size) == ERROR_SUCCESS) {
  3083. ret = String::utf16((const char16_t *)buffer, buffer_size);
  3084. }
  3085. }
  3086. RegCloseKey(key);
  3087. return ret;
  3088. }
  3089. String DisplayServerWindows::_get_klid(HKL p_hkl) const {
  3090. String ret;
  3091. WORD device = HIWORD(p_hkl);
  3092. if ((device & 0xf000) == 0xf000) {
  3093. WORD layout_id = device & 0x0fff;
  3094. HKEY key;
  3095. if (RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts", &key) != ERROR_SUCCESS) {
  3096. return String();
  3097. }
  3098. DWORD index = 0;
  3099. wchar_t klid_buffer[KL_NAMELENGTH];
  3100. DWORD klid_buffer_size = KL_NAMELENGTH;
  3101. while (RegEnumKeyExW(key, index, klid_buffer, &klid_buffer_size, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS) {
  3102. wchar_t layout_id_buf[MAX_PATH] = {};
  3103. DWORD layout_id_size = MAX_PATH;
  3104. if (RegGetValueW(key, klid_buffer, L"Layout Id", RRF_RT_REG_SZ, nullptr, layout_id_buf, &layout_id_size) == ERROR_SUCCESS) {
  3105. if (layout_id == String::utf16((char16_t *)layout_id_buf, layout_id_size).hex_to_int()) {
  3106. ret = String::utf16((const char16_t *)klid_buffer, klid_buffer_size).lpad(8, "0");
  3107. break;
  3108. }
  3109. }
  3110. klid_buffer_size = KL_NAMELENGTH;
  3111. ++index;
  3112. }
  3113. RegCloseKey(key);
  3114. } else {
  3115. if (device == 0) {
  3116. device = LOWORD(p_hkl);
  3117. }
  3118. ret = (String::num_uint64((uint64_t)device, 16, false)).lpad(8, "0");
  3119. }
  3120. return ret;
  3121. }
  3122. String DisplayServerWindows::keyboard_get_layout_name(int p_index) const {
  3123. int layout_count = GetKeyboardLayoutList(0, nullptr);
  3124. ERR_FAIL_INDEX_V(p_index, layout_count, "");
  3125. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  3126. GetKeyboardLayoutList(layout_count, layouts);
  3127. String ret = _get_keyboard_layout_display_name(_get_klid(layouts[p_index])); // Try reading full name from Windows registry, fallback to locale name if failed (e.g. on Wine).
  3128. if (ret.is_empty()) {
  3129. WCHAR buf[LOCALE_NAME_MAX_LENGTH];
  3130. memset(buf, 0, LOCALE_NAME_MAX_LENGTH * sizeof(WCHAR));
  3131. LCIDToLocaleName(MAKELCID(LOWORD(layouts[p_index]), SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
  3132. WCHAR name[1024];
  3133. memset(name, 0, 1024 * sizeof(WCHAR));
  3134. GetLocaleInfoEx(buf, LOCALE_SLOCALIZEDDISPLAYNAME, (LPWSTR)&name, 1024);
  3135. ret = String::utf16((const char16_t *)name);
  3136. }
  3137. memfree(layouts);
  3138. return ret;
  3139. }
  3140. void DisplayServerWindows::process_events() {
  3141. ERR_FAIL_COND(!Thread::is_main_thread());
  3142. if (!drop_events) {
  3143. joypad->process_joypads();
  3144. }
  3145. _THREAD_SAFE_LOCK_
  3146. MSG msg = {};
  3147. while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
  3148. TranslateMessage(&msg);
  3149. DispatchMessageW(&msg);
  3150. }
  3151. _THREAD_SAFE_UNLOCK_
  3152. if (tts) {
  3153. tts->process_events();
  3154. }
  3155. if (!drop_events) {
  3156. _process_key_events();
  3157. Input::get_singleton()->flush_buffered_events();
  3158. }
  3159. LocalVector<List<FileDialogData *>::Element *> to_remove;
  3160. for (List<FileDialogData *>::Element *E = file_dialogs.front(); E; E = E->next()) {
  3161. FileDialogData *fd = E->get();
  3162. if (fd->finished.is_set()) {
  3163. if (fd->listener_thread.is_started()) {
  3164. fd->listener_thread.wait_to_finish();
  3165. }
  3166. to_remove.push_back(E);
  3167. }
  3168. }
  3169. for (List<FileDialogData *>::Element *E : to_remove) {
  3170. memdelete(E->get());
  3171. E->erase();
  3172. }
  3173. process_file_dialog_callbacks();
  3174. }
  3175. void DisplayServerWindows::force_process_and_drop_events() {
  3176. ERR_FAIL_COND(!Thread::is_main_thread());
  3177. drop_events = true;
  3178. process_events();
  3179. drop_events = false;
  3180. }
  3181. void DisplayServerWindows::release_rendering_thread() {
  3182. #if defined(GLES3_ENABLED)
  3183. if (gl_manager_angle) {
  3184. gl_manager_angle->release_current();
  3185. }
  3186. if (gl_manager_native) {
  3187. gl_manager_native->release_current();
  3188. }
  3189. #endif
  3190. }
  3191. void DisplayServerWindows::swap_buffers() {
  3192. #if defined(GLES3_ENABLED)
  3193. if (gl_manager_angle) {
  3194. gl_manager_angle->swap_buffers();
  3195. }
  3196. if (gl_manager_native) {
  3197. gl_manager_native->swap_buffers();
  3198. }
  3199. #endif
  3200. }
  3201. void DisplayServerWindows::set_native_icon(const String &p_filename) {
  3202. _THREAD_SAFE_METHOD_
  3203. Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::READ);
  3204. ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file with icon '" + p_filename + "'.");
  3205. ICONDIR *icon_dir = (ICONDIR *)memalloc(sizeof(ICONDIR));
  3206. int pos = 0;
  3207. icon_dir->idReserved = f->get_32();
  3208. pos += sizeof(WORD);
  3209. f->seek(pos);
  3210. icon_dir->idType = f->get_32();
  3211. pos += sizeof(WORD);
  3212. f->seek(pos);
  3213. ERR_FAIL_COND_MSG(icon_dir->idType != 1, "Invalid icon file format!");
  3214. icon_dir->idCount = f->get_32();
  3215. pos += sizeof(WORD);
  3216. f->seek(pos);
  3217. icon_dir = (ICONDIR *)memrealloc(icon_dir, sizeof(ICONDIR) - sizeof(ICONDIRENTRY) + icon_dir->idCount * sizeof(ICONDIRENTRY));
  3218. f->get_buffer((uint8_t *)&icon_dir->idEntries[0], icon_dir->idCount * sizeof(ICONDIRENTRY));
  3219. int small_icon_index = -1; // Select 16x16 with largest color count.
  3220. int small_icon_cc = 0;
  3221. int big_icon_index = -1; // Select largest.
  3222. int big_icon_width = 16;
  3223. int big_icon_cc = 0;
  3224. for (int i = 0; i < icon_dir->idCount; i++) {
  3225. int colors = (icon_dir->idEntries[i].bColorCount == 0) ? 32768 : icon_dir->idEntries[i].bColorCount;
  3226. int width = (icon_dir->idEntries[i].bWidth == 0) ? 256 : icon_dir->idEntries[i].bWidth;
  3227. if (width == 16) {
  3228. if (colors >= small_icon_cc) {
  3229. small_icon_index = i;
  3230. small_icon_cc = colors;
  3231. }
  3232. }
  3233. if (width >= big_icon_width) {
  3234. if (colors >= big_icon_cc) {
  3235. big_icon_index = i;
  3236. big_icon_width = width;
  3237. big_icon_cc = colors;
  3238. }
  3239. }
  3240. }
  3241. ERR_FAIL_COND_MSG(big_icon_index == -1, "No valid icons found!");
  3242. if (small_icon_index == -1) {
  3243. WARN_PRINT("No small icon found, reusing " + itos(big_icon_width) + "x" + itos(big_icon_width) + " @" + itos(big_icon_cc) + " icon!");
  3244. small_icon_index = big_icon_index;
  3245. small_icon_cc = big_icon_cc;
  3246. }
  3247. // Read the big icon.
  3248. DWORD bytecount_big = icon_dir->idEntries[big_icon_index].dwBytesInRes;
  3249. Vector<uint8_t> data_big;
  3250. data_big.resize(bytecount_big);
  3251. pos = icon_dir->idEntries[big_icon_index].dwImageOffset;
  3252. f->seek(pos);
  3253. f->get_buffer((uint8_t *)&data_big.write[0], bytecount_big);
  3254. HICON icon_big = CreateIconFromResource((PBYTE)&data_big.write[0], bytecount_big, TRUE, 0x00030000);
  3255. ERR_FAIL_NULL_MSG(icon_big, "Could not create " + itos(big_icon_width) + "x" + itos(big_icon_width) + " @" + itos(big_icon_cc) + " icon, error: " + format_error_message(GetLastError()) + ".");
  3256. // Read the small icon.
  3257. DWORD bytecount_small = icon_dir->idEntries[small_icon_index].dwBytesInRes;
  3258. Vector<uint8_t> data_small;
  3259. data_small.resize(bytecount_small);
  3260. pos = icon_dir->idEntries[small_icon_index].dwImageOffset;
  3261. f->seek(pos);
  3262. f->get_buffer((uint8_t *)&data_small.write[0], bytecount_small);
  3263. HICON icon_small = CreateIconFromResource((PBYTE)&data_small.write[0], bytecount_small, TRUE, 0x00030000);
  3264. ERR_FAIL_NULL_MSG(icon_small, "Could not create 16x16 @" + itos(small_icon_cc) + " icon, error: " + format_error_message(GetLastError()) + ".");
  3265. // Online tradition says to be sure last error is cleared and set the small icon first.
  3266. int err = 0;
  3267. SetLastError(err);
  3268. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)icon_small);
  3269. err = GetLastError();
  3270. ERR_FAIL_COND_MSG(err, "Error setting ICON_SMALL: " + format_error_message(err) + ".");
  3271. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_BIG, (LPARAM)icon_big);
  3272. err = GetLastError();
  3273. ERR_FAIL_COND_MSG(err, "Error setting ICON_BIG: " + format_error_message(err) + ".");
  3274. memdelete(icon_dir);
  3275. }
  3276. void DisplayServerWindows::set_icon(const Ref<Image> &p_icon) {
  3277. _THREAD_SAFE_METHOD_
  3278. if (p_icon.is_valid()) {
  3279. ERR_FAIL_COND(p_icon->get_width() <= 0 || p_icon->get_height() <= 0);
  3280. Ref<Image> img = p_icon;
  3281. if (img != icon) {
  3282. img = img->duplicate();
  3283. img->convert(Image::FORMAT_RGBA8);
  3284. }
  3285. int w = img->get_width();
  3286. int h = img->get_height();
  3287. // Create temporary bitmap buffer.
  3288. int icon_len = 40 + h * w * 4;
  3289. Vector<BYTE> v;
  3290. v.resize(icon_len);
  3291. BYTE *icon_bmp = v.ptrw();
  3292. encode_uint32(40, &icon_bmp[0]);
  3293. encode_uint32(w, &icon_bmp[4]);
  3294. encode_uint32(h * 2, &icon_bmp[8]);
  3295. encode_uint16(1, &icon_bmp[12]);
  3296. encode_uint16(32, &icon_bmp[14]);
  3297. encode_uint32(BI_RGB, &icon_bmp[16]);
  3298. encode_uint32(w * h * 4, &icon_bmp[20]);
  3299. encode_uint32(0, &icon_bmp[24]);
  3300. encode_uint32(0, &icon_bmp[28]);
  3301. encode_uint32(0, &icon_bmp[32]);
  3302. encode_uint32(0, &icon_bmp[36]);
  3303. uint8_t *wr = &icon_bmp[40];
  3304. const uint8_t *r = img->get_data().ptr();
  3305. for (int i = 0; i < h; i++) {
  3306. for (int j = 0; j < w; j++) {
  3307. const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
  3308. uint8_t *wpx = &wr[(i * w + j) * 4];
  3309. wpx[0] = rpx[2];
  3310. wpx[1] = rpx[1];
  3311. wpx[2] = rpx[0];
  3312. wpx[3] = rpx[3];
  3313. }
  3314. }
  3315. HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  3316. ERR_FAIL_NULL(hicon);
  3317. icon = img;
  3318. // Set the icon for the window.
  3319. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
  3320. // Set the icon in the task manager (should we do this?).
  3321. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
  3322. } else {
  3323. icon = Ref<Image>();
  3324. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_SMALL, 0);
  3325. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_BIG, 0);
  3326. }
  3327. }
  3328. DisplayServer::IndicatorID DisplayServerWindows::create_status_indicator(const Ref<Texture2D> &p_icon, const String &p_tooltip, const Callable &p_callback) {
  3329. HICON hicon = nullptr;
  3330. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  3331. Ref<Image> img = p_icon->get_image();
  3332. img = img->duplicate();
  3333. if (img->is_compressed()) {
  3334. img->decompress();
  3335. }
  3336. img->convert(Image::FORMAT_RGBA8);
  3337. int w = img->get_width();
  3338. int h = img->get_height();
  3339. // Create temporary bitmap buffer.
  3340. int icon_len = 40 + h * w * 4;
  3341. Vector<BYTE> v;
  3342. v.resize(icon_len);
  3343. BYTE *icon_bmp = v.ptrw();
  3344. encode_uint32(40, &icon_bmp[0]);
  3345. encode_uint32(w, &icon_bmp[4]);
  3346. encode_uint32(h * 2, &icon_bmp[8]);
  3347. encode_uint16(1, &icon_bmp[12]);
  3348. encode_uint16(32, &icon_bmp[14]);
  3349. encode_uint32(BI_RGB, &icon_bmp[16]);
  3350. encode_uint32(w * h * 4, &icon_bmp[20]);
  3351. encode_uint32(0, &icon_bmp[24]);
  3352. encode_uint32(0, &icon_bmp[28]);
  3353. encode_uint32(0, &icon_bmp[32]);
  3354. encode_uint32(0, &icon_bmp[36]);
  3355. uint8_t *wr = &icon_bmp[40];
  3356. const uint8_t *r = img->get_data().ptr();
  3357. for (int i = 0; i < h; i++) {
  3358. for (int j = 0; j < w; j++) {
  3359. const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
  3360. uint8_t *wpx = &wr[(i * w + j) * 4];
  3361. wpx[0] = rpx[2];
  3362. wpx[1] = rpx[1];
  3363. wpx[2] = rpx[0];
  3364. wpx[3] = rpx[3];
  3365. }
  3366. }
  3367. hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  3368. }
  3369. IndicatorData idat;
  3370. idat.callback = p_callback;
  3371. NOTIFYICONDATAW ndat;
  3372. ZeroMemory(&ndat, sizeof(NOTIFYICONDATAW));
  3373. ndat.cbSize = sizeof(NOTIFYICONDATAW);
  3374. ndat.hWnd = windows[MAIN_WINDOW_ID].hWnd;
  3375. ndat.uID = indicator_id_counter;
  3376. ndat.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
  3377. ndat.uCallbackMessage = WM_INDICATOR_CALLBACK_MESSAGE;
  3378. ndat.hIcon = hicon;
  3379. memcpy(ndat.szTip, p_tooltip.utf16().get_data(), MIN(p_tooltip.utf16().length(), 127) * sizeof(WCHAR));
  3380. ndat.uVersion = NOTIFYICON_VERSION;
  3381. Shell_NotifyIconW(NIM_ADD, &ndat);
  3382. Shell_NotifyIconW(NIM_SETVERSION, &ndat);
  3383. IndicatorID iid = indicator_id_counter++;
  3384. indicators[iid] = idat;
  3385. return iid;
  3386. }
  3387. void DisplayServerWindows::status_indicator_set_icon(IndicatorID p_id, const Ref<Texture2D> &p_icon) {
  3388. ERR_FAIL_COND(!indicators.has(p_id));
  3389. HICON hicon = nullptr;
  3390. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  3391. Ref<Image> img = p_icon->get_image();
  3392. img = img->duplicate();
  3393. if (img->is_compressed()) {
  3394. img->decompress();
  3395. }
  3396. img->convert(Image::FORMAT_RGBA8);
  3397. int w = img->get_width();
  3398. int h = img->get_height();
  3399. // Create temporary bitmap buffer.
  3400. int icon_len = 40 + h * w * 4;
  3401. Vector<BYTE> v;
  3402. v.resize(icon_len);
  3403. BYTE *icon_bmp = v.ptrw();
  3404. encode_uint32(40, &icon_bmp[0]);
  3405. encode_uint32(w, &icon_bmp[4]);
  3406. encode_uint32(h * 2, &icon_bmp[8]);
  3407. encode_uint16(1, &icon_bmp[12]);
  3408. encode_uint16(32, &icon_bmp[14]);
  3409. encode_uint32(BI_RGB, &icon_bmp[16]);
  3410. encode_uint32(w * h * 4, &icon_bmp[20]);
  3411. encode_uint32(0, &icon_bmp[24]);
  3412. encode_uint32(0, &icon_bmp[28]);
  3413. encode_uint32(0, &icon_bmp[32]);
  3414. encode_uint32(0, &icon_bmp[36]);
  3415. uint8_t *wr = &icon_bmp[40];
  3416. const uint8_t *r = img->get_data().ptr();
  3417. for (int i = 0; i < h; i++) {
  3418. for (int j = 0; j < w; j++) {
  3419. const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
  3420. uint8_t *wpx = &wr[(i * w + j) * 4];
  3421. wpx[0] = rpx[2];
  3422. wpx[1] = rpx[1];
  3423. wpx[2] = rpx[0];
  3424. wpx[3] = rpx[3];
  3425. }
  3426. }
  3427. hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  3428. }
  3429. NOTIFYICONDATAW ndat;
  3430. ZeroMemory(&ndat, sizeof(NOTIFYICONDATAW));
  3431. ndat.cbSize = sizeof(NOTIFYICONDATAW);
  3432. ndat.hWnd = windows[MAIN_WINDOW_ID].hWnd;
  3433. ndat.uID = p_id;
  3434. ndat.uFlags = NIF_ICON;
  3435. ndat.hIcon = hicon;
  3436. ndat.uVersion = NOTIFYICON_VERSION;
  3437. Shell_NotifyIconW(NIM_MODIFY, &ndat);
  3438. }
  3439. void DisplayServerWindows::status_indicator_set_tooltip(IndicatorID p_id, const String &p_tooltip) {
  3440. ERR_FAIL_COND(!indicators.has(p_id));
  3441. NOTIFYICONDATAW ndat;
  3442. ZeroMemory(&ndat, sizeof(NOTIFYICONDATAW));
  3443. ndat.cbSize = sizeof(NOTIFYICONDATAW);
  3444. ndat.hWnd = windows[MAIN_WINDOW_ID].hWnd;
  3445. ndat.uID = p_id;
  3446. ndat.uFlags = NIF_TIP;
  3447. memcpy(ndat.szTip, p_tooltip.utf16().get_data(), MIN(p_tooltip.utf16().length(), 127) * sizeof(WCHAR));
  3448. ndat.uVersion = NOTIFYICON_VERSION;
  3449. Shell_NotifyIconW(NIM_MODIFY, &ndat);
  3450. }
  3451. void DisplayServerWindows::status_indicator_set_menu(IndicatorID p_id, const RID &p_menu_rid) {
  3452. ERR_FAIL_COND(!indicators.has(p_id));
  3453. indicators[p_id].menu_rid = p_menu_rid;
  3454. }
  3455. void DisplayServerWindows::status_indicator_set_callback(IndicatorID p_id, const Callable &p_callback) {
  3456. ERR_FAIL_COND(!indicators.has(p_id));
  3457. indicators[p_id].callback = p_callback;
  3458. }
  3459. Rect2 DisplayServerWindows::status_indicator_get_rect(IndicatorID p_id) const {
  3460. ERR_FAIL_COND_V(!indicators.has(p_id), Rect2());
  3461. NOTIFYICONIDENTIFIER nid;
  3462. ZeroMemory(&nid, sizeof(NOTIFYICONIDENTIFIER));
  3463. nid.cbSize = sizeof(NOTIFYICONIDENTIFIER);
  3464. nid.hWnd = windows[MAIN_WINDOW_ID].hWnd;
  3465. nid.uID = p_id;
  3466. nid.guidItem = GUID_NULL;
  3467. RECT rect;
  3468. if (Shell_NotifyIconGetRect(&nid, &rect) != S_OK) {
  3469. return Rect2();
  3470. }
  3471. Rect2 ind_rect = Rect2(Point2(rect.left, rect.top) - _get_screens_origin(), Size2(rect.right - rect.left, rect.bottom - rect.top));
  3472. for (int i = 0; i < get_screen_count(); i++) {
  3473. Rect2 screen_rect = Rect2(screen_get_position(i), screen_get_size(i));
  3474. if (screen_rect.encloses(ind_rect)) {
  3475. return ind_rect;
  3476. }
  3477. }
  3478. return Rect2();
  3479. }
  3480. void DisplayServerWindows::delete_status_indicator(IndicatorID p_id) {
  3481. ERR_FAIL_COND(!indicators.has(p_id));
  3482. NOTIFYICONDATAW ndat;
  3483. ZeroMemory(&ndat, sizeof(NOTIFYICONDATAW));
  3484. ndat.cbSize = sizeof(NOTIFYICONDATAW);
  3485. ndat.hWnd = windows[MAIN_WINDOW_ID].hWnd;
  3486. ndat.uID = p_id;
  3487. ndat.uVersion = NOTIFYICON_VERSION;
  3488. Shell_NotifyIconW(NIM_DELETE, &ndat);
  3489. indicators.erase(p_id);
  3490. }
  3491. void DisplayServerWindows::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  3492. _THREAD_SAFE_METHOD_
  3493. #if defined(RD_ENABLED)
  3494. if (rendering_context) {
  3495. rendering_context->window_set_vsync_mode(p_window, p_vsync_mode);
  3496. }
  3497. #endif
  3498. #if defined(GLES3_ENABLED)
  3499. if (gl_manager_native) {
  3500. gl_manager_native->set_use_vsync(p_window, p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  3501. }
  3502. if (gl_manager_angle) {
  3503. gl_manager_angle->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  3504. }
  3505. #endif
  3506. }
  3507. DisplayServer::VSyncMode DisplayServerWindows::window_get_vsync_mode(WindowID p_window) const {
  3508. _THREAD_SAFE_METHOD_
  3509. #if defined(RD_ENABLED)
  3510. if (rendering_context) {
  3511. return rendering_context->window_get_vsync_mode(p_window);
  3512. }
  3513. #endif
  3514. #if defined(GLES3_ENABLED)
  3515. if (gl_manager_native) {
  3516. return gl_manager_native->is_using_vsync(p_window) ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
  3517. }
  3518. if (gl_manager_angle) {
  3519. return gl_manager_angle->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
  3520. }
  3521. #endif
  3522. return DisplayServer::VSYNC_ENABLED;
  3523. }
  3524. void DisplayServerWindows::window_start_drag(WindowID p_window) {
  3525. _THREAD_SAFE_METHOD_
  3526. ERR_FAIL_COND(!windows.has(p_window));
  3527. WindowData &wd = windows[p_window];
  3528. if (wd.parent_hwnd) {
  3529. return; // Embedded window.
  3530. }
  3531. ReleaseCapture();
  3532. POINT coords;
  3533. GetCursorPos(&coords);
  3534. ScreenToClient(wd.hWnd, &coords);
  3535. SendMessage(wd.hWnd, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, MAKELPARAM(coords.x, coords.y));
  3536. }
  3537. void DisplayServerWindows::window_start_resize(WindowResizeEdge p_edge, WindowID p_window) {
  3538. _THREAD_SAFE_METHOD_
  3539. ERR_FAIL_INDEX(int(p_edge), WINDOW_EDGE_MAX);
  3540. ERR_FAIL_COND(!windows.has(p_window));
  3541. WindowData &wd = windows[p_window];
  3542. if (wd.parent_hwnd) {
  3543. return; // Embedded window.
  3544. }
  3545. ReleaseCapture();
  3546. POINT coords;
  3547. GetCursorPos(&coords);
  3548. ScreenToClient(wd.hWnd, &coords);
  3549. DWORD op = 0;
  3550. switch (p_edge) {
  3551. case DisplayServer::WINDOW_EDGE_TOP_LEFT: {
  3552. op = WMSZ_TOPLEFT;
  3553. } break;
  3554. case DisplayServer::WINDOW_EDGE_TOP: {
  3555. op = WMSZ_TOP;
  3556. } break;
  3557. case DisplayServer::WINDOW_EDGE_TOP_RIGHT: {
  3558. op = WMSZ_TOPRIGHT;
  3559. } break;
  3560. case DisplayServer::WINDOW_EDGE_LEFT: {
  3561. op = WMSZ_LEFT;
  3562. } break;
  3563. case DisplayServer::WINDOW_EDGE_RIGHT: {
  3564. op = WMSZ_RIGHT;
  3565. } break;
  3566. case DisplayServer::WINDOW_EDGE_BOTTOM_LEFT: {
  3567. op = WMSZ_BOTTOMLEFT;
  3568. } break;
  3569. case DisplayServer::WINDOW_EDGE_BOTTOM: {
  3570. op = WMSZ_BOTTOM;
  3571. } break;
  3572. case DisplayServer::WINDOW_EDGE_BOTTOM_RIGHT: {
  3573. op = WMSZ_BOTTOMRIGHT;
  3574. } break;
  3575. default:
  3576. break;
  3577. }
  3578. SendMessage(wd.hWnd, WM_SYSCOMMAND, SC_SIZE | op, MAKELPARAM(coords.x, coords.y));
  3579. }
  3580. void DisplayServerWindows::set_context(Context p_context) {
  3581. }
  3582. bool DisplayServerWindows::is_window_transparency_available() const {
  3583. #if defined(RD_ENABLED)
  3584. if (rendering_device && !rendering_device->is_composite_alpha_supported()) {
  3585. return false;
  3586. }
  3587. #endif
  3588. return OS::get_singleton()->is_layered_allowed();
  3589. }
  3590. #define MI_WP_SIGNATURE 0xFF515700
  3591. #define SIGNATURE_MASK 0xFFFFFF00
  3592. // Keeping the name suggested by Microsoft, but this macro really answers:
  3593. // Is this mouse event emulated from touch or pen input?
  3594. #define IsPenEvent(dw) (((dw) & SIGNATURE_MASK) == MI_WP_SIGNATURE)
  3595. // This one tells whether the event comes from touchscreen (and not from pen).
  3596. #define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw) & 0x80))
  3597. void DisplayServerWindows::_touch_event(WindowID p_window, bool p_pressed, float p_x, float p_y, int idx) {
  3598. if (touch_state.has(idx) == p_pressed) {
  3599. return;
  3600. }
  3601. if (p_pressed) {
  3602. touch_state.insert(idx, Vector2(p_x, p_y));
  3603. } else {
  3604. touch_state.erase(idx);
  3605. }
  3606. Ref<InputEventScreenTouch> event;
  3607. event.instantiate();
  3608. event->set_index(idx);
  3609. event->set_window_id(p_window);
  3610. event->set_pressed(p_pressed);
  3611. event->set_position(Vector2(p_x, p_y));
  3612. Input::get_singleton()->parse_input_event(event);
  3613. }
  3614. void DisplayServerWindows::_drag_event(WindowID p_window, float p_x, float p_y, int idx) {
  3615. RBMap<int, Vector2>::Element *curr = touch_state.find(idx);
  3616. if (!curr) {
  3617. return;
  3618. }
  3619. if (curr->get() == Vector2(p_x, p_y)) {
  3620. return;
  3621. }
  3622. Ref<InputEventScreenDrag> event;
  3623. event.instantiate();
  3624. event->set_window_id(p_window);
  3625. event->set_index(idx);
  3626. event->set_position(Vector2(p_x, p_y));
  3627. event->set_relative(Vector2(p_x, p_y) - curr->get());
  3628. event->set_relative_screen_position(event->get_relative());
  3629. Input::get_singleton()->parse_input_event(event);
  3630. curr->get() = Vector2(p_x, p_y);
  3631. }
  3632. void DisplayServerWindows::_send_window_event(const WindowData &wd, WindowEvent p_event) {
  3633. if (wd.event_callback.is_valid()) {
  3634. Variant event = int(p_event);
  3635. wd.event_callback.call(event);
  3636. }
  3637. }
  3638. void DisplayServerWindows::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  3639. static_cast<DisplayServerWindows *>(get_singleton())->_dispatch_input_event(p_event);
  3640. }
  3641. void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  3642. if (in_dispatch_input_event) {
  3643. return;
  3644. }
  3645. in_dispatch_input_event = true;
  3646. {
  3647. List<WindowID>::Element *E = popup_list.back();
  3648. if (E && Object::cast_to<InputEventKey>(*p_event)) {
  3649. // Redirect keyboard input to active popup.
  3650. if (windows.has(E->get())) {
  3651. Callable callable = windows[E->get()].input_event_callback;
  3652. if (callable.is_valid()) {
  3653. callable.call(p_event);
  3654. }
  3655. }
  3656. in_dispatch_input_event = false;
  3657. return;
  3658. }
  3659. }
  3660. Ref<InputEventFromWindow> event_from_window = p_event;
  3661. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  3662. // Send to a single window.
  3663. if (windows.has(event_from_window->get_window_id())) {
  3664. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  3665. if (callable.is_valid()) {
  3666. callable.call(p_event);
  3667. }
  3668. }
  3669. } else {
  3670. // Send to all windows. Copy all pending callbacks, since callback can erase window.
  3671. Vector<Callable> cbs;
  3672. for (KeyValue<WindowID, WindowData> &E : windows) {
  3673. Callable callable = E.value.input_event_callback;
  3674. if (callable.is_valid()) {
  3675. cbs.push_back(callable);
  3676. }
  3677. }
  3678. for (const Callable &cb : cbs) {
  3679. cb.call(p_event);
  3680. }
  3681. }
  3682. in_dispatch_input_event = false;
  3683. }
  3684. LRESULT CALLBACK MouseProc(int code, WPARAM wParam, LPARAM lParam) {
  3685. DisplayServerWindows *ds_win = static_cast<DisplayServerWindows *>(DisplayServer::get_singleton());
  3686. if (ds_win) {
  3687. return ds_win->MouseProc(code, wParam, lParam);
  3688. } else {
  3689. return ::CallNextHookEx(nullptr, code, wParam, lParam);
  3690. }
  3691. }
  3692. DisplayServer::WindowID DisplayServerWindows::window_get_active_popup() const {
  3693. const List<WindowID>::Element *E = popup_list.back();
  3694. if (E) {
  3695. return E->get();
  3696. } else {
  3697. return INVALID_WINDOW_ID;
  3698. }
  3699. }
  3700. void DisplayServerWindows::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
  3701. _THREAD_SAFE_METHOD_
  3702. ERR_FAIL_COND(!windows.has(p_window));
  3703. WindowData &wd = windows[p_window];
  3704. wd.parent_safe_rect = p_rect;
  3705. }
  3706. Rect2i DisplayServerWindows::window_get_popup_safe_rect(WindowID p_window) const {
  3707. _THREAD_SAFE_METHOD_
  3708. ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
  3709. const WindowData &wd = windows[p_window];
  3710. return wd.parent_safe_rect;
  3711. }
  3712. void DisplayServerWindows::popup_open(WindowID p_window) {
  3713. _THREAD_SAFE_METHOD_
  3714. bool has_popup_ancestor = false;
  3715. WindowID transient_root = p_window;
  3716. while (true) {
  3717. WindowID parent = windows[transient_root].transient_parent;
  3718. if (parent == INVALID_WINDOW_ID) {
  3719. break;
  3720. } else {
  3721. transient_root = parent;
  3722. if (windows[parent].is_popup) {
  3723. has_popup_ancestor = true;
  3724. break;
  3725. }
  3726. }
  3727. }
  3728. // Detect tooltips and other similar popups that shouldn't block input to their parent.
  3729. bool ignores_input = window_get_flag(WINDOW_FLAG_NO_FOCUS, p_window) && window_get_flag(WINDOW_FLAG_MOUSE_PASSTHROUGH, p_window);
  3730. WindowData &wd = windows[p_window];
  3731. if (wd.is_popup || (has_popup_ancestor && !ignores_input)) {
  3732. // Find current popup parent, or root popup if new window is not transient.
  3733. List<WindowID>::Element *C = nullptr;
  3734. List<WindowID>::Element *E = popup_list.back();
  3735. while (E) {
  3736. if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
  3737. C = E;
  3738. E = E->prev();
  3739. } else {
  3740. break;
  3741. }
  3742. }
  3743. if (C) {
  3744. _send_window_event(windows[C->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST);
  3745. }
  3746. time_since_popup = OS::get_singleton()->get_ticks_msec();
  3747. popup_list.push_back(p_window);
  3748. }
  3749. }
  3750. void DisplayServerWindows::popup_close(WindowID p_window) {
  3751. _THREAD_SAFE_METHOD_
  3752. List<WindowID>::Element *E = popup_list.find(p_window);
  3753. while (E) {
  3754. List<WindowID>::Element *F = E->next();
  3755. WindowID win_id = E->get();
  3756. popup_list.erase(E);
  3757. if (win_id != p_window) {
  3758. // Only request close on related windows, not this window. We are already processing it.
  3759. _send_window_event(windows[win_id], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST);
  3760. }
  3761. E = F;
  3762. }
  3763. }
  3764. BitField<DisplayServerWindows::WinKeyModifierMask> DisplayServerWindows::_get_mods() const {
  3765. BitField<WinKeyModifierMask> mask = {};
  3766. static unsigned char keyboard_state[256];
  3767. if (GetKeyboardState((PBYTE)&keyboard_state)) {
  3768. if ((keyboard_state[VK_LSHIFT] & 0x80) || (keyboard_state[VK_RSHIFT] & 0x80)) {
  3769. mask.set_flag(WinKeyModifierMask::SHIFT);
  3770. }
  3771. if ((keyboard_state[VK_LCONTROL] & 0x80) || (keyboard_state[VK_RCONTROL] & 0x80)) {
  3772. mask.set_flag(WinKeyModifierMask::CTRL);
  3773. }
  3774. if ((keyboard_state[VK_LMENU] & 0x80) || (keyboard_state[VK_RMENU] & 0x80)) {
  3775. mask.set_flag(WinKeyModifierMask::ALT);
  3776. }
  3777. if ((keyboard_state[VK_RMENU] & 0x80)) {
  3778. mask.set_flag(WinKeyModifierMask::ALT_GR);
  3779. }
  3780. if ((keyboard_state[VK_LWIN] & 0x80) || (keyboard_state[VK_RWIN] & 0x80)) {
  3781. mask.set_flag(WinKeyModifierMask::META);
  3782. }
  3783. }
  3784. return mask;
  3785. }
  3786. LRESULT DisplayServerWindows::MouseProc(int code, WPARAM wParam, LPARAM lParam) {
  3787. _THREAD_SAFE_METHOD_
  3788. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  3789. if (delta > 250) {
  3790. switch (wParam) {
  3791. case WM_NCLBUTTONDOWN:
  3792. case WM_NCRBUTTONDOWN:
  3793. case WM_NCMBUTTONDOWN:
  3794. case WM_LBUTTONDOWN:
  3795. case WM_RBUTTONDOWN:
  3796. case WM_MBUTTONDOWN: {
  3797. MOUSEHOOKSTRUCT *ms = (MOUSEHOOKSTRUCT *)lParam;
  3798. Point2i pos = Point2i(ms->pt.x, ms->pt.y) - _get_screens_origin();
  3799. List<WindowID>::Element *C = nullptr;
  3800. List<WindowID>::Element *E = popup_list.back();
  3801. // Find top popup to close.
  3802. while (E) {
  3803. // Popup window area.
  3804. Rect2i win_rect = Rect2i(window_get_position_with_decorations(E->get()), window_get_size_with_decorations(E->get()));
  3805. // Area of the parent window, which responsible for opening sub-menu.
  3806. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  3807. if (win_rect.has_point(pos)) {
  3808. break;
  3809. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  3810. break;
  3811. } else {
  3812. C = E;
  3813. E = E->prev();
  3814. }
  3815. }
  3816. if (C) {
  3817. _send_window_event(windows[C->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST);
  3818. return 1;
  3819. }
  3820. } break;
  3821. }
  3822. }
  3823. return ::CallNextHookEx(mouse_monitor, code, wParam, lParam);
  3824. }
  3825. // Handle a single window message received while CreateWindowEx is still on the stack and our data
  3826. // structures are not fully initialized.
  3827. LRESULT DisplayServerWindows::_handle_early_window_message(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  3828. switch (uMsg) {
  3829. case WM_GETMINMAXINFO: {
  3830. // We receive this during CreateWindowEx and we haven't initialized the window
  3831. // struct, so let Windows figure out the maximized size.
  3832. // Silently forward to user/default.
  3833. } break;
  3834. case WM_NCCREATE: {
  3835. // We tunnel an unowned pointer to our window context (WindowData) through the
  3836. // first possible message (WM_NCCREATE) to fix up our window context collection.
  3837. CREATESTRUCTW *pCreate = (CREATESTRUCTW *)lParam;
  3838. WindowData *pWindowData = reinterpret_cast<WindowData *>(pCreate->lpCreateParams);
  3839. // Fix this up so we can recognize the remaining messages.
  3840. pWindowData->hWnd = hWnd;
  3841. #ifdef ACCESSKIT_ENABLED
  3842. if (accessibility_driver && !accessibility_driver->window_create(pWindowData->id, (void *)hWnd)) {
  3843. if (OS::get_singleton()->is_stdout_verbose()) {
  3844. ERR_PRINT("Can't create an accessibility adapter for window, accessibility support disabled!");
  3845. }
  3846. memdelete(accessibility_driver);
  3847. accessibility_driver = nullptr;
  3848. }
  3849. #endif
  3850. } break;
  3851. default: {
  3852. // Additional messages during window creation should happen after we fixed
  3853. // up the data structures on WM_NCCREATE, but this might change in the future,
  3854. // so report an error here and then we can implement them.
  3855. ERR_PRINT_ONCE(vformat("Unexpected window message 0x%x received for window we cannot recognize in our collection; sequence error.", uMsg));
  3856. } break;
  3857. }
  3858. if (user_proc) {
  3859. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  3860. }
  3861. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  3862. }
  3863. // The window procedure for our window class "Engine", used to handle processing of window-related system messages/events.
  3864. // See: https://docs.microsoft.com/en-us/windows/win32/winmsg/window-procedures
  3865. LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  3866. if (drop_events) {
  3867. if (user_proc) {
  3868. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  3869. } else {
  3870. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  3871. }
  3872. }
  3873. WindowID window_id = INVALID_WINDOW_ID;
  3874. bool window_created = false;
  3875. // Check whether window exists
  3876. // FIXME this is O(n), where n is the set of currently open windows and subwindows
  3877. // we should have a secondary map from HWND to WindowID or even WindowData* alias, if we want to eliminate all the map lookups below
  3878. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3879. if (E.value.hWnd == hWnd) {
  3880. window_id = E.key;
  3881. window_created = true;
  3882. break;
  3883. }
  3884. }
  3885. // WARNING: We get called with events before the window is registered in our collection
  3886. // specifically, even the call to CreateWindowEx already calls here while still on the stack,
  3887. // so there is no way to store the window handle in our collection before we get here.
  3888. if (!window_created) {
  3889. // don't let code below operate on incompletely initialized window objects or missing window_id
  3890. return _handle_early_window_message(hWnd, uMsg, wParam, lParam);
  3891. }
  3892. // Process window messages.
  3893. switch (uMsg) {
  3894. case WM_GETOBJECT: {
  3895. get_object_recieved = true;
  3896. } break;
  3897. case WM_MENUCOMMAND: {
  3898. native_menu->_menu_activate(HMENU(lParam), (int)wParam);
  3899. } break;
  3900. case WM_CREATE: {
  3901. {
  3902. DWORD value = windows[window_id].sharp_corners ? DWMWCP_DONOTROUND : DWMWCP_DEFAULT;
  3903. ::DwmSetWindowAttribute(windows[window_id].hWnd, DWMWA_WINDOW_CORNER_PREFERENCE, &value, sizeof(value));
  3904. }
  3905. if (is_dark_mode_supported() && dark_title_available) {
  3906. BOOL value = is_dark_mode();
  3907. ::DwmSetWindowAttribute(windows[window_id].hWnd, use_legacy_dark_mode_before_20H1 ? DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 : DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
  3908. SendMessageW(windows[window_id].hWnd, WM_PAINT, 0, 0);
  3909. }
  3910. } break;
  3911. case WM_NCHITTEST: {
  3912. if (windows[window_id].mpass) {
  3913. return HTTRANSPARENT;
  3914. }
  3915. } break;
  3916. case WM_MOUSEACTIVATE: {
  3917. if (windows[window_id].no_focus || windows[window_id].is_popup) {
  3918. return MA_NOACTIVATE; // Do not activate, but process mouse messages.
  3919. }
  3920. // When embedded, the window is a child of the parent and is not activated
  3921. // by default because it lacks native controls.
  3922. if (windows[window_id].parent_hwnd) {
  3923. SetFocus(windows[window_id].hWnd);
  3924. return MA_ACTIVATE;
  3925. }
  3926. } break;
  3927. case WM_ACTIVATEAPP: {
  3928. bool new_app_focused = (bool)wParam;
  3929. if (new_app_focused == app_focused) {
  3930. break;
  3931. }
  3932. app_focused = new_app_focused;
  3933. if (OS::get_singleton()->get_main_loop()) {
  3934. OS::get_singleton()->get_main_loop()->notification(app_focused ? MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN : MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  3935. }
  3936. } break;
  3937. case WM_ACTIVATE: {
  3938. // Activation can happen just after the window has been created, even before the callbacks are set.
  3939. // Therefore, it's safer to defer the delivery of the event.
  3940. // It's important to set an nIDEvent different from the SetTimer for move_timer_id because
  3941. // if the same nIDEvent is passed, the timer is replaced and the same timer_id is returned.
  3942. // The problem with the timer is that the window cannot be resized or the buttons cannot be used correctly
  3943. // if the window is not activated first. This happens because the code in the activation process runs
  3944. // after the mouse click is handled. To address this, the timer is now used only when the window is created.
  3945. windows[window_id].activate_state = GET_WM_ACTIVATE_STATE(wParam, lParam);
  3946. if (windows[window_id].first_activation_done) {
  3947. _process_activate_event(window_id);
  3948. } else {
  3949. windows[window_id].activate_timer_id = SetTimer(windows[window_id].hWnd, DisplayServerWindows::TIMER_ID_WINDOW_ACTIVATION, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
  3950. }
  3951. return 0;
  3952. } break;
  3953. case WM_GETMINMAXINFO: {
  3954. if (windows[window_id].resizable && !windows[window_id].fullscreen) {
  3955. // Size of window decorations.
  3956. Size2 decor = window_get_size_with_decorations(window_id) - window_get_size(window_id);
  3957. MINMAXINFO *min_max_info = (MINMAXINFO *)lParam;
  3958. if (windows[window_id].min_size != Size2()) {
  3959. min_max_info->ptMinTrackSize.x = windows[window_id].min_size.x + decor.x;
  3960. min_max_info->ptMinTrackSize.y = windows[window_id].min_size.y + decor.y;
  3961. }
  3962. if (windows[window_id].max_size != Size2()) {
  3963. min_max_info->ptMaxTrackSize.x = windows[window_id].max_size.x + decor.x;
  3964. min_max_info->ptMaxTrackSize.y = windows[window_id].max_size.y + decor.y;
  3965. }
  3966. if (windows[window_id].borderless) {
  3967. Rect2i screen_rect = screen_get_usable_rect(window_get_current_screen(window_id));
  3968. // Set the size of (borderless) maximized mode to exclude taskbar (or any other panel) if present.
  3969. min_max_info->ptMaxPosition.x = screen_rect.position.x;
  3970. min_max_info->ptMaxPosition.y = screen_rect.position.y;
  3971. min_max_info->ptMaxSize.x = screen_rect.size.x;
  3972. min_max_info->ptMaxSize.y = screen_rect.size.y;
  3973. }
  3974. return 0;
  3975. }
  3976. } break;
  3977. case WM_ERASEBKGND: {
  3978. Color early_color;
  3979. if (!_get_window_early_clear_override(early_color)) {
  3980. break;
  3981. }
  3982. bool must_recreate_brush = !window_bkg_brush || window_bkg_brush_color != early_color.to_argb32();
  3983. if (must_recreate_brush) {
  3984. if (window_bkg_brush) {
  3985. DeleteObject(window_bkg_brush);
  3986. }
  3987. window_bkg_brush = CreateSolidBrush(RGB(early_color.get_r8(), early_color.get_g8(), early_color.get_b8()));
  3988. }
  3989. HDC hdc = (HDC)wParam;
  3990. RECT rect = {};
  3991. if (GetUpdateRect(hWnd, &rect, true)) {
  3992. FillRect(hdc, &rect, window_bkg_brush);
  3993. }
  3994. return 1;
  3995. } break;
  3996. case WM_PAINT: {
  3997. Main::force_redraw();
  3998. } break;
  3999. case WM_SETTINGCHANGE:
  4000. case WM_SYSCOLORCHANGE: {
  4001. if (lParam && CompareStringOrdinal(reinterpret_cast<LPCWCH>(lParam), -1, L"ImmersiveColorSet", -1, true) == CSTR_EQUAL) {
  4002. if (is_dark_mode_supported() && dark_title_available) {
  4003. BOOL value = is_dark_mode();
  4004. ::DwmSetWindowAttribute(windows[window_id].hWnd, use_legacy_dark_mode_before_20H1 ? DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 : DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
  4005. }
  4006. }
  4007. if (system_theme_changed.is_valid()) {
  4008. Variant ret;
  4009. Callable::CallError ce;
  4010. system_theme_changed.callp(nullptr, 0, ret, ce);
  4011. if (ce.error != Callable::CallError::CALL_OK) {
  4012. ERR_PRINT(vformat("Failed to execute system theme changed callback: %s.", Variant::get_callable_error_text(system_theme_changed, nullptr, 0, ce)));
  4013. }
  4014. }
  4015. } break;
  4016. case WM_THEMECHANGED: {
  4017. if (is_dark_mode_supported() && dark_title_available) {
  4018. BOOL value = is_dark_mode();
  4019. ::DwmSetWindowAttribute(windows[window_id].hWnd, use_legacy_dark_mode_before_20H1 ? DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 : DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
  4020. }
  4021. } break;
  4022. case WM_SYSCOMMAND: // Intercept system commands.
  4023. {
  4024. switch (wParam) // Check system calls.
  4025. {
  4026. case SC_SCREENSAVE: // Screensaver trying to start?
  4027. case SC_MONITORPOWER: // Monitor trying to enter powersave?
  4028. return 0; // Prevent from happening.
  4029. case SC_KEYMENU:
  4030. Engine *engine = Engine::get_singleton();
  4031. if (((lParam >> 16) <= 0) && !engine->is_project_manager_hint() && !engine->is_editor_hint() && !GLOBAL_GET_CACHED(bool, "application/run/enable_alt_space_menu")) {
  4032. return 0;
  4033. }
  4034. if (!_get_mods().has_flag(WinKeyModifierMask::ALT) || !(GetAsyncKeyState(VK_SPACE) & (1 << 15))) {
  4035. return 0;
  4036. }
  4037. SendMessage(windows[window_id].hWnd, WM_SYSKEYUP, VK_SPACE, 0);
  4038. SendMessage(windows[window_id].hWnd, WM_SYSKEYUP, VK_MENU, 0);
  4039. }
  4040. } break;
  4041. case WM_INDICATOR_CALLBACK_MESSAGE: {
  4042. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN || lParam == WM_MBUTTONDOWN || lParam == WM_XBUTTONDOWN) {
  4043. IndicatorID iid = (IndicatorID)wParam;
  4044. MouseButton mb = MouseButton::LEFT;
  4045. if (lParam == WM_RBUTTONDOWN) {
  4046. mb = MouseButton::RIGHT;
  4047. } else if (lParam == WM_MBUTTONDOWN) {
  4048. mb = MouseButton::MIDDLE;
  4049. } else if (lParam == WM_XBUTTONDOWN) {
  4050. mb = MouseButton::MB_XBUTTON1;
  4051. }
  4052. if (indicators.has(iid)) {
  4053. if (lParam == WM_RBUTTONDOWN && indicators[iid].menu_rid.is_valid() && native_menu->has_menu(indicators[iid].menu_rid)) {
  4054. NOTIFYICONIDENTIFIER nid;
  4055. ZeroMemory(&nid, sizeof(NOTIFYICONIDENTIFIER));
  4056. nid.cbSize = sizeof(NOTIFYICONIDENTIFIER);
  4057. nid.hWnd = windows[MAIN_WINDOW_ID].hWnd;
  4058. nid.uID = iid;
  4059. nid.guidItem = GUID_NULL;
  4060. RECT rect;
  4061. if (Shell_NotifyIconGetRect(&nid, &rect) == S_OK) {
  4062. native_menu->popup(indicators[iid].menu_rid, Vector2i((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2));
  4063. }
  4064. } else if (indicators[iid].callback.is_valid()) {
  4065. Variant v_button = mb;
  4066. Variant v_pos = mouse_get_position();
  4067. const Variant *v_args[2] = { &v_button, &v_pos };
  4068. Variant ret;
  4069. Callable::CallError ce;
  4070. indicators[iid].callback.callp((const Variant **)&v_args, 2, ret, ce);
  4071. if (ce.error != Callable::CallError::CALL_OK) {
  4072. ERR_PRINT(vformat("Failed to execute status indicator callback: %s.", Variant::get_callable_error_text(indicators[iid].callback, v_args, 2, ce)));
  4073. }
  4074. }
  4075. }
  4076. return 0;
  4077. }
  4078. } break;
  4079. case WM_CLOSE: {
  4080. if (windows[window_id].activate_timer_id) {
  4081. KillTimer(windows[window_id].hWnd, windows[window_id].activate_timer_id);
  4082. windows[window_id].activate_timer_id = 0;
  4083. }
  4084. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  4085. return 0;
  4086. }
  4087. case WM_MOUSELEAVE: {
  4088. if (window_mouseover_id == window_id) {
  4089. old_invalid = true;
  4090. window_mouseover_id = INVALID_WINDOW_ID;
  4091. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
  4092. } else if (window_mouseover_id != INVALID_WINDOW_ID && windows.has(window_mouseover_id)) {
  4093. // This is reached during drag and drop, after dropping in a different window.
  4094. // Once-off notification, must call again.
  4095. track_mouse_leave_event(windows[window_mouseover_id].hWnd);
  4096. }
  4097. } break;
  4098. case WM_INPUT: {
  4099. if (!use_raw_input) {
  4100. break;
  4101. }
  4102. UINT dwSize;
  4103. GetRawInputData((HRAWINPUT)lParam, RID_INPUT, nullptr, &dwSize, sizeof(RAWINPUTHEADER));
  4104. LPBYTE lpb = new BYTE[dwSize];
  4105. if (lpb == nullptr) {
  4106. return 0;
  4107. }
  4108. if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) {
  4109. OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));
  4110. }
  4111. RAWINPUT *raw = (RAWINPUT *)lpb;
  4112. const BitField<WinKeyModifierMask> &mods = _get_mods();
  4113. if (raw->header.dwType == RIM_TYPEKEYBOARD) {
  4114. if (raw->data.keyboard.VKey == VK_SHIFT) {
  4115. // If multiple Shifts are held down at the same time,
  4116. // Windows natively only sends a KEYUP for the last one to be released.
  4117. if (raw->data.keyboard.Flags & RI_KEY_BREAK) {
  4118. // Make sure to check the latest key state since
  4119. // we're in the middle of the message queue.
  4120. if (GetAsyncKeyState(VK_SHIFT) < 0) {
  4121. // A Shift is released, but another Shift is still held
  4122. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  4123. KeyEvent ke;
  4124. ke.shift = false;
  4125. ke.altgr = mods.has_flag(WinKeyModifierMask::ALT_GR);
  4126. ke.alt = mods.has_flag(WinKeyModifierMask::ALT);
  4127. ke.control = mods.has_flag(WinKeyModifierMask::CTRL);
  4128. ke.meta = mods.has_flag(WinKeyModifierMask::META);
  4129. ke.uMsg = WM_KEYUP;
  4130. ke.window_id = window_id;
  4131. ke.wParam = VK_SHIFT;
  4132. // data.keyboard.MakeCode -> 0x2A - left shift, 0x36 - right shift.
  4133. // Bit 30 -> key was previously down, bit 31 -> key is being released.
  4134. ke.lParam = raw->data.keyboard.MakeCode << 16 | 1 << 30 | 1 << 31;
  4135. key_event_buffer[key_event_pos++] = ke;
  4136. }
  4137. }
  4138. }
  4139. } else if (mouse_mode == MOUSE_MODE_CAPTURED && raw->header.dwType == RIM_TYPEMOUSE) {
  4140. Ref<InputEventMouseMotion> mm;
  4141. mm.instantiate();
  4142. mm->set_window_id(window_id);
  4143. mm->set_ctrl_pressed(mods.has_flag(WinKeyModifierMask::CTRL));
  4144. mm->set_shift_pressed(mods.has_flag(WinKeyModifierMask::SHIFT));
  4145. mm->set_alt_pressed(mods.has_flag(WinKeyModifierMask::ALT));
  4146. mm->set_meta_pressed(mods.has_flag(WinKeyModifierMask::META));
  4147. mm->set_pressure((raw->data.mouse.ulButtons & RI_MOUSE_LEFT_BUTTON_DOWN) ? 1.0f : 0.0f);
  4148. mm->set_button_mask(mouse_get_button_state());
  4149. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  4150. // Centering just so it works as before.
  4151. POINT pos = { (int)c.x, (int)c.y };
  4152. ClientToScreen(windows[window_id].hWnd, &pos);
  4153. SetCursorPos(pos.x, pos.y);
  4154. mm->set_position(c);
  4155. mm->set_global_position(c);
  4156. mm->set_velocity(Vector2(0, 0));
  4157. mm->set_screen_velocity(Vector2(0, 0));
  4158. if (raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE) {
  4159. mm->set_relative(Vector2(raw->data.mouse.lLastX, raw->data.mouse.lLastY));
  4160. } else if (raw->data.mouse.usFlags == MOUSE_MOVE_ABSOLUTE) {
  4161. int nScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
  4162. int nScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
  4163. int nScreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN);
  4164. int nScreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN);
  4165. Vector2 abs_pos(
  4166. (double(raw->data.mouse.lLastX) - 65536.0 / (nScreenWidth)) * nScreenWidth / 65536.0 + nScreenLeft,
  4167. (double(raw->data.mouse.lLastY) - 65536.0 / (nScreenHeight)) * nScreenHeight / 65536.0 + nScreenTop);
  4168. POINT coords; // Client coords.
  4169. coords.x = abs_pos.x;
  4170. coords.y = abs_pos.y;
  4171. ScreenToClient(hWnd, &coords);
  4172. mm->set_relative(Vector2(coords.x - old_x, coords.y - old_y));
  4173. old_x = coords.x;
  4174. old_y = coords.y;
  4175. }
  4176. mm->set_relative_screen_position(mm->get_relative());
  4177. if ((windows[window_id].window_focused || windows[window_id].is_popup) && mm->get_relative() != Vector2()) {
  4178. Input::get_singleton()->parse_input_event(mm);
  4179. }
  4180. }
  4181. delete[] lpb;
  4182. } break;
  4183. case WT_CSRCHANGE:
  4184. case WT_PROXIMITY: {
  4185. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  4186. AXIS pressure;
  4187. if (wintab_WTInfo(WTI_DEVICES + windows[window_id].wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  4188. windows[window_id].min_pressure = int(pressure.axMin);
  4189. windows[window_id].max_pressure = int(pressure.axMax);
  4190. }
  4191. AXIS orientation[3];
  4192. if (wintab_WTInfo(WTI_DEVICES + windows[window_id].wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  4193. windows[window_id].tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  4194. }
  4195. return 0;
  4196. }
  4197. } break;
  4198. case WT_PACKET: {
  4199. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  4200. PACKET packet;
  4201. if (wintab_WTPacket(windows[window_id].wtctx, wParam, &packet)) {
  4202. POINT coords;
  4203. GetCursorPos(&coords);
  4204. ScreenToClient(windows[window_id].hWnd, &coords);
  4205. windows[window_id].last_pressure_update = 0;
  4206. float pressure = float(packet.pkNormalPressure - windows[window_id].min_pressure) / float(windows[window_id].max_pressure - windows[window_id].min_pressure);
  4207. double azim = (packet.pkOrientation.orAzimuth / 10.0f) * (Math::PI / 180);
  4208. double alt = Math::tan((Math::abs(packet.pkOrientation.orAltitude / 10.0f)) * (Math::PI / 180));
  4209. bool inverted = packet.pkStatus & TPS_INVERT;
  4210. Vector2 tilt = (windows[window_id].tilt_supported) ? Vector2(Math::atan(Math::sin(azim) / alt), Math::atan(Math::cos(azim) / alt)) : Vector2();
  4211. // Nothing changed, ignore event.
  4212. if (!old_invalid && coords.x == old_x && coords.y == old_y && windows[window_id].last_pressure == pressure && windows[window_id].last_tilt == tilt && windows[window_id].last_pen_inverted == inverted) {
  4213. break;
  4214. }
  4215. windows[window_id].last_pressure = pressure;
  4216. windows[window_id].last_tilt = tilt;
  4217. windows[window_id].last_pen_inverted = inverted;
  4218. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  4219. if (!windows[window_id].window_focused && mouse_mode == MOUSE_MODE_CAPTURED) {
  4220. break;
  4221. }
  4222. const BitField<WinKeyModifierMask> &mods = _get_mods();
  4223. Ref<InputEventMouseMotion> mm;
  4224. mm.instantiate();
  4225. mm->set_window_id(window_id);
  4226. mm->set_ctrl_pressed(mods.has_flag(WinKeyModifierMask::CTRL));
  4227. mm->set_shift_pressed(mods.has_flag(WinKeyModifierMask::SHIFT));
  4228. mm->set_alt_pressed(mods.has_flag(WinKeyModifierMask::ALT));
  4229. mm->set_meta_pressed(mods.has_flag(WinKeyModifierMask::META));
  4230. mm->set_pressure(windows[window_id].last_pressure);
  4231. mm->set_tilt(windows[window_id].last_tilt);
  4232. mm->set_pen_inverted(windows[window_id].last_pen_inverted);
  4233. mm->set_button_mask(mouse_get_button_state());
  4234. mm->set_position(Vector2(coords.x, coords.y));
  4235. mm->set_global_position(Vector2(coords.x, coords.y));
  4236. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  4237. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  4238. old_x = c.x;
  4239. old_y = c.y;
  4240. if (mm->get_position() == c) {
  4241. center = c;
  4242. return 0;
  4243. }
  4244. Point2i ncenter = mm->get_position();
  4245. center = ncenter;
  4246. POINT pos = { (int)c.x, (int)c.y };
  4247. ClientToScreen(windows[window_id].hWnd, &pos);
  4248. SetCursorPos(pos.x, pos.y);
  4249. }
  4250. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  4251. mm->set_screen_velocity(mm->get_velocity());
  4252. if (old_invalid) {
  4253. old_x = mm->get_position().x;
  4254. old_y = mm->get_position().y;
  4255. old_invalid = false;
  4256. }
  4257. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  4258. mm->set_relative_screen_position(mm->get_relative());
  4259. old_x = mm->get_position().x;
  4260. old_y = mm->get_position().y;
  4261. if (windows[window_id].window_focused || window_get_active_popup() == window_id) {
  4262. Input::get_singleton()->parse_input_event(mm);
  4263. }
  4264. }
  4265. return 0;
  4266. }
  4267. } break;
  4268. case WM_POINTERENTER: {
  4269. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  4270. break;
  4271. }
  4272. if (tablet_get_current_driver() != "winink") {
  4273. break;
  4274. }
  4275. uint32_t pointer_id = LOWORD(wParam);
  4276. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  4277. if (!GetPointerType(pointer_id, &pointer_type)) {
  4278. break;
  4279. }
  4280. if (pointer_type != PT_PEN) {
  4281. break;
  4282. }
  4283. pointer_button[GET_POINTERID_WPARAM(wParam)] = MouseButton::NONE;
  4284. windows[window_id].block_mm = true;
  4285. return 0;
  4286. } break;
  4287. case WM_POINTERLEAVE: {
  4288. pointer_button[GET_POINTERID_WPARAM(wParam)] = MouseButton::NONE;
  4289. windows[window_id].block_mm = false;
  4290. return 0;
  4291. } break;
  4292. case WM_POINTERDOWN:
  4293. case WM_POINTERUP: {
  4294. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  4295. break;
  4296. }
  4297. if (tablet_get_current_driver() != "winink") {
  4298. break;
  4299. }
  4300. uint32_t pointer_id = LOWORD(wParam);
  4301. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  4302. if (!GetPointerType(pointer_id, &pointer_type)) {
  4303. break;
  4304. }
  4305. if (pointer_type != PT_PEN) {
  4306. break;
  4307. }
  4308. Ref<InputEventMouseButton> mb;
  4309. mb.instantiate();
  4310. mb->set_window_id(window_id);
  4311. BitField<MouseButtonMask> last_button_state = MouseButtonMask::NONE;
  4312. if (IS_POINTER_FIRSTBUTTON_WPARAM(wParam)) {
  4313. last_button_state.set_flag(MouseButtonMask::LEFT);
  4314. mb->set_button_index(MouseButton::LEFT);
  4315. }
  4316. if (IS_POINTER_SECONDBUTTON_WPARAM(wParam)) {
  4317. last_button_state.set_flag(MouseButtonMask::RIGHT);
  4318. mb->set_button_index(MouseButton::RIGHT);
  4319. }
  4320. if (IS_POINTER_THIRDBUTTON_WPARAM(wParam)) {
  4321. last_button_state.set_flag(MouseButtonMask::MIDDLE);
  4322. mb->set_button_index(MouseButton::MIDDLE);
  4323. }
  4324. if (IS_POINTER_FOURTHBUTTON_WPARAM(wParam)) {
  4325. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON1);
  4326. mb->set_button_index(MouseButton::MB_XBUTTON1);
  4327. }
  4328. if (IS_POINTER_FIFTHBUTTON_WPARAM(wParam)) {
  4329. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON2);
  4330. mb->set_button_index(MouseButton::MB_XBUTTON2);
  4331. }
  4332. mb->set_button_mask(last_button_state);
  4333. const BitField<WinKeyModifierMask> &mods = _get_mods();
  4334. mb->set_ctrl_pressed(mods.has_flag(WinKeyModifierMask::CTRL));
  4335. mb->set_shift_pressed(mods.has_flag(WinKeyModifierMask::SHIFT));
  4336. mb->set_alt_pressed(mods.has_flag(WinKeyModifierMask::ALT));
  4337. mb->set_meta_pressed(mods.has_flag(WinKeyModifierMask::META));
  4338. POINT coords; // Client coords.
  4339. coords.x = GET_X_LPARAM(lParam);
  4340. coords.y = GET_Y_LPARAM(lParam);
  4341. // Note: Handle popup closing here, since mouse event is not emulated and hook will not be called.
  4342. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  4343. if (delta > 250) {
  4344. Point2i pos = Point2i(coords.x, coords.y) - _get_screens_origin();
  4345. List<WindowID>::Element *C = nullptr;
  4346. List<WindowID>::Element *E = popup_list.back();
  4347. // Find top popup to close.
  4348. while (E) {
  4349. // Popup window area.
  4350. Rect2i win_rect = Rect2i(window_get_position_with_decorations(E->get()), window_get_size_with_decorations(E->get()));
  4351. // Area of the parent window, which responsible for opening sub-menu.
  4352. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  4353. if (win_rect.has_point(pos)) {
  4354. break;
  4355. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  4356. break;
  4357. } else {
  4358. C = E;
  4359. E = E->prev();
  4360. }
  4361. }
  4362. if (C) {
  4363. _send_window_event(windows[C->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST);
  4364. }
  4365. }
  4366. int64_t pen_id = GET_POINTERID_WPARAM(wParam);
  4367. if (uMsg == WM_POINTERDOWN) {
  4368. mb->set_pressed(true);
  4369. if (pointer_down_time.has(pen_id) && (pointer_prev_button[pen_id] == mb->get_button_index()) && (Math::abs(coords.y - pointer_last_pos[pen_id].y) < GetSystemMetrics(SM_CYDOUBLECLK)) && GetMessageTime() - pointer_down_time[pen_id] < (LONG)GetDoubleClickTime()) {
  4370. mb->set_double_click(true);
  4371. pointer_down_time[pen_id] = 0;
  4372. } else {
  4373. pointer_down_time[pen_id] = GetMessageTime();
  4374. pointer_prev_button[pen_id] = mb->get_button_index();
  4375. pointer_last_pos[pen_id] = Vector2(coords.x, coords.y);
  4376. }
  4377. pointer_button[pen_id] = mb->get_button_index();
  4378. } else {
  4379. if (!pointer_button.has(pen_id)) {
  4380. return 0;
  4381. }
  4382. mb->set_pressed(false);
  4383. mb->set_button_index(pointer_button[pen_id]);
  4384. pointer_button[pen_id] = MouseButton::NONE;
  4385. }
  4386. ScreenToClient(windows[window_id].hWnd, &coords);
  4387. mb->set_position(Vector2(coords.x, coords.y));
  4388. mb->set_global_position(Vector2(coords.x, coords.y));
  4389. Input::get_singleton()->parse_input_event(mb);
  4390. return 0;
  4391. } break;
  4392. case WM_POINTERUPDATE: {
  4393. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  4394. break;
  4395. }
  4396. if (tablet_get_current_driver() != "winink") {
  4397. break;
  4398. }
  4399. uint32_t pointer_id = LOWORD(wParam);
  4400. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  4401. if (!GetPointerType(pointer_id, &pointer_type)) {
  4402. break;
  4403. }
  4404. if (pointer_type != PT_PEN) {
  4405. break;
  4406. }
  4407. POINTER_PEN_INFO pen_info;
  4408. if (!GetPointerPenInfo(pointer_id, &pen_info)) {
  4409. break;
  4410. }
  4411. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  4412. // Universal translation enabled; ignore OS translation.
  4413. LPARAM extra = GetMessageExtraInfo();
  4414. if (IsTouchEvent(extra)) {
  4415. break;
  4416. }
  4417. }
  4418. if (window_mouseover_id != window_id) {
  4419. // Mouse enter.
  4420. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  4421. if (window_mouseover_id != INVALID_WINDOW_ID && windows.has(window_mouseover_id)) {
  4422. // Leave previous window.
  4423. _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
  4424. }
  4425. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  4426. }
  4427. CursorShape c = cursor_shape;
  4428. cursor_shape = CURSOR_MAX;
  4429. cursor_set_shape(c);
  4430. window_mouseover_id = window_id;
  4431. // Once-off notification, must call again.
  4432. track_mouse_leave_event(hWnd);
  4433. }
  4434. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  4435. if (!windows[window_id].window_focused && mouse_mode == MOUSE_MODE_CAPTURED) {
  4436. break;
  4437. }
  4438. Ref<InputEventMouseMotion> mm;
  4439. mm.instantiate();
  4440. mm->set_window_id(window_id);
  4441. if (pen_info.penMask & PEN_MASK_PRESSURE) {
  4442. mm->set_pressure((float)pen_info.pressure / 1024);
  4443. } else {
  4444. mm->set_pressure((HIWORD(wParam) & POINTER_MESSAGE_FLAG_FIRSTBUTTON) ? 1.0f : 0.0f);
  4445. }
  4446. if ((pen_info.penMask & PEN_MASK_TILT_X) && (pen_info.penMask & PEN_MASK_TILT_Y)) {
  4447. mm->set_tilt(Vector2((float)pen_info.tiltX / 90, (float)pen_info.tiltY / 90));
  4448. }
  4449. mm->set_pen_inverted(pen_info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER));
  4450. const BitField<WinKeyModifierMask> &mods = _get_mods();
  4451. mm->set_ctrl_pressed(mods.has_flag(WinKeyModifierMask::CTRL));
  4452. mm->set_shift_pressed(mods.has_flag(WinKeyModifierMask::SHIFT));
  4453. mm->set_alt_pressed(mods.has_flag(WinKeyModifierMask::ALT));
  4454. mm->set_meta_pressed(mods.has_flag(WinKeyModifierMask::META));
  4455. BitField<MouseButtonMask> last_button_state = MouseButtonMask::NONE;
  4456. if (IS_POINTER_FIRSTBUTTON_WPARAM(wParam)) {
  4457. last_button_state.set_flag(MouseButtonMask::LEFT);
  4458. }
  4459. if (IS_POINTER_SECONDBUTTON_WPARAM(wParam)) {
  4460. last_button_state.set_flag(MouseButtonMask::RIGHT);
  4461. }
  4462. if (IS_POINTER_THIRDBUTTON_WPARAM(wParam)) {
  4463. last_button_state.set_flag(MouseButtonMask::MIDDLE);
  4464. }
  4465. if (IS_POINTER_FOURTHBUTTON_WPARAM(wParam)) {
  4466. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON1);
  4467. }
  4468. if (IS_POINTER_FIFTHBUTTON_WPARAM(wParam)) {
  4469. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON2);
  4470. }
  4471. mm->set_button_mask(last_button_state);
  4472. POINT coords; // Client coords.
  4473. coords.x = GET_X_LPARAM(lParam);
  4474. coords.y = GET_Y_LPARAM(lParam);
  4475. ScreenToClient(windows[window_id].hWnd, &coords);
  4476. mm->set_position(Vector2(coords.x, coords.y));
  4477. mm->set_global_position(Vector2(coords.x, coords.y));
  4478. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  4479. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  4480. old_x = c.x;
  4481. old_y = c.y;
  4482. if (mm->get_position() == c) {
  4483. center = c;
  4484. return 0;
  4485. }
  4486. Point2i ncenter = mm->get_position();
  4487. center = ncenter;
  4488. POINT pos = { (int)c.x, (int)c.y };
  4489. ClientToScreen(hWnd, &pos);
  4490. SetCursorPos(pos.x, pos.y);
  4491. }
  4492. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  4493. mm->set_screen_velocity(mm->get_velocity());
  4494. if (old_invalid) {
  4495. old_x = mm->get_position().x;
  4496. old_y = mm->get_position().y;
  4497. old_invalid = false;
  4498. }
  4499. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  4500. mm->set_relative_screen_position(mm->get_relative());
  4501. old_x = mm->get_position().x;
  4502. old_y = mm->get_position().y;
  4503. if (windows[window_id].window_focused || window_get_active_popup() == window_id) {
  4504. Input::get_singleton()->parse_input_event(mm);
  4505. }
  4506. return 0; // Pointer event handled return 0 to avoid duplicate WM_MOUSEMOVE event.
  4507. } break;
  4508. case WM_MOUSEMOVE: {
  4509. if (windows[window_id].block_mm) {
  4510. break;
  4511. }
  4512. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  4513. break;
  4514. }
  4515. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  4516. // Universal translation enabled; ignore OS translation.
  4517. LPARAM extra = GetMessageExtraInfo();
  4518. if (IsTouchEvent(extra)) {
  4519. break;
  4520. }
  4521. }
  4522. DisplayServer::WindowID over_id = get_window_at_screen_position(mouse_get_position());
  4523. if (windows.has(over_id) && !Rect2(window_get_position(over_id), Point2(windows[over_id].width, windows[over_id].height)).has_point(mouse_get_position())) {
  4524. // Don't consider the windowborder as part of the window.
  4525. over_id = INVALID_WINDOW_ID;
  4526. }
  4527. if (window_mouseover_id != over_id) {
  4528. // Mouse enter.
  4529. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  4530. if (window_mouseover_id != INVALID_WINDOW_ID && windows.has(window_mouseover_id)) {
  4531. // Leave previous window.
  4532. _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
  4533. }
  4534. if (over_id != INVALID_WINDOW_ID && windows.has(over_id)) {
  4535. _send_window_event(windows[over_id], WINDOW_EVENT_MOUSE_ENTER);
  4536. }
  4537. }
  4538. CursorShape c = cursor_shape;
  4539. cursor_shape = CURSOR_MAX;
  4540. cursor_set_shape(c);
  4541. window_mouseover_id = over_id;
  4542. // Once-off notification, must call again.
  4543. track_mouse_leave_event(hWnd);
  4544. }
  4545. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  4546. if (!windows[window_id].window_focused && mouse_mode == MOUSE_MODE_CAPTURED) {
  4547. break;
  4548. }
  4549. DisplayServer::WindowID receiving_window_id = window_id;
  4550. if (!windows[window_id].no_focus) {
  4551. receiving_window_id = _get_focused_window_or_popup();
  4552. if (receiving_window_id == INVALID_WINDOW_ID) {
  4553. receiving_window_id = window_id;
  4554. }
  4555. }
  4556. const BitField<WinKeyModifierMask> &mods = _get_mods();
  4557. Ref<InputEventMouseMotion> mm;
  4558. mm.instantiate();
  4559. mm->set_window_id(receiving_window_id);
  4560. mm->set_ctrl_pressed(mods.has_flag(WinKeyModifierMask::CTRL));
  4561. mm->set_shift_pressed(mods.has_flag(WinKeyModifierMask::SHIFT));
  4562. mm->set_alt_pressed(mods.has_flag(WinKeyModifierMask::ALT));
  4563. mm->set_meta_pressed(mods.has_flag(WinKeyModifierMask::META));
  4564. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  4565. // Note: WinTab sends both WT_PACKET and WM_xBUTTONDOWN/UP/MOUSEMOVE events, use mouse 1/0 pressure only when last_pressure was not updated recently.
  4566. if (windows[window_id].last_pressure_update < 10) {
  4567. windows[window_id].last_pressure_update++;
  4568. } else {
  4569. windows[window_id].last_tilt = Vector2();
  4570. windows[window_id].last_pressure = (wParam & MK_LBUTTON) ? 1.0f : 0.0f;
  4571. windows[window_id].last_pen_inverted = false;
  4572. }
  4573. } else {
  4574. windows[window_id].last_tilt = Vector2();
  4575. windows[window_id].last_pressure = (wParam & MK_LBUTTON) ? 1.0f : 0.0f;
  4576. windows[window_id].last_pen_inverted = false;
  4577. }
  4578. mm->set_pressure(windows[window_id].last_pressure);
  4579. mm->set_tilt(windows[window_id].last_tilt);
  4580. mm->set_pen_inverted(windows[window_id].last_pen_inverted);
  4581. mm->set_button_mask(mouse_get_button_state());
  4582. mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  4583. mm->set_global_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  4584. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  4585. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  4586. old_x = c.x;
  4587. old_y = c.y;
  4588. if (mm->get_position() == c) {
  4589. center = c;
  4590. return 0;
  4591. }
  4592. Point2i ncenter = mm->get_position();
  4593. center = ncenter;
  4594. POINT pos = { (int)c.x, (int)c.y };
  4595. ClientToScreen(windows[window_id].hWnd, &pos);
  4596. SetCursorPos(pos.x, pos.y);
  4597. }
  4598. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  4599. mm->set_screen_velocity(mm->get_velocity());
  4600. if (old_invalid) {
  4601. old_x = mm->get_position().x;
  4602. old_y = mm->get_position().y;
  4603. old_invalid = false;
  4604. }
  4605. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  4606. mm->set_relative_screen_position(mm->get_relative());
  4607. old_x = mm->get_position().x;
  4608. old_y = mm->get_position().y;
  4609. if (receiving_window_id != window_id) {
  4610. // Adjust event position relative to window distance when event is sent to a different window.
  4611. mm->set_position(mm->get_position() - window_get_position(receiving_window_id) + window_get_position(window_id));
  4612. mm->set_global_position(mm->get_position());
  4613. }
  4614. Input::get_singleton()->parse_input_event(mm);
  4615. } break;
  4616. case WM_LBUTTONDOWN:
  4617. case WM_LBUTTONUP:
  4618. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  4619. // Universal translation enabled; ignore OS translations for left button.
  4620. LPARAM extra = GetMessageExtraInfo();
  4621. if (IsTouchEvent(extra)) {
  4622. break;
  4623. }
  4624. }
  4625. [[fallthrough]];
  4626. case WM_MBUTTONDOWN:
  4627. case WM_MBUTTONUP:
  4628. case WM_RBUTTONDOWN:
  4629. case WM_RBUTTONUP:
  4630. case WM_MOUSEWHEEL:
  4631. case WM_MOUSEHWHEEL:
  4632. case WM_LBUTTONDBLCLK:
  4633. case WM_MBUTTONDBLCLK:
  4634. case WM_RBUTTONDBLCLK:
  4635. case WM_XBUTTONDBLCLK:
  4636. case WM_XBUTTONDOWN:
  4637. case WM_XBUTTONUP: {
  4638. Ref<InputEventMouseButton> mb;
  4639. mb.instantiate();
  4640. mb->set_window_id(window_id);
  4641. switch (uMsg) {
  4642. case WM_LBUTTONDOWN: {
  4643. mb->set_pressed(true);
  4644. mb->set_button_index(MouseButton::LEFT);
  4645. } break;
  4646. case WM_LBUTTONUP: {
  4647. mb->set_pressed(false);
  4648. mb->set_button_index(MouseButton::LEFT);
  4649. } break;
  4650. case WM_MBUTTONDOWN: {
  4651. mb->set_pressed(true);
  4652. mb->set_button_index(MouseButton::MIDDLE);
  4653. } break;
  4654. case WM_MBUTTONUP: {
  4655. mb->set_pressed(false);
  4656. mb->set_button_index(MouseButton::MIDDLE);
  4657. } break;
  4658. case WM_RBUTTONDOWN: {
  4659. mb->set_pressed(true);
  4660. mb->set_button_index(MouseButton::RIGHT);
  4661. } break;
  4662. case WM_RBUTTONUP: {
  4663. mb->set_pressed(false);
  4664. mb->set_button_index(MouseButton::RIGHT);
  4665. } break;
  4666. case WM_LBUTTONDBLCLK: {
  4667. mb->set_pressed(true);
  4668. mb->set_button_index(MouseButton::LEFT);
  4669. mb->set_double_click(true);
  4670. } break;
  4671. case WM_RBUTTONDBLCLK: {
  4672. mb->set_pressed(true);
  4673. mb->set_button_index(MouseButton::RIGHT);
  4674. mb->set_double_click(true);
  4675. } break;
  4676. case WM_MBUTTONDBLCLK: {
  4677. mb->set_pressed(true);
  4678. mb->set_button_index(MouseButton::MIDDLE);
  4679. mb->set_double_click(true);
  4680. } break;
  4681. case WM_MOUSEWHEEL: {
  4682. mb->set_pressed(true);
  4683. int motion = (short)HIWORD(wParam);
  4684. if (!motion) {
  4685. return 0;
  4686. }
  4687. if (motion > 0) {
  4688. mb->set_button_index(MouseButton::WHEEL_UP);
  4689. } else {
  4690. mb->set_button_index(MouseButton::WHEEL_DOWN);
  4691. }
  4692. mb->set_factor(std::fabs((double)motion / (double)WHEEL_DELTA));
  4693. } break;
  4694. case WM_MOUSEHWHEEL: {
  4695. mb->set_pressed(true);
  4696. int motion = (short)HIWORD(wParam);
  4697. if (!motion) {
  4698. return 0;
  4699. }
  4700. if (motion < 0) {
  4701. mb->set_button_index(MouseButton::WHEEL_LEFT);
  4702. } else {
  4703. mb->set_button_index(MouseButton::WHEEL_RIGHT);
  4704. }
  4705. mb->set_factor(std::fabs((double)motion / (double)WHEEL_DELTA));
  4706. } break;
  4707. case WM_XBUTTONDOWN: {
  4708. mb->set_pressed(true);
  4709. if (HIWORD(wParam) == XBUTTON1) {
  4710. mb->set_button_index(MouseButton::MB_XBUTTON1);
  4711. } else {
  4712. mb->set_button_index(MouseButton::MB_XBUTTON2);
  4713. }
  4714. } break;
  4715. case WM_XBUTTONUP: {
  4716. mb->set_pressed(false);
  4717. if (HIWORD(wParam) == XBUTTON1) {
  4718. mb->set_button_index(MouseButton::MB_XBUTTON1);
  4719. } else {
  4720. mb->set_button_index(MouseButton::MB_XBUTTON2);
  4721. }
  4722. } break;
  4723. case WM_XBUTTONDBLCLK: {
  4724. mb->set_pressed(true);
  4725. if (HIWORD(wParam) == XBUTTON1) {
  4726. mb->set_button_index(MouseButton::MB_XBUTTON1);
  4727. } else {
  4728. mb->set_button_index(MouseButton::MB_XBUTTON2);
  4729. }
  4730. mb->set_double_click(true);
  4731. } break;
  4732. default: {
  4733. return 0;
  4734. }
  4735. }
  4736. const BitField<WinKeyModifierMask> &mods = _get_mods();
  4737. mb->set_ctrl_pressed(mods.has_flag(WinKeyModifierMask::CTRL));
  4738. mb->set_shift_pressed(mods.has_flag(WinKeyModifierMask::SHIFT));
  4739. mb->set_alt_pressed(mods.has_flag(WinKeyModifierMask::ALT));
  4740. mb->set_meta_pressed(mods.has_flag(WinKeyModifierMask::META));
  4741. if (mb->is_pressed() && mb->get_button_index() >= MouseButton::WHEEL_UP && mb->get_button_index() <= MouseButton::WHEEL_RIGHT) {
  4742. MouseButtonMask mask = mouse_button_to_mask(mb->get_button_index());
  4743. BitField<MouseButtonMask> scroll_mask = mouse_get_button_state();
  4744. scroll_mask.set_flag(mask);
  4745. mb->set_button_mask(scroll_mask);
  4746. } else {
  4747. mb->set_button_mask(mouse_get_button_state());
  4748. }
  4749. mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  4750. if (mouse_mode == MOUSE_MODE_CAPTURED && !use_raw_input) {
  4751. mb->set_position(Vector2(old_x, old_y));
  4752. }
  4753. if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) {
  4754. if (mb->is_pressed()) {
  4755. if (++pressrc > 0 && mouse_mode != MOUSE_MODE_CAPTURED) {
  4756. SetCapture(hWnd);
  4757. }
  4758. } else {
  4759. if (--pressrc <= 0 || mouse_get_button_state().is_empty()) {
  4760. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  4761. ReleaseCapture();
  4762. }
  4763. pressrc = 0;
  4764. }
  4765. }
  4766. } else {
  4767. // For reasons unknown to humanity, wheel comes in screen coordinates.
  4768. POINT coords;
  4769. coords.x = mb->get_position().x;
  4770. coords.y = mb->get_position().y;
  4771. ScreenToClient(hWnd, &coords);
  4772. mb->set_position(Vector2(coords.x, coords.y));
  4773. }
  4774. mb->set_global_position(mb->get_position());
  4775. Input::get_singleton()->parse_input_event(mb);
  4776. if (mb->is_pressed() && mb->get_button_index() >= MouseButton::WHEEL_UP && mb->get_button_index() <= MouseButton::WHEEL_RIGHT) {
  4777. // Send release for mouse wheel.
  4778. Ref<InputEventMouseButton> mbd = mb->duplicate();
  4779. mbd->set_window_id(window_id);
  4780. mbd->set_button_mask(mouse_get_button_state());
  4781. mbd->set_pressed(false);
  4782. Input::get_singleton()->parse_input_event(mbd);
  4783. }
  4784. // Propagate the button up event to the window on which the button down
  4785. // event was triggered. This is needed for drag & drop to work between windows,
  4786. // because the engine expects events to keep being processed
  4787. // on the same window dragging started.
  4788. if (mb->is_pressed()) {
  4789. last_mouse_button_down_window = window_id;
  4790. } else if (last_mouse_button_down_window != INVALID_WINDOW_ID) {
  4791. mb->set_window_id(last_mouse_button_down_window);
  4792. last_mouse_button_down_window = INVALID_WINDOW_ID;
  4793. }
  4794. } break;
  4795. case WM_WINDOWPOSCHANGED: {
  4796. WindowData &window = windows[window_id];
  4797. int off_x = (window.multiwindow_fs || (!window.fullscreen && window.borderless && IsZoomed(hWnd))) ? FS_TRANSP_BORDER : 0;
  4798. Rect2i window_client_rect;
  4799. Rect2i window_rect;
  4800. {
  4801. RECT rect;
  4802. GetClientRect(hWnd, &rect);
  4803. ClientToScreen(hWnd, (POINT *)&rect.left);
  4804. ClientToScreen(hWnd, (POINT *)&rect.right);
  4805. window_client_rect = Rect2i(rect.left, rect.top, rect.right - rect.left - off_x, rect.bottom - rect.top);
  4806. window_client_rect.position -= _get_screens_origin();
  4807. RECT wrect;
  4808. GetWindowRect(hWnd, &wrect);
  4809. window_rect = Rect2i(wrect.left, wrect.top, wrect.right - wrect.left - off_x, wrect.bottom - wrect.top);
  4810. window_rect.position -= _get_screens_origin();
  4811. }
  4812. WINDOWPOS *window_pos_params = (WINDOWPOS *)lParam;
  4813. bool rect_changed = false;
  4814. if (!(window_pos_params->flags & SWP_NOSIZE) || window_pos_params->flags & SWP_FRAMECHANGED) {
  4815. int screen_id = window_get_current_screen(window_id);
  4816. Size2i screen_size = screen_get_size(screen_id);
  4817. Point2i screen_position = screen_get_position(screen_id);
  4818. Rect2i usable = screen_get_usable_rect(screen_id);
  4819. window.maximized = false;
  4820. window.minimized = false;
  4821. window.fullscreen = false;
  4822. if (IsIconic(hWnd)) {
  4823. window.minimized = true;
  4824. } else if (IsZoomed(hWnd)) {
  4825. window.maximized = true;
  4826. // If maximized_window_size == screen_size add 1px border to prevent switching to exclusive_fs.
  4827. if (!window.maximized_fs && window.borderless && window_rect.position == screen_position && window_rect.size == screen_size) {
  4828. // Window (borderless) was just maximized and the covers the entire screen.
  4829. window.maximized_fs = true;
  4830. _update_window_style(window_id, false);
  4831. }
  4832. if (window.borderless && (screen_size != usable.size || screen_position != usable.position)) {
  4833. Point2 pos = usable.position + _get_screens_origin();
  4834. Size2 size = usable.size;
  4835. MoveWindow(window.hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  4836. }
  4837. } else if (window_rect.position == screen_position && window_rect.size == screen_size) {
  4838. window.fullscreen = true;
  4839. } else if (window.borderless && usable.position == window_rect.position && usable.size == window_rect.size) {
  4840. window.maximized = true;
  4841. }
  4842. if (window.maximized_fs && !window.maximized) {
  4843. // Window (maximized and covering fullscreen) was just non-maximized.
  4844. window.maximized_fs = false;
  4845. _update_window_style(window_id, false);
  4846. }
  4847. if (!window.minimized) {
  4848. window.width = window_client_rect.size.width;
  4849. window.height = window_client_rect.size.height;
  4850. rect_changed = true;
  4851. }
  4852. #if defined(RD_ENABLED)
  4853. if (window.create_completed && rendering_context && window.context_created) {
  4854. // Note: Trigger resize event to update swapchains when window is minimized/restored, even if size is not changed.
  4855. rendering_context->window_set_size(window_id, window.width, window.height);
  4856. }
  4857. #endif
  4858. #if defined(GLES3_ENABLED)
  4859. if (window.create_completed && gl_manager_native) {
  4860. gl_manager_native->window_resize(window_id, window.width, window.height);
  4861. }
  4862. if (window.create_completed && gl_manager_angle) {
  4863. gl_manager_angle->window_resize(window_id, window.width, window.height);
  4864. }
  4865. #endif
  4866. }
  4867. if (!window.minimized && (!(window_pos_params->flags & SWP_NOMOVE) || window_pos_params->flags & SWP_FRAMECHANGED)) {
  4868. window.last_pos = window_client_rect.position;
  4869. rect_changed = true;
  4870. }
  4871. if (rect_changed) {
  4872. if (window.rect_changed_callback.is_valid()) {
  4873. window.rect_changed_callback.call(Rect2i(window.last_pos.x, window.last_pos.y, window.width, window.height));
  4874. }
  4875. // Update cursor clip region after window rect has changed.
  4876. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  4877. RECT crect;
  4878. GetClientRect(window.hWnd, &crect);
  4879. crect.right -= off_x;
  4880. ClientToScreen(window.hWnd, (POINT *)&crect.left);
  4881. ClientToScreen(window.hWnd, (POINT *)&crect.right);
  4882. ClipCursor(&crect);
  4883. }
  4884. if (!window.minimized && window.was_fullscreen_pre_min) {
  4885. // Restore fullscreen mode if window was in fullscreen before it was minimized.
  4886. int cs = window_get_current_screen(window_id);
  4887. Point2 pos = screen_get_position(cs) + _get_screens_origin();
  4888. Size2 size = screen_get_size(cs);
  4889. window.was_fullscreen_pre_min = false;
  4890. window.fullscreen = true;
  4891. window.maximized = false;
  4892. window.minimized = false;
  4893. _update_window_style(window_id, false);
  4894. MoveWindow(window.hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  4895. }
  4896. } else {
  4897. if (window.parent_hwnd) {
  4898. // WM_WINDOWPOSCHANGED is sent when the parent changes.
  4899. // If we are supposed to have a parent and now we don't, it's likely
  4900. // because the parent was closed. We will close our window as well.
  4901. // This prevents an embedded game from staying alive when the editor is closed or crashes.
  4902. if (!GetParent(window.hWnd)) {
  4903. SendMessage(window.hWnd, WM_CLOSE, 0, 0);
  4904. }
  4905. }
  4906. }
  4907. // Return here to prevent WM_MOVE and WM_SIZE from being sent
  4908. // See: https://docs.microsoft.com/en-us/windows/win32/winmsg/wm-windowposchanged#remarks
  4909. return 0;
  4910. } break;
  4911. case WM_ENTERSIZEMOVE: {
  4912. Input::get_singleton()->release_pressed_events();
  4913. windows[window_id].move_timer_id = SetTimer(windows[window_id].hWnd, DisplayServerWindows::TIMER_ID_MOVE_REDRAW, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
  4914. } break;
  4915. case WM_EXITSIZEMOVE: {
  4916. KillTimer(windows[window_id].hWnd, windows[window_id].move_timer_id);
  4917. windows[window_id].move_timer_id = 0;
  4918. // Reset the correct mouse mode because we couldn't call ReleaseCapture in
  4919. // _set_mouse_mode_impl while in _process_activate_event (because the user was moving a window).
  4920. _set_mouse_mode_impl(mouse_mode);
  4921. } break;
  4922. case WM_TIMER: {
  4923. if (wParam == windows[window_id].move_timer_id) {
  4924. _THREAD_SAFE_UNLOCK_
  4925. _process_key_events();
  4926. if (!Main::is_iterating()) {
  4927. Main::iteration();
  4928. }
  4929. _THREAD_SAFE_LOCK_
  4930. } else if (wParam == windows[window_id].activate_timer_id) {
  4931. _process_activate_event(window_id);
  4932. KillTimer(windows[window_id].hWnd, windows[window_id].activate_timer_id);
  4933. windows[window_id].activate_timer_id = 0;
  4934. windows[window_id].first_activation_done = true;
  4935. }
  4936. } break;
  4937. case WM_SYSKEYUP:
  4938. case WM_KEYUP:
  4939. case WM_SYSKEYDOWN:
  4940. case WM_KEYDOWN: {
  4941. if (windows[window_id].ime_suppress_next_keyup && (uMsg == WM_KEYUP || uMsg == WM_SYSKEYUP)) {
  4942. windows[window_id].ime_suppress_next_keyup = false;
  4943. break;
  4944. }
  4945. if (windows[window_id].ime_in_progress) {
  4946. break;
  4947. }
  4948. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  4949. // When SetCapture is used, ALT+F4 hotkey is ignored by Windows, so handle it ourselves
  4950. if (wParam == VK_F4 && _get_mods().has_flag(WinKeyModifierMask::ALT) && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN)) {
  4951. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  4952. }
  4953. }
  4954. [[fallthrough]];
  4955. }
  4956. case WM_CHAR: {
  4957. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  4958. const BitField<WinKeyModifierMask> &mods = _get_mods();
  4959. KeyEvent ke;
  4960. ke.shift = mods.has_flag(WinKeyModifierMask::SHIFT);
  4961. ke.alt = mods.has_flag(WinKeyModifierMask::ALT);
  4962. ke.altgr = mods.has_flag(WinKeyModifierMask::ALT_GR);
  4963. ke.control = mods.has_flag(WinKeyModifierMask::CTRL);
  4964. ke.meta = mods.has_flag(WinKeyModifierMask::META);
  4965. ke.uMsg = uMsg;
  4966. ke.window_id = window_id;
  4967. if (ke.uMsg == WM_SYSKEYDOWN) {
  4968. ke.uMsg = WM_KEYDOWN;
  4969. }
  4970. if (ke.uMsg == WM_SYSKEYUP) {
  4971. ke.uMsg = WM_KEYUP;
  4972. }
  4973. ke.wParam = wParam;
  4974. ke.lParam = lParam;
  4975. key_event_buffer[key_event_pos++] = ke;
  4976. } break;
  4977. case WM_IME_COMPOSITION: {
  4978. CANDIDATEFORM cf;
  4979. cf.dwIndex = 0;
  4980. cf.dwStyle = CFS_CANDIDATEPOS;
  4981. cf.ptCurrentPos.x = windows[window_id].im_position.x;
  4982. cf.ptCurrentPos.y = windows[window_id].im_position.y;
  4983. ImmSetCandidateWindow(windows[window_id].im_himc, &cf);
  4984. cf.dwStyle = CFS_EXCLUDE;
  4985. cf.rcArea.left = windows[window_id].im_position.x;
  4986. cf.rcArea.right = windows[window_id].im_position.x;
  4987. cf.rcArea.top = windows[window_id].im_position.y;
  4988. cf.rcArea.bottom = windows[window_id].im_position.y;
  4989. ImmSetCandidateWindow(windows[window_id].im_himc, &cf);
  4990. if (windows[window_id].ime_active) {
  4991. SetCaretPos(windows[window_id].im_position.x, windows[window_id].im_position.y);
  4992. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  4993. }
  4994. } break;
  4995. case WM_INPUTLANGCHANGEREQUEST: {
  4996. // FIXME: Do something?
  4997. } break;
  4998. case WM_IME_STARTCOMPOSITION: {
  4999. if (windows[window_id].ime_active) {
  5000. windows[window_id].ime_in_progress = true;
  5001. if (key_event_pos > 0) {
  5002. key_event_pos--;
  5003. }
  5004. }
  5005. return 0;
  5006. } break;
  5007. case WM_IME_ENDCOMPOSITION: {
  5008. if (windows[window_id].ime_active) {
  5009. windows[window_id].ime_in_progress = false;
  5010. windows[window_id].ime_suppress_next_keyup = true;
  5011. }
  5012. return 0;
  5013. } break;
  5014. case WM_IME_NOTIFY: {
  5015. return 0;
  5016. } break;
  5017. case WM_TOUCH: {
  5018. BOOL bHandled = FALSE;
  5019. UINT cInputs = LOWORD(wParam);
  5020. PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
  5021. if (pInputs) {
  5022. if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
  5023. for (UINT i = 0; i < cInputs; i++) {
  5024. TOUCHINPUT ti = pInputs[i];
  5025. POINT touch_pos = {
  5026. TOUCH_COORD_TO_PIXEL(ti.x),
  5027. TOUCH_COORD_TO_PIXEL(ti.y),
  5028. };
  5029. ScreenToClient(hWnd, &touch_pos);
  5030. // Do something with each touch input entry.
  5031. if (ti.dwFlags & TOUCHEVENTF_MOVE) {
  5032. _drag_event(window_id, touch_pos.x, touch_pos.y, ti.dwID);
  5033. } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
  5034. _touch_event(window_id, ti.dwFlags & TOUCHEVENTF_DOWN, touch_pos.x, touch_pos.y, ti.dwID);
  5035. }
  5036. }
  5037. bHandled = TRUE;
  5038. } else {
  5039. // TODO: Handle the error here.
  5040. }
  5041. memdelete_arr(pInputs);
  5042. } else {
  5043. // TODO: Handle the error here, probably out of memory.
  5044. }
  5045. if (bHandled) {
  5046. CloseTouchInputHandle((HTOUCHINPUT)lParam);
  5047. return 0;
  5048. }
  5049. } break;
  5050. case WM_DEVICECHANGE: {
  5051. joypad->probe_joypads();
  5052. } break;
  5053. case WM_DESTROY: {
  5054. #ifdef ACCESSKIT_ENABLED
  5055. if (accessibility_driver) {
  5056. accessibility_driver->window_destroy(window_id);
  5057. }
  5058. #endif
  5059. Input::get_singleton()->flush_buffered_events();
  5060. if (window_mouseover_id == window_id) {
  5061. window_mouseover_id = INVALID_WINDOW_ID;
  5062. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
  5063. }
  5064. } break;
  5065. case WM_SETCURSOR: {
  5066. if (LOWORD(lParam) == HTCLIENT) {
  5067. if (windows[window_id].window_focused && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN)) {
  5068. // Hide the cursor.
  5069. if (hCursor == nullptr) {
  5070. hCursor = SetCursor(nullptr);
  5071. } else {
  5072. SetCursor(nullptr);
  5073. }
  5074. } else {
  5075. if (hCursor != nullptr) {
  5076. CursorShape c = cursor_shape;
  5077. cursor_shape = CURSOR_MAX;
  5078. cursor_set_shape(c);
  5079. hCursor = nullptr;
  5080. }
  5081. }
  5082. }
  5083. } break;
  5084. default: {
  5085. if (user_proc) {
  5086. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  5087. }
  5088. }
  5089. }
  5090. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  5091. }
  5092. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  5093. DisplayServerWindows *ds_win = static_cast<DisplayServerWindows *>(DisplayServer::get_singleton());
  5094. if (ds_win) {
  5095. return ds_win->WndProc(hWnd, uMsg, wParam, lParam);
  5096. } else {
  5097. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  5098. }
  5099. }
  5100. void DisplayServerWindows::_process_activate_event(WindowID p_window_id) {
  5101. WindowData &wd = windows[p_window_id];
  5102. if (wd.activate_state == WA_ACTIVE || wd.activate_state == WA_CLICKACTIVE) {
  5103. last_focused_window = p_window_id;
  5104. _set_mouse_mode_impl(mouse_mode);
  5105. if (!IsIconic(wd.hWnd)) {
  5106. SetFocus(wd.hWnd);
  5107. }
  5108. wd.window_focused = true;
  5109. #ifdef ACCESSKIT_ENABLED
  5110. if (accessibility_driver) {
  5111. accessibility_driver->accessibility_set_window_focused(p_window_id, true);
  5112. }
  5113. #endif
  5114. _send_window_event(wd, WINDOW_EVENT_FOCUS_IN);
  5115. } else { // WM_INACTIVE.
  5116. Input::get_singleton()->release_pressed_events();
  5117. track_mouse_leave_event(wd.hWnd);
  5118. // Release capture unconditionally because it can be set due to dragging, in addition to captured mode.
  5119. // When the user is moving a window, it's important to not ReleaseCapture because it will cause
  5120. // the window movement to stop and if the user tries to move the Windows when it's not activated,
  5121. // it will prevent the window movement. If we are here and a window is moving, it's because we had multiple
  5122. // opened windows in the editor and we are definitively not in a middle of dragging.
  5123. if (!_has_moving_window()) {
  5124. ReleaseCapture();
  5125. }
  5126. wd.window_focused = false;
  5127. #ifdef ACCESSKIT_ENABLED
  5128. if (accessibility_driver) {
  5129. accessibility_driver->accessibility_set_window_focused(p_window_id, false);
  5130. }
  5131. #endif
  5132. _send_window_event(wd, WINDOW_EVENT_FOCUS_OUT);
  5133. }
  5134. if ((tablet_get_current_driver() == "wintab") && wintab_available && wd.wtctx) {
  5135. wintab_WTEnable(wd.wtctx, wd.activate_state);
  5136. }
  5137. }
  5138. void DisplayServerWindows::_process_key_events() {
  5139. for (int i = 0; i < key_event_pos; i++) {
  5140. KeyEvent &ke = key_event_buffer[i];
  5141. switch (ke.uMsg) {
  5142. case WM_CHAR: {
  5143. // Extended keys should only be processed as WM_KEYDOWN message.
  5144. if (!KeyMappingWindows::is_extended_key(ke.wParam) && ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR))) {
  5145. static char32_t prev_wc = 0;
  5146. char32_t unicode = ke.wParam;
  5147. if ((unicode & 0xfffffc00) == 0xd800) {
  5148. if (prev_wc != 0) {
  5149. ERR_PRINT("invalid utf16 surrogate input");
  5150. }
  5151. prev_wc = unicode;
  5152. break; // Skip surrogate.
  5153. } else if ((unicode & 0xfffffc00) == 0xdc00) {
  5154. if (prev_wc == 0) {
  5155. ERR_PRINT("invalid utf16 surrogate input");
  5156. break; // Skip invalid surrogate.
  5157. }
  5158. unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  5159. prev_wc = 0;
  5160. } else {
  5161. prev_wc = 0;
  5162. }
  5163. Ref<InputEventKey> k;
  5164. k.instantiate();
  5165. UINT vk = MapVirtualKey((ke.lParam >> 16) & 0xFF, MAPVK_VSC_TO_VK);
  5166. bool is_oem = (vk >= 0xB8) && (vk <= 0xE6);
  5167. Key keycode = KeyMappingWindows::get_keysym(vk);
  5168. Key key_label = keycode;
  5169. Key physical_keycode = KeyMappingWindows::get_scansym((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24));
  5170. static BYTE keyboard_state[256];
  5171. memset(keyboard_state, 0, 256);
  5172. wchar_t chars[256] = {};
  5173. UINT extended_code = MapVirtualKey((ke.lParam >> 16) & 0xFF, MAPVK_VSC_TO_VK_EX);
  5174. if (!(ke.lParam & (1 << 24)) && ToUnicodeEx(extended_code, (ke.lParam >> 16) & 0xFF, keyboard_state, chars, 255, 4, GetKeyboardLayout(0)) > 0) {
  5175. String keysym = String::utf16((char16_t *)chars, 255);
  5176. if (!keysym.is_empty()) {
  5177. char32_t unicode_value = keysym[0];
  5178. // For printable ASCII characters (0x20-0x7E), override the original keycode with the character value.
  5179. if (is_oem && Key::SPACE <= (Key)unicode_value && (Key)unicode_value <= Key::ASCIITILDE) {
  5180. keycode = fix_keycode(unicode_value, (Key)unicode_value);
  5181. }
  5182. key_label = fix_key_label(unicode_value, keycode);
  5183. }
  5184. }
  5185. k->set_window_id(ke.window_id);
  5186. if (keycode != Key::SHIFT) {
  5187. k->set_shift_pressed(ke.shift);
  5188. }
  5189. if (keycode != Key::ALT) {
  5190. k->set_alt_pressed(ke.alt);
  5191. }
  5192. if (keycode != Key::CTRL) {
  5193. k->set_ctrl_pressed(ke.control);
  5194. }
  5195. if (keycode != Key::META) {
  5196. k->set_meta_pressed(ke.meta);
  5197. }
  5198. k->set_pressed(true);
  5199. k->set_keycode(keycode);
  5200. k->set_physical_keycode(physical_keycode);
  5201. k->set_key_label(key_label);
  5202. k->set_unicode(fix_unicode(unicode));
  5203. if (k->get_unicode() && ke.altgr && windows[ke.window_id].ime_active) {
  5204. k->set_alt_pressed(false);
  5205. k->set_ctrl_pressed(false);
  5206. }
  5207. Input::get_singleton()->parse_input_event(k);
  5208. } else {
  5209. // Do nothing.
  5210. }
  5211. } break;
  5212. case WM_KEYUP:
  5213. case WM_KEYDOWN: {
  5214. Ref<InputEventKey> k;
  5215. k.instantiate();
  5216. k->set_window_id(ke.window_id);
  5217. k->set_pressed(ke.uMsg == WM_KEYDOWN);
  5218. bool is_oem = (ke.wParam >= 0xB8) && (ke.wParam <= 0xE6);
  5219. Key keycode = KeyMappingWindows::get_keysym(ke.wParam);
  5220. if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
  5221. // Special case for Numpad Enter key.
  5222. keycode = Key::KP_ENTER;
  5223. }
  5224. Key key_label = keycode;
  5225. Key physical_keycode = KeyMappingWindows::get_scansym((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24));
  5226. KeyLocation location = KeyMappingWindows::get_location((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24));
  5227. static BYTE keyboard_state[256];
  5228. memset(keyboard_state, 0, 256);
  5229. wchar_t chars[256] = {};
  5230. UINT extended_code = MapVirtualKey((ke.lParam >> 16) & 0xFF, MAPVK_VSC_TO_VK_EX);
  5231. if (!(ke.lParam & (1 << 24)) && ToUnicodeEx(extended_code, (ke.lParam >> 16) & 0xFF, keyboard_state, chars, 255, 4, GetKeyboardLayout(0)) > 0) {
  5232. String keysym = String::utf16((char16_t *)chars, 255);
  5233. if (!keysym.is_empty()) {
  5234. char32_t unicode_value = keysym[0];
  5235. // For printable ASCII characters (0x20-0x7E), override the original keycode with the character value.
  5236. if (is_oem && Key::SPACE <= (Key)unicode_value && (Key)unicode_value <= Key::ASCIITILDE) {
  5237. keycode = fix_keycode(unicode_value, (Key)unicode_value);
  5238. }
  5239. key_label = fix_key_label(unicode_value, keycode);
  5240. }
  5241. }
  5242. if (keycode != Key::SHIFT) {
  5243. k->set_shift_pressed(ke.shift);
  5244. }
  5245. if (keycode != Key::ALT) {
  5246. k->set_alt_pressed(ke.alt);
  5247. }
  5248. if (keycode != Key::CTRL) {
  5249. k->set_ctrl_pressed(ke.control);
  5250. }
  5251. if (keycode != Key::META) {
  5252. k->set_meta_pressed(ke.meta);
  5253. }
  5254. k->set_keycode(keycode);
  5255. k->set_physical_keycode(physical_keycode);
  5256. k->set_location(location);
  5257. k->set_key_label(key_label);
  5258. if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
  5259. char32_t unicode = key_event_buffer[i + 1].wParam;
  5260. static char32_t prev_wck = 0;
  5261. if ((unicode & 0xfffffc00) == 0xd800) {
  5262. if (prev_wck != 0) {
  5263. ERR_PRINT("invalid utf16 surrogate input");
  5264. }
  5265. prev_wck = unicode;
  5266. break; // Skip surrogate.
  5267. } else if ((unicode & 0xfffffc00) == 0xdc00) {
  5268. if (prev_wck == 0) {
  5269. ERR_PRINT("invalid utf16 surrogate input");
  5270. break; // Skip invalid surrogate.
  5271. }
  5272. unicode = (prev_wck << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  5273. prev_wck = 0;
  5274. } else {
  5275. prev_wck = 0;
  5276. }
  5277. k->set_unicode(fix_unicode(unicode));
  5278. }
  5279. if (k->get_unicode() && ke.altgr && windows[ke.window_id].ime_active) {
  5280. k->set_alt_pressed(false);
  5281. k->set_ctrl_pressed(false);
  5282. }
  5283. k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));
  5284. Input::get_singleton()->parse_input_event(k);
  5285. } break;
  5286. }
  5287. }
  5288. key_event_pos = 0;
  5289. }
  5290. void DisplayServerWindows::_update_tablet_ctx(const String &p_old_driver, const String &p_new_driver) {
  5291. for (KeyValue<WindowID, WindowData> &E : windows) {
  5292. WindowData &wd = E.value;
  5293. wd.block_mm = false;
  5294. if ((p_old_driver == "wintab") && wintab_available && wd.wtctx) {
  5295. wintab_WTEnable(wd.wtctx, false);
  5296. wintab_WTClose(wd.wtctx);
  5297. wd.wtctx = nullptr;
  5298. }
  5299. if ((p_new_driver == "wintab") && wintab_available) {
  5300. wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
  5301. wd.wtlc.lcOptions |= CXO_MESSAGES;
  5302. wd.wtlc.lcPktData = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
  5303. wd.wtlc.lcMoveMask = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE;
  5304. wd.wtlc.lcPktMode = 0;
  5305. wd.wtlc.lcOutOrgX = 0;
  5306. wd.wtlc.lcOutExtX = wd.wtlc.lcInExtX;
  5307. wd.wtlc.lcOutOrgY = 0;
  5308. wd.wtlc.lcOutExtY = -wd.wtlc.lcInExtY;
  5309. wd.wtctx = wintab_WTOpen(wd.hWnd, &wd.wtlc, false);
  5310. if (wd.wtctx) {
  5311. wintab_WTEnable(wd.wtctx, true);
  5312. AXIS pressure;
  5313. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  5314. wd.min_pressure = int(pressure.axMin);
  5315. wd.max_pressure = int(pressure.axMax);
  5316. }
  5317. AXIS orientation[3];
  5318. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  5319. wd.tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  5320. }
  5321. wintab_WTEnable(wd.wtctx, true);
  5322. } else {
  5323. print_verbose("WinTab context creation failed.");
  5324. }
  5325. }
  5326. }
  5327. }
  5328. DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect, bool p_exclusive, WindowID p_transient_parent, HWND p_parent_hwnd) {
  5329. DWORD dwExStyle;
  5330. DWORD dwStyle;
  5331. _get_window_style(window_id_counter == MAIN_WINDOW_ID, false, (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN), p_mode != WINDOW_MODE_EXCLUSIVE_FULLSCREEN, p_flags & WINDOW_FLAG_BORDERLESS_BIT, !(p_flags & WINDOW_FLAG_RESIZE_DISABLED_BIT), p_flags & WINDOW_FLAG_MINIMIZE_DISABLED_BIT, p_flags & WINDOW_FLAG_MAXIMIZE_DISABLED_BIT, p_mode == WINDOW_MODE_MINIMIZED, p_mode == WINDOW_MODE_MAXIMIZED, false, (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) | (p_flags & WINDOW_FLAG_POPUP_BIT), p_parent_hwnd, dwStyle, dwExStyle);
  5332. int rq_screen = get_screen_from_rect(p_rect);
  5333. if (rq_screen < 0) {
  5334. rq_screen = get_primary_screen(); // Requested window rect is outside any screen bounds.
  5335. }
  5336. Rect2i usable_rect = screen_get_usable_rect(rq_screen);
  5337. Point2i offset = _get_screens_origin();
  5338. RECT WindowRect;
  5339. int off_x = (p_mode == WINDOW_MODE_FULLSCREEN || ((p_flags & WINDOW_FLAG_BORDERLESS_BIT) && p_mode == WINDOW_MODE_MAXIMIZED)) ? FS_TRANSP_BORDER : 0;
  5340. WindowRect.left = p_rect.position.x;
  5341. WindowRect.right = p_rect.position.x + p_rect.size.x + off_x;
  5342. WindowRect.top = p_rect.position.y;
  5343. WindowRect.bottom = p_rect.position.y + p_rect.size.y;
  5344. if (!p_parent_hwnd) {
  5345. if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  5346. Rect2i screen_rect = Rect2i(screen_get_position(rq_screen), screen_get_size(rq_screen));
  5347. WindowRect.left = screen_rect.position.x;
  5348. WindowRect.right = screen_rect.position.x + screen_rect.size.x + off_x;
  5349. WindowRect.top = screen_rect.position.y;
  5350. WindowRect.bottom = screen_rect.position.y + screen_rect.size.y;
  5351. } else {
  5352. Rect2i srect = screen_get_usable_rect(rq_screen);
  5353. Point2i wpos = p_rect.position;
  5354. if (srect != Rect2i()) {
  5355. wpos = wpos.clamp(srect.position, srect.position + srect.size - p_rect.size / 3);
  5356. }
  5357. WindowRect.left = wpos.x;
  5358. WindowRect.right = wpos.x + p_rect.size.x + off_x;
  5359. WindowRect.top = wpos.y;
  5360. WindowRect.bottom = wpos.y + p_rect.size.y;
  5361. }
  5362. }
  5363. WindowRect.left += offset.x;
  5364. WindowRect.right += offset.x;
  5365. WindowRect.top += offset.y;
  5366. WindowRect.bottom += offset.y;
  5367. if (p_mode != WINDOW_MODE_FULLSCREEN && p_mode != WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  5368. AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
  5369. }
  5370. WindowID id = window_id_counter;
  5371. {
  5372. WindowData *wd_transient_parent = nullptr;
  5373. HWND owner_hwnd = nullptr;
  5374. if (p_parent_hwnd) {
  5375. owner_hwnd = p_parent_hwnd;
  5376. } else if (p_transient_parent != INVALID_WINDOW_ID) {
  5377. if (!windows.has(p_transient_parent)) {
  5378. ERR_PRINT("Condition \"!windows.has(p_transient_parent)\" is true.");
  5379. p_transient_parent = INVALID_WINDOW_ID;
  5380. } else {
  5381. wd_transient_parent = &windows[p_transient_parent];
  5382. if (p_exclusive) {
  5383. owner_hwnd = wd_transient_parent->hWnd;
  5384. }
  5385. }
  5386. }
  5387. WindowData &wd = windows[id];
  5388. wd.id = id;
  5389. wd.hWnd = CreateWindowExW(
  5390. dwExStyle,
  5391. L"Engine", L"",
  5392. dwStyle,
  5393. WindowRect.left,
  5394. WindowRect.top,
  5395. WindowRect.right - WindowRect.left,
  5396. WindowRect.bottom - WindowRect.top,
  5397. owner_hwnd,
  5398. nullptr,
  5399. hInstance,
  5400. // tunnel the WindowData we need to handle creation message
  5401. // lifetime is ensured because we are still on the stack when this is
  5402. // processed in the window proc
  5403. reinterpret_cast<void *>(&wd));
  5404. if (!wd.hWnd) {
  5405. MessageBoxW(nullptr, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  5406. windows.erase(id);
  5407. ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create Windows OS window.");
  5408. }
  5409. wd.parent_hwnd = p_parent_hwnd;
  5410. // Detach the input queue from the parent window.
  5411. // This prevents the embedded window from waiting on the main window's input queue,
  5412. // causing lags input lags when resizing or moving the main window.
  5413. if (p_parent_hwnd) {
  5414. DWORD mainThreadId = GetWindowThreadProcessId(owner_hwnd, nullptr);
  5415. DWORD embeddedThreadId = GetCurrentThreadId();
  5416. AttachThreadInput(embeddedThreadId, mainThreadId, FALSE);
  5417. }
  5418. if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  5419. wd.fullscreen = true;
  5420. if (p_mode == WINDOW_MODE_FULLSCREEN) {
  5421. wd.multiwindow_fs = true;
  5422. }
  5423. }
  5424. if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  5425. // Save initial non-fullscreen rect.
  5426. Rect2i srect = screen_get_usable_rect(rq_screen);
  5427. Point2i wpos = p_rect.position;
  5428. if (srect != Rect2i()) {
  5429. wpos = wpos.clamp(srect.position, srect.position + srect.size - p_rect.size / 3);
  5430. }
  5431. wd.pre_fs_rect.left = wpos.x + offset.x;
  5432. wd.pre_fs_rect.right = wpos.x + p_rect.size.x + offset.x;
  5433. wd.pre_fs_rect.top = wpos.y + offset.y;
  5434. wd.pre_fs_rect.bottom = wpos.y + p_rect.size.y + offset.y;
  5435. wd.pre_fs_valid = true;
  5436. }
  5437. wd.exclusive = p_exclusive;
  5438. if (wd_transient_parent) {
  5439. wd.transient_parent = p_transient_parent;
  5440. wd_transient_parent->transient_children.insert(id);
  5441. }
  5442. wd.sharp_corners = p_flags & WINDOW_FLAG_SHARP_CORNERS_BIT;
  5443. {
  5444. DWORD value = wd.sharp_corners ? DWMWCP_DONOTROUND : DWMWCP_DEFAULT;
  5445. ::DwmSetWindowAttribute(wd.hWnd, DWMWA_WINDOW_CORNER_PREFERENCE, &value, sizeof(value));
  5446. }
  5447. if (is_dark_mode_supported() && dark_title_available) {
  5448. BOOL value = is_dark_mode();
  5449. ::DwmSetWindowAttribute(wd.hWnd, use_legacy_dark_mode_before_20H1 ? DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 : DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
  5450. }
  5451. RECT real_client_rect;
  5452. GetClientRect(wd.hWnd, &real_client_rect);
  5453. #ifdef RD_ENABLED
  5454. if (rendering_context) {
  5455. union {
  5456. #ifdef VULKAN_ENABLED
  5457. RenderingContextDriverVulkanWindows::WindowPlatformData vulkan;
  5458. #endif
  5459. #ifdef D3D12_ENABLED
  5460. RenderingContextDriverD3D12::WindowPlatformData d3d12;
  5461. #endif
  5462. } wpd;
  5463. #ifdef VULKAN_ENABLED
  5464. if (rendering_driver == "vulkan") {
  5465. wpd.vulkan.window = wd.hWnd;
  5466. wpd.vulkan.instance = hInstance;
  5467. }
  5468. #endif
  5469. #ifdef D3D12_ENABLED
  5470. if (rendering_driver == "d3d12") {
  5471. wpd.d3d12.window = wd.hWnd;
  5472. }
  5473. #endif
  5474. if (rendering_context->window_create(id, &wpd) != OK) {
  5475. ERR_PRINT(vformat("Failed to create %s window.", rendering_driver));
  5476. memdelete(rendering_context);
  5477. rendering_context = nullptr;
  5478. windows.erase(id);
  5479. return INVALID_WINDOW_ID;
  5480. }
  5481. rendering_context->window_set_size(id, real_client_rect.right - real_client_rect.left - off_x, real_client_rect.bottom - real_client_rect.top);
  5482. rendering_context->window_set_vsync_mode(id, p_vsync_mode);
  5483. wd.context_created = true;
  5484. }
  5485. #endif
  5486. #ifdef GLES3_ENABLED
  5487. if (gl_manager_native) {
  5488. if (gl_manager_native->window_create(id, wd.hWnd, hInstance, real_client_rect.right - real_client_rect.left - off_x, real_client_rect.bottom - real_client_rect.top) != OK) {
  5489. memdelete(gl_manager_native);
  5490. gl_manager_native = nullptr;
  5491. windows.erase(id);
  5492. ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create an OpenGL window.");
  5493. }
  5494. window_set_vsync_mode(p_vsync_mode, id);
  5495. }
  5496. if (gl_manager_angle) {
  5497. if (gl_manager_angle->window_create(id, nullptr, wd.hWnd, real_client_rect.right - real_client_rect.left - off_x, real_client_rect.bottom - real_client_rect.top) != OK) {
  5498. memdelete(gl_manager_angle);
  5499. gl_manager_angle = nullptr;
  5500. windows.erase(id);
  5501. ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create an OpenGL window.");
  5502. }
  5503. window_set_vsync_mode(p_vsync_mode, id);
  5504. }
  5505. #endif
  5506. RegisterTouchWindow(wd.hWnd, 0);
  5507. DragAcceptFiles(wd.hWnd, true);
  5508. if ((tablet_get_current_driver() == "wintab") && wintab_available) {
  5509. wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
  5510. wd.wtlc.lcOptions |= CXO_MESSAGES;
  5511. wd.wtlc.lcPktData = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
  5512. wd.wtlc.lcMoveMask = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE;
  5513. wd.wtlc.lcPktMode = 0;
  5514. wd.wtlc.lcOutOrgX = 0;
  5515. wd.wtlc.lcOutExtX = wd.wtlc.lcInExtX;
  5516. wd.wtlc.lcOutOrgY = 0;
  5517. wd.wtlc.lcOutExtY = -wd.wtlc.lcInExtY;
  5518. wd.wtctx = wintab_WTOpen(wd.hWnd, &wd.wtlc, false);
  5519. if (wd.wtctx) {
  5520. wintab_WTEnable(wd.wtctx, true);
  5521. AXIS pressure;
  5522. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  5523. wd.min_pressure = int(pressure.axMin);
  5524. wd.max_pressure = int(pressure.axMax);
  5525. }
  5526. AXIS orientation[3];
  5527. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  5528. wd.tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  5529. }
  5530. } else {
  5531. print_verbose("WinTab context creation failed.");
  5532. }
  5533. } else {
  5534. wd.wtctx = nullptr;
  5535. }
  5536. if (p_mode == WINDOW_MODE_MAXIMIZED) {
  5537. wd.maximized = true;
  5538. wd.minimized = false;
  5539. }
  5540. if (p_mode == WINDOW_MODE_MINIMIZED) {
  5541. wd.maximized = false;
  5542. wd.minimized = true;
  5543. }
  5544. wd.last_pressure = 0;
  5545. wd.last_pressure_update = 0;
  5546. wd.last_tilt = Vector2();
  5547. IPropertyStore *prop_store;
  5548. HRESULT hr = SHGetPropertyStoreForWindow(wd.hWnd, IID_IPropertyStore, (void **)&prop_store);
  5549. if (hr == S_OK) {
  5550. PROPVARIANT val;
  5551. String appname;
  5552. if (Engine::get_singleton()->is_editor_hint()) {
  5553. appname = "Godot.GodotEditor." + String(GODOT_VERSION_FULL_CONFIG);
  5554. } else {
  5555. String name = GLOBAL_GET("application/config/name");
  5556. String version = GLOBAL_GET("application/config/version");
  5557. if (version.is_empty()) {
  5558. version = "0";
  5559. }
  5560. String clean_app_name = name.to_pascal_case();
  5561. for (int i = 0; i < clean_app_name.length(); i++) {
  5562. if (!is_ascii_alphanumeric_char(clean_app_name[i]) && clean_app_name[i] != '_' && clean_app_name[i] != '.') {
  5563. clean_app_name[i] = '_';
  5564. }
  5565. }
  5566. clean_app_name = clean_app_name.substr(0, 120 - version.length()).trim_suffix(".");
  5567. appname = "Godot." + clean_app_name + "." + version;
  5568. }
  5569. InitPropVariantFromString((PCWSTR)appname.utf16().get_data(), &val);
  5570. prop_store->SetValue(PKEY_AppUserModel_ID, val);
  5571. prop_store->Release();
  5572. }
  5573. // IME.
  5574. wd.im_himc = ImmGetContext(wd.hWnd);
  5575. ImmAssociateContext(wd.hWnd, (HIMC) nullptr);
  5576. wd.im_position = Vector2();
  5577. if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN || p_mode == WINDOW_MODE_MAXIMIZED) {
  5578. RECT r;
  5579. GetClientRect(wd.hWnd, &r);
  5580. ClientToScreen(wd.hWnd, (POINT *)&r.left);
  5581. ClientToScreen(wd.hWnd, (POINT *)&r.right);
  5582. wd.last_pos = Point2i(r.left, r.top) - _get_screens_origin();
  5583. wd.width = r.right - r.left - off_x;
  5584. wd.height = r.bottom - r.top;
  5585. } else {
  5586. wd.last_pos = p_rect.position;
  5587. wd.width = p_rect.size.width;
  5588. wd.height = p_rect.size.height;
  5589. }
  5590. wd.create_completed = true;
  5591. // Set size of maximized borderless window (by default it covers the entire screen).
  5592. if (!p_parent_hwnd && p_mode == WINDOW_MODE_MAXIMIZED && (p_flags & WINDOW_FLAG_BORDERLESS_BIT)) {
  5593. SetWindowPos(wd.hWnd, HWND_TOP, usable_rect.position.x - off_x, usable_rect.position.y, usable_rect.size.width + off_x, usable_rect.size.height, SWP_NOZORDER | SWP_NOACTIVATE);
  5594. }
  5595. _update_window_mouse_passthrough(id);
  5596. window_id_counter++;
  5597. }
  5598. return id;
  5599. }
  5600. BitField<DisplayServerWindows::DriverID> DisplayServerWindows::tested_drivers = 0;
  5601. // WinTab API.
  5602. bool DisplayServerWindows::wintab_available = false;
  5603. WTOpenPtr DisplayServerWindows::wintab_WTOpen = nullptr;
  5604. WTClosePtr DisplayServerWindows::wintab_WTClose = nullptr;
  5605. WTInfoPtr DisplayServerWindows::wintab_WTInfo = nullptr;
  5606. WTPacketPtr DisplayServerWindows::wintab_WTPacket = nullptr;
  5607. WTEnablePtr DisplayServerWindows::wintab_WTEnable = nullptr;
  5608. // UXTheme API.
  5609. bool DisplayServerWindows::dark_title_available = false;
  5610. bool DisplayServerWindows::use_legacy_dark_mode_before_20H1 = false;
  5611. bool DisplayServerWindows::ux_theme_available = false;
  5612. ShouldAppsUseDarkModePtr DisplayServerWindows::ShouldAppsUseDarkMode = nullptr;
  5613. GetImmersiveColorFromColorSetExPtr DisplayServerWindows::GetImmersiveColorFromColorSetEx = nullptr;
  5614. GetImmersiveColorTypeFromNamePtr DisplayServerWindows::GetImmersiveColorTypeFromName = nullptr;
  5615. GetImmersiveUserColorSetPreferencePtr DisplayServerWindows::GetImmersiveUserColorSetPreference = nullptr;
  5616. Vector2i _get_device_ids(const String &p_device_name) {
  5617. if (p_device_name.is_empty()) {
  5618. return Vector2i();
  5619. }
  5620. REFCLSID clsid = CLSID_WbemLocator; // Unmarshaler CLSID
  5621. REFIID uuid = IID_IWbemLocator; // Interface UUID
  5622. IWbemLocator *wbemLocator = nullptr; // to get the services
  5623. IWbemServices *wbemServices = nullptr; // to get the class
  5624. IEnumWbemClassObject *iter = nullptr;
  5625. IWbemClassObject *pnpSDriverObject[1]; // contains driver name, version, etc.
  5626. HRESULT hr = CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, uuid, (LPVOID *)&wbemLocator);
  5627. if (hr != S_OK) {
  5628. return Vector2i();
  5629. }
  5630. BSTR resource_name = SysAllocString(L"root\\CIMV2");
  5631. hr = wbemLocator->ConnectServer(resource_name, nullptr, nullptr, nullptr, 0, nullptr, nullptr, &wbemServices);
  5632. SysFreeString(resource_name);
  5633. SAFE_RELEASE(wbemLocator) // from now on, use `wbemServices`
  5634. if (hr != S_OK) {
  5635. SAFE_RELEASE(wbemServices)
  5636. return Vector2i();
  5637. }
  5638. Vector2i ids;
  5639. const String gpu_device_class_query = vformat("SELECT * FROM Win32_PnPSignedDriver WHERE DeviceName = \"%s\"", p_device_name);
  5640. BSTR query = SysAllocString((const WCHAR *)gpu_device_class_query.utf16().get_data());
  5641. BSTR query_lang = SysAllocString(L"WQL");
  5642. hr = wbemServices->ExecQuery(query_lang, query, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, nullptr, &iter);
  5643. SysFreeString(query_lang);
  5644. SysFreeString(query);
  5645. if (hr == S_OK) {
  5646. ULONG resultCount;
  5647. hr = iter->Next(5000, 1, pnpSDriverObject, &resultCount); // Get exactly 1. Wait max 5 seconds.
  5648. if (hr == S_OK && resultCount > 0) {
  5649. VARIANT did;
  5650. VariantInit(&did);
  5651. BSTR object_name = SysAllocString(L"DeviceID");
  5652. hr = pnpSDriverObject[0]->Get(object_name, 0, &did, nullptr, nullptr);
  5653. SysFreeString(object_name);
  5654. if (hr == S_OK) {
  5655. String device_id = String(V_BSTR(&did));
  5656. ids.x = device_id.get_slicec('&', 0).lstrip("PCI\\VEN_").hex_to_int();
  5657. ids.y = device_id.get_slicec('&', 1).lstrip("DEV_").hex_to_int();
  5658. }
  5659. for (ULONG i = 0; i < resultCount; i++) {
  5660. SAFE_RELEASE(pnpSDriverObject[i])
  5661. }
  5662. }
  5663. }
  5664. SAFE_RELEASE(wbemServices)
  5665. SAFE_RELEASE(iter)
  5666. return ids;
  5667. }
  5668. bool DisplayServerWindows::is_dark_mode_supported() const {
  5669. return ux_theme_available;
  5670. }
  5671. bool DisplayServerWindows::is_dark_mode() const {
  5672. return ux_theme_available && ShouldAppsUseDarkMode();
  5673. }
  5674. Color DisplayServerWindows::get_accent_color() const {
  5675. if (!ux_theme_available) {
  5676. return Color(0, 0, 0, 0);
  5677. }
  5678. int argb = GetImmersiveColorFromColorSetEx((UINT)GetImmersiveUserColorSetPreference(false, false), GetImmersiveColorTypeFromName(L"ImmersiveSystemAccent"), false, 0);
  5679. return Color((argb & 0xFF) / 255.f, ((argb & 0xFF00) >> 8) / 255.f, ((argb & 0xFF0000) >> 16) / 255.f, ((argb & 0xFF000000) >> 24) / 255.f);
  5680. }
  5681. Color DisplayServerWindows::get_base_color() const {
  5682. if (!ux_theme_available) {
  5683. return Color(0, 0, 0, 0);
  5684. }
  5685. int argb = GetImmersiveColorFromColorSetEx((UINT)GetImmersiveUserColorSetPreference(false, false), GetImmersiveColorTypeFromName(ShouldAppsUseDarkMode() ? L"ImmersiveDarkChromeMediumLow" : L"ImmersiveLightChromeMediumLow"), false, 0);
  5686. return Color((argb & 0xFF) / 255.f, ((argb & 0xFF00) >> 8) / 255.f, ((argb & 0xFF0000) >> 16) / 255.f, ((argb & 0xFF000000) >> 24) / 255.f);
  5687. }
  5688. void DisplayServerWindows::set_system_theme_change_callback(const Callable &p_callable) {
  5689. system_theme_changed = p_callable;
  5690. }
  5691. int DisplayServerWindows::tablet_get_driver_count() const {
  5692. return tablet_drivers.size();
  5693. }
  5694. String DisplayServerWindows::tablet_get_driver_name(int p_driver) const {
  5695. if (p_driver < 0 || p_driver >= tablet_drivers.size()) {
  5696. return "";
  5697. } else {
  5698. return tablet_drivers[p_driver];
  5699. }
  5700. }
  5701. String DisplayServerWindows::tablet_get_current_driver() const {
  5702. return tablet_driver;
  5703. }
  5704. void DisplayServerWindows::tablet_set_current_driver(const String &p_driver) {
  5705. if (tablet_get_driver_count() == 0) {
  5706. return;
  5707. }
  5708. String driver = p_driver;
  5709. if (driver == "auto") {
  5710. if (!winink_disabled) {
  5711. driver = "winink";
  5712. } else if (wintab_available) {
  5713. driver = "wintab";
  5714. } else {
  5715. driver = "dummy";
  5716. }
  5717. }
  5718. bool found = false;
  5719. for (int i = 0; i < tablet_get_driver_count(); i++) {
  5720. if (driver == tablet_get_driver_name(i)) {
  5721. found = true;
  5722. }
  5723. }
  5724. if (found) {
  5725. _update_tablet_ctx(tablet_driver, driver);
  5726. tablet_driver = driver;
  5727. } else {
  5728. ERR_PRINT("Unknown tablet driver " + p_driver + ".");
  5729. }
  5730. }
  5731. DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, int p_screen, Context p_context, int64_t p_parent_window, Error &r_error) {
  5732. KeyMappingWindows::initialize();
  5733. tested_drivers.clear();
  5734. drop_events = false;
  5735. key_event_pos = 0;
  5736. hInstance = static_cast<OS_Windows *>(OS::get_singleton())->get_hinstance();
  5737. pressrc = 0;
  5738. old_invalid = true;
  5739. mouse_mode = MOUSE_MODE_VISIBLE;
  5740. rendering_driver = p_rendering_driver;
  5741. // Init TTS
  5742. bool tts_enabled = GLOBAL_GET("audio/general/text_to_speech");
  5743. if (tts_enabled) {
  5744. initialize_tts();
  5745. }
  5746. native_menu = memnew(NativeMenuWindows);
  5747. #ifdef ACCESSKIT_ENABLED
  5748. if (accessibility_get_mode() != DisplayServer::AccessibilityMode::ACCESSIBILITY_DISABLED) {
  5749. accessibility_driver = memnew(AccessibilityDriverAccessKit);
  5750. if (accessibility_driver->init() != OK) {
  5751. if (OS::get_singleton()->is_stdout_verbose()) {
  5752. ERR_PRINT("Can't create an accessibility driver, accessibility support disabled!");
  5753. }
  5754. memdelete(accessibility_driver);
  5755. accessibility_driver = nullptr;
  5756. }
  5757. }
  5758. #endif
  5759. // Enforce default keep screen on value.
  5760. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
  5761. // Load Windows version info.
  5762. ZeroMemory(&os_ver, sizeof(OSVERSIONINFOW));
  5763. os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
  5764. HMODULE nt_lib = LoadLibraryW(L"ntdll.dll");
  5765. if (nt_lib) {
  5766. WineGetVersionPtr wine_get_version = (WineGetVersionPtr)(void *)GetProcAddress(nt_lib, "wine_get_version"); // Do not read Windows build number under Wine, it can be set to arbitrary value.
  5767. if (!wine_get_version) {
  5768. RtlGetVersionPtr RtlGetVersion = (RtlGetVersionPtr)(void *)GetProcAddress(nt_lib, "RtlGetVersion");
  5769. if (RtlGetVersion) {
  5770. RtlGetVersion(&os_ver);
  5771. }
  5772. }
  5773. FreeLibrary(nt_lib);
  5774. }
  5775. // Load UXTheme.
  5776. if (os_ver.dwBuildNumber >= 10240) { // Not available on Wine, use only if real Windows 10/11 detected.
  5777. HMODULE ux_theme_lib = LoadLibraryW(L"uxtheme.dll");
  5778. if (ux_theme_lib) {
  5779. ShouldAppsUseDarkMode = (ShouldAppsUseDarkModePtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(132));
  5780. GetImmersiveColorFromColorSetEx = (GetImmersiveColorFromColorSetExPtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(95));
  5781. GetImmersiveColorTypeFromName = (GetImmersiveColorTypeFromNamePtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(96));
  5782. GetImmersiveUserColorSetPreference = (GetImmersiveUserColorSetPreferencePtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(98));
  5783. if (os_ver.dwBuildNumber >= 17763) { // Windows 10 Redstone 5 (1809)+ only.
  5784. AllowDarkModeForAppPtr AllowDarkModeForApp = nullptr;
  5785. SetPreferredAppModePtr SetPreferredAppMode = nullptr;
  5786. FlushMenuThemesPtr FlushMenuThemes = nullptr;
  5787. if (os_ver.dwBuildNumber < 18362) { // Windows 10 Redstone 5 (1809) and 19H1 (1903) only.
  5788. AllowDarkModeForApp = (AllowDarkModeForAppPtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(135));
  5789. } else { // Windows 10 19H2 (1909)+ only.
  5790. SetPreferredAppMode = (SetPreferredAppModePtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(135));
  5791. FlushMenuThemes = (FlushMenuThemesPtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(136));
  5792. }
  5793. RefreshImmersiveColorPolicyStatePtr RefreshImmersiveColorPolicyState = (RefreshImmersiveColorPolicyStatePtr)(void *)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(104));
  5794. if (ShouldAppsUseDarkMode) {
  5795. bool dark_mode = ShouldAppsUseDarkMode();
  5796. if (SetPreferredAppMode) {
  5797. SetPreferredAppMode(dark_mode ? APPMODE_ALLOWDARK : APPMODE_DEFAULT);
  5798. } else if (AllowDarkModeForApp) {
  5799. AllowDarkModeForApp(dark_mode);
  5800. }
  5801. if (RefreshImmersiveColorPolicyState) {
  5802. RefreshImmersiveColorPolicyState();
  5803. }
  5804. if (FlushMenuThemes) {
  5805. FlushMenuThemes();
  5806. }
  5807. }
  5808. }
  5809. ux_theme_available = ShouldAppsUseDarkMode && GetImmersiveColorFromColorSetEx && GetImmersiveColorTypeFromName && GetImmersiveUserColorSetPreference;
  5810. if (os_ver.dwBuildNumber >= 18363) {
  5811. dark_title_available = true;
  5812. if (os_ver.dwBuildNumber < 19041) {
  5813. use_legacy_dark_mode_before_20H1 = true;
  5814. }
  5815. }
  5816. }
  5817. }
  5818. tablet_drivers.push_back("auto");
  5819. tablet_drivers.push_back("winink");
  5820. // Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
  5821. HMODULE wintab_lib = LoadLibraryW(L"wintab32.dll");
  5822. if (wintab_lib) {
  5823. wintab_WTOpen = (WTOpenPtr)(void *)GetProcAddress(wintab_lib, "WTOpenW");
  5824. wintab_WTClose = (WTClosePtr)(void *)GetProcAddress(wintab_lib, "WTClose");
  5825. wintab_WTInfo = (WTInfoPtr)(void *)GetProcAddress(wintab_lib, "WTInfoW");
  5826. wintab_WTPacket = (WTPacketPtr)(void *)GetProcAddress(wintab_lib, "WTPacket");
  5827. wintab_WTEnable = (WTEnablePtr)(void *)GetProcAddress(wintab_lib, "WTEnable");
  5828. wintab_available = wintab_WTOpen && wintab_WTClose && wintab_WTInfo && wintab_WTPacket && wintab_WTEnable;
  5829. }
  5830. if (wintab_available) {
  5831. tablet_drivers.push_back("wintab");
  5832. }
  5833. tablet_drivers.push_back("dummy");
  5834. String wacom_cfg = OS::get_singleton()->get_config_path().path_join("WTablet").path_join("Wacom_Tablet.dat");
  5835. if (FileAccess::exists(wacom_cfg)) {
  5836. Ref<XMLParser> parser;
  5837. parser.instantiate();
  5838. if (parser->open(wacom_cfg) == OK) {
  5839. while (parser->read() == OK) {
  5840. if (parser->get_node_type() != XMLParser::NODE_ELEMENT) {
  5841. continue;
  5842. }
  5843. if (parser->get_node_name() == "WinUseInk") {
  5844. parser->read();
  5845. if (parser->get_node_type() == XMLParser::NODE_TEXT) {
  5846. winink_disabled = (parser->get_node_data().to_lower().strip_edges() != "true");
  5847. print_verbose(vformat("Wacom tablet config found at \"%s\", Windows Ink support is %s.", wacom_cfg, winink_disabled ? "disabled" : "enabled"));
  5848. break;
  5849. }
  5850. }
  5851. }
  5852. }
  5853. }
  5854. if (OS::get_singleton()->is_hidpi_allowed()) {
  5855. SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE);
  5856. }
  5857. HMODULE comctl32 = LoadLibraryW(L"comctl32.dll");
  5858. if (comctl32) {
  5859. typedef BOOL(WINAPI * InitCommonControlsExPtr)(_In_ const INITCOMMONCONTROLSEX *picce);
  5860. InitCommonControlsExPtr init_common_controls_ex = (InitCommonControlsExPtr)(void *)GetProcAddress(comctl32, "InitCommonControlsEx");
  5861. // Fails if the incorrect version was loaded. Probably not a big enough deal to print an error about.
  5862. if (init_common_controls_ex) {
  5863. INITCOMMONCONTROLSEX icc = {};
  5864. icc.dwICC = ICC_STANDARD_CLASSES;
  5865. icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
  5866. if (!init_common_controls_ex(&icc)) {
  5867. WARN_PRINT("Unable to initialize Windows common controls. Native dialogs may not work properly.");
  5868. }
  5869. }
  5870. FreeLibrary(comctl32);
  5871. }
  5872. OleInitialize(nullptr);
  5873. memset(&wc, 0, sizeof(WNDCLASSEXW));
  5874. wc.cbSize = sizeof(WNDCLASSEXW);
  5875. wc.style = CS_OWNDC | CS_DBLCLKS;
  5876. wc.lpfnWndProc = (WNDPROC)::WndProc;
  5877. wc.cbClsExtra = 0;
  5878. wc.cbWndExtra = 0;
  5879. wc.hInstance = hInstance ? hInstance : GetModuleHandle(nullptr);
  5880. wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
  5881. wc.hCursor = nullptr;
  5882. wc.hbrBackground = nullptr;
  5883. wc.lpszMenuName = nullptr;
  5884. wc.lpszClassName = L"Engine";
  5885. if (!RegisterClassExW(&wc)) {
  5886. r_error = ERR_UNAVAILABLE;
  5887. return;
  5888. }
  5889. _register_raw_input_devices(INVALID_WINDOW_ID);
  5890. // Init context and rendering device.
  5891. if (rendering_driver == "dummy") {
  5892. RasterizerDummy::make_current();
  5893. }
  5894. #if defined(RD_ENABLED)
  5895. [[maybe_unused]] bool fallback_to_vulkan = GLOBAL_GET("rendering/rendering_device/fallback_to_vulkan");
  5896. [[maybe_unused]] bool fallback_to_d3d12 = GLOBAL_GET("rendering/rendering_device/fallback_to_d3d12");
  5897. #if defined(VULKAN_ENABLED)
  5898. if (rendering_driver == "vulkan") {
  5899. rendering_context = memnew(RenderingContextDriverVulkanWindows);
  5900. tested_drivers.set_flag(DRIVER_ID_RD_VULKAN);
  5901. }
  5902. #else
  5903. fallback_to_d3d12 = true; // Always enable fallback if engine was built w/o other driver support.
  5904. #endif
  5905. #if defined(D3D12_ENABLED)
  5906. if (rendering_driver == "d3d12") {
  5907. rendering_context = memnew(RenderingContextDriverD3D12);
  5908. tested_drivers.set_flag(DRIVER_ID_RD_D3D12);
  5909. }
  5910. #else
  5911. fallback_to_vulkan = true; // Always enable fallback if engine was built w/o other driver support.
  5912. #endif
  5913. if (rendering_context) {
  5914. if (rendering_context->initialize() != OK) {
  5915. bool failed = true;
  5916. #if defined(VULKAN_ENABLED)
  5917. if (failed && fallback_to_vulkan && rendering_driver != "vulkan") {
  5918. memdelete(rendering_context);
  5919. rendering_context = memnew(RenderingContextDriverVulkanWindows);
  5920. tested_drivers.set_flag(DRIVER_ID_RD_VULKAN);
  5921. if (rendering_context->initialize() == OK) {
  5922. WARN_PRINT("Your video card drivers seem not to support Direct3D 12, switching to Vulkan.");
  5923. rendering_driver = "vulkan";
  5924. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  5925. failed = false;
  5926. }
  5927. }
  5928. #endif
  5929. #if defined(D3D12_ENABLED)
  5930. if (failed && fallback_to_d3d12 && rendering_driver != "d3d12") {
  5931. memdelete(rendering_context);
  5932. rendering_context = memnew(RenderingContextDriverD3D12);
  5933. tested_drivers.set_flag(DRIVER_ID_RD_D3D12);
  5934. if (rendering_context->initialize() == OK) {
  5935. WARN_PRINT("Your video card drivers seem not to support Vulkan, switching to Direct3D 12.");
  5936. rendering_driver = "d3d12";
  5937. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  5938. failed = false;
  5939. }
  5940. }
  5941. #endif
  5942. #if defined(GLES3_ENABLED)
  5943. bool fallback_to_opengl3 = GLOBAL_GET("rendering/rendering_device/fallback_to_opengl3");
  5944. if (failed && fallback_to_opengl3 && rendering_driver != "opengl3") {
  5945. memdelete(rendering_context);
  5946. rendering_context = nullptr;
  5947. tested_drivers.set_flag(DRIVER_ID_COMPAT_OPENGL3);
  5948. WARN_PRINT("Your video card drivers seem not to support Direct3D 12 or Vulkan, switching to OpenGL 3.");
  5949. rendering_driver = "opengl3";
  5950. OS::get_singleton()->set_current_rendering_method("gl_compatibility");
  5951. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  5952. failed = false;
  5953. }
  5954. #endif
  5955. if (failed) {
  5956. memdelete(rendering_context);
  5957. rendering_context = nullptr;
  5958. r_error = ERR_UNAVAILABLE;
  5959. return;
  5960. }
  5961. }
  5962. }
  5963. #endif
  5964. #if defined(GLES3_ENABLED)
  5965. bool fallback = GLOBAL_GET("rendering/gl_compatibility/fallback_to_angle");
  5966. bool show_warning = true;
  5967. if (rendering_driver == "opengl3") {
  5968. // There's no native OpenGL drivers on Windows for ARM, always enable fallback.
  5969. #if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  5970. fallback = true;
  5971. show_warning = false;
  5972. #else
  5973. typedef BOOL(WINAPI * IsWow64Process2Ptr)(HANDLE, USHORT *, USHORT *);
  5974. IsWow64Process2Ptr IsWow64Process2 = (IsWow64Process2Ptr)(void *)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process2");
  5975. if (IsWow64Process2) {
  5976. USHORT process_arch = 0;
  5977. USHORT machine_arch = 0;
  5978. if (!IsWow64Process2(GetCurrentProcess(), &process_arch, &machine_arch)) {
  5979. machine_arch = 0;
  5980. }
  5981. if (machine_arch == 0xAA64) {
  5982. fallback = true;
  5983. show_warning = false;
  5984. }
  5985. }
  5986. #endif
  5987. }
  5988. bool gl_supported = true;
  5989. if (fallback && (rendering_driver == "opengl3")) {
  5990. Dictionary gl_info = detect_wgl();
  5991. bool force_angle = false;
  5992. gl_supported = gl_info["version"].operator int() >= 30003;
  5993. Vector2i device_id = _get_device_ids(gl_info["name"]);
  5994. Array device_list = GLOBAL_GET("rendering/gl_compatibility/force_angle_on_devices");
  5995. for (int i = 0; i < device_list.size(); i++) {
  5996. const Dictionary &device = device_list[i];
  5997. if (device.has("vendor") && device.has("name")) {
  5998. const String &vendor = device["vendor"];
  5999. const String &name = device["name"];
  6000. if (device_id != Vector2i() && vendor.begins_with("0x") && name.begins_with("0x") && device_id.x == vendor.lstrip("0x").hex_to_int() && device_id.y == name.lstrip("0x").hex_to_int()) {
  6001. // Check vendor/device IDs.
  6002. force_angle = true;
  6003. break;
  6004. } else if (gl_info["vendor"].operator String().to_upper().contains(vendor.to_upper()) && (name == "*" || gl_info["name"].operator String().to_upper().contains(name.to_upper()))) {
  6005. // Check vendor/device names.
  6006. force_angle = true;
  6007. break;
  6008. }
  6009. }
  6010. }
  6011. if (force_angle || (gl_info["version"].operator int() < 30003)) {
  6012. tested_drivers.set_flag(DRIVER_ID_COMPAT_OPENGL3);
  6013. if (show_warning) {
  6014. if (gl_info["version"].operator int() < 30003) {
  6015. WARN_PRINT("Your video card drivers seem not to support the required OpenGL 3.3 version, switching to ANGLE.");
  6016. } else {
  6017. WARN_PRINT("Your video card drivers are known to have low quality OpenGL 3.3 support, switching to ANGLE.");
  6018. }
  6019. }
  6020. rendering_driver = "opengl3_angle";
  6021. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  6022. }
  6023. }
  6024. if (rendering_driver == "opengl3_angle") {
  6025. gl_manager_angle = memnew(GLManagerANGLE_Windows);
  6026. tested_drivers.set_flag(DRIVER_ID_COMPAT_ANGLE_D3D11);
  6027. if (gl_manager_angle->initialize() != OK) {
  6028. memdelete(gl_manager_angle);
  6029. gl_manager_angle = nullptr;
  6030. bool fallback_to_native = GLOBAL_GET("rendering/gl_compatibility/fallback_to_native");
  6031. if (fallback_to_native && gl_supported) {
  6032. #ifdef EGL_STATIC
  6033. WARN_PRINT("Your video card drivers seem not to support GLES3 / ANGLE, switching to native OpenGL.");
  6034. #else
  6035. WARN_PRINT("Your video card drivers seem not to support GLES3 / ANGLE or ANGLE dynamic libraries (libEGL.dll and libGLESv2.dll) are missing, switching to native OpenGL.");
  6036. #endif
  6037. rendering_driver = "opengl3";
  6038. } else {
  6039. r_error = ERR_UNAVAILABLE;
  6040. ERR_FAIL_MSG("Could not initialize ANGLE OpenGL.");
  6041. }
  6042. }
  6043. }
  6044. if (rendering_driver == "opengl3") {
  6045. gl_manager_native = memnew(GLManagerNative_Windows);
  6046. tested_drivers.set_flag(DRIVER_ID_COMPAT_OPENGL3);
  6047. if (gl_manager_native->initialize() != OK) {
  6048. memdelete(gl_manager_native);
  6049. gl_manager_native = nullptr;
  6050. r_error = ERR_UNAVAILABLE;
  6051. ERR_FAIL_MSG("Could not initialize native OpenGL.");
  6052. }
  6053. }
  6054. if (rendering_driver == "opengl3") {
  6055. RasterizerGLES3::make_current(true);
  6056. }
  6057. if (rendering_driver == "opengl3_angle") {
  6058. RasterizerGLES3::make_current(false);
  6059. }
  6060. #endif
  6061. String appname;
  6062. if (Engine::get_singleton()->is_editor_hint()) {
  6063. appname = "Godot.GodotEditor." + String(GODOT_VERSION_FULL_CONFIG);
  6064. } else {
  6065. String name = GLOBAL_GET("application/config/name");
  6066. String version = GLOBAL_GET("application/config/version");
  6067. if (version.is_empty()) {
  6068. version = "0";
  6069. }
  6070. String clean_app_name = name.to_pascal_case();
  6071. for (int i = 0; i < clean_app_name.length(); i++) {
  6072. if (!is_ascii_alphanumeric_char(clean_app_name[i]) && clean_app_name[i] != '_' && clean_app_name[i] != '.') {
  6073. clean_app_name[i] = '_';
  6074. }
  6075. }
  6076. clean_app_name = clean_app_name.substr(0, 120 - version.length()).trim_suffix(".");
  6077. appname = "Godot." + clean_app_name + "." + version;
  6078. #ifndef TOOLS_ENABLED
  6079. // Set for exported projects only.
  6080. HKEY key;
  6081. if (RegOpenKeyW(HKEY_CURRENT_USER_LOCAL_SETTINGS, L"Software\\Microsoft\\Windows\\Shell\\MuiCache", &key) == ERROR_SUCCESS) {
  6082. Char16String cs_name = name.utf16();
  6083. String value_name = OS::get_singleton()->get_executable_path().replace_char('/', '\\') + ".FriendlyAppName";
  6084. RegSetValueExW(key, (LPCWSTR)value_name.utf16().get_data(), 0, REG_SZ, (const BYTE *)cs_name.get_data(), cs_name.size() * sizeof(WCHAR));
  6085. RegCloseKey(key);
  6086. }
  6087. #endif
  6088. }
  6089. SetCurrentProcessExplicitAppUserModelID((PCWSTR)appname.utf16().get_data());
  6090. mouse_monitor = SetWindowsHookEx(WH_MOUSE, ::MouseProc, nullptr, GetCurrentThreadId());
  6091. Point2i window_position;
  6092. if (p_position != nullptr) {
  6093. window_position = *p_position;
  6094. } else {
  6095. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  6096. p_screen = SCREEN_PRIMARY;
  6097. }
  6098. Rect2i scr_rect = screen_get_usable_rect(p_screen);
  6099. window_position = scr_rect.position + (scr_rect.size - p_resolution) / 2;
  6100. }
  6101. HWND parent_hwnd = NULL;
  6102. if (p_parent_window) {
  6103. // Parented window.
  6104. parent_hwnd = (HWND)p_parent_window;
  6105. }
  6106. WindowID main_window = _create_window(p_mode, p_vsync_mode, p_flags, Rect2i(window_position, p_resolution), false, INVALID_WINDOW_ID, parent_hwnd);
  6107. if (main_window == INVALID_WINDOW_ID) {
  6108. r_error = ERR_UNAVAILABLE;
  6109. ERR_FAIL_MSG("Failed to create main window.");
  6110. }
  6111. joypad = new JoypadWindows(&windows[MAIN_WINDOW_ID].hWnd);
  6112. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  6113. if (p_flags & (1 << i)) {
  6114. window_set_flag(WindowFlags(i), true, main_window);
  6115. }
  6116. }
  6117. windows[MAIN_WINDOW_ID].initialized = true;
  6118. #ifdef ACCESSKIT_ENABLED
  6119. if (accessibility_screen_reader_active()) {
  6120. _THREAD_SAFE_LOCK_
  6121. uint64_t time_wait = OS::get_singleton()->get_ticks_msec();
  6122. while (true) {
  6123. MSG msg = {};
  6124. while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
  6125. TranslateMessage(&msg);
  6126. DispatchMessageW(&msg);
  6127. }
  6128. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_wait;
  6129. if (delta > 500 || get_object_recieved) {
  6130. break;
  6131. }
  6132. }
  6133. _THREAD_SAFE_UNLOCK_
  6134. }
  6135. #endif
  6136. #if defined(RD_ENABLED)
  6137. if (rendering_context) {
  6138. rendering_device = memnew(RenderingDevice);
  6139. if (rendering_device->initialize(rendering_context, MAIN_WINDOW_ID) != OK) {
  6140. memdelete(rendering_device);
  6141. rendering_device = nullptr;
  6142. memdelete(rendering_context);
  6143. rendering_context = nullptr;
  6144. r_error = ERR_UNAVAILABLE;
  6145. return;
  6146. }
  6147. rendering_device->screen_create(MAIN_WINDOW_ID);
  6148. RendererCompositorRD::make_current();
  6149. }
  6150. #endif
  6151. if (!Engine::get_singleton()->is_editor_hint() && !OS::get_singleton()->is_in_low_processor_usage_mode()) {
  6152. // Increase priority for projects that are not in low-processor mode (typically games)
  6153. // to reduce the risk of frame stuttering.
  6154. // This is not done for the editor to prevent importers or resource bakers
  6155. // from making the system unresponsive.
  6156. SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  6157. DWORD index = 0;
  6158. HANDLE handle = AvSetMmThreadCharacteristicsW(L"Games", &index);
  6159. if (handle) {
  6160. AvSetMmThreadPriority(handle, AVRT_PRIORITY_CRITICAL);
  6161. }
  6162. // This is needed to make sure that background work does not starve the main thread.
  6163. // This is only setting the priority of this thread, not the whole process.
  6164. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  6165. }
  6166. cursor_shape = CURSOR_ARROW;
  6167. _update_real_mouse_position(MAIN_WINDOW_ID);
  6168. r_error = OK;
  6169. static_cast<OS_Windows *>(OS::get_singleton())->set_main_window(windows[MAIN_WINDOW_ID].hWnd);
  6170. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  6171. }
  6172. Vector<String> DisplayServerWindows::get_rendering_drivers_func() {
  6173. Vector<String> drivers;
  6174. #ifdef VULKAN_ENABLED
  6175. drivers.push_back("vulkan");
  6176. #endif
  6177. #ifdef D3D12_ENABLED
  6178. drivers.push_back("d3d12");
  6179. #endif
  6180. #ifdef GLES3_ENABLED
  6181. drivers.push_back("opengl3");
  6182. drivers.push_back("opengl3_angle");
  6183. #endif
  6184. drivers.push_back("dummy");
  6185. return drivers;
  6186. }
  6187. DisplayServer *DisplayServerWindows::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, int p_screen, Context p_context, int64_t p_parent_window, Error &r_error) {
  6188. DisplayServer *ds = memnew(DisplayServerWindows(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, p_screen, p_context, p_parent_window, r_error));
  6189. if (r_error != OK) {
  6190. if (tested_drivers == 0) {
  6191. OS::get_singleton()->alert("Failed to register the window class.", "Unable to initialize DisplayServer");
  6192. } else if (tested_drivers.has_flag(DRIVER_ID_RD_VULKAN) || tested_drivers.has_flag(DRIVER_ID_RD_D3D12)) {
  6193. Vector<String> drivers;
  6194. if (tested_drivers.has_flag(DRIVER_ID_RD_VULKAN)) {
  6195. drivers.push_back("Vulkan");
  6196. }
  6197. if (tested_drivers.has_flag(DRIVER_ID_RD_D3D12)) {
  6198. drivers.push_back("Direct3D 12");
  6199. }
  6200. String executable_name = OS::get_singleton()->get_executable_path().get_file();
  6201. OS::get_singleton()->alert(
  6202. vformat("Your video card drivers seem not to support the required %s version.\n\n"
  6203. "If possible, consider updating your video card drivers or using the OpenGL 3 driver.\n\n"
  6204. "You can enable the OpenGL 3 driver by starting the engine from the\n"
  6205. "command line with the command:\n\n \"%s\" --rendering-driver opengl3\n\n"
  6206. "If you have recently updated your video card drivers, try rebooting.",
  6207. String(" or ").join(drivers),
  6208. executable_name),
  6209. "Unable to initialize video driver");
  6210. } else {
  6211. Vector<String> drivers;
  6212. if (tested_drivers.has_flag(DRIVER_ID_COMPAT_OPENGL3)) {
  6213. drivers.push_back("OpenGL 3.3");
  6214. }
  6215. if (tested_drivers.has_flag(DRIVER_ID_COMPAT_ANGLE_D3D11)) {
  6216. drivers.push_back("Direct3D 11");
  6217. }
  6218. OS::get_singleton()->alert(
  6219. vformat(
  6220. "Your video card drivers seem not to support the required %s version.\n\n"
  6221. "If possible, consider updating your video card drivers.\n\n"
  6222. "If you have recently updated your video card drivers, try rebooting.",
  6223. String(" or ").join(drivers)),
  6224. "Unable to initialize video driver");
  6225. }
  6226. }
  6227. return ds;
  6228. }
  6229. void DisplayServerWindows::register_windows_driver() {
  6230. register_create_function("windows", create_func, get_rendering_drivers_func);
  6231. }
  6232. DisplayServerWindows::~DisplayServerWindows() {
  6233. LocalVector<List<FileDialogData *>::Element *> to_remove;
  6234. for (List<FileDialogData *>::Element *E = file_dialogs.front(); E; E = E->next()) {
  6235. FileDialogData *fd = E->get();
  6236. if (fd->listener_thread.is_started()) {
  6237. fd->close_requested.set();
  6238. fd->listener_thread.wait_to_finish();
  6239. }
  6240. to_remove.push_back(E);
  6241. }
  6242. for (List<FileDialogData *>::Element *E : to_remove) {
  6243. memdelete(E->get());
  6244. E->erase();
  6245. }
  6246. delete joypad;
  6247. touch_state.clear();
  6248. cursors_cache.clear();
  6249. // Destroy all status indicators.
  6250. for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E; ++E) {
  6251. NOTIFYICONDATAW ndat;
  6252. ZeroMemory(&ndat, sizeof(NOTIFYICONDATAW));
  6253. ndat.cbSize = sizeof(NOTIFYICONDATAW);
  6254. ndat.hWnd = windows[MAIN_WINDOW_ID].hWnd;
  6255. ndat.uID = E->key;
  6256. ndat.uVersion = NOTIFYICON_VERSION;
  6257. Shell_NotifyIconW(NIM_DELETE, &ndat);
  6258. }
  6259. if (mouse_monitor) {
  6260. UnhookWindowsHookEx(mouse_monitor);
  6261. }
  6262. if (user_proc) {
  6263. SetWindowLongPtr(windows[MAIN_WINDOW_ID].hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
  6264. }
  6265. // Close power request handle.
  6266. screen_set_keep_on(false);
  6267. if (native_menu) {
  6268. memdelete(native_menu);
  6269. native_menu = nullptr;
  6270. }
  6271. #ifdef GLES3_ENABLED
  6272. // destroy windows .. NYI?
  6273. // FIXME wglDeleteContext is never called
  6274. #endif
  6275. if (windows.has(MAIN_WINDOW_ID)) {
  6276. #ifdef RD_ENABLED
  6277. if (rendering_device) {
  6278. rendering_device->screen_free(MAIN_WINDOW_ID);
  6279. }
  6280. if (rendering_context) {
  6281. rendering_context->window_destroy(MAIN_WINDOW_ID);
  6282. }
  6283. #endif
  6284. if (wintab_available && windows[MAIN_WINDOW_ID].wtctx) {
  6285. wintab_WTClose(windows[MAIN_WINDOW_ID].wtctx);
  6286. windows[MAIN_WINDOW_ID].wtctx = nullptr;
  6287. }
  6288. if (windows[MAIN_WINDOW_ID].drop_target != nullptr) {
  6289. RevokeDragDrop(windows[MAIN_WINDOW_ID].hWnd);
  6290. windows[MAIN_WINDOW_ID].drop_target->Release();
  6291. }
  6292. DestroyWindow(windows[MAIN_WINDOW_ID].hWnd);
  6293. }
  6294. #ifdef RD_ENABLED
  6295. if (rendering_device) {
  6296. memdelete(rendering_device);
  6297. rendering_device = nullptr;
  6298. }
  6299. if (rendering_context) {
  6300. memdelete(rendering_context);
  6301. rendering_context = nullptr;
  6302. }
  6303. #endif
  6304. if (restore_mouse_trails > 1) {
  6305. SystemParametersInfoA(SPI_SETMOUSETRAILS, restore_mouse_trails, nullptr, 0);
  6306. }
  6307. #ifdef GLES3_ENABLED
  6308. if (gl_manager_angle) {
  6309. memdelete(gl_manager_angle);
  6310. gl_manager_angle = nullptr;
  6311. }
  6312. if (gl_manager_native) {
  6313. memdelete(gl_manager_native);
  6314. gl_manager_native = nullptr;
  6315. }
  6316. #endif
  6317. #ifdef ACCESSKIT_ENABLED
  6318. if (accessibility_driver) {
  6319. memdelete(accessibility_driver);
  6320. }
  6321. #endif
  6322. if (tts) {
  6323. memdelete(tts);
  6324. }
  6325. OleUninitialize();
  6326. }