display_server_windows.cpp 215 KB

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