display_server_windows.cpp 229 KB

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