display_server_windows.cpp 201 KB

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