display_server_windows.cpp 229 KB

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