display_server_windows.cpp 208 KB

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