display_server_windows.cpp 227 KB

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