Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_win32_Windowing.cpp 170KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  19. #include <juce_audio_plugin_client/AAX/juce_AAX_Modifier_Injector.h>
  20. #endif
  21. #if JUCE_WIN_PER_MONITOR_DPI_AWARE && JUCE_MODULE_AVAILABLE_juce_gui_extra
  22. #include <juce_gui_extra/embedding/juce_ScopedDPIAwarenessDisabler.h>
  23. #endif
  24. namespace juce
  25. {
  26. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wcast-function-type")
  27. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  28. // these are in the windows SDK, but need to be repeated here for GCC..
  29. #ifndef GET_APPCOMMAND_LPARAM
  30. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  31. #define FAPPCOMMAND_MASK 0xF000
  32. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  33. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  34. #define APPCOMMAND_MEDIA_STOP 13
  35. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  36. #endif
  37. #ifndef WM_APPCOMMAND
  38. #define WM_APPCOMMAND 0x0319
  39. #endif
  40. void juce_repeatLastProcessPriority();
  41. bool juce_isRunningInWine();
  42. using CheckEventBlockedByModalComps = bool (*) (const MSG&);
  43. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  44. static bool shouldDeactivateTitleBar = true;
  45. void* getUser32Function (const char*);
  46. //==============================================================================
  47. #ifndef WM_TOUCH
  48. enum
  49. {
  50. WM_TOUCH = 0x0240,
  51. TOUCHEVENTF_MOVE = 0x0001,
  52. TOUCHEVENTF_DOWN = 0x0002,
  53. TOUCHEVENTF_UP = 0x0004
  54. };
  55. typedef HANDLE HTOUCHINPUT;
  56. typedef HANDLE HGESTUREINFO;
  57. struct TOUCHINPUT
  58. {
  59. LONG x;
  60. LONG y;
  61. HANDLE hSource;
  62. DWORD dwID;
  63. DWORD dwFlags;
  64. DWORD dwMask;
  65. DWORD dwTime;
  66. ULONG_PTR dwExtraInfo;
  67. DWORD cxContact;
  68. DWORD cyContact;
  69. };
  70. struct GESTUREINFO
  71. {
  72. UINT cbSize;
  73. DWORD dwFlags;
  74. DWORD dwID;
  75. HWND hwndTarget;
  76. POINTS ptsLocation;
  77. DWORD dwInstanceID;
  78. DWORD dwSequenceID;
  79. ULONGLONG ullArguments;
  80. UINT cbExtraArgs;
  81. };
  82. #endif
  83. #ifndef WM_NCPOINTERUPDATE
  84. enum
  85. {
  86. WM_NCPOINTERUPDATE = 0x241,
  87. WM_NCPOINTERDOWN = 0x242,
  88. WM_NCPOINTERUP = 0x243,
  89. WM_POINTERUPDATE = 0x245,
  90. WM_POINTERDOWN = 0x246,
  91. WM_POINTERUP = 0x247,
  92. WM_POINTERENTER = 0x249,
  93. WM_POINTERLEAVE = 0x24A,
  94. WM_POINTERACTIVATE = 0x24B,
  95. WM_POINTERCAPTURECHANGED = 0x24C,
  96. WM_TOUCHHITTESTING = 0x24D,
  97. WM_POINTERWHEEL = 0x24E,
  98. WM_POINTERHWHEEL = 0x24F,
  99. WM_POINTERHITTEST = 0x250
  100. };
  101. enum
  102. {
  103. PT_TOUCH = 0x00000002,
  104. PT_PEN = 0x00000003
  105. };
  106. enum POINTER_BUTTON_CHANGE_TYPE
  107. {
  108. POINTER_CHANGE_NONE,
  109. POINTER_CHANGE_FIRSTBUTTON_DOWN,
  110. POINTER_CHANGE_FIRSTBUTTON_UP,
  111. POINTER_CHANGE_SECONDBUTTON_DOWN,
  112. POINTER_CHANGE_SECONDBUTTON_UP,
  113. POINTER_CHANGE_THIRDBUTTON_DOWN,
  114. POINTER_CHANGE_THIRDBUTTON_UP,
  115. POINTER_CHANGE_FOURTHBUTTON_DOWN,
  116. POINTER_CHANGE_FOURTHBUTTON_UP,
  117. POINTER_CHANGE_FIFTHBUTTON_DOWN,
  118. POINTER_CHANGE_FIFTHBUTTON_UP
  119. };
  120. enum
  121. {
  122. PEN_MASK_NONE = 0x00000000,
  123. PEN_MASK_PRESSURE = 0x00000001,
  124. PEN_MASK_ROTATION = 0x00000002,
  125. PEN_MASK_TILT_X = 0x00000004,
  126. PEN_MASK_TILT_Y = 0x00000008
  127. };
  128. enum
  129. {
  130. TOUCH_MASK_NONE = 0x00000000,
  131. TOUCH_MASK_CONTACTAREA = 0x00000001,
  132. TOUCH_MASK_ORIENTATION = 0x00000002,
  133. TOUCH_MASK_PRESSURE = 0x00000004
  134. };
  135. enum
  136. {
  137. POINTER_FLAG_NONE = 0x00000000,
  138. POINTER_FLAG_NEW = 0x00000001,
  139. POINTER_FLAG_INRANGE = 0x00000002,
  140. POINTER_FLAG_INCONTACT = 0x00000004,
  141. POINTER_FLAG_FIRSTBUTTON = 0x00000010,
  142. POINTER_FLAG_SECONDBUTTON = 0x00000020,
  143. POINTER_FLAG_THIRDBUTTON = 0x00000040,
  144. POINTER_FLAG_FOURTHBUTTON = 0x00000080,
  145. POINTER_FLAG_FIFTHBUTTON = 0x00000100,
  146. POINTER_FLAG_PRIMARY = 0x00002000,
  147. POINTER_FLAG_CONFIDENCE = 0x00004000,
  148. POINTER_FLAG_CANCELED = 0x00008000,
  149. POINTER_FLAG_DOWN = 0x00010000,
  150. POINTER_FLAG_UPDATE = 0x00020000,
  151. POINTER_FLAG_UP = 0x00040000,
  152. POINTER_FLAG_WHEEL = 0x00080000,
  153. POINTER_FLAG_HWHEEL = 0x00100000,
  154. POINTER_FLAG_CAPTURECHANGED = 0x00200000,
  155. POINTER_FLAG_HASTRANSFORM = 0x00400000
  156. };
  157. typedef DWORD POINTER_INPUT_TYPE;
  158. typedef UINT32 POINTER_FLAGS;
  159. typedef UINT32 PEN_FLAGS;
  160. typedef UINT32 PEN_MASK;
  161. typedef UINT32 TOUCH_FLAGS;
  162. typedef UINT32 TOUCH_MASK;
  163. struct POINTER_INFO
  164. {
  165. POINTER_INPUT_TYPE pointerType;
  166. UINT32 pointerId;
  167. UINT32 frameId;
  168. POINTER_FLAGS pointerFlags;
  169. HANDLE sourceDevice;
  170. HWND hwndTarget;
  171. POINT ptPixelLocation;
  172. POINT ptHimetricLocation;
  173. POINT ptPixelLocationRaw;
  174. POINT ptHimetricLocationRaw;
  175. DWORD dwTime;
  176. UINT32 historyCount;
  177. INT32 InputData;
  178. DWORD dwKeyStates;
  179. UINT64 PerformanceCount;
  180. POINTER_BUTTON_CHANGE_TYPE ButtonChangeType;
  181. };
  182. struct POINTER_TOUCH_INFO
  183. {
  184. POINTER_INFO pointerInfo;
  185. TOUCH_FLAGS touchFlags;
  186. TOUCH_MASK touchMask;
  187. RECT rcContact;
  188. RECT rcContactRaw;
  189. UINT32 orientation;
  190. UINT32 pressure;
  191. };
  192. struct POINTER_PEN_INFO
  193. {
  194. POINTER_INFO pointerInfo;
  195. PEN_FLAGS penFlags;
  196. PEN_MASK penMask;
  197. UINT32 pressure;
  198. UINT32 rotation;
  199. INT32 tiltX;
  200. INT32 tiltY;
  201. };
  202. #define GET_POINTERID_WPARAM(wParam) (LOWORD(wParam))
  203. #endif
  204. #ifndef MONITOR_DPI_TYPE
  205. enum Monitor_DPI_Type
  206. {
  207. MDT_Effective_DPI = 0,
  208. MDT_Angular_DPI = 1,
  209. MDT_Raw_DPI = 2,
  210. MDT_Default = MDT_Effective_DPI
  211. };
  212. #endif
  213. #ifndef DPI_AWARENESS
  214. enum DPI_Awareness
  215. {
  216. DPI_Awareness_Invalid = -1,
  217. DPI_Awareness_Unaware = 0,
  218. DPI_Awareness_System_Aware = 1,
  219. DPI_Awareness_Per_Monitor_Aware = 2
  220. };
  221. #endif
  222. #ifndef USER_DEFAULT_SCREEN_DPI
  223. #define USER_DEFAULT_SCREEN_DPI 96
  224. #endif
  225. #ifndef _DPI_AWARENESS_CONTEXTS_
  226. typedef HANDLE DPI_AWARENESS_CONTEXT;
  227. #define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT) - 1)
  228. #define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((DPI_AWARENESS_CONTEXT) - 2)
  229. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((DPI_AWARENESS_CONTEXT) - 3)
  230. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
  231. #endif
  232. // Some versions of the Windows 10 SDK define _DPI_AWARENESS_CONTEXTS_ but not
  233. // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  234. #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  235. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
  236. #endif
  237. //==============================================================================
  238. using RegisterTouchWindowFunc = BOOL (WINAPI*) (HWND, ULONG);
  239. using GetTouchInputInfoFunc = BOOL (WINAPI*) (HTOUCHINPUT, UINT, TOUCHINPUT*, int);
  240. using CloseTouchInputHandleFunc = BOOL (WINAPI*) (HTOUCHINPUT);
  241. using GetGestureInfoFunc = BOOL (WINAPI*) (HGESTUREINFO, GESTUREINFO*);
  242. static RegisterTouchWindowFunc registerTouchWindow = nullptr;
  243. static GetTouchInputInfoFunc getTouchInputInfo = nullptr;
  244. static CloseTouchInputHandleFunc closeTouchInputHandle = nullptr;
  245. static GetGestureInfoFunc getGestureInfo = nullptr;
  246. static bool hasCheckedForMultiTouch = false;
  247. static bool canUseMultiTouch()
  248. {
  249. if (registerTouchWindow == nullptr && ! hasCheckedForMultiTouch)
  250. {
  251. hasCheckedForMultiTouch = true;
  252. registerTouchWindow = (RegisterTouchWindowFunc) getUser32Function ("RegisterTouchWindow");
  253. getTouchInputInfo = (GetTouchInputInfoFunc) getUser32Function ("GetTouchInputInfo");
  254. closeTouchInputHandle = (CloseTouchInputHandleFunc) getUser32Function ("CloseTouchInputHandle");
  255. getGestureInfo = (GetGestureInfoFunc) getUser32Function ("GetGestureInfo");
  256. }
  257. return registerTouchWindow != nullptr;
  258. }
  259. //==============================================================================
  260. using GetPointerTypeFunc = BOOL (WINAPI*) (UINT32, POINTER_INPUT_TYPE*);
  261. using GetPointerTouchInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_TOUCH_INFO*);
  262. using GetPointerPenInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_PEN_INFO*);
  263. static GetPointerTypeFunc getPointerTypeFunction = nullptr;
  264. static GetPointerTouchInfoFunc getPointerTouchInfo = nullptr;
  265. static GetPointerPenInfoFunc getPointerPenInfo = nullptr;
  266. static bool canUsePointerAPI = false;
  267. static void checkForPointerAPI()
  268. {
  269. getPointerTypeFunction = (GetPointerTypeFunc) getUser32Function ("GetPointerType");
  270. getPointerTouchInfo = (GetPointerTouchInfoFunc) getUser32Function ("GetPointerTouchInfo");
  271. getPointerPenInfo = (GetPointerPenInfoFunc) getUser32Function ("GetPointerPenInfo");
  272. canUsePointerAPI = (getPointerTypeFunction != nullptr
  273. && getPointerTouchInfo != nullptr
  274. && getPointerPenInfo != nullptr);
  275. }
  276. //==============================================================================
  277. using SetProcessDPIAwareFunc = BOOL (WINAPI*) ();
  278. using SetProcessDPIAwarenessContextFunc = BOOL (WINAPI*) (DPI_AWARENESS_CONTEXT);
  279. using SetProcessDPIAwarenessFunc = BOOL (WINAPI*) (DPI_Awareness);
  280. using SetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (DPI_AWARENESS_CONTEXT);
  281. using GetDPIForWindowFunc = UINT (WINAPI*) (HWND);
  282. using GetDPIForMonitorFunc = HRESULT (WINAPI*) (HMONITOR, Monitor_DPI_Type, UINT*, UINT*);
  283. using GetProcessDPIAwarenessFunc = HRESULT (WINAPI*) (HANDLE, DPI_Awareness*);
  284. using GetWindowDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (HWND);
  285. using GetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) ();
  286. using GetAwarenessFromDpiAwarenessContextFunc = DPI_Awareness (WINAPI*) (DPI_AWARENESS_CONTEXT);
  287. using EnableNonClientDPIScalingFunc = BOOL (WINAPI*) (HWND);
  288. static SetProcessDPIAwareFunc setProcessDPIAware = nullptr;
  289. static SetProcessDPIAwarenessContextFunc setProcessDPIAwarenessContext = nullptr;
  290. static SetProcessDPIAwarenessFunc setProcessDPIAwareness = nullptr;
  291. static SetThreadDPIAwarenessContextFunc setThreadDPIAwarenessContext = nullptr;
  292. static GetDPIForMonitorFunc getDPIForMonitor = nullptr;
  293. static GetDPIForWindowFunc getDPIForWindow = nullptr;
  294. static GetProcessDPIAwarenessFunc getProcessDPIAwareness = nullptr;
  295. static GetWindowDPIAwarenessContextFunc getWindowDPIAwarenessContext = nullptr;
  296. static GetThreadDPIAwarenessContextFunc getThreadDPIAwarenessContext = nullptr;
  297. static GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromDPIAwarenessContext = nullptr;
  298. static EnableNonClientDPIScalingFunc enableNonClientDPIScaling = nullptr;
  299. static bool hasCheckedForDPIAwareness = false;
  300. static void setDPIAwareness()
  301. {
  302. if (hasCheckedForDPIAwareness)
  303. return;
  304. hasCheckedForDPIAwareness = true;
  305. if (! JUCEApplicationBase::isStandaloneApp())
  306. return;
  307. HMODULE shcoreModule = GetModuleHandleA ("SHCore.dll");
  308. if (shcoreModule != nullptr)
  309. {
  310. getDPIForMonitor = (GetDPIForMonitorFunc) GetProcAddress (shcoreModule, "GetDpiForMonitor");
  311. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  312. getDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
  313. getProcessDPIAwareness = (GetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "GetProcessDpiAwareness");
  314. getWindowDPIAwarenessContext = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
  315. setThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  316. getThreadDPIAwarenessContext = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
  317. getAwarenessFromDPIAwarenessContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
  318. setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
  319. setProcessDPIAwarenessContext = (SetProcessDPIAwarenessContextFunc) getUser32Function ("SetProcessDpiAwarenessContext");
  320. if (setProcessDPIAwarenessContext != nullptr
  321. && SUCCEEDED (setProcessDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)))
  322. return;
  323. enableNonClientDPIScaling = (EnableNonClientDPIScalingFunc) getUser32Function ("EnableNonClientDpiScaling");
  324. if (setProcessDPIAwareness != nullptr && enableNonClientDPIScaling != nullptr
  325. && SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_Per_Monitor_Aware)))
  326. return;
  327. #endif
  328. if (setProcessDPIAwareness == nullptr)
  329. setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
  330. if (setProcessDPIAwareness != nullptr && getDPIForMonitor != nullptr
  331. && SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_System_Aware)))
  332. return;
  333. }
  334. // fallback for pre Windows 8.1 - equivalent to Process_System_DPI_Aware
  335. setProcessDPIAware = (SetProcessDPIAwareFunc) getUser32Function ("SetProcessDPIAware");
  336. if (setProcessDPIAware != nullptr)
  337. setProcessDPIAware();
  338. }
  339. static bool isPerMonitorDPIAwareProcess()
  340. {
  341. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  342. static bool dpiAware = []() -> bool
  343. {
  344. setDPIAwareness();
  345. if (getProcessDPIAwareness == nullptr)
  346. return false;
  347. DPI_Awareness context;
  348. getProcessDPIAwareness (nullptr, &context);
  349. return context == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
  350. }();
  351. return dpiAware;
  352. #else
  353. return false;
  354. #endif
  355. }
  356. static bool isPerMonitorDPIAwareWindow (HWND h)
  357. {
  358. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  359. jassert (h != nullptr);
  360. setDPIAwareness();
  361. if (getWindowDPIAwarenessContext != nullptr && getAwarenessFromDPIAwarenessContext != nullptr)
  362. return getAwarenessFromDPIAwarenessContext (getWindowDPIAwarenessContext (h)) == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
  363. return isPerMonitorDPIAwareProcess();
  364. #else
  365. ignoreUnused (h);
  366. return false;
  367. #endif
  368. }
  369. static bool isPerMonitorDPIAwareThread()
  370. {
  371. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  372. setDPIAwareness();
  373. if (getThreadDPIAwarenessContext != nullptr && getAwarenessFromDPIAwarenessContext != nullptr)
  374. return getAwarenessFromDPIAwarenessContext (getThreadDPIAwarenessContext()) == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
  375. return isPerMonitorDPIAwareProcess();
  376. #else
  377. return false;
  378. #endif
  379. }
  380. static double getGlobalDPI()
  381. {
  382. setDPIAwareness();
  383. HDC dc = GetDC (nullptr);
  384. auto dpi = (GetDeviceCaps (dc, LOGPIXELSX) + GetDeviceCaps (dc, LOGPIXELSY)) / 2.0;
  385. ReleaseDC (nullptr, dc);
  386. return dpi;
  387. }
  388. //==============================================================================
  389. #if JUCE_WIN_PER_MONITOR_DPI_AWARE && JUCE_MODULE_AVAILABLE_juce_gui_extra
  390. ScopedDPIAwarenessDisabler::ScopedDPIAwarenessDisabler()
  391. {
  392. if (! isPerMonitorDPIAwareThread())
  393. return;
  394. if (setThreadDPIAwarenessContext != nullptr)
  395. previousContext = setThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_UNAWARE);
  396. }
  397. ScopedDPIAwarenessDisabler::~ScopedDPIAwarenessDisabler()
  398. {
  399. if (previousContext != nullptr)
  400. setThreadDPIAwarenessContext ((DPI_AWARENESS_CONTEXT) previousContext);
  401. }
  402. #endif
  403. //==============================================================================
  404. using SettingChangeCallbackFunc = void (*)(void);
  405. extern SettingChangeCallbackFunc settingChangeCallback;
  406. //==============================================================================
  407. static Rectangle<int> rectangleFromRECT (const RECT& r) noexcept { return { r.left, r.top, r.right - r.left, r.bottom - r.top }; }
  408. static RECT RECTFromRectangle (const Rectangle<int>& r) noexcept { return { r.getX(), r.getY(), r.getRight(), r.getBottom() }; }
  409. static Point<int> pointFromPOINT (const POINT& p) noexcept { return { p.x, p.y }; }
  410. static POINT POINTFromPoint (const Point<int>& p) noexcept { return { p.x, p.y }; }
  411. //==============================================================================
  412. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd);
  413. static Rectangle<int> convertPhysicalScreenRectangleToLogical (const Rectangle<int>& r, HWND h) noexcept
  414. {
  415. if (isPerMonitorDPIAwareWindow (h))
  416. return Desktop::getInstance().getDisplays().physicalToLogical (r, getCurrentDisplayFromScaleFactor (h));
  417. return r;
  418. }
  419. static Rectangle<int> convertLogicalScreenRectangleToPhysical (const Rectangle<int>& r, HWND h) noexcept
  420. {
  421. if (isPerMonitorDPIAwareWindow (h))
  422. return Desktop::getInstance().getDisplays().logicalToPhysical (r, getCurrentDisplayFromScaleFactor (h));
  423. return r;
  424. }
  425. static Point<int> convertPhysicalScreenPointToLogical (const Point<int>& p, HWND h) noexcept
  426. {
  427. if (isPerMonitorDPIAwareWindow (h))
  428. return Desktop::getInstance().getDisplays().physicalToLogical (p, getCurrentDisplayFromScaleFactor (h));
  429. return p;
  430. }
  431. JUCE_API double getScaleFactorForWindow (HWND h)
  432. {
  433. // NB. Using a local function here because we need to call this method from the plug-in wrappers
  434. // which don't load the DPI-awareness functions on startup
  435. static GetDPIForWindowFunc localGetDPIForWindow = nullptr;
  436. static bool hasChecked = false;
  437. if (! hasChecked)
  438. {
  439. hasChecked = true;
  440. if (localGetDPIForWindow == nullptr)
  441. localGetDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
  442. }
  443. if (localGetDPIForWindow != nullptr)
  444. return (double) localGetDPIForWindow (h) / USER_DEFAULT_SCREEN_DPI;
  445. return 1.0;
  446. }
  447. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  448. JUCE_API void setThreadDPIAwarenessForWindow (HWND nativeWindow)
  449. {
  450. // NB. Using local functions here because we need to call this method from the plug-in wrappers
  451. // which don't load the DPI-awareness functions on startup
  452. static SetThreadDPIAwarenessContextFunc localSetThreadDPIAwarenessContext = nullptr;
  453. static GetWindowDPIAwarenessContextFunc localGetWindowDPIAwarenessContext = nullptr;
  454. static GetThreadDPIAwarenessContextFunc localGetThreadDPIAwarenessContext = nullptr;
  455. static GetAwarenessFromDpiAwarenessContextFunc localGetAwarenessFromDPIAwarenessContext = nullptr;
  456. static bool hasChecked = false;
  457. static bool loadedOK = false;
  458. if (! hasChecked)
  459. {
  460. hasChecked = true;
  461. localSetThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  462. localGetWindowDPIAwarenessContext = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
  463. localGetThreadDPIAwarenessContext = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
  464. localGetAwarenessFromDPIAwarenessContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
  465. loadedOK = (localSetThreadDPIAwarenessContext != nullptr && localGetWindowDPIAwarenessContext != nullptr
  466. && localGetThreadDPIAwarenessContext != nullptr && localGetAwarenessFromDPIAwarenessContext != nullptr);
  467. }
  468. if (loadedOK)
  469. {
  470. auto dpiAwareWindow = localGetAwarenessFromDPIAwarenessContext (localGetWindowDPIAwarenessContext (nativeWindow)) == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
  471. auto dpiAwareThread = localGetAwarenessFromDPIAwarenessContext (localGetThreadDPIAwarenessContext()) == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
  472. if (dpiAwareWindow && ! dpiAwareThread)
  473. localSetThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
  474. else if (! dpiAwareWindow && dpiAwareThread)
  475. localSetThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_UNAWARE);
  476. }
  477. }
  478. #endif
  479. //==============================================================================
  480. static void setWindowPos (HWND hwnd, Rectangle<int> bounds, UINT flags, bool adjustTopLeft = false)
  481. {
  482. if (isPerMonitorDPIAwareWindow (hwnd))
  483. {
  484. if (adjustTopLeft)
  485. bounds = convertLogicalScreenRectangleToPhysical (bounds, hwnd)
  486. .withPosition (Desktop::getInstance().getDisplays().logicalToPhysical (bounds.getTopLeft()));
  487. else
  488. bounds = convertLogicalScreenRectangleToPhysical (bounds, hwnd);
  489. }
  490. SetWindowPos (hwnd, nullptr, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), flags);
  491. }
  492. static RECT getWindowRect (HWND hwnd)
  493. {
  494. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  495. setThreadDPIAwarenessForWindow (hwnd);
  496. #endif
  497. RECT r;
  498. GetWindowRect (hwnd, &r);
  499. return r;
  500. }
  501. static void setWindowZOrder (HWND hwnd, HWND insertAfter)
  502. {
  503. SetWindowPos (hwnd, insertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  504. }
  505. //==============================================================================
  506. double Desktop::getDefaultMasterScale()
  507. {
  508. if (! JUCEApplicationBase::isStandaloneApp()
  509. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  510. || isPerMonitorDPIAwareProcess()
  511. #endif
  512. )
  513. {
  514. return 1.0;
  515. }
  516. return getGlobalDPI() / USER_DEFAULT_SCREEN_DPI;
  517. }
  518. bool Desktop::canUseSemiTransparentWindows() noexcept { return true; }
  519. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  520. {
  521. return upright;
  522. }
  523. int64 getMouseEventTime()
  524. {
  525. static int64 eventTimeOffset = 0;
  526. static LONG lastMessageTime = 0;
  527. const LONG thisMessageTime = GetMessageTime();
  528. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  529. {
  530. lastMessageTime = thisMessageTime;
  531. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  532. }
  533. return eventTimeOffset + thisMessageTime;
  534. }
  535. //==============================================================================
  536. const int extendedKeyModifier = 0x10000;
  537. const int KeyPress::spaceKey = VK_SPACE;
  538. const int KeyPress::returnKey = VK_RETURN;
  539. const int KeyPress::escapeKey = VK_ESCAPE;
  540. const int KeyPress::backspaceKey = VK_BACK;
  541. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  542. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  543. const int KeyPress::tabKey = VK_TAB;
  544. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  545. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  546. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  547. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  548. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  549. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  550. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  551. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  552. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  553. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  554. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  555. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  556. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  557. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  558. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  559. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  560. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  561. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  562. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  563. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  564. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  565. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  566. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  567. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  568. const int KeyPress::F17Key = VK_F17 | extendedKeyModifier;
  569. const int KeyPress::F18Key = VK_F18 | extendedKeyModifier;
  570. const int KeyPress::F19Key = VK_F19 | extendedKeyModifier;
  571. const int KeyPress::F20Key = VK_F20 | extendedKeyModifier;
  572. const int KeyPress::F21Key = VK_F21 | extendedKeyModifier;
  573. const int KeyPress::F22Key = VK_F22 | extendedKeyModifier;
  574. const int KeyPress::F23Key = VK_F23 | extendedKeyModifier;
  575. const int KeyPress::F24Key = VK_F24 | extendedKeyModifier;
  576. const int KeyPress::F25Key = 0x31000; // Windows doesn't support F-keys 25 or higher
  577. const int KeyPress::F26Key = 0x31001;
  578. const int KeyPress::F27Key = 0x31002;
  579. const int KeyPress::F28Key = 0x31003;
  580. const int KeyPress::F29Key = 0x31004;
  581. const int KeyPress::F30Key = 0x31005;
  582. const int KeyPress::F31Key = 0x31006;
  583. const int KeyPress::F32Key = 0x31007;
  584. const int KeyPress::F33Key = 0x31008;
  585. const int KeyPress::F34Key = 0x31009;
  586. const int KeyPress::F35Key = 0x3100a;
  587. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  588. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  589. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  590. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  591. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  592. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  593. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  594. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  595. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  596. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  597. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  598. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  599. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  600. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  601. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  602. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  603. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  604. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  605. const int KeyPress::playKey = 0x30000;
  606. const int KeyPress::stopKey = 0x30001;
  607. const int KeyPress::fastForwardKey = 0x30002;
  608. const int KeyPress::rewindKey = 0x30003;
  609. //==============================================================================
  610. class WindowsBitmapImage : public ImagePixelData
  611. {
  612. public:
  613. WindowsBitmapImage (const Image::PixelFormat format,
  614. const int w, const int h, const bool clearImage)
  615. : ImagePixelData (format, w, h)
  616. {
  617. jassert (format == Image::RGB || format == Image::ARGB);
  618. static bool alwaysUse32Bits = isGraphicsCard32Bit(); // NB: for 32-bit cards, it's faster to use a 32-bit image.
  619. pixelStride = (alwaysUse32Bits || format == Image::ARGB) ? 4 : 3;
  620. lineStride = -((w * pixelStride + 3) & ~3);
  621. zerostruct (bitmapInfo);
  622. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  623. bitmapInfo.bV4Width = w;
  624. bitmapInfo.bV4Height = h;
  625. bitmapInfo.bV4Planes = 1;
  626. bitmapInfo.bV4CSType = 1;
  627. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  628. if (format == Image::ARGB)
  629. {
  630. bitmapInfo.bV4AlphaMask = 0xff000000;
  631. bitmapInfo.bV4RedMask = 0xff0000;
  632. bitmapInfo.bV4GreenMask = 0xff00;
  633. bitmapInfo.bV4BlueMask = 0xff;
  634. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  635. }
  636. else
  637. {
  638. bitmapInfo.bV4V4Compression = BI_RGB;
  639. }
  640. HDC dc = GetDC (nullptr);
  641. hdc = CreateCompatibleDC (dc);
  642. ReleaseDC (nullptr, dc);
  643. SetMapMode (hdc, MM_TEXT);
  644. hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
  645. (void**) &bitmapData, nullptr, 0);
  646. previousBitmap = SelectObject (hdc, hBitmap);
  647. if (format == Image::ARGB && clearImage)
  648. zeromem (bitmapData, (size_t) std::abs (h * lineStride));
  649. imageData = bitmapData - (lineStride * (h - 1));
  650. }
  651. ~WindowsBitmapImage()
  652. {
  653. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  654. DeleteDC (hdc);
  655. DeleteObject (hBitmap);
  656. }
  657. std::unique_ptr<ImageType> createType() const override { return std::make_unique<NativeImageType>(); }
  658. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  659. {
  660. sendDataChangeMessage();
  661. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
  662. }
  663. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  664. {
  665. bitmap.data = imageData + x * pixelStride + y * lineStride;
  666. bitmap.pixelFormat = pixelFormat;
  667. bitmap.lineStride = lineStride;
  668. bitmap.pixelStride = pixelStride;
  669. if (mode != Image::BitmapData::readOnly)
  670. sendDataChangeMessage();
  671. }
  672. ImagePixelData::Ptr clone() override
  673. {
  674. auto im = new WindowsBitmapImage (pixelFormat, width, height, false);
  675. for (int i = 0; i < height; ++i)
  676. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  677. return im;
  678. }
  679. void blitToWindow (HWND hwnd, HDC dc, bool transparent, int x, int y, uint8 updateLayeredWindowAlpha) noexcept
  680. {
  681. SetMapMode (dc, MM_TEXT);
  682. if (transparent)
  683. {
  684. auto windowBounds = getWindowRect (hwnd);
  685. POINT p = { -x, -y };
  686. POINT pos = { windowBounds.left, windowBounds.top };
  687. SIZE size = { windowBounds.right - windowBounds.left,
  688. windowBounds.bottom - windowBounds.top };
  689. BLENDFUNCTION bf;
  690. bf.AlphaFormat = 1 /*AC_SRC_ALPHA*/;
  691. bf.BlendFlags = 0;
  692. bf.BlendOp = AC_SRC_OVER;
  693. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  694. UpdateLayeredWindow (hwnd, nullptr, &pos, &size, hdc, &p, 0, &bf, 2 /*ULW_ALPHA*/);
  695. }
  696. else
  697. {
  698. StretchDIBits (dc,
  699. x, y, width, height,
  700. 0, 0, width, height,
  701. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  702. DIB_RGB_COLORS, SRCCOPY);
  703. }
  704. }
  705. HBITMAP hBitmap;
  706. HGDIOBJ previousBitmap;
  707. BITMAPV4HEADER bitmapInfo;
  708. HDC hdc;
  709. uint8* bitmapData;
  710. int pixelStride, lineStride;
  711. uint8* imageData;
  712. private:
  713. static bool isGraphicsCard32Bit()
  714. {
  715. auto dc = GetDC (nullptr);
  716. auto bitsPerPixel = GetDeviceCaps (dc, BITSPIXEL);
  717. ReleaseDC (nullptr, dc);
  718. return bitsPerPixel > 24;
  719. }
  720. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage)
  721. };
  722. //==============================================================================
  723. Image createSnapshotOfNativeWindow (void*);
  724. Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
  725. {
  726. auto hwnd = (HWND) nativeWindowHandle;
  727. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowRect (hwnd)), hwnd);
  728. const int w = r.getWidth();
  729. const int h = r.getHeight();
  730. auto nativeBitmap = new WindowsBitmapImage (Image::RGB, w, h, true);
  731. Image bitmap (nativeBitmap);
  732. HDC dc = GetDC (hwnd);
  733. if (isPerMonitorDPIAwareProcess())
  734. {
  735. auto scale = getScaleFactorForWindow (hwnd);
  736. auto prevStretchMode = SetStretchBltMode (nativeBitmap->hdc, HALFTONE);
  737. SetBrushOrgEx (nativeBitmap->hdc, 0, 0, NULL);
  738. StretchBlt (nativeBitmap->hdc, 0, 0, w, h,
  739. dc, 0, 0, roundToInt (w * scale), roundToInt (h * scale),
  740. SRCCOPY);
  741. SetStretchBltMode (nativeBitmap->hdc, prevStretchMode);
  742. }
  743. else
  744. {
  745. BitBlt (nativeBitmap->hdc, 0, 0, w, h, dc, 0, 0, SRCCOPY);
  746. }
  747. ReleaseDC (hwnd, dc);
  748. return SoftwareImageType().convert (bitmap);
  749. }
  750. //==============================================================================
  751. namespace IconConverters
  752. {
  753. Image createImageFromHICON (HICON icon)
  754. {
  755. if (icon == nullptr)
  756. return {};
  757. struct ScopedICONINFO : public ICONINFO
  758. {
  759. ScopedICONINFO()
  760. {
  761. hbmColor = nullptr;
  762. hbmMask = nullptr;
  763. }
  764. ~ScopedICONINFO()
  765. {
  766. if (hbmColor != nullptr)
  767. ::DeleteObject (hbmColor);
  768. if (hbmMask != nullptr)
  769. ::DeleteObject (hbmMask);
  770. }
  771. };
  772. ScopedICONINFO info;
  773. if (! SUCCEEDED (::GetIconInfo (icon, &info)))
  774. return {};
  775. BITMAP bm;
  776. if (! (::GetObject (info.hbmColor, sizeof (BITMAP), &bm)
  777. && bm.bmWidth > 0 && bm.bmHeight > 0))
  778. return {};
  779. if (auto* tempDC = ::GetDC (nullptr))
  780. {
  781. if (auto* dc = ::CreateCompatibleDC (tempDC))
  782. {
  783. BITMAPV5HEADER header = {};
  784. header.bV5Size = sizeof (BITMAPV5HEADER);
  785. header.bV5Width = bm.bmWidth;
  786. header.bV5Height = -bm.bmHeight;
  787. header.bV5Planes = 1;
  788. header.bV5Compression = BI_RGB;
  789. header.bV5BitCount = 32;
  790. header.bV5RedMask = 0x00FF0000;
  791. header.bV5GreenMask = 0x0000FF00;
  792. header.bV5BlueMask = 0x000000FF;
  793. header.bV5AlphaMask = 0xFF000000;
  794. header.bV5CSType = LCS_WINDOWS_COLOR_SPACE;
  795. header.bV5Intent = LCS_GM_IMAGES;
  796. uint32* bitmapImageData = nullptr;
  797. if (auto* dib = ::CreateDIBSection (tempDC, (BITMAPINFO*) &header, DIB_RGB_COLORS,
  798. (void**) &bitmapImageData, nullptr, 0))
  799. {
  800. auto oldObject = ::SelectObject (dc, dib);
  801. auto numPixels = bm.bmWidth * bm.bmHeight;
  802. auto numColourComponents = (size_t) numPixels * 4;
  803. // Windows icon data comes as two layers, an XOR mask which contains the bulk
  804. // of the image data and an AND mask which provides the transparency. Annoyingly
  805. // the XOR mask can also contain an alpha channel, in which case the transparency
  806. // mask should not be applied, but there's no way to find out a priori if the XOR
  807. // mask contains an alpha channel.
  808. HeapBlock<bool> opacityMask (numPixels);
  809. memset (bitmapImageData, 0, numColourComponents);
  810. ::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_MASK);
  811. for (int i = 0; i < numPixels; ++i)
  812. opacityMask[i] = (bitmapImageData[i] == 0);
  813. Image result = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  814. Image::BitmapData imageData (result, Image::BitmapData::readWrite);
  815. memset (bitmapImageData, 0, numColourComponents);
  816. ::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_NORMAL);
  817. memcpy (imageData.data, bitmapImageData, numColourComponents);
  818. auto imageHasAlphaChannel = [&imageData, numPixels]()
  819. {
  820. for (int i = 0; i < numPixels; ++i)
  821. if (imageData.data[i * 4] != 0)
  822. return true;
  823. return false;
  824. };
  825. if (! imageHasAlphaChannel())
  826. for (int i = 0; i < numPixels; ++i)
  827. imageData.data[i * 4] = opacityMask[i] ? 0xff : 0x00;
  828. ::SelectObject (dc, oldObject);
  829. ::DeleteObject(dib);
  830. ::DeleteDC (dc);
  831. ::ReleaseDC (nullptr, tempDC);
  832. return result;
  833. }
  834. ::DeleteDC (dc);
  835. }
  836. ::ReleaseDC (nullptr, tempDC);
  837. }
  838. return {};
  839. }
  840. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  841. {
  842. auto nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  843. Image bitmap (nativeBitmap);
  844. {
  845. Graphics g (bitmap);
  846. g.drawImageAt (image, 0, 0);
  847. }
  848. auto mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, nullptr);
  849. ICONINFO info;
  850. info.fIcon = isIcon;
  851. info.xHotspot = (DWORD) hotspotX;
  852. info.yHotspot = (DWORD) hotspotY;
  853. info.hbmMask = mask;
  854. info.hbmColor = nativeBitmap->hBitmap;
  855. auto hi = CreateIconIndirect (&info);
  856. DeleteObject (mask);
  857. return hi;
  858. }
  859. }
  860. //==============================================================================
  861. JUCE_COMCLASS (ITipInvocation, "37c994e7-432b-4834-a2f7-dce1f13b834b") : public IUnknown
  862. {
  863. static CLSID getCLSID() noexcept { return { 0x4ce576fa, 0x83dc, 0x4f88, { 0x95, 0x1c, 0x9d, 0x07, 0x82, 0xb4, 0xe3, 0x76 } }; }
  864. virtual HRESULT STDMETHODCALLTYPE Toggle (HWND) = 0;
  865. };
  866. struct OnScreenKeyboard : public DeletedAtShutdown,
  867. private Timer
  868. {
  869. void activate()
  870. {
  871. shouldBeActive = true;
  872. startTimer (10);
  873. }
  874. void deactivate()
  875. {
  876. shouldBeActive = false;
  877. startTimer (10);
  878. }
  879. JUCE_DECLARE_SINGLETON_SINGLETHREADED (OnScreenKeyboard, false)
  880. private:
  881. OnScreenKeyboard()
  882. {
  883. tipInvocation.CoCreateInstance (ITipInvocation::getCLSID(), CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER);
  884. }
  885. ~OnScreenKeyboard()
  886. {
  887. clearSingletonInstance();
  888. }
  889. void timerCallback() override
  890. {
  891. stopTimer();
  892. if (reentrant || tipInvocation == nullptr)
  893. return;
  894. const ScopedValueSetter<bool> setter (reentrant, true, false);
  895. auto isActive = isKeyboardVisible();
  896. if (isActive != shouldBeActive)
  897. {
  898. if (! isActive)
  899. {
  900. tipInvocation->Toggle (GetDesktopWindow());
  901. }
  902. else
  903. {
  904. if (auto hwnd = FindWindow (L"IPTip_Main_Window", NULL))
  905. PostMessage (hwnd, WM_SYSCOMMAND, (int) SC_CLOSE, 0);
  906. }
  907. }
  908. }
  909. bool isVisible()
  910. {
  911. if (auto hwnd = FindWindowEx (NULL, NULL, L"ApplicationFrameWindow", NULL))
  912. return FindWindowEx (hwnd, NULL, L"Windows.UI.Core.CoreWindow", L"Microsoft Text Input Application") != NULL;
  913. return false;
  914. }
  915. bool isVisibleLegacy()
  916. {
  917. if (auto hwnd = FindWindow (L"IPTip_Main_Window", NULL))
  918. {
  919. auto style = GetWindowLong (hwnd, GWL_STYLE);
  920. return (style & WS_DISABLED) == 0 && (style & WS_VISIBLE) != 0;
  921. }
  922. return false;
  923. }
  924. bool isKeyboardVisible()
  925. {
  926. if (isVisible())
  927. return true;
  928. // isVisible() may fail on Win10 versions < 1709 so try the old method too
  929. return isVisibleLegacy();
  930. }
  931. bool shouldBeActive = false, reentrant = false;
  932. ComSmartPtr<ITipInvocation> tipInvocation;
  933. };
  934. JUCE_IMPLEMENT_SINGLETON (OnScreenKeyboard)
  935. //==============================================================================
  936. struct HSTRING_PRIVATE;
  937. typedef HSTRING_PRIVATE* HSTRING;
  938. struct IInspectable : public IUnknown
  939. {
  940. virtual HRESULT STDMETHODCALLTYPE GetIids (ULONG* ,IID**) = 0;
  941. virtual HRESULT STDMETHODCALLTYPE GetRuntimeClassName (HSTRING*) = 0;
  942. virtual HRESULT STDMETHODCALLTYPE GetTrustLevel (void*) = 0;
  943. };
  944. JUCE_COMCLASS (IUIViewSettingsInterop, "3694dbf9-8f68-44be-8ff5-195c98ede8a6") : public IInspectable
  945. {
  946. virtual HRESULT STDMETHODCALLTYPE GetForWindow (HWND, REFIID, void**) = 0;
  947. };
  948. JUCE_COMCLASS (IUIViewSettings, "c63657f6-8850-470d-88f8-455e16ea2c26") : public IInspectable
  949. {
  950. enum UserInteractionMode
  951. {
  952. Mouse = 0,
  953. Touch = 1
  954. };
  955. virtual HRESULT STDMETHODCALLTYPE GetUserInteractionMode (UserInteractionMode*) = 0;
  956. };
  957. struct UWPUIViewSettings
  958. {
  959. UWPUIViewSettings()
  960. {
  961. ComBaseModule dll (L"api-ms-win-core-winrt-l1-1-0");
  962. if (dll.h != nullptr)
  963. {
  964. roInitialize = (RoInitializeFuncPtr) ::GetProcAddress (dll.h, "RoInitialize");
  965. roGetActivationFactory = (RoGetActivationFactoryFuncPtr) ::GetProcAddress (dll.h, "RoGetActivationFactory");
  966. createHString = (WindowsCreateStringFuncPtr) ::GetProcAddress (dll.h, "WindowsCreateString");
  967. deleteHString = (WindowsDeleteStringFuncPtr) ::GetProcAddress (dll.h, "WindowsDeleteString");
  968. if (roInitialize == nullptr || roGetActivationFactory == nullptr
  969. || createHString == nullptr || deleteHString == nullptr)
  970. return;
  971. auto status = roInitialize (1);
  972. if (status != S_OK && status != S_FALSE && (unsigned) status != 0x80010106L)
  973. return;
  974. LPCWSTR uwpClassName = L"Windows.UI.ViewManagement.UIViewSettings";
  975. HSTRING uwpClassId;
  976. if (createHString (uwpClassName, (::UINT32) wcslen (uwpClassName), &uwpClassId) != S_OK
  977. || uwpClassId == nullptr)
  978. return;
  979. status = roGetActivationFactory (uwpClassId, __uuidof (IUIViewSettingsInterop),
  980. (void**) viewSettingsInterop.resetAndGetPointerAddress());
  981. deleteHString (uwpClassId);
  982. if (status != S_OK || viewSettingsInterop == nullptr)
  983. return;
  984. // move dll into member var
  985. comBaseDLL = std::move (dll);
  986. }
  987. }
  988. bool isTabletModeActivatedForWindow (::HWND hWnd) const
  989. {
  990. if (viewSettingsInterop == nullptr)
  991. return false;
  992. ComSmartPtr<IUIViewSettings> viewSettings;
  993. if (viewSettingsInterop->GetForWindow (hWnd, __uuidof (IUIViewSettings),
  994. (void**) viewSettings.resetAndGetPointerAddress()) == S_OK
  995. && viewSettings != nullptr)
  996. {
  997. IUIViewSettings::UserInteractionMode mode;
  998. if (viewSettings->GetUserInteractionMode (&mode) == S_OK)
  999. return mode == IUIViewSettings::Touch;
  1000. }
  1001. return false;
  1002. }
  1003. private:
  1004. //==============================================================================
  1005. struct ComBaseModule
  1006. {
  1007. ComBaseModule() {}
  1008. ComBaseModule (LPCWSTR libraryName) : h (::LoadLibrary (libraryName)) {}
  1009. ComBaseModule (ComBaseModule&& o) : h (o.h) { o.h = nullptr; }
  1010. ~ComBaseModule() { release(); }
  1011. void release() { if (h != nullptr) ::FreeLibrary (h); h = nullptr; }
  1012. ComBaseModule& operator= (ComBaseModule&& o) { release(); h = o.h; o.h = nullptr; return *this; }
  1013. HMODULE h = {};
  1014. };
  1015. using RoInitializeFuncPtr = HRESULT (WINAPI*) (int);
  1016. using RoGetActivationFactoryFuncPtr = HRESULT (WINAPI*) (HSTRING, REFIID, void**);
  1017. using WindowsCreateStringFuncPtr = HRESULT (WINAPI*) (LPCWSTR,UINT32, HSTRING*);
  1018. using WindowsDeleteStringFuncPtr = HRESULT (WINAPI*) (HSTRING);
  1019. ComBaseModule comBaseDLL;
  1020. ComSmartPtr<IUIViewSettingsInterop> viewSettingsInterop;
  1021. RoInitializeFuncPtr roInitialize;
  1022. RoGetActivationFactoryFuncPtr roGetActivationFactory;
  1023. WindowsCreateStringFuncPtr createHString;
  1024. WindowsDeleteStringFuncPtr deleteHString;
  1025. };
  1026. //==============================================================================
  1027. class HWNDComponentPeer : public ComponentPeer,
  1028. private Timer
  1029. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1030. , public ModifierKeyReceiver
  1031. #endif
  1032. {
  1033. public:
  1034. enum RenderingEngineType
  1035. {
  1036. softwareRenderingEngine = 0,
  1037. direct2DRenderingEngine
  1038. };
  1039. //==============================================================================
  1040. HWNDComponentPeer (Component& comp, int windowStyleFlags, HWND parent, bool nonRepainting)
  1041. : ComponentPeer (comp, windowStyleFlags),
  1042. dontRepaint (nonRepainting),
  1043. parentToAddTo (parent),
  1044. currentRenderingEngine (softwareRenderingEngine)
  1045. {
  1046. callFunctionIfNotLocked (&createWindowCallback, this);
  1047. setTitle (component.getName());
  1048. updateShadower();
  1049. // make sure that the on-screen keyboard code is loaded
  1050. OnScreenKeyboard::getInstance();
  1051. getNativeRealtimeModifiers = []
  1052. {
  1053. HWNDComponentPeer::updateKeyModifiers();
  1054. int mouseMods = 0;
  1055. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  1056. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  1057. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  1058. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1059. return ModifierKeys::currentModifiers;
  1060. };
  1061. }
  1062. ~HWNDComponentPeer()
  1063. {
  1064. shadower = nullptr;
  1065. currentTouches.deleteAllTouchesForPeer (this);
  1066. // do this before the next bit to avoid messages arriving for this window
  1067. // before it's destroyed
  1068. JuceWindowIdentifier::setAsJUCEWindow (hwnd, false);
  1069. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  1070. if (currentWindowIcon != nullptr)
  1071. DestroyIcon (currentWindowIcon);
  1072. if (dropTarget != nullptr)
  1073. {
  1074. dropTarget->peerIsDeleted = true;
  1075. dropTarget->Release();
  1076. dropTarget = nullptr;
  1077. }
  1078. #if JUCE_DIRECT2D
  1079. direct2DContext = nullptr;
  1080. #endif
  1081. }
  1082. //==============================================================================
  1083. void* getNativeHandle() const override { return hwnd; }
  1084. void setVisible (bool shouldBeVisible) override
  1085. {
  1086. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  1087. if (shouldBeVisible)
  1088. InvalidateRect (hwnd, nullptr, 0);
  1089. else
  1090. lastPaintTime = 0;
  1091. }
  1092. void setTitle (const String& title) override
  1093. {
  1094. // Unfortunately some ancient bits of win32 mean you can only perform this operation from the message thread.
  1095. JUCE_ASSERT_MESSAGE_THREAD
  1096. SetWindowText (hwnd, title.toWideCharPointer());
  1097. }
  1098. void repaintNowIfTransparent()
  1099. {
  1100. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  1101. handlePaintMessage();
  1102. }
  1103. void updateBorderSize()
  1104. {
  1105. WINDOWINFO info;
  1106. info.cbSize = sizeof (info);
  1107. if (GetWindowInfo (hwnd, &info))
  1108. windowBorder = BorderSize<int> (roundToInt ((info.rcClient.top - info.rcWindow.top) / scaleFactor),
  1109. roundToInt ((info.rcClient.left - info.rcWindow.left) / scaleFactor),
  1110. roundToInt ((info.rcWindow.bottom - info.rcClient.bottom) / scaleFactor),
  1111. roundToInt ((info.rcWindow.right - info.rcClient.right) / scaleFactor));
  1112. #if JUCE_DIRECT2D
  1113. if (direct2DContext != nullptr)
  1114. direct2DContext->resized();
  1115. #endif
  1116. }
  1117. void setBounds (const Rectangle<int>& bounds, bool isNowFullScreen) override
  1118. {
  1119. fullScreen = isNowFullScreen;
  1120. auto newBounds = windowBorder.addedTo (bounds);
  1121. if (isUsingUpdateLayeredWindow())
  1122. {
  1123. if (auto parentHwnd = GetParent (hwnd))
  1124. {
  1125. auto parentRect = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowRect (parentHwnd)), hwnd);
  1126. newBounds.translate (parentRect.getX(), parentRect.getY());
  1127. }
  1128. }
  1129. auto oldBounds = getBounds();
  1130. const bool hasMoved = (oldBounds.getPosition() != bounds.getPosition());
  1131. const bool hasResized = (oldBounds.getWidth() != bounds.getWidth()
  1132. || oldBounds.getHeight() != bounds.getHeight());
  1133. DWORD flags = SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER;
  1134. if (! hasMoved) flags |= SWP_NOMOVE;
  1135. if (! hasResized) flags |= SWP_NOSIZE;
  1136. setWindowPos (hwnd, newBounds, flags, ! isInDPIChange);
  1137. if (hasResized && isValidPeer (this))
  1138. {
  1139. updateBorderSize();
  1140. repaintNowIfTransparent();
  1141. }
  1142. }
  1143. Rectangle<int> getBounds() const override
  1144. {
  1145. auto bounds = getWindowRect (hwnd);
  1146. if (auto parentH = GetParent (hwnd))
  1147. {
  1148. auto r = getWindowRect (parentH);
  1149. auto localBounds = Rectangle<int>::leftTopRightBottom (bounds.left, bounds.top,
  1150. bounds.right, bounds.bottom).translated (-r.left, -r.top);
  1151. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1152. if (isPerMonitorDPIAwareWindow (hwnd))
  1153. localBounds = (localBounds.toDouble() / getPlatformScaleFactor()).toNearestInt();
  1154. #endif
  1155. return windowBorder.subtractedFrom (localBounds);
  1156. }
  1157. return windowBorder.subtractedFrom (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (bounds), hwnd));
  1158. }
  1159. Point<int> getScreenPosition() const
  1160. {
  1161. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowRect (hwnd)), hwnd);
  1162. return { r.getX() + windowBorder.getLeft(),
  1163. r.getY() + windowBorder.getTop() };
  1164. }
  1165. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition().toFloat(); }
  1166. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition().toFloat(); }
  1167. using ComponentPeer::localToGlobal;
  1168. using ComponentPeer::globalToLocal;
  1169. void setAlpha (float newAlpha) override
  1170. {
  1171. auto intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  1172. if (component.isOpaque())
  1173. {
  1174. if (newAlpha < 1.0f)
  1175. {
  1176. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  1177. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  1178. }
  1179. else
  1180. {
  1181. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  1182. RedrawWindow (hwnd, nullptr, nullptr, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  1183. }
  1184. }
  1185. else
  1186. {
  1187. updateLayeredWindowAlpha = intAlpha;
  1188. component.repaint();
  1189. }
  1190. }
  1191. void setMinimised (bool shouldBeMinimised) override
  1192. {
  1193. if (shouldBeMinimised != isMinimised())
  1194. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  1195. }
  1196. bool isMinimised() const override
  1197. {
  1198. WINDOWPLACEMENT wp;
  1199. wp.length = sizeof (WINDOWPLACEMENT);
  1200. GetWindowPlacement (hwnd, &wp);
  1201. return wp.showCmd == SW_SHOWMINIMIZED;
  1202. }
  1203. void setFullScreen (bool shouldBeFullScreen) override
  1204. {
  1205. setMinimised (false);
  1206. if (isFullScreen() != shouldBeFullScreen)
  1207. {
  1208. if (constrainer != nullptr)
  1209. constrainer->resizeStart();
  1210. fullScreen = shouldBeFullScreen;
  1211. const WeakReference<Component> deletionChecker (&component);
  1212. if (! fullScreen)
  1213. {
  1214. auto boundsCopy = lastNonFullscreenBounds;
  1215. if (hasTitleBar())
  1216. ShowWindow (hwnd, SW_SHOWNORMAL);
  1217. if (! boundsCopy.isEmpty())
  1218. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, boundsCopy), false);
  1219. }
  1220. else
  1221. {
  1222. if (hasTitleBar())
  1223. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  1224. else
  1225. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  1226. }
  1227. if (deletionChecker != nullptr)
  1228. handleMovedOrResized();
  1229. if (constrainer != nullptr)
  1230. constrainer->resizeEnd();
  1231. }
  1232. }
  1233. bool isFullScreen() const override
  1234. {
  1235. if (! hasTitleBar())
  1236. return fullScreen;
  1237. WINDOWPLACEMENT wp;
  1238. wp.length = sizeof (wp);
  1239. GetWindowPlacement (hwnd, &wp);
  1240. return wp.showCmd == SW_SHOWMAXIMIZED;
  1241. }
  1242. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  1243. {
  1244. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowRect (hwnd)), hwnd);
  1245. if (! r.withZeroOrigin().contains (localPos))
  1246. return false;
  1247. auto globalPos = localPos + getScreenPosition();
  1248. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1249. if (isPerMonitorDPIAwareThread() || isPerMonitorDPIAwareWindow (hwnd))
  1250. globalPos = Desktop::getInstance().getDisplays().logicalToPhysical (globalPos);
  1251. #endif
  1252. auto w = WindowFromPoint (POINTFromPoint (globalPos));
  1253. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  1254. }
  1255. BorderSize<int> getFrameSize() const override
  1256. {
  1257. return windowBorder;
  1258. }
  1259. bool setAlwaysOnTop (bool alwaysOnTop) override
  1260. {
  1261. const bool oldDeactivate = shouldDeactivateTitleBar;
  1262. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1263. setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
  1264. shouldDeactivateTitleBar = oldDeactivate;
  1265. if (shadower != nullptr)
  1266. handleBroughtToFront();
  1267. return true;
  1268. }
  1269. void toFront (bool makeActive) override
  1270. {
  1271. setMinimised (false);
  1272. const bool oldDeactivate = shouldDeactivateTitleBar;
  1273. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1274. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  1275. shouldDeactivateTitleBar = oldDeactivate;
  1276. if (! makeActive)
  1277. {
  1278. // in this case a broughttofront call won't have occurred, so do it now..
  1279. handleBroughtToFront();
  1280. }
  1281. }
  1282. void toBehind (ComponentPeer* other) override
  1283. {
  1284. if (auto* otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
  1285. {
  1286. setMinimised (false);
  1287. // Must be careful not to try to put a topmost window behind a normal one, or Windows
  1288. // promotes the normal one to be topmost!
  1289. if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
  1290. setWindowZOrder (hwnd, otherPeer->hwnd);
  1291. else if (otherPeer->getComponent().isAlwaysOnTop())
  1292. setWindowZOrder (hwnd, HWND_TOP);
  1293. }
  1294. else
  1295. {
  1296. jassertfalse; // wrong type of window?
  1297. }
  1298. }
  1299. bool isFocused() const override
  1300. {
  1301. return callFunctionIfNotLocked (&getFocusCallback, nullptr) == (void*) hwnd;
  1302. }
  1303. void grabFocus() override
  1304. {
  1305. const bool oldDeactivate = shouldDeactivateTitleBar;
  1306. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1307. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  1308. shouldDeactivateTitleBar = oldDeactivate;
  1309. }
  1310. void textInputRequired (Point<int>, TextInputTarget&) override
  1311. {
  1312. if (! hasCreatedCaret)
  1313. {
  1314. hasCreatedCaret = true;
  1315. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  1316. }
  1317. ShowCaret (hwnd);
  1318. SetCaretPos (0, 0);
  1319. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1320. OnScreenKeyboard::getInstance()->activate();
  1321. }
  1322. void dismissPendingTextInput() override
  1323. {
  1324. imeHandler.handleSetContext (hwnd, false);
  1325. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1326. OnScreenKeyboard::getInstance()->deactivate();
  1327. }
  1328. void repaint (const Rectangle<int>& area) override
  1329. {
  1330. auto scale = getPlatformScaleFactor();
  1331. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1332. // if the calling thread is DPI-aware but we are invalidating a non-DPI aware window RECT, we actually have to
  1333. // divide the bounds by the scale factor as it will get multiplied for the virtualised paint callback...
  1334. if (isPerMonitorDPIAwareThread() && ! isPerMonitorDPIAwareWindow (hwnd))
  1335. scale = 1.0 / Desktop::getInstance().getDisplays().getMainDisplay().scale;
  1336. #endif
  1337. auto scaled = area.toDouble() * scale;
  1338. auto r = RECTFromRectangle (scaled.getSmallestIntegerContainer());
  1339. InvalidateRect (hwnd, &r, FALSE);
  1340. }
  1341. void performAnyPendingRepaintsNow() override
  1342. {
  1343. if (component.isVisible())
  1344. {
  1345. WeakReference<Component> localRef (&component);
  1346. MSG m;
  1347. if (isUsingUpdateLayeredWindow() || PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  1348. if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
  1349. handlePaintMessage();
  1350. }
  1351. }
  1352. //==============================================================================
  1353. static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
  1354. {
  1355. if (h != nullptr && JuceWindowIdentifier::isJUCEWindow (h))
  1356. return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
  1357. return nullptr;
  1358. }
  1359. //==============================================================================
  1360. bool isInside (HWND h) const noexcept
  1361. {
  1362. return GetAncestor (hwnd, GA_ROOT) == h;
  1363. }
  1364. //==============================================================================
  1365. static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
  1366. static void updateKeyModifiers() noexcept
  1367. {
  1368. int keyMods = 0;
  1369. if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
  1370. if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
  1371. if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
  1372. // workaround: Windows maps AltGr to left-Ctrl + right-Alt.
  1373. if (isKeyDown (VK_RMENU) && !isKeyDown (VK_RCONTROL))
  1374. {
  1375. keyMods = (keyMods & ~ModifierKeys::ctrlModifier) | ModifierKeys::altModifier;
  1376. }
  1377. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1378. }
  1379. static void updateModifiersFromWParam (const WPARAM wParam)
  1380. {
  1381. int mouseMods = 0;
  1382. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  1383. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  1384. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  1385. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1386. updateKeyModifiers();
  1387. }
  1388. //==============================================================================
  1389. bool dontRepaint;
  1390. static ModifierKeys modifiersAtLastCallback;
  1391. //==============================================================================
  1392. struct FileDropTarget : public ComBaseClassHelper<IDropTarget>
  1393. {
  1394. FileDropTarget (HWNDComponentPeer& p) : peer (p) {}
  1395. JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect) override
  1396. {
  1397. auto hr = updateFileList (pDataObject);
  1398. if (FAILED (hr))
  1399. return hr;
  1400. return DragOver (grfKeyState, mousePos, pdwEffect);
  1401. }
  1402. JUCE_COMRESULT DragLeave() override
  1403. {
  1404. if (peerIsDeleted)
  1405. return S_FALSE;
  1406. peer.handleDragExit (dragInfo);
  1407. return S_OK;
  1408. }
  1409. JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1410. {
  1411. if (peerIsDeleted)
  1412. return S_FALSE;
  1413. dragInfo.position = getMousePos (mousePos).roundToInt();
  1414. *pdwEffect = peer.handleDragMove (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1415. : (DWORD) DROPEFFECT_NONE;
  1416. return S_OK;
  1417. }
  1418. JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1419. {
  1420. auto hr = updateFileList (pDataObject);
  1421. if (FAILED (hr))
  1422. return hr;
  1423. dragInfo.position = getMousePos (mousePos).roundToInt();
  1424. *pdwEffect = peer.handleDragDrop (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1425. : (DWORD) DROPEFFECT_NONE;
  1426. return S_OK;
  1427. }
  1428. HWNDComponentPeer& peer;
  1429. ComponentPeer::DragInfo dragInfo;
  1430. bool peerIsDeleted = false;
  1431. private:
  1432. Point<float> getMousePos (POINTL mousePos) const
  1433. {
  1434. auto screenPos = pointFromPOINT ({ mousePos.x, mousePos.y }).toFloat();
  1435. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1436. auto h = (HWND) peer.getNativeHandle();
  1437. if (isPerMonitorDPIAwareWindow (h))
  1438. screenPos = convertPhysicalScreenPointToLogical (screenPos.roundToInt(), h).toFloat();
  1439. #else
  1440. if (JUCEApplication::isStandaloneApp())
  1441. screenPos /= static_cast<float> (getGlobalDPI() / USER_DEFAULT_SCREEN_DPI);
  1442. #endif
  1443. return peer.getComponent().getLocalPoint (nullptr, screenPos);
  1444. }
  1445. template <typename CharType>
  1446. void parseFileList (const CharType* names, const SIZE_T totalLen)
  1447. {
  1448. for (unsigned int i = 0;;)
  1449. {
  1450. unsigned int len = 0;
  1451. while (i + len < totalLen && names[i + len] != 0)
  1452. ++len;
  1453. if (len == 0)
  1454. break;
  1455. dragInfo.files.add (String (names + i, len));
  1456. i += len + 1;
  1457. }
  1458. }
  1459. struct DroppedData
  1460. {
  1461. DroppedData (IDataObject* dataObject, CLIPFORMAT type)
  1462. {
  1463. FORMATETC format = { type, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1464. STGMEDIUM resetMedium = { TYMED_HGLOBAL, { nullptr }, nullptr };
  1465. medium = resetMedium;
  1466. if (SUCCEEDED (error = dataObject->GetData (&format, &medium)))
  1467. {
  1468. dataSize = GlobalSize (medium.hGlobal);
  1469. data = GlobalLock (medium.hGlobal);
  1470. }
  1471. }
  1472. ~DroppedData()
  1473. {
  1474. if (data != nullptr)
  1475. GlobalUnlock (medium.hGlobal);
  1476. }
  1477. HRESULT error;
  1478. STGMEDIUM medium;
  1479. void* data = {};
  1480. SIZE_T dataSize;
  1481. };
  1482. HRESULT updateFileList (IDataObject* const dataObject)
  1483. {
  1484. if (peerIsDeleted)
  1485. return S_FALSE;
  1486. dragInfo.clear();
  1487. {
  1488. DroppedData fileData (dataObject, CF_HDROP);
  1489. if (SUCCEEDED (fileData.error))
  1490. {
  1491. auto dropFiles = static_cast<const LPDROPFILES> (fileData.data);
  1492. const void* const names = addBytesToPointer (dropFiles, sizeof (DROPFILES));
  1493. if (dropFiles->fWide)
  1494. parseFileList (static_cast<const WCHAR*> (names), fileData.dataSize);
  1495. else
  1496. parseFileList (static_cast<const char*> (names), fileData.dataSize);
  1497. return S_OK;
  1498. }
  1499. }
  1500. DroppedData textData (dataObject, CF_UNICODETEXT);
  1501. if (SUCCEEDED (textData.error))
  1502. {
  1503. dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
  1504. CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
  1505. return S_OK;
  1506. }
  1507. return textData.error;
  1508. }
  1509. JUCE_DECLARE_NON_COPYABLE (FileDropTarget)
  1510. };
  1511. static bool offerKeyMessageToJUCEWindow (MSG& m)
  1512. {
  1513. if (m.message == WM_KEYDOWN || m.message == WM_KEYUP)
  1514. if (Component::getCurrentlyFocusedComponent() != nullptr)
  1515. if (auto* h = getOwnerOfWindow (m.hwnd))
  1516. return m.message == WM_KEYDOWN ? h->doKeyDown (m.wParam)
  1517. : h->doKeyUp (m.wParam);
  1518. return false;
  1519. }
  1520. double getPlatformScaleFactor() const noexcept override
  1521. {
  1522. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1523. if (! isPerMonitorDPIAwareWindow (hwnd))
  1524. return 1.0;
  1525. if (auto* parentHWND = GetParent (hwnd))
  1526. {
  1527. if (auto* parentPeer = getOwnerOfWindow (parentHWND))
  1528. return parentPeer->getPlatformScaleFactor();
  1529. if (getDPIForWindow != nullptr)
  1530. return getScaleFactorForWindow (parentHWND);
  1531. }
  1532. return scaleFactor;
  1533. #else
  1534. return 1.0;
  1535. #endif
  1536. }
  1537. private:
  1538. HWND hwnd, parentToAddTo;
  1539. std::unique_ptr<DropShadower> shadower;
  1540. RenderingEngineType currentRenderingEngine;
  1541. #if JUCE_DIRECT2D
  1542. std::unique_ptr<Direct2DLowLevelGraphicsContext> direct2DContext;
  1543. #endif
  1544. uint32 lastPaintTime = 0;
  1545. ULONGLONG lastMagnifySize = 0;
  1546. bool fullScreen = false, isDragging = false, isMouseOver = false,
  1547. hasCreatedCaret = false, constrainerIsResizing = false;
  1548. BorderSize<int> windowBorder;
  1549. HICON currentWindowIcon = nullptr;
  1550. FileDropTarget* dropTarget = nullptr;
  1551. uint8 updateLayeredWindowAlpha = 255;
  1552. UWPUIViewSettings uwpViewSettings;
  1553. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1554. ModifierKeyProvider* modProvider = nullptr;
  1555. #endif
  1556. double scaleFactor = 1.0;
  1557. bool isInDPIChange = false;
  1558. //==============================================================================
  1559. static MultiTouchMapper<DWORD> currentTouches;
  1560. //==============================================================================
  1561. struct TemporaryImage : private Timer
  1562. {
  1563. TemporaryImage() {}
  1564. Image& getImage (bool transparent, int w, int h)
  1565. {
  1566. auto format = transparent ? Image::ARGB : Image::RGB;
  1567. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  1568. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  1569. startTimer (3000);
  1570. return image;
  1571. }
  1572. void timerCallback() override
  1573. {
  1574. stopTimer();
  1575. image = {};
  1576. }
  1577. private:
  1578. Image image;
  1579. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  1580. };
  1581. TemporaryImage offscreenImageGenerator;
  1582. //==============================================================================
  1583. class WindowClassHolder : private DeletedAtShutdown
  1584. {
  1585. public:
  1586. WindowClassHolder()
  1587. {
  1588. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  1589. // get a bit confused (even despite it not being a process-global window class).
  1590. String windowClassName ("JUCE_");
  1591. windowClassName << String::toHexString (Time::currentTimeMillis());
  1592. auto moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  1593. TCHAR moduleFile[1024] = {};
  1594. GetModuleFileName (moduleHandle, moduleFile, 1024);
  1595. WORD iconNum = 0;
  1596. WNDCLASSEX wcex = {};
  1597. wcex.cbSize = sizeof (wcex);
  1598. wcex.style = CS_OWNDC;
  1599. wcex.lpfnWndProc = (WNDPROC) windowProc;
  1600. wcex.lpszClassName = windowClassName.toWideCharPointer();
  1601. wcex.cbWndExtra = 32;
  1602. wcex.hInstance = moduleHandle;
  1603. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1604. iconNum = 1;
  1605. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1606. atom = RegisterClassEx (&wcex);
  1607. jassert (atom != 0);
  1608. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  1609. }
  1610. ~WindowClassHolder()
  1611. {
  1612. if (ComponentPeer::getNumPeers() == 0)
  1613. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  1614. clearSingletonInstance();
  1615. }
  1616. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
  1617. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (WindowClassHolder)
  1618. private:
  1619. ATOM atom;
  1620. static bool isHWNDBlockedByModalComponents (HWND h)
  1621. {
  1622. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1623. if (auto* c = Desktop::getInstance().getComponent (i))
  1624. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  1625. && IsChild ((HWND) c->getWindowHandle(), h))
  1626. return false;
  1627. return true;
  1628. }
  1629. static bool checkEventBlockedByModalComps (const MSG& m)
  1630. {
  1631. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  1632. return false;
  1633. switch (m.message)
  1634. {
  1635. case WM_MOUSEMOVE:
  1636. case WM_NCMOUSEMOVE:
  1637. case 0x020A: /* WM_MOUSEWHEEL */
  1638. case 0x020E: /* WM_MOUSEHWHEEL */
  1639. case WM_KEYUP:
  1640. case WM_SYSKEYUP:
  1641. case WM_CHAR:
  1642. case WM_APPCOMMAND:
  1643. case WM_LBUTTONUP:
  1644. case WM_MBUTTONUP:
  1645. case WM_RBUTTONUP:
  1646. case WM_MOUSEACTIVATE:
  1647. case WM_NCMOUSEHOVER:
  1648. case WM_MOUSEHOVER:
  1649. case WM_TOUCH:
  1650. case WM_POINTERUPDATE:
  1651. case WM_NCPOINTERUPDATE:
  1652. case WM_POINTERWHEEL:
  1653. case WM_POINTERHWHEEL:
  1654. case WM_POINTERUP:
  1655. case WM_POINTERACTIVATE:
  1656. return isHWNDBlockedByModalComponents(m.hwnd);
  1657. case WM_NCLBUTTONDOWN:
  1658. case WM_NCLBUTTONDBLCLK:
  1659. case WM_NCRBUTTONDOWN:
  1660. case WM_NCRBUTTONDBLCLK:
  1661. case WM_NCMBUTTONDOWN:
  1662. case WM_NCMBUTTONDBLCLK:
  1663. case WM_LBUTTONDOWN:
  1664. case WM_LBUTTONDBLCLK:
  1665. case WM_MBUTTONDOWN:
  1666. case WM_MBUTTONDBLCLK:
  1667. case WM_RBUTTONDOWN:
  1668. case WM_RBUTTONDBLCLK:
  1669. case WM_KEYDOWN:
  1670. case WM_SYSKEYDOWN:
  1671. case WM_NCPOINTERDOWN:
  1672. case WM_POINTERDOWN:
  1673. if (isHWNDBlockedByModalComponents (m.hwnd))
  1674. {
  1675. if (auto* modal = Component::getCurrentlyModalComponent (0))
  1676. modal->inputAttemptWhenModal();
  1677. return true;
  1678. }
  1679. break;
  1680. default:
  1681. break;
  1682. }
  1683. return false;
  1684. }
  1685. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  1686. };
  1687. //==============================================================================
  1688. static void* createWindowCallback (void* userData)
  1689. {
  1690. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  1691. return nullptr;
  1692. }
  1693. void createWindow()
  1694. {
  1695. DWORD exstyle = 0;
  1696. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  1697. if (hasTitleBar())
  1698. {
  1699. type |= WS_OVERLAPPED;
  1700. if ((styleFlags & windowHasCloseButton) != 0)
  1701. {
  1702. type |= WS_SYSMENU;
  1703. }
  1704. else
  1705. {
  1706. // annoyingly, windows won't let you have a min/max button without a close button
  1707. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  1708. }
  1709. if ((styleFlags & windowIsResizable) != 0)
  1710. type |= WS_THICKFRAME;
  1711. }
  1712. else if (parentToAddTo != nullptr)
  1713. {
  1714. type |= WS_CHILD;
  1715. }
  1716. else
  1717. {
  1718. type |= WS_POPUP | WS_SYSMENU;
  1719. }
  1720. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1721. exstyle |= WS_EX_TOOLWINDOW;
  1722. else
  1723. exstyle |= WS_EX_APPWINDOW;
  1724. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  1725. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  1726. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  1727. if ((styleFlags & windowIsSemiTransparent) != 0) exstyle |= WS_EX_LAYERED;
  1728. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  1729. L"", type, 0, 0, 0, 0, parentToAddTo, nullptr,
  1730. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), nullptr);
  1731. if (hwnd != nullptr)
  1732. {
  1733. SetWindowLongPtr (hwnd, 0, 0);
  1734. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  1735. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  1736. if (dropTarget == nullptr)
  1737. {
  1738. HWNDComponentPeer* peer = nullptr;
  1739. if (dontRepaint)
  1740. peer = getOwnerOfWindow (parentToAddTo);
  1741. if (peer == nullptr)
  1742. peer = this;
  1743. dropTarget = new FileDropTarget (*peer);
  1744. }
  1745. RegisterDragDrop (hwnd, dropTarget);
  1746. if (canUseMultiTouch())
  1747. registerTouchWindow (hwnd, 0);
  1748. setDPIAwareness();
  1749. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1750. if (isPerMonitorDPIAwareThread())
  1751. {
  1752. auto bounds = component.getBounds();
  1753. if (bounds.isEmpty())
  1754. scaleFactor = Desktop::getInstance().getDisplays().getMainDisplay().scale;
  1755. else
  1756. scaleFactor = Desktop::getInstance().getDisplays().findDisplayForRect (bounds).scale;
  1757. scaleFactor /= Desktop::getInstance().getGlobalScaleFactor();
  1758. }
  1759. #endif
  1760. setMessageFilter();
  1761. updateBorderSize();
  1762. checkForPointerAPI();
  1763. // This is needed so that our plugin window gets notified of WM_SETTINGCHANGE messages
  1764. // and can respond to display scale changes
  1765. if (! JUCEApplication::isStandaloneApp())
  1766. settingChangeCallback = forceDisplayUpdate;
  1767. // Calling this function here is (for some reason) necessary to make Windows
  1768. // correctly enable the menu items that we specify in the wm_initmenu message.
  1769. GetSystemMenu (hwnd, false);
  1770. auto alpha = component.getAlpha();
  1771. if (alpha < 1.0f)
  1772. setAlpha (alpha);
  1773. }
  1774. else
  1775. {
  1776. jassertfalse;
  1777. }
  1778. }
  1779. static BOOL CALLBACK revokeChildDragDropCallback (HWND hwnd, LPARAM) { RevokeDragDrop (hwnd); return TRUE; }
  1780. static void* destroyWindowCallback (void* handle)
  1781. {
  1782. auto hwnd = reinterpret_cast<HWND> (handle);
  1783. if (IsWindow (hwnd))
  1784. {
  1785. RevokeDragDrop (hwnd);
  1786. // NB: we need to do this before DestroyWindow() as child HWNDs will be invalid after
  1787. EnumChildWindows (hwnd, revokeChildDragDropCallback, 0);
  1788. DestroyWindow (hwnd);
  1789. }
  1790. return nullptr;
  1791. }
  1792. static void* toFrontCallback1 (void* h)
  1793. {
  1794. SetForegroundWindow ((HWND) h);
  1795. return nullptr;
  1796. }
  1797. static void* toFrontCallback2 (void* h)
  1798. {
  1799. setWindowZOrder ((HWND) h, HWND_TOP);
  1800. return nullptr;
  1801. }
  1802. static void* setFocusCallback (void* h)
  1803. {
  1804. SetFocus ((HWND) h);
  1805. return nullptr;
  1806. }
  1807. static void* getFocusCallback (void*)
  1808. {
  1809. return GetFocus();
  1810. }
  1811. bool isUsingUpdateLayeredWindow() const
  1812. {
  1813. return ! component.isOpaque();
  1814. }
  1815. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  1816. void updateShadower()
  1817. {
  1818. if (! component.isCurrentlyModal() && (styleFlags & windowHasDropShadow) != 0
  1819. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  1820. {
  1821. shadower.reset (component.getLookAndFeel().createDropShadowerForComponent (&component));
  1822. if (shadower != nullptr)
  1823. shadower->setOwner (&component);
  1824. }
  1825. }
  1826. void setIcon (const Image& newIcon) override
  1827. {
  1828. if (auto hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0))
  1829. {
  1830. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  1831. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  1832. if (currentWindowIcon != nullptr)
  1833. DestroyIcon (currentWindowIcon);
  1834. currentWindowIcon = hicon;
  1835. }
  1836. }
  1837. void setMessageFilter()
  1838. {
  1839. using ChangeWindowMessageFilterExFunc = BOOL (WINAPI*) (HWND, UINT, DWORD, PVOID);
  1840. if (auto changeMessageFilter = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx"))
  1841. {
  1842. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  1843. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  1844. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  1845. }
  1846. }
  1847. struct ChildWindowClippingInfo
  1848. {
  1849. HDC dc;
  1850. HWNDComponentPeer* peer;
  1851. RectangleList<int>* clip;
  1852. Point<int> origin;
  1853. int savedDC;
  1854. };
  1855. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  1856. {
  1857. if (IsWindowVisible (hwnd))
  1858. {
  1859. auto& info = *(ChildWindowClippingInfo*) context;
  1860. auto parent = GetParent (hwnd);
  1861. if (parent == info.peer->hwnd)
  1862. {
  1863. auto r = getWindowRect (hwnd);
  1864. POINT pos = { r.left, r.top };
  1865. ScreenToClient (GetParent (hwnd), &pos);
  1866. Rectangle<int> clip (pos.x, pos.y,
  1867. r.right - r.left,
  1868. r.bottom - r.top);
  1869. info.clip->subtract (clip - info.origin);
  1870. if (info.savedDC == 0)
  1871. info.savedDC = SaveDC (info.dc);
  1872. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  1873. }
  1874. }
  1875. return TRUE;
  1876. }
  1877. //==============================================================================
  1878. void handlePaintMessage()
  1879. {
  1880. #if JUCE_DIRECT2D
  1881. if (direct2DContext != nullptr)
  1882. {
  1883. RECT r;
  1884. if (GetUpdateRect (hwnd, &r, false))
  1885. {
  1886. direct2DContext->start();
  1887. direct2DContext->clipToRectangle (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  1888. handlePaint (*direct2DContext);
  1889. direct2DContext->end();
  1890. ValidateRect (hwnd, &r);
  1891. }
  1892. }
  1893. else
  1894. #endif
  1895. {
  1896. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  1897. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  1898. PAINTSTRUCT paintStruct;
  1899. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  1900. // message and become re-entrant, but that's OK
  1901. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  1902. // corrupt the image it's using to paint into, so do a check here.
  1903. static bool reentrant = false;
  1904. if (! reentrant)
  1905. {
  1906. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1907. if (dontRepaint)
  1908. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  1909. else
  1910. performPaint (dc, rgn, regionType, paintStruct);
  1911. }
  1912. DeleteObject (rgn);
  1913. EndPaint (hwnd, &paintStruct);
  1914. #if JUCE_MSVC
  1915. _fpreset(); // because some graphics cards can unmask FP exceptions
  1916. #endif
  1917. }
  1918. lastPaintTime = Time::getMillisecondCounter();
  1919. }
  1920. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1921. {
  1922. int x = paintStruct.rcPaint.left;
  1923. int y = paintStruct.rcPaint.top;
  1924. int w = paintStruct.rcPaint.right - x;
  1925. int h = paintStruct.rcPaint.bottom - y;
  1926. const bool transparent = isUsingUpdateLayeredWindow();
  1927. if (transparent)
  1928. {
  1929. // it's not possible to have a transparent window with a title bar at the moment!
  1930. jassert (! hasTitleBar());
  1931. auto r = getWindowRect (hwnd);
  1932. x = y = 0;
  1933. w = r.right - r.left;
  1934. h = r.bottom - r.top;
  1935. }
  1936. if (w > 0 && h > 0)
  1937. {
  1938. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1939. RectangleList<int> contextClip;
  1940. const Rectangle<int> clipBounds (w, h);
  1941. bool needToPaintAll = true;
  1942. if (regionType == COMPLEXREGION && ! transparent)
  1943. {
  1944. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1945. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1946. DeleteObject (clipRgn);
  1947. char rgnData[8192];
  1948. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1949. if (res > 0 && res <= sizeof (rgnData))
  1950. {
  1951. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1952. if (hdr->iType == RDH_RECTANGLES
  1953. && hdr->rcBound.right - hdr->rcBound.left >= w
  1954. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1955. {
  1956. needToPaintAll = false;
  1957. auto rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1958. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  1959. {
  1960. if (rects->right <= x + w && rects->bottom <= y + h)
  1961. {
  1962. const int cx = jmax (x, (int) rects->left);
  1963. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  1964. rects->right - cx, rects->bottom - rects->top)
  1965. .getIntersection (clipBounds));
  1966. }
  1967. else
  1968. {
  1969. needToPaintAll = true;
  1970. break;
  1971. }
  1972. ++rects;
  1973. }
  1974. }
  1975. }
  1976. }
  1977. if (needToPaintAll)
  1978. {
  1979. contextClip.clear();
  1980. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  1981. }
  1982. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  1983. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  1984. if (! contextClip.isEmpty())
  1985. {
  1986. if (transparent)
  1987. for (auto& i : contextClip)
  1988. offscreenImage.clear (i);
  1989. {
  1990. auto context = component.getLookAndFeel()
  1991. .createGraphicsContext (offscreenImage, { -x, -y }, contextClip);
  1992. context->addTransform (AffineTransform::scale ((float) getPlatformScaleFactor()));
  1993. handlePaint (*context);
  1994. }
  1995. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  1996. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  1997. }
  1998. if (childClipInfo.savedDC != 0)
  1999. RestoreDC (dc, childClipInfo.savedDC);
  2000. }
  2001. }
  2002. //==============================================================================
  2003. void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = ModifierKeys::currentModifiers)
  2004. {
  2005. handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
  2006. }
  2007. StringArray getAvailableRenderingEngines() override
  2008. {
  2009. StringArray s ("Software Renderer");
  2010. #if JUCE_DIRECT2D
  2011. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  2012. s.add ("Direct2D");
  2013. #endif
  2014. return s;
  2015. }
  2016. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  2017. #if JUCE_DIRECT2D
  2018. void updateDirect2DContext()
  2019. {
  2020. if (currentRenderingEngine != direct2DRenderingEngine)
  2021. direct2DContext = nullptr;
  2022. else if (direct2DContext == nullptr)
  2023. direct2DContext.reset (new Direct2DLowLevelGraphicsContext (hwnd));
  2024. }
  2025. #endif
  2026. void setCurrentRenderingEngine (int index) override
  2027. {
  2028. ignoreUnused (index);
  2029. #if JUCE_DIRECT2D
  2030. if (getAvailableRenderingEngines().size() > 1)
  2031. {
  2032. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  2033. updateDirect2DContext();
  2034. repaint (component.getLocalBounds());
  2035. }
  2036. #endif
  2037. }
  2038. static uint32 getMinTimeBetweenMouseMoves()
  2039. {
  2040. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  2041. return 0;
  2042. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  2043. }
  2044. bool isTouchEvent() noexcept
  2045. {
  2046. if (registerTouchWindow == nullptr)
  2047. return false;
  2048. // Relevant info about touch/pen detection flags:
  2049. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  2050. // http://www.petertissen.de/?p=4
  2051. return (GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  2052. }
  2053. static bool areOtherTouchSourcesActive()
  2054. {
  2055. for (auto& ms : Desktop::getInstance().getMouseSources())
  2056. if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
  2057. || ms.getType() == MouseInputSource::InputSourceType::pen))
  2058. return true;
  2059. return false;
  2060. }
  2061. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  2062. {
  2063. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2064. // this will be handled by WM_TOUCH
  2065. if (isTouchEvent() || areOtherTouchSourcesActive())
  2066. return;
  2067. if (! isMouseOver)
  2068. {
  2069. isMouseOver = true;
  2070. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  2071. // not be called as part of a move, in case it's actually a mouse-drag from another
  2072. // app which ends up here when we get focus before the mouse is released..
  2073. if (isMouseDownEvent && getNativeRealtimeModifiers != nullptr)
  2074. getNativeRealtimeModifiers();
  2075. updateKeyModifiers();
  2076. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2077. if (modProvider != nullptr)
  2078. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2079. #endif
  2080. TRACKMOUSEEVENT tme;
  2081. tme.cbSize = sizeof (tme);
  2082. tme.dwFlags = TME_LEAVE;
  2083. tme.hwndTrack = hwnd;
  2084. tme.dwHoverTime = 0;
  2085. if (! TrackMouseEvent (&tme))
  2086. jassertfalse;
  2087. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  2088. }
  2089. else if (! isDragging)
  2090. {
  2091. if (! contains (position.roundToInt(), false))
  2092. return;
  2093. }
  2094. static uint32 lastMouseTime = 0;
  2095. static auto minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  2096. auto now = Time::getMillisecondCounter();
  2097. if (! Desktop::getInstance().getMainMouseSource().isDragging())
  2098. modsToSend = modsToSend.withoutMouseButtons();
  2099. if (now >= lastMouseTime + minTimeBetweenMouses)
  2100. {
  2101. lastMouseTime = now;
  2102. doMouseEvent (position, MouseInputSource::invalidPressure,
  2103. MouseInputSource::invalidOrientation, modsToSend);
  2104. }
  2105. }
  2106. void doMouseDown (Point<float> position, const WPARAM wParam)
  2107. {
  2108. // this will be handled by WM_TOUCH
  2109. if (isTouchEvent() || areOtherTouchSourcesActive())
  2110. return;
  2111. if (GetCapture() != hwnd)
  2112. SetCapture (hwnd);
  2113. doMouseMove (position, true);
  2114. if (isValidPeer (this))
  2115. {
  2116. updateModifiersFromWParam (wParam);
  2117. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2118. if (modProvider != nullptr)
  2119. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2120. #endif
  2121. isDragging = true;
  2122. doMouseEvent (position, MouseInputSource::invalidPressure);
  2123. }
  2124. }
  2125. void doMouseUp (Point<float> position, const WPARAM wParam)
  2126. {
  2127. // this will be handled by WM_TOUCH
  2128. if (isTouchEvent() || areOtherTouchSourcesActive())
  2129. return;
  2130. updateModifiersFromWParam (wParam);
  2131. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2132. if (modProvider != nullptr)
  2133. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2134. #endif
  2135. const bool wasDragging = isDragging;
  2136. isDragging = false;
  2137. // release the mouse capture if the user has released all buttons
  2138. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  2139. ReleaseCapture();
  2140. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  2141. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  2142. if (wasDragging)
  2143. doMouseEvent (position, MouseInputSource::invalidPressure);
  2144. }
  2145. void doCaptureChanged()
  2146. {
  2147. if (constrainerIsResizing)
  2148. {
  2149. if (constrainer != nullptr)
  2150. constrainer->resizeEnd();
  2151. constrainerIsResizing = false;
  2152. }
  2153. if (isDragging)
  2154. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  2155. }
  2156. void doMouseExit()
  2157. {
  2158. isMouseOver = false;
  2159. if (! areOtherTouchSourcesActive())
  2160. doMouseEvent (getCurrentMousePos(), MouseInputSource::invalidPressure);
  2161. }
  2162. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  2163. {
  2164. auto currentMousePos = getPOINTFromLParam (GetMessagePos());
  2165. // Because Windows stupidly sends all wheel events to the window with the keyboard
  2166. // focus, we have to redirect them here according to the mouse pos..
  2167. auto* peer = getOwnerOfWindow (WindowFromPoint (currentMousePos));
  2168. if (peer == nullptr)
  2169. peer = this;
  2170. localPos = peer->globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (currentMousePos), hwnd).toFloat());
  2171. return peer;
  2172. }
  2173. static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
  2174. {
  2175. if (getPointerTypeFunction != nullptr)
  2176. {
  2177. POINTER_INPUT_TYPE pointerType;
  2178. if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
  2179. {
  2180. if (pointerType == 2)
  2181. return MouseInputSource::InputSourceType::touch;
  2182. if (pointerType == 3)
  2183. return MouseInputSource::InputSourceType::pen;
  2184. }
  2185. }
  2186. return MouseInputSource::InputSourceType::mouse;
  2187. }
  2188. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  2189. {
  2190. updateKeyModifiers();
  2191. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  2192. MouseWheelDetails wheel;
  2193. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  2194. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  2195. wheel.isReversed = false;
  2196. wheel.isSmooth = false;
  2197. wheel.isInertial = false;
  2198. Point<float> localPos;
  2199. if (auto* peer = findPeerUnderMouse (localPos))
  2200. peer->handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
  2201. }
  2202. bool doGestureEvent (LPARAM lParam)
  2203. {
  2204. GESTUREINFO gi;
  2205. zerostruct (gi);
  2206. gi.cbSize = sizeof (gi);
  2207. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  2208. {
  2209. updateKeyModifiers();
  2210. Point<float> localPos;
  2211. if (auto* peer = findPeerUnderMouse (localPos))
  2212. {
  2213. switch (gi.dwID)
  2214. {
  2215. case 3: /*GID_ZOOM*/
  2216. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  2217. peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
  2218. (float) (gi.ullArguments / (double) lastMagnifySize));
  2219. lastMagnifySize = gi.ullArguments;
  2220. return true;
  2221. case 4: /*GID_PAN*/
  2222. case 5: /*GID_ROTATE*/
  2223. case 6: /*GID_TWOFINGERTAP*/
  2224. case 7: /*GID_PRESSANDTAP*/
  2225. default:
  2226. break;
  2227. }
  2228. }
  2229. }
  2230. return false;
  2231. }
  2232. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  2233. {
  2234. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2235. if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
  2236. if (parent != this)
  2237. return parent->doTouchEvent (numInputs, eventHandle);
  2238. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  2239. if (getTouchInputInfo (eventHandle, (UINT) numInputs, inputInfo, sizeof (TOUCHINPUT)))
  2240. {
  2241. for (int i = 0; i < numInputs; ++i)
  2242. {
  2243. auto flags = inputInfo[i].dwFlags;
  2244. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  2245. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  2246. return 0; // abandon method if this window was deleted by the callback
  2247. }
  2248. }
  2249. closeTouchInputHandle (eventHandle);
  2250. return 0;
  2251. }
  2252. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
  2253. const float touchPressure = MouseInputSource::invalidPressure,
  2254. const float orientation = 0.0f)
  2255. {
  2256. auto isCancel = false;
  2257. const auto touchIndex = currentTouches.getIndexOfTouch (this, touch.dwID);
  2258. const auto time = getMouseEventTime();
  2259. const auto pos = globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT ({ roundToInt (touch.x / 100.0f),
  2260. roundToInt (touch.y / 100.0f) }), hwnd).toFloat());
  2261. const auto pressure = touchPressure;
  2262. auto modsToSend = ModifierKeys::currentModifiers;
  2263. if (isDown)
  2264. {
  2265. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2266. modsToSend = ModifierKeys::currentModifiers;
  2267. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2268. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  2269. pressure, orientation, time, {}, touchIndex);
  2270. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2271. return false;
  2272. }
  2273. else if (isUp)
  2274. {
  2275. modsToSend = modsToSend.withoutMouseButtons();
  2276. ModifierKeys::currentModifiers = modsToSend;
  2277. currentTouches.clearTouch (touchIndex);
  2278. if (! currentTouches.areAnyTouchesActive())
  2279. isCancel = true;
  2280. }
  2281. else
  2282. {
  2283. modsToSend = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2284. }
  2285. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
  2286. pressure, orientation, time, {}, touchIndex);
  2287. if (! isValidPeer (this))
  2288. return false;
  2289. if (isUp)
  2290. {
  2291. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers.withoutMouseButtons(),
  2292. pressure, orientation, time, {}, touchIndex);
  2293. if (! isValidPeer (this))
  2294. return false;
  2295. if (isCancel)
  2296. {
  2297. currentTouches.clear();
  2298. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2299. }
  2300. }
  2301. return true;
  2302. }
  2303. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  2304. {
  2305. if (! canUsePointerAPI)
  2306. return false;
  2307. auto pointerType = getPointerType (wParam);
  2308. if (pointerType == MouseInputSource::InputSourceType::touch)
  2309. {
  2310. POINTER_TOUCH_INFO touchInfo;
  2311. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  2312. return false;
  2313. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? touchInfo.pressure
  2314. : MouseInputSource::invalidPressure;
  2315. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  2316. : MouseInputSource::invalidOrientation;
  2317. if (! handleTouchInput (emulateTouchEventFromPointer (touchInfo.pointerInfo.ptPixelLocationRaw, wParam),
  2318. isDown, isUp, pressure, orientation))
  2319. return false;
  2320. }
  2321. else if (pointerType == MouseInputSource::InputSourceType::pen)
  2322. {
  2323. POINTER_PEN_INFO penInfo;
  2324. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  2325. return false;
  2326. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? penInfo.pressure / 1024.0f : MouseInputSource::invalidPressure;
  2327. if (! handlePenInput (penInfo, globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (lParam)), hwnd).toFloat()),
  2328. pressure, isDown, isUp))
  2329. return false;
  2330. }
  2331. else
  2332. {
  2333. return false;
  2334. }
  2335. return true;
  2336. }
  2337. TOUCHINPUT emulateTouchEventFromPointer (POINT p, WPARAM wParam)
  2338. {
  2339. TOUCHINPUT touchInput;
  2340. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  2341. touchInput.x = p.x * 100;
  2342. touchInput.y = p.y * 100;
  2343. return touchInput;
  2344. }
  2345. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  2346. {
  2347. const auto time = getMouseEventTime();
  2348. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2349. PenDetails penDetails;
  2350. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::invalidRotation;
  2351. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? penInfo.tiltX / 90.0f : MouseInputSource::invalidTiltX;
  2352. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? penInfo.tiltY / 90.0f : MouseInputSource::invalidTiltY;
  2353. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  2354. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  2355. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2356. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  2357. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  2358. if (isDown)
  2359. {
  2360. modsToSend = ModifierKeys::currentModifiers;
  2361. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2362. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  2363. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2364. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2365. return false;
  2366. }
  2367. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  2368. {
  2369. modsToSend = modsToSend.withoutMouseButtons();
  2370. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2371. }
  2372. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  2373. MouseInputSource::invalidOrientation, time, penDetails);
  2374. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2375. return false;
  2376. if (isUp)
  2377. {
  2378. handleMouseEvent (MouseInputSource::InputSourceType::pen, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  2379. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2380. if (! isValidPeer (this))
  2381. return false;
  2382. }
  2383. return true;
  2384. }
  2385. //==============================================================================
  2386. void sendModifierKeyChangeIfNeeded()
  2387. {
  2388. if (modifiersAtLastCallback != ModifierKeys::currentModifiers)
  2389. {
  2390. modifiersAtLastCallback = ModifierKeys::currentModifiers;
  2391. handleModifierKeysChange();
  2392. }
  2393. }
  2394. bool doKeyUp (const WPARAM key)
  2395. {
  2396. updateKeyModifiers();
  2397. switch (key)
  2398. {
  2399. case VK_SHIFT:
  2400. case VK_CONTROL:
  2401. case VK_MENU:
  2402. case VK_CAPITAL:
  2403. case VK_LWIN:
  2404. case VK_RWIN:
  2405. case VK_APPS:
  2406. case VK_NUMLOCK:
  2407. case VK_SCROLL:
  2408. case VK_LSHIFT:
  2409. case VK_RSHIFT:
  2410. case VK_LCONTROL:
  2411. case VK_LMENU:
  2412. case VK_RCONTROL:
  2413. case VK_RMENU:
  2414. sendModifierKeyChangeIfNeeded();
  2415. }
  2416. return handleKeyUpOrDown (false)
  2417. || Component::getCurrentlyModalComponent() != nullptr;
  2418. }
  2419. bool doKeyDown (const WPARAM key)
  2420. {
  2421. updateKeyModifiers();
  2422. bool used = false;
  2423. switch (key)
  2424. {
  2425. case VK_SHIFT:
  2426. case VK_LSHIFT:
  2427. case VK_RSHIFT:
  2428. case VK_CONTROL:
  2429. case VK_LCONTROL:
  2430. case VK_RCONTROL:
  2431. case VK_MENU:
  2432. case VK_LMENU:
  2433. case VK_RMENU:
  2434. case VK_LWIN:
  2435. case VK_RWIN:
  2436. case VK_CAPITAL:
  2437. case VK_NUMLOCK:
  2438. case VK_SCROLL:
  2439. case VK_APPS:
  2440. used = handleKeyUpOrDown (true);
  2441. sendModifierKeyChangeIfNeeded();
  2442. break;
  2443. case VK_LEFT:
  2444. case VK_RIGHT:
  2445. case VK_UP:
  2446. case VK_DOWN:
  2447. case VK_PRIOR:
  2448. case VK_NEXT:
  2449. case VK_HOME:
  2450. case VK_END:
  2451. case VK_DELETE:
  2452. case VK_INSERT:
  2453. case VK_F1:
  2454. case VK_F2:
  2455. case VK_F3:
  2456. case VK_F4:
  2457. case VK_F5:
  2458. case VK_F6:
  2459. case VK_F7:
  2460. case VK_F8:
  2461. case VK_F9:
  2462. case VK_F10:
  2463. case VK_F11:
  2464. case VK_F12:
  2465. case VK_F13:
  2466. case VK_F14:
  2467. case VK_F15:
  2468. case VK_F16:
  2469. case VK_F17:
  2470. case VK_F18:
  2471. case VK_F19:
  2472. case VK_F20:
  2473. case VK_F21:
  2474. case VK_F22:
  2475. case VK_F23:
  2476. case VK_F24:
  2477. used = handleKeyUpOrDown (true);
  2478. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2479. break;
  2480. default:
  2481. used = handleKeyUpOrDown (true);
  2482. {
  2483. MSG msg;
  2484. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2485. {
  2486. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2487. // manually generate the key-press event that matches this key-down.
  2488. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2489. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2490. BYTE keyState[256];
  2491. GetKeyboardState (keyState);
  2492. WCHAR text[16] = { 0 };
  2493. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2494. text[0] = 0;
  2495. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2496. }
  2497. }
  2498. break;
  2499. }
  2500. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2501. }
  2502. bool doKeyChar (int key, const LPARAM flags)
  2503. {
  2504. updateKeyModifiers();
  2505. auto textChar = (juce_wchar) key;
  2506. const int virtualScanCode = (flags >> 16) & 0xff;
  2507. if (key >= '0' && key <= '9')
  2508. {
  2509. switch (virtualScanCode) // check for a numeric keypad scan-code
  2510. {
  2511. case 0x52:
  2512. case 0x4f:
  2513. case 0x50:
  2514. case 0x51:
  2515. case 0x4b:
  2516. case 0x4c:
  2517. case 0x4d:
  2518. case 0x47:
  2519. case 0x48:
  2520. case 0x49:
  2521. key = (key - '0') + KeyPress::numberPad0;
  2522. break;
  2523. default:
  2524. break;
  2525. }
  2526. }
  2527. else
  2528. {
  2529. // convert the scan code to an unmodified character code..
  2530. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2531. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2532. keyChar = LOWORD (keyChar);
  2533. if (keyChar != 0)
  2534. key = (int) keyChar;
  2535. // avoid sending junk text characters for some control-key combinations
  2536. if (textChar < ' ' && ModifierKeys::currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2537. textChar = 0;
  2538. }
  2539. return handleKeyPress (key, textChar);
  2540. }
  2541. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2542. {
  2543. if (HWND parentH = GetParent (hwnd))
  2544. PostMessage (parentH, message, wParam, lParam);
  2545. }
  2546. bool doAppCommand (const LPARAM lParam)
  2547. {
  2548. int key = 0;
  2549. switch (GET_APPCOMMAND_LPARAM (lParam))
  2550. {
  2551. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2552. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2553. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2554. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2555. default: break;
  2556. }
  2557. if (key != 0)
  2558. {
  2559. updateKeyModifiers();
  2560. if (hwnd == GetActiveWindow())
  2561. return handleKeyPress (key, 0);
  2562. }
  2563. return false;
  2564. }
  2565. bool isConstrainedNativeWindow() const
  2566. {
  2567. return constrainer != nullptr
  2568. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2569. && ! isKioskMode();
  2570. }
  2571. Rectangle<int> getCurrentScaledBounds() const
  2572. {
  2573. return ScalingHelpers::unscaledScreenPosToScaled (component, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (component, component.getBounds())));
  2574. }
  2575. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2576. {
  2577. if (isConstrainedNativeWindow())
  2578. {
  2579. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  2580. auto current = getCurrentScaledBounds();
  2581. constrainer->checkBounds (pos, current,
  2582. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2583. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2584. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2585. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2586. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2587. r = RECTFromRectangle (convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos), hwnd));
  2588. }
  2589. return TRUE;
  2590. }
  2591. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2592. {
  2593. if (isConstrainedNativeWindow())
  2594. {
  2595. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2596. && (wp.x > -32000 && wp.y > -32000)
  2597. && ! Component::isMouseButtonDownAnywhere())
  2598. {
  2599. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, convertPhysicalScreenRectangleToLogical (rectangleFromRECT ({ wp.x, wp.y, wp.x + wp.cx, wp.y + wp.cy }), hwnd));
  2600. auto current = getCurrentScaledBounds();
  2601. constrainer->checkBounds (pos, current,
  2602. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2603. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  2604. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  2605. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  2606. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  2607. pos = convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos), hwnd);
  2608. wp.x = pos.getX();
  2609. wp.y = pos.getY();
  2610. wp.cx = pos.getWidth();
  2611. wp.cy = pos.getHeight();
  2612. }
  2613. }
  2614. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2615. component.setVisible (true);
  2616. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2617. component.setVisible (false);
  2618. return 0;
  2619. }
  2620. bool handlePositionChanged()
  2621. {
  2622. auto pos = getCurrentMousePos();
  2623. if (contains (pos.roundToInt(), false))
  2624. {
  2625. if (! areOtherTouchSourcesActive())
  2626. doMouseEvent (pos, MouseInputSource::invalidPressure);
  2627. if (! isValidPeer (this))
  2628. return true;
  2629. }
  2630. handleMovedOrResized();
  2631. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  2632. }
  2633. LRESULT handleDPIChanging (int newDPI, RECT newRect)
  2634. {
  2635. auto newScale = (double) newDPI / USER_DEFAULT_SCREEN_DPI;
  2636. if (! approximatelyEqual (scaleFactor, newScale))
  2637. {
  2638. const ScopedValueSetter<bool> setter (isInDPIChange, true);
  2639. auto oldScale = scaleFactor;
  2640. scaleFactor = newScale;
  2641. auto scaleRatio = scaleFactor / oldScale;
  2642. EnumChildWindows (hwnd, scaleChildHWNDCallback, (LPARAM) &scaleRatio);
  2643. setBounds (windowBorder.subtractedFrom (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (newRect), hwnd)), false);
  2644. updateShadower();
  2645. InvalidateRect (hwnd, nullptr, FALSE);
  2646. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2647. }
  2648. return 0;
  2649. }
  2650. static BOOL CALLBACK scaleChildHWNDCallback (HWND hwnd, LPARAM context)
  2651. {
  2652. auto r = getWindowRect (hwnd);
  2653. POINT p { r.left, r.top };
  2654. ScreenToClient (GetParent (hwnd), &p);
  2655. auto ratio = *(double*) context;
  2656. SetWindowPos (hwnd, nullptr, roundToInt (p.x * ratio), roundToInt (p.y * ratio),
  2657. roundToInt ((r.right - r.left) * ratio), roundToInt ((r.bottom - r.top) * ratio),
  2658. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  2659. if (auto* peer = getOwnerOfWindow (hwnd))
  2660. peer->handleChildDPIChanging();
  2661. return TRUE;
  2662. }
  2663. void handleChildDPIChanging()
  2664. {
  2665. const ScopedValueSetter<bool> setter (isInDPIChange, true);
  2666. scaleFactor = getScaleFactorForWindow (parentToAddTo);
  2667. updateShadower();
  2668. InvalidateRect (hwnd, nullptr, FALSE);
  2669. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2670. }
  2671. void handleAppActivation (const WPARAM wParam)
  2672. {
  2673. modifiersAtLastCallback = -1;
  2674. updateKeyModifiers();
  2675. if (isMinimised())
  2676. {
  2677. component.repaint();
  2678. handleMovedOrResized();
  2679. if (! isValidPeer (this))
  2680. return;
  2681. }
  2682. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  2683. if (underMouse == nullptr)
  2684. underMouse = &component;
  2685. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  2686. {
  2687. if (LOWORD (wParam) == WA_CLICKACTIVE)
  2688. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  2689. else
  2690. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  2691. }
  2692. else
  2693. {
  2694. handleBroughtToFront();
  2695. }
  2696. }
  2697. void handlePowerBroadcast (WPARAM wParam)
  2698. {
  2699. if (auto* app = JUCEApplicationBase::getInstance())
  2700. {
  2701. switch (wParam)
  2702. {
  2703. case PBT_APMSUSPEND: app->suspended(); break;
  2704. case PBT_APMQUERYSUSPENDFAILED:
  2705. case PBT_APMRESUMECRITICAL:
  2706. case PBT_APMRESUMESUSPEND:
  2707. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  2708. default: break;
  2709. }
  2710. }
  2711. }
  2712. void handleLeftClickInNCArea (WPARAM wParam)
  2713. {
  2714. if (! sendInputAttemptWhenModalMessage())
  2715. {
  2716. switch (wParam)
  2717. {
  2718. case HTBOTTOM:
  2719. case HTBOTTOMLEFT:
  2720. case HTBOTTOMRIGHT:
  2721. case HTGROWBOX:
  2722. case HTLEFT:
  2723. case HTRIGHT:
  2724. case HTTOP:
  2725. case HTTOPLEFT:
  2726. case HTTOPRIGHT:
  2727. if (isConstrainedNativeWindow())
  2728. {
  2729. constrainerIsResizing = true;
  2730. constrainer->resizeStart();
  2731. }
  2732. break;
  2733. default:
  2734. break;
  2735. }
  2736. }
  2737. }
  2738. void initialiseSysMenu (HMENU menu) const
  2739. {
  2740. if (! hasTitleBar())
  2741. {
  2742. if (isFullScreen())
  2743. {
  2744. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  2745. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  2746. }
  2747. else if (! isMinimised())
  2748. {
  2749. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  2750. }
  2751. }
  2752. }
  2753. void doSettingChange()
  2754. {
  2755. forceDisplayUpdate();
  2756. if (fullScreen && ! isMinimised())
  2757. setWindowPos (hwnd, ScalingHelpers::scaledScreenPosToUnscaled (component, Desktop::getInstance().getDisplays()
  2758. .findDisplayForRect (component.getScreenBounds()).userArea),
  2759. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  2760. }
  2761. static void forceDisplayUpdate()
  2762. {
  2763. const_cast<Displays&> (Desktop::getInstance().getDisplays()).refresh();
  2764. }
  2765. //==============================================================================
  2766. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2767. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  2768. {
  2769. modProvider = provider;
  2770. }
  2771. void removeModifierKeyProvider() override
  2772. {
  2773. modProvider = nullptr;
  2774. }
  2775. #endif
  2776. //==============================================================================
  2777. public:
  2778. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2779. {
  2780. // Ensure that non-client areas are scaled for per-monitor DPI awareness v1 - can't
  2781. // do this in peerWindowProc as we have no window at this point
  2782. if (message == WM_NCCREATE && enableNonClientDPIScaling != nullptr)
  2783. enableNonClientDPIScaling (h);
  2784. if (auto* peer = getOwnerOfWindow (h))
  2785. {
  2786. jassert (isValidPeer (peer));
  2787. return peer->peerWindowProc (h, message, wParam, lParam);
  2788. }
  2789. return DefWindowProcW (h, message, wParam, lParam);
  2790. }
  2791. private:
  2792. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  2793. {
  2794. auto& mm = *MessageManager::getInstance();
  2795. if (mm.currentThreadHasLockedMessageManager())
  2796. return callback (userData);
  2797. return mm.callFunctionOnMessageThread (callback, userData);
  2798. }
  2799. static POINT getPOINTFromLParam (LPARAM lParam) noexcept
  2800. {
  2801. return { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
  2802. }
  2803. Point<float> getPointFromLocalLParam (LPARAM lParam) noexcept
  2804. {
  2805. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  2806. if (isPerMonitorDPIAwareWindow (hwnd))
  2807. {
  2808. // LPARAM is relative to this window's top-left but may be on a different monitor so we need to calculate the
  2809. // physical screen position and then convert this to local logical coordinates
  2810. auto localPos = getPOINTFromLParam (lParam);
  2811. auto r = getWindowRect (hwnd);
  2812. return globalToLocal (Desktop::getInstance().getDisplays().physicalToLogical (pointFromPOINT ({ r.left + localPos.x + roundToInt (windowBorder.getLeft() * scaleFactor),
  2813. r.top + localPos.y + roundToInt (windowBorder.getTop() * scaleFactor) })).toFloat());
  2814. }
  2815. #endif
  2816. return { static_cast<float> (GET_X_LPARAM (lParam)), static_cast<float> (GET_Y_LPARAM (lParam)) };
  2817. }
  2818. Point<float> getCurrentMousePos() noexcept
  2819. {
  2820. return globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (GetMessagePos())), hwnd).toFloat());
  2821. }
  2822. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2823. {
  2824. switch (message)
  2825. {
  2826. //==============================================================================
  2827. case WM_NCHITTEST:
  2828. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2829. return HTTRANSPARENT;
  2830. if (! hasTitleBar())
  2831. return HTCLIENT;
  2832. break;
  2833. //==============================================================================
  2834. case WM_PAINT:
  2835. handlePaintMessage();
  2836. return 0;
  2837. case WM_NCPAINT:
  2838. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  2839. if (hasTitleBar())
  2840. break; // let the DefWindowProc handle drawing the frame.
  2841. return 0;
  2842. case WM_ERASEBKGND:
  2843. case WM_NCCALCSIZE:
  2844. if (hasTitleBar())
  2845. break;
  2846. return 1;
  2847. //==============================================================================
  2848. case WM_POINTERUPDATE:
  2849. if (handlePointerInput (wParam, lParam, false, false))
  2850. return 0;
  2851. break;
  2852. case WM_POINTERDOWN:
  2853. if (handlePointerInput (wParam, lParam, true, false))
  2854. return 0;
  2855. break;
  2856. case WM_POINTERUP:
  2857. if (handlePointerInput (wParam, lParam, false, true))
  2858. return 0;
  2859. break;
  2860. //==============================================================================
  2861. case WM_MOUSEMOVE: doMouseMove (getPointFromLocalLParam (lParam), false); return 0;
  2862. case WM_POINTERLEAVE:
  2863. case WM_MOUSELEAVE: doMouseExit(); return 0;
  2864. case WM_LBUTTONDOWN:
  2865. case WM_MBUTTONDOWN:
  2866. case WM_RBUTTONDOWN: doMouseDown (getPointFromLocalLParam (lParam), wParam); return 0;
  2867. case WM_LBUTTONUP:
  2868. case WM_MBUTTONUP:
  2869. case WM_RBUTTONUP: doMouseUp (getPointFromLocalLParam (lParam), wParam); return 0;
  2870. case WM_POINTERWHEEL:
  2871. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  2872. case WM_POINTERHWHEEL:
  2873. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  2874. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  2875. case WM_NCPOINTERUPDATE:
  2876. case WM_NCMOUSEMOVE:
  2877. if (hasTitleBar())
  2878. break;
  2879. return 0;
  2880. case WM_TOUCH:
  2881. if (getTouchInputInfo != nullptr)
  2882. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2883. break;
  2884. case 0x119: /* WM_GESTURE */
  2885. if (doGestureEvent (lParam))
  2886. return 0;
  2887. break;
  2888. //==============================================================================
  2889. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2890. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2891. case 0x2e0: /* WM_DPICHANGED */ return handleDPIChanging ((int) HIWORD (wParam), *(RECT*) lParam);
  2892. case WM_WINDOWPOSCHANGED:
  2893. {
  2894. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  2895. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  2896. startTimer (100);
  2897. else
  2898. if (handlePositionChanged())
  2899. return 0;
  2900. }
  2901. break;
  2902. //==============================================================================
  2903. case WM_KEYDOWN:
  2904. case WM_SYSKEYDOWN:
  2905. if (doKeyDown (wParam))
  2906. return 0;
  2907. forwardMessageToParent (message, wParam, lParam);
  2908. break;
  2909. case WM_KEYUP:
  2910. case WM_SYSKEYUP:
  2911. if (doKeyUp (wParam))
  2912. return 0;
  2913. forwardMessageToParent (message, wParam, lParam);
  2914. break;
  2915. case WM_CHAR:
  2916. if (doKeyChar ((int) wParam, lParam))
  2917. return 0;
  2918. forwardMessageToParent (message, wParam, lParam);
  2919. break;
  2920. case WM_APPCOMMAND:
  2921. if (doAppCommand (lParam))
  2922. return TRUE;
  2923. break;
  2924. case WM_MENUCHAR: // triggered when alt+something is pressed
  2925. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2926. //==============================================================================
  2927. case WM_SETFOCUS:
  2928. updateKeyModifiers();
  2929. handleFocusGain();
  2930. break;
  2931. case WM_KILLFOCUS:
  2932. if (hasCreatedCaret)
  2933. {
  2934. hasCreatedCaret = false;
  2935. DestroyCaret();
  2936. }
  2937. handleFocusLoss();
  2938. break;
  2939. case WM_ACTIVATEAPP:
  2940. // Windows does weird things to process priority when you swap apps,
  2941. // so this forces an update when the app is brought to the front
  2942. if (wParam != FALSE)
  2943. juce_repeatLastProcessPriority();
  2944. else
  2945. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2946. juce_checkCurrentlyFocusedTopLevelWindow();
  2947. modifiersAtLastCallback = -1;
  2948. return 0;
  2949. case WM_ACTIVATE:
  2950. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2951. {
  2952. handleAppActivation (wParam);
  2953. return 0;
  2954. }
  2955. break;
  2956. case WM_NCACTIVATE:
  2957. // while a temporary window is being shown, prevent Windows from deactivating the
  2958. // title bars of our main windows.
  2959. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2960. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2961. break;
  2962. case WM_POINTERACTIVATE:
  2963. case WM_MOUSEACTIVATE:
  2964. if (! component.getMouseClickGrabsKeyboardFocus())
  2965. return MA_NOACTIVATE;
  2966. break;
  2967. case WM_SHOWWINDOW:
  2968. if (wParam != 0)
  2969. {
  2970. component.setVisible (true);
  2971. handleBroughtToFront();
  2972. }
  2973. break;
  2974. case WM_CLOSE:
  2975. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2976. handleUserClosingWindow();
  2977. return 0;
  2978. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  2979. case WM_DESTROY:
  2980. getComponent().removeFromDesktop();
  2981. return 0;
  2982. #endif
  2983. case WM_QUERYENDSESSION:
  2984. if (auto* app = JUCEApplicationBase::getInstance())
  2985. {
  2986. app->systemRequestedQuit();
  2987. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2988. }
  2989. return TRUE;
  2990. case WM_POWERBROADCAST:
  2991. handlePowerBroadcast (wParam);
  2992. break;
  2993. case WM_SYNCPAINT:
  2994. return 0;
  2995. case WM_DISPLAYCHANGE:
  2996. InvalidateRect (h, nullptr, 0);
  2997. // intentional fall-through...
  2998. JUCE_FALLTHROUGH
  2999. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  3000. doSettingChange();
  3001. break;
  3002. case WM_INITMENU:
  3003. initialiseSysMenu ((HMENU) wParam);
  3004. break;
  3005. case WM_SYSCOMMAND:
  3006. switch (wParam & 0xfff0)
  3007. {
  3008. case SC_CLOSE:
  3009. if (sendInputAttemptWhenModalMessage())
  3010. return 0;
  3011. if (hasTitleBar())
  3012. {
  3013. PostMessage (h, WM_CLOSE, 0, 0);
  3014. return 0;
  3015. }
  3016. break;
  3017. case SC_KEYMENU:
  3018. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  3019. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  3020. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  3021. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  3022. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  3023. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  3024. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  3025. return 0;
  3026. #endif
  3027. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  3028. // situations that can arise if a modal loop is started from an alt-key keypress).
  3029. if (hasTitleBar() && h == GetCapture())
  3030. ReleaseCapture();
  3031. break;
  3032. case SC_MAXIMIZE:
  3033. if (! sendInputAttemptWhenModalMessage())
  3034. setFullScreen (true);
  3035. return 0;
  3036. case SC_MINIMIZE:
  3037. if (sendInputAttemptWhenModalMessage())
  3038. return 0;
  3039. if (! hasTitleBar())
  3040. {
  3041. setMinimised (true);
  3042. return 0;
  3043. }
  3044. break;
  3045. case SC_RESTORE:
  3046. if (sendInputAttemptWhenModalMessage())
  3047. return 0;
  3048. if (hasTitleBar())
  3049. {
  3050. if (isFullScreen())
  3051. {
  3052. setFullScreen (false);
  3053. return 0;
  3054. }
  3055. }
  3056. else
  3057. {
  3058. if (isMinimised())
  3059. setMinimised (false);
  3060. else if (isFullScreen())
  3061. setFullScreen (false);
  3062. return 0;
  3063. }
  3064. break;
  3065. }
  3066. break;
  3067. case WM_NCPOINTERDOWN:
  3068. case WM_NCLBUTTONDOWN:
  3069. handleLeftClickInNCArea (wParam);
  3070. break;
  3071. case WM_NCRBUTTONDOWN:
  3072. case WM_NCMBUTTONDOWN:
  3073. sendInputAttemptWhenModalMessage();
  3074. break;
  3075. case WM_IME_SETCONTEXT:
  3076. imeHandler.handleSetContext (h, wParam == TRUE);
  3077. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  3078. break;
  3079. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  3080. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  3081. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  3082. case WM_GETDLGCODE:
  3083. return DLGC_WANTALLKEYS;
  3084. default:
  3085. break;
  3086. }
  3087. return DefWindowProcW (h, message, wParam, lParam);
  3088. }
  3089. bool sendInputAttemptWhenModalMessage()
  3090. {
  3091. if (component.isCurrentlyBlockedByAnotherModalComponent())
  3092. {
  3093. if (Component* const current = Component::getCurrentlyModalComponent())
  3094. current->inputAttemptWhenModal();
  3095. return true;
  3096. }
  3097. return false;
  3098. }
  3099. //==============================================================================
  3100. struct IMEHandler
  3101. {
  3102. IMEHandler()
  3103. {
  3104. reset();
  3105. }
  3106. void handleSetContext (HWND hWnd, const bool windowIsActive)
  3107. {
  3108. if (compositionInProgress && ! windowIsActive)
  3109. {
  3110. compositionInProgress = false;
  3111. if (HIMC hImc = ImmGetContext (hWnd))
  3112. {
  3113. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  3114. ImmReleaseContext (hWnd, hImc);
  3115. }
  3116. }
  3117. }
  3118. void handleStartComposition (ComponentPeer& owner)
  3119. {
  3120. reset();
  3121. if (auto* target = owner.findCurrentTextInputTarget())
  3122. target->insertTextAtCaret (String());
  3123. }
  3124. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  3125. {
  3126. if (compositionInProgress)
  3127. {
  3128. // If this occurs, the user has cancelled the composition, so clear their changes..
  3129. if (auto* target = owner.findCurrentTextInputTarget())
  3130. {
  3131. target->setHighlightedRegion (compositionRange);
  3132. target->insertTextAtCaret (String());
  3133. compositionRange.setLength (0);
  3134. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  3135. target->setTemporaryUnderlining ({});
  3136. }
  3137. if (auto hImc = ImmGetContext (hWnd))
  3138. {
  3139. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  3140. ImmReleaseContext (hWnd, hImc);
  3141. }
  3142. }
  3143. reset();
  3144. }
  3145. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  3146. {
  3147. if (auto* target = owner.findCurrentTextInputTarget())
  3148. {
  3149. if (auto hImc = ImmGetContext (hWnd))
  3150. {
  3151. if (compositionRange.getStart() < 0)
  3152. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  3153. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  3154. {
  3155. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  3156. Range<int>::emptyRange (-1));
  3157. reset();
  3158. target->setTemporaryUnderlining ({});
  3159. }
  3160. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  3161. {
  3162. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  3163. getCompositionSelection (hImc, lParam));
  3164. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  3165. compositionInProgress = true;
  3166. }
  3167. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  3168. ImmReleaseContext (hWnd, hImc);
  3169. }
  3170. }
  3171. }
  3172. private:
  3173. //==============================================================================
  3174. Range<int> compositionRange; // The range being modified in the TextInputTarget
  3175. bool compositionInProgress;
  3176. //==============================================================================
  3177. void reset()
  3178. {
  3179. compositionRange = Range<int>::emptyRange (-1);
  3180. compositionInProgress = false;
  3181. }
  3182. String getCompositionString (HIMC hImc, const DWORD type) const
  3183. {
  3184. jassert (hImc != nullptr);
  3185. const auto stringSizeBytes = ImmGetCompositionString (hImc, type, nullptr, 0);
  3186. if (stringSizeBytes > 0)
  3187. {
  3188. HeapBlock<TCHAR> buffer;
  3189. buffer.calloc ((size_t) stringSizeBytes / sizeof (TCHAR) + 1);
  3190. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  3191. return String (buffer.get());
  3192. }
  3193. return {};
  3194. }
  3195. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  3196. {
  3197. jassert (hImc != nullptr);
  3198. if ((lParam & CS_NOMOVECARET) != 0)
  3199. return compositionRange.getStart();
  3200. if ((lParam & GCS_CURSORPOS) != 0)
  3201. {
  3202. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, nullptr, 0);
  3203. return compositionRange.getStart() + jmax (0, localCaretPos);
  3204. }
  3205. return compositionRange.getStart() + currentIMEString.length();
  3206. }
  3207. // Get selected/highlighted range while doing composition:
  3208. // returned range is relative to beginning of TextInputTarget, not composition string
  3209. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  3210. {
  3211. jassert (hImc != nullptr);
  3212. int selectionStart = 0;
  3213. int selectionEnd = 0;
  3214. if ((lParam & GCS_COMPATTR) != 0)
  3215. {
  3216. // Get size of attributes array:
  3217. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, nullptr, 0);
  3218. if (attributeSizeBytes > 0)
  3219. {
  3220. // Get attributes (8 bit flag per character):
  3221. HeapBlock<char> attributes (attributeSizeBytes);
  3222. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  3223. selectionStart = 0;
  3224. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  3225. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  3226. break;
  3227. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  3228. if (attributes[selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  3229. break;
  3230. }
  3231. }
  3232. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  3233. }
  3234. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  3235. {
  3236. if (compositionInProgress)
  3237. target->setHighlightedRegion (compositionRange);
  3238. target->insertTextAtCaret (newContent);
  3239. compositionRange.setLength (newContent.length());
  3240. if (newSelection.getStart() < 0)
  3241. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  3242. target->setHighlightedRegion (newSelection);
  3243. }
  3244. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  3245. {
  3246. Array<Range<int>> result;
  3247. if (hImc != nullptr && (lParam & GCS_COMPCLAUSE) != 0)
  3248. {
  3249. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, nullptr, 0);
  3250. if (clauseDataSizeBytes > 0)
  3251. {
  3252. const auto numItems = (size_t) clauseDataSizeBytes / sizeof (uint32);
  3253. HeapBlock<uint32> clauseData (numItems);
  3254. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  3255. for (size_t i = 0; i + 1 < numItems; ++i)
  3256. result.add (Range<int> ((int) clauseData[i], (int) clauseData[i + 1]) + compositionRange.getStart());
  3257. }
  3258. }
  3259. return result;
  3260. }
  3261. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  3262. {
  3263. if (auto* targetComp = dynamic_cast<Component*> (target))
  3264. {
  3265. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  3266. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  3267. ImmSetCandidateWindow (hImc, &pos);
  3268. }
  3269. }
  3270. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  3271. };
  3272. void timerCallback() override
  3273. {
  3274. handlePositionChanged();
  3275. stopTimer();
  3276. }
  3277. IMEHandler imeHandler;
  3278. //==============================================================================
  3279. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  3280. };
  3281. MultiTouchMapper<DWORD> HWNDComponentPeer::currentTouches;
  3282. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  3283. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  3284. {
  3285. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  3286. }
  3287. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  3288. {
  3289. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  3290. (HWND) parentHWND, true);
  3291. }
  3292. JUCE_IMPLEMENT_SINGLETON (HWNDComponentPeer::WindowClassHolder)
  3293. //==============================================================================
  3294. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  3295. {
  3296. auto k = (SHORT) keyCode;
  3297. if ((keyCode & extendedKeyModifier) == 0)
  3298. {
  3299. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  3300. k += (SHORT) 'A' - (SHORT) 'a';
  3301. // Only translate if extendedKeyModifier flag is not set
  3302. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  3303. (SHORT) '+', VK_OEM_PLUS,
  3304. (SHORT) '-', VK_OEM_MINUS,
  3305. (SHORT) '.', VK_OEM_PERIOD,
  3306. (SHORT) ';', VK_OEM_1,
  3307. (SHORT) ':', VK_OEM_1,
  3308. (SHORT) '/', VK_OEM_2,
  3309. (SHORT) '?', VK_OEM_2,
  3310. (SHORT) '[', VK_OEM_4,
  3311. (SHORT) ']', VK_OEM_6 };
  3312. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  3313. if (k == translatedValues[i])
  3314. k = translatedValues[i + 1];
  3315. }
  3316. return HWNDComponentPeer::isKeyDown (k);
  3317. }
  3318. // (This internal function is used by the plugin client module)
  3319. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  3320. //==============================================================================
  3321. bool JUCE_CALLTYPE Process::isForegroundProcess()
  3322. {
  3323. if (auto fg = GetForegroundWindow())
  3324. {
  3325. DWORD processID = 0;
  3326. GetWindowThreadProcessId (fg, &processID);
  3327. return processID == GetCurrentProcessId();
  3328. }
  3329. return true;
  3330. }
  3331. // N/A on Windows as far as I know.
  3332. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  3333. void JUCE_CALLTYPE Process::hide() {}
  3334. //==============================================================================
  3335. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  3336. {
  3337. if (IsWindowVisible (hwnd))
  3338. {
  3339. DWORD processID = 0;
  3340. GetWindowThreadProcessId (hwnd, &processID);
  3341. if (processID == GetCurrentProcessId())
  3342. {
  3343. WINDOWINFO info;
  3344. if (GetWindowInfo (hwnd, &info)
  3345. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  3346. {
  3347. *reinterpret_cast<bool*> (lParam) = true;
  3348. return FALSE;
  3349. }
  3350. }
  3351. }
  3352. return TRUE;
  3353. }
  3354. bool juce_areThereAnyAlwaysOnTopWindows()
  3355. {
  3356. bool anyAlwaysOnTopFound = false;
  3357. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  3358. return anyAlwaysOnTopFound;
  3359. }
  3360. //==============================================================================
  3361. class WindowsMessageBox : public AsyncUpdater
  3362. {
  3363. public:
  3364. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  3365. const String& boxTitle, const String& m,
  3366. Component* associatedComponent, UINT extraFlags,
  3367. ModalComponentManager::Callback* cb, const bool runAsync)
  3368. : flags (extraFlags | getMessageBoxFlags (iconType)),
  3369. owner (getWindowForMessageBox (associatedComponent)),
  3370. title (boxTitle), message (m), callback (cb)
  3371. {
  3372. if (runAsync)
  3373. triggerAsyncUpdate();
  3374. }
  3375. int getResult() const
  3376. {
  3377. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  3378. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO && (flags & 1) != 0 ? 2 : 0);
  3379. }
  3380. void handleAsyncUpdate() override
  3381. {
  3382. const int result = getResult();
  3383. if (callback != nullptr)
  3384. callback->modalStateFinished (result);
  3385. delete this;
  3386. }
  3387. private:
  3388. UINT flags;
  3389. HWND owner;
  3390. String title, message;
  3391. std::unique_ptr<ModalComponentManager::Callback> callback;
  3392. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  3393. {
  3394. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  3395. // this window can get lost behind JUCE windows which are set to be alwaysOnTop
  3396. // so if there are any set it to be topmost
  3397. if (juce_areThereAnyAlwaysOnTopWindows())
  3398. flags |= MB_TOPMOST;
  3399. switch (iconType)
  3400. {
  3401. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  3402. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  3403. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  3404. case AlertWindow::NoIcon: JUCE_FALLTHROUGH
  3405. default: break;
  3406. }
  3407. return flags;
  3408. }
  3409. static HWND getWindowForMessageBox (Component* associatedComponent)
  3410. {
  3411. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : nullptr;
  3412. }
  3413. };
  3414. #if JUCE_MODAL_LOOPS_PERMITTED
  3415. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3416. const String& title, const String& message,
  3417. Component* associatedComponent)
  3418. {
  3419. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, nullptr, false);
  3420. (void) box.getResult();
  3421. }
  3422. #endif
  3423. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3424. const String& title, const String& message,
  3425. Component* associatedComponent,
  3426. ModalComponentManager::Callback* callback)
  3427. {
  3428. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  3429. }
  3430. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3431. const String& title, const String& message,
  3432. Component* associatedComponent,
  3433. ModalComponentManager::Callback* callback)
  3434. {
  3435. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3436. MB_OKCANCEL, callback, callback != nullptr));
  3437. if (callback == nullptr)
  3438. return mb->getResult() != 0;
  3439. mb.release();
  3440. return false;
  3441. }
  3442. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3443. const String& title, const String& message,
  3444. Component* associatedComponent,
  3445. ModalComponentManager::Callback* callback)
  3446. {
  3447. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3448. MB_YESNOCANCEL, callback, callback != nullptr));
  3449. if (callback == nullptr)
  3450. return mb->getResult();
  3451. mb.release();
  3452. return 0;
  3453. }
  3454. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3455. const String& title, const String& message,
  3456. Component* associatedComponent,
  3457. ModalComponentManager::Callback* callback)
  3458. {
  3459. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3460. MB_YESNO, callback, callback != nullptr));
  3461. if (callback == nullptr)
  3462. return mb->getResult();
  3463. mb.release();
  3464. return 0;
  3465. }
  3466. //==============================================================================
  3467. bool MouseInputSource::SourceList::addSource()
  3468. {
  3469. auto numSources = sources.size();
  3470. if (numSources == 0 || canUseMultiTouch())
  3471. {
  3472. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  3473. : MouseInputSource::InputSourceType::touch);
  3474. return true;
  3475. }
  3476. return false;
  3477. }
  3478. bool MouseInputSource::SourceList::canUseTouch()
  3479. {
  3480. return canUseMultiTouch();
  3481. }
  3482. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3483. {
  3484. POINT mousePos;
  3485. GetCursorPos (&mousePos);
  3486. auto p = pointFromPOINT (mousePos);
  3487. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3488. if (isPerMonitorDPIAwareThread())
  3489. p = Desktop::getInstance().getDisplays().physicalToLogical (p);
  3490. #endif
  3491. return p.toFloat();
  3492. }
  3493. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3494. {
  3495. auto newPositionInt = newPosition.roundToInt();
  3496. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3497. if (isPerMonitorDPIAwareThread())
  3498. newPositionInt = Desktop::getInstance().getDisplays().logicalToPhysical (newPositionInt);
  3499. #endif
  3500. auto point = POINTFromPoint (newPositionInt);
  3501. SetCursorPos (point.x, point.y);
  3502. }
  3503. //==============================================================================
  3504. class ScreenSaverDefeater : public Timer
  3505. {
  3506. public:
  3507. ScreenSaverDefeater()
  3508. {
  3509. startTimer (10000);
  3510. timerCallback();
  3511. }
  3512. void timerCallback() override
  3513. {
  3514. if (Process::isForegroundProcess())
  3515. {
  3516. INPUT input = {};
  3517. input.type = INPUT_MOUSE;
  3518. input.mi.mouseData = MOUSEEVENTF_MOVE;
  3519. SendInput (1, &input, sizeof (INPUT));
  3520. }
  3521. }
  3522. };
  3523. static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
  3524. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3525. {
  3526. if (isEnabled)
  3527. screenSaverDefeater = nullptr;
  3528. else if (screenSaverDefeater == nullptr)
  3529. screenSaverDefeater.reset (new ScreenSaverDefeater());
  3530. }
  3531. bool Desktop::isScreenSaverEnabled()
  3532. {
  3533. return screenSaverDefeater == nullptr;
  3534. }
  3535. //==============================================================================
  3536. void LookAndFeel::playAlertSound()
  3537. {
  3538. MessageBeep (MB_OK);
  3539. }
  3540. //==============================================================================
  3541. void SystemClipboard::copyTextToClipboard (const String& text)
  3542. {
  3543. if (OpenClipboard (nullptr) != 0)
  3544. {
  3545. if (EmptyClipboard() != 0)
  3546. {
  3547. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  3548. if (bytesNeeded > 0)
  3549. {
  3550. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  3551. {
  3552. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  3553. {
  3554. text.copyToUTF16 (data, bytesNeeded);
  3555. GlobalUnlock (bufH);
  3556. SetClipboardData (CF_UNICODETEXT, bufH);
  3557. }
  3558. }
  3559. }
  3560. }
  3561. CloseClipboard();
  3562. }
  3563. }
  3564. String SystemClipboard::getTextFromClipboard()
  3565. {
  3566. String result;
  3567. if (OpenClipboard (nullptr) != 0)
  3568. {
  3569. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  3570. {
  3571. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  3572. {
  3573. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  3574. GlobalUnlock (bufH);
  3575. }
  3576. }
  3577. CloseClipboard();
  3578. }
  3579. return result;
  3580. }
  3581. //==============================================================================
  3582. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  3583. {
  3584. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  3585. tlw->setUsingNativeTitleBar (! enableOrDisable);
  3586. if (enableOrDisable)
  3587. kioskModeComp->setBounds (getDisplays().findDisplayForRect (kioskModeComp->getScreenBounds()).totalArea);
  3588. }
  3589. void Desktop::allowedOrientationsChanged() {}
  3590. //==============================================================================
  3591. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd)
  3592. {
  3593. Array<const Displays::Display*> candidateDisplays;
  3594. double scaleToLookFor = -1.0;
  3595. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3596. scaleToLookFor = peer->getPlatformScaleFactor();
  3597. else
  3598. scaleToLookFor = getScaleFactorForWindow (hwnd);
  3599. auto globalScale = Desktop::getInstance().getGlobalScaleFactor();
  3600. for (auto& d : Desktop::getInstance().getDisplays().displays)
  3601. if (approximatelyEqual (d.scale / globalScale, scaleToLookFor))
  3602. candidateDisplays.add (&d);
  3603. if (candidateDisplays.size() > 0)
  3604. {
  3605. if (candidateDisplays.size() == 1)
  3606. return candidateDisplays[0];
  3607. Rectangle<int> bounds;
  3608. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3609. bounds = peer->getComponent().getTopLevelComponent()->getBounds();
  3610. else
  3611. bounds = Desktop::getInstance().getDisplays().physicalToLogical (rectangleFromRECT (getWindowRect (hwnd)));
  3612. const Displays::Display* retVal = nullptr;
  3613. int maxArea = -1;
  3614. for (auto* d : candidateDisplays)
  3615. {
  3616. auto intersection = d->totalArea.getIntersection (bounds);
  3617. auto area = intersection.getWidth() * intersection.getHeight();
  3618. if (area > maxArea)
  3619. {
  3620. maxArea = area;
  3621. retVal = d;
  3622. }
  3623. }
  3624. if (retVal != nullptr)
  3625. return retVal;
  3626. }
  3627. return &Desktop::getInstance().getDisplays().getMainDisplay();
  3628. }
  3629. //==============================================================================
  3630. struct MonitorInfo
  3631. {
  3632. MonitorInfo (bool main, RECT rect, double d) noexcept
  3633. : isMain (main), bounds (rect), dpi (d) {}
  3634. bool isMain;
  3635. RECT bounds;
  3636. double dpi;
  3637. };
  3638. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  3639. {
  3640. MONITORINFO info = {};
  3641. info.cbSize = sizeof (info);
  3642. GetMonitorInfo (hm, &info);
  3643. auto isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  3644. auto dpi = 0.0;
  3645. if (getDPIForMonitor != nullptr)
  3646. {
  3647. UINT dpiX = 0, dpiY = 0;
  3648. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  3649. dpi = (dpiX + dpiY) / 2.0;
  3650. }
  3651. ((Array<MonitorInfo>*) userInfo)->add ({ isMain, *r, dpi });
  3652. return TRUE;
  3653. }
  3654. void Displays::findDisplays (float masterScale)
  3655. {
  3656. setDPIAwareness();
  3657. Array<MonitorInfo> monitors;
  3658. EnumDisplayMonitors (nullptr, nullptr, &enumMonitorsProc, (LPARAM) &monitors);
  3659. auto globalDPI = getGlobalDPI();
  3660. if (monitors.size() == 0)
  3661. monitors.add ({ true, getWindowRect (GetDesktopWindow()), globalDPI });
  3662. // make sure the first in the list is the main monitor
  3663. for (int i = 1; i < monitors.size(); ++i)
  3664. if (monitors.getReference (i).isMain)
  3665. monitors.swap (i, 0);
  3666. for (auto& monitor : monitors)
  3667. {
  3668. Display d;
  3669. d.isMain = monitor.isMain;
  3670. d.dpi = monitor.dpi;
  3671. if (d.dpi == 0)
  3672. {
  3673. d.dpi = globalDPI;
  3674. d.scale = masterScale;
  3675. }
  3676. else
  3677. {
  3678. d.scale = (d.dpi / USER_DEFAULT_SCREEN_DPI) * (masterScale / Desktop::getDefaultMasterScale());
  3679. }
  3680. d.userArea = d.totalArea = Rectangle<int>::leftTopRightBottom (monitor.bounds.left, monitor.bounds.top,
  3681. monitor.bounds.right, monitor.bounds.bottom);
  3682. if (d.isMain)
  3683. {
  3684. RECT workArea;
  3685. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  3686. d.userArea = d.userArea.getIntersection (Rectangle<int>::leftTopRightBottom (workArea.left, workArea.top,
  3687. workArea.right, workArea.bottom));
  3688. }
  3689. displays.add (d);
  3690. }
  3691. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3692. updateToLogical();
  3693. #else
  3694. for (auto& d : displays)
  3695. {
  3696. d.totalArea /= masterScale;
  3697. d.userArea /= masterScale;
  3698. }
  3699. #endif
  3700. }
  3701. //==============================================================================
  3702. static HICON extractFileHICON (const File& file)
  3703. {
  3704. WORD iconNum = 0;
  3705. WCHAR name[MAX_PATH * 2];
  3706. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  3707. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  3708. name, &iconNum);
  3709. }
  3710. Image juce_createIconForFile (const File& file)
  3711. {
  3712. Image image;
  3713. if (auto icon = extractFileHICON (file))
  3714. {
  3715. image = IconConverters::createImageFromHICON (icon);
  3716. DestroyIcon (icon);
  3717. }
  3718. return image;
  3719. }
  3720. //==============================================================================
  3721. void* CustomMouseCursorInfo::create() const
  3722. {
  3723. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  3724. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  3725. Image im (image);
  3726. int hotspotX = hotspot.x;
  3727. int hotspotY = hotspot.y;
  3728. if (im.getWidth() > maxW || im.getHeight() > maxH)
  3729. {
  3730. im = im.rescaled (maxW, maxH);
  3731. hotspotX = (hotspotX * maxW) / juce::jmax (1, image.getWidth());
  3732. hotspotY = (hotspotY * maxH) / juce::jmax (1, image.getHeight());
  3733. }
  3734. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  3735. }
  3736. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool isStandard)
  3737. {
  3738. if (cursorHandle != nullptr && ! isStandard)
  3739. DestroyCursor ((HCURSOR) cursorHandle);
  3740. }
  3741. enum
  3742. {
  3743. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  3744. };
  3745. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  3746. {
  3747. LPCTSTR cursorName = IDC_ARROW;
  3748. switch (type)
  3749. {
  3750. case NormalCursor:
  3751. case ParentCursor: break;
  3752. case NoCursor: return (void*) hiddenMouseCursorHandle;
  3753. case WaitCursor: cursorName = IDC_WAIT; break;
  3754. case IBeamCursor: cursorName = IDC_IBEAM; break;
  3755. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  3756. case CrosshairCursor: cursorName = IDC_CROSS; break;
  3757. case LeftRightResizeCursor:
  3758. case LeftEdgeResizeCursor:
  3759. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  3760. case UpDownResizeCursor:
  3761. case TopEdgeResizeCursor:
  3762. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  3763. case TopLeftCornerResizeCursor:
  3764. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  3765. case TopRightCornerResizeCursor:
  3766. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  3767. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  3768. case DraggingHandCursor:
  3769. {
  3770. static void* dragHandCursor = nullptr;
  3771. if (dragHandCursor == nullptr)
  3772. {
  3773. static const unsigned char dragHandData[] =
  3774. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  3775. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,132,117,151,116,132,146,248,60,209,138,
  3776. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  3777. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), { 8, 7 }).create();
  3778. }
  3779. return dragHandCursor;
  3780. }
  3781. case CopyingCursor:
  3782. {
  3783. static void* copyCursor = nullptr;
  3784. if (copyCursor == nullptr)
  3785. {
  3786. static unsigned char copyCursorData[] = {
  3787. 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  3788. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,78,133,218,215,137,31,82,154,100,200,86,91,202,142,
  3789. 12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,252,114,147,74,83,
  3790. 5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0
  3791. };
  3792. const int copyCursorSize = 119;
  3793. copyCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), { 1, 3 }).create();
  3794. }
  3795. return copyCursor;
  3796. }
  3797. case NumStandardCursorTypes: JUCE_FALLTHROUGH
  3798. default:
  3799. jassertfalse; break;
  3800. }
  3801. if (auto cursorH = LoadCursor (nullptr, cursorName))
  3802. return cursorH;
  3803. return LoadCursor (nullptr, IDC_ARROW);
  3804. }
  3805. //==============================================================================
  3806. void MouseCursor::showInWindow (ComponentPeer*) const
  3807. {
  3808. auto c = (HCURSOR) getHandle();
  3809. if (c == nullptr)
  3810. c = LoadCursor (nullptr, IDC_ARROW);
  3811. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  3812. c = nullptr;
  3813. SetCursor (c);
  3814. }
  3815. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  3816. } // namespace juce