display_server_windows.cpp 228 KB

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