display_server_windows.cpp 234 KB

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