juce_win32_Windowing.cpp 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  18. // these are in the windows SDK, but need to be repeated here for GCC..
  19. #ifndef GET_APPCOMMAND_LPARAM
  20. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  21. #define FAPPCOMMAND_MASK 0xF000
  22. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  23. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  24. #define APPCOMMAND_MEDIA_STOP 13
  25. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  26. #endif
  27. #ifndef WM_APPCOMMAND
  28. #define WM_APPCOMMAND 0x0319
  29. #endif
  30. extern void juce_repeatLastProcessPriority();
  31. extern void juce_checkCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  32. extern bool juce_isRunningInWine();
  33. typedef bool (*CheckEventBlockedByModalComps) (const MSG&);
  34. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  35. static bool shouldDeactivateTitleBar = true;
  36. extern void* getUser32Function (const char*);
  37. //==============================================================================
  38. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  39. static UpdateLayeredWinFunc updateLayeredWindow = nullptr;
  40. bool Desktop::canUseSemiTransparentWindows() noexcept
  41. {
  42. if (updateLayeredWindow == nullptr && ! juce_isRunningInWine())
  43. updateLayeredWindow = (UpdateLayeredWinFunc) getUser32Function ("UpdateLayeredWindow");
  44. return updateLayeredWindow != nullptr;
  45. }
  46. //==============================================================================
  47. #ifndef WM_TOUCH
  48. #define WM_TOUCH 0x0240
  49. #define TOUCH_COORD_TO_PIXEL(l) ((l) / 100)
  50. #define TOUCHEVENTF_MOVE 0x0001
  51. #define TOUCHEVENTF_DOWN 0x0002
  52. #define TOUCHEVENTF_UP 0x0004
  53. #define TOUCHEVENTF_PRIMARY 0x0010
  54. DECLARE_HANDLE (HTOUCHINPUT);
  55. DECLARE_HANDLE (HGESTUREINFO);
  56. struct TOUCHINPUT
  57. {
  58. LONG x;
  59. LONG y;
  60. HANDLE hSource;
  61. DWORD dwID;
  62. DWORD dwFlags;
  63. DWORD dwMask;
  64. DWORD dwTime;
  65. ULONG_PTR dwExtraInfo;
  66. DWORD cxContact;
  67. DWORD cyContact;
  68. };
  69. struct GESTUREINFO
  70. {
  71. UINT cbSize;
  72. DWORD dwFlags;
  73. DWORD dwID;
  74. HWND hwndTarget;
  75. POINTS ptsLocation;
  76. DWORD dwInstanceID;
  77. DWORD dwSequenceID;
  78. ULONGLONG ullArguments;
  79. UINT cbExtraArgs;
  80. };
  81. #endif
  82. #ifndef MONITOR_DPI_TYPE
  83. enum Monitor_DPI_Type
  84. {
  85. MDT_Effective_DPI = 0,
  86. MDT_Angular_DPI = 1,
  87. MDT_Raw_DPI = 2,
  88. MDT_Default = MDT_Effective_DPI
  89. };
  90. enum Process_DPI_Awareness
  91. {
  92. Process_DPI_Unaware = 0,
  93. Process_System_DPI_Aware = 1,
  94. Process_Per_Monitor_DPI_Aware = 2
  95. };
  96. #endif
  97. typedef BOOL (WINAPI* RegisterTouchWindowFunc) (HWND, ULONG);
  98. typedef BOOL (WINAPI* GetTouchInputInfoFunc) (HTOUCHINPUT, UINT, TOUCHINPUT*, int);
  99. typedef BOOL (WINAPI* CloseTouchInputHandleFunc) (HTOUCHINPUT);
  100. typedef BOOL (WINAPI* GetGestureInfoFunc) (HGESTUREINFO, GESTUREINFO*);
  101. typedef BOOL (WINAPI* SetProcessDPIAwareFunc)();
  102. typedef BOOL (WINAPI* SetProcessDPIAwarenessFunc) (Process_DPI_Awareness);
  103. typedef HRESULT (WINAPI* GetDPIForMonitorFunc) (HMONITOR, Monitor_DPI_Type, UINT*, UINT*);
  104. static RegisterTouchWindowFunc registerTouchWindow = nullptr;
  105. static GetTouchInputInfoFunc getTouchInputInfo = nullptr;
  106. static CloseTouchInputHandleFunc closeTouchInputHandle = nullptr;
  107. static GetGestureInfoFunc getGestureInfo = nullptr;
  108. static SetProcessDPIAwareFunc setProcessDPIAware = nullptr;
  109. static SetProcessDPIAwarenessFunc setProcessDPIAwareness = nullptr;
  110. static GetDPIForMonitorFunc getDPIForMonitor = nullptr;
  111. static bool hasCheckedForMultiTouch = false;
  112. static bool canUseMultiTouch()
  113. {
  114. if (registerTouchWindow == nullptr && ! hasCheckedForMultiTouch)
  115. {
  116. hasCheckedForMultiTouch = true;
  117. registerTouchWindow = (RegisterTouchWindowFunc) getUser32Function ("RegisterTouchWindow");
  118. getTouchInputInfo = (GetTouchInputInfoFunc) getUser32Function ("GetTouchInputInfo");
  119. closeTouchInputHandle = (CloseTouchInputHandleFunc) getUser32Function ("CloseTouchInputHandle");
  120. getGestureInfo = (GetGestureInfoFunc) getUser32Function ("GetGestureInfo");
  121. }
  122. return registerTouchWindow != nullptr;
  123. }
  124. static Rectangle<int> rectangleFromRECT (const RECT& r) noexcept
  125. {
  126. return Rectangle<int>::leftTopRightBottom ((int) r.left, (int) r.top, (int) r.right, (int) r.bottom);
  127. }
  128. static void setWindowPos (HWND hwnd, Rectangle<int> bounds, UINT flags)
  129. {
  130. SetWindowPos (hwnd, 0, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), flags);
  131. }
  132. static RECT getWindowRect (HWND hwnd)
  133. {
  134. RECT r;
  135. GetWindowRect (hwnd, &r);
  136. return r;
  137. }
  138. static void setWindowZOrder (HWND hwnd, HWND insertAfter)
  139. {
  140. SetWindowPos (hwnd, insertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  141. }
  142. //==============================================================================
  143. static void setDPIAwareness()
  144. {
  145. #if ! JUCE_DISABLE_WIN32_DPI_AWARENESS
  146. if (JUCEApplicationBase::isStandaloneApp())
  147. {
  148. if (setProcessDPIAwareness == nullptr)
  149. {
  150. HMODULE shcoreModule = GetModuleHandleA ("SHCore.dll");
  151. if (shcoreModule != 0)
  152. {
  153. setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
  154. getDPIForMonitor = (GetDPIForMonitorFunc) GetProcAddress (shcoreModule, "GetDpiForMonitor");
  155. if (setProcessDPIAwareness != nullptr && getDPIForMonitor != nullptr
  156. // && SUCCEEDED (setProcessDPIAwareness (Process_Per_Monitor_DPI_Aware)))
  157. && SUCCEEDED (setProcessDPIAwareness (Process_System_DPI_Aware))) // (keep using this mode temporarily..)
  158. return;
  159. }
  160. if (setProcessDPIAware == nullptr)
  161. {
  162. setProcessDPIAware = (SetProcessDPIAwareFunc) getUser32Function ("SetProcessDPIAware");
  163. if (setProcessDPIAware != nullptr)
  164. setProcessDPIAware();
  165. }
  166. }
  167. }
  168. #endif
  169. }
  170. static double getGlobalDPI()
  171. {
  172. setDPIAwareness();
  173. HDC dc = GetDC (0);
  174. const double dpi = (GetDeviceCaps (dc, LOGPIXELSX)
  175. + GetDeviceCaps (dc, LOGPIXELSY)) / 2.0;
  176. ReleaseDC (0, dc);
  177. return dpi;
  178. }
  179. double Desktop::getDefaultMasterScale()
  180. {
  181. return JUCEApplicationBase::isStandaloneApp() ? getGlobalDPI() / 96.0
  182. : 1.0;
  183. }
  184. //==============================================================================
  185. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  186. {
  187. return upright;
  188. }
  189. int64 getMouseEventTime()
  190. {
  191. static int64 eventTimeOffset = 0;
  192. static LONG lastMessageTime = 0;
  193. const LONG thisMessageTime = GetMessageTime();
  194. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  195. {
  196. lastMessageTime = thisMessageTime;
  197. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  198. }
  199. return eventTimeOffset + thisMessageTime;
  200. }
  201. //==============================================================================
  202. const int extendedKeyModifier = 0x10000;
  203. const int KeyPress::spaceKey = VK_SPACE;
  204. const int KeyPress::returnKey = VK_RETURN;
  205. const int KeyPress::escapeKey = VK_ESCAPE;
  206. const int KeyPress::backspaceKey = VK_BACK;
  207. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  208. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  209. const int KeyPress::tabKey = VK_TAB;
  210. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  211. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  212. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  213. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  214. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  215. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  216. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  217. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  218. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  219. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  220. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  221. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  222. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  223. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  224. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  225. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  226. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  227. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  228. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  229. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  230. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  231. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  232. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  233. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  234. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  235. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  236. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  237. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  238. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  239. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  240. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  241. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  242. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  243. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  244. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  245. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  246. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  247. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  248. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  249. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  250. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  251. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  252. const int KeyPress::playKey = 0x30000;
  253. const int KeyPress::stopKey = 0x30001;
  254. const int KeyPress::fastForwardKey = 0x30002;
  255. const int KeyPress::rewindKey = 0x30003;
  256. //==============================================================================
  257. class WindowsBitmapImage : public ImagePixelData
  258. {
  259. public:
  260. WindowsBitmapImage (const Image::PixelFormat format,
  261. const int w, const int h, const bool clearImage)
  262. : ImagePixelData (format, w, h)
  263. {
  264. jassert (format == Image::RGB || format == Image::ARGB);
  265. static bool alwaysUse32Bits = isGraphicsCard32Bit(); // NB: for 32-bit cards, it's faster to use a 32-bit image.
  266. pixelStride = (alwaysUse32Bits || format == Image::ARGB) ? 4 : 3;
  267. lineStride = -((w * pixelStride + 3) & ~3);
  268. zerostruct (bitmapInfo);
  269. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  270. bitmapInfo.bV4Width = w;
  271. bitmapInfo.bV4Height = h;
  272. bitmapInfo.bV4Planes = 1;
  273. bitmapInfo.bV4CSType = 1;
  274. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  275. if (format == Image::ARGB)
  276. {
  277. bitmapInfo.bV4AlphaMask = 0xff000000;
  278. bitmapInfo.bV4RedMask = 0xff0000;
  279. bitmapInfo.bV4GreenMask = 0xff00;
  280. bitmapInfo.bV4BlueMask = 0xff;
  281. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  282. }
  283. else
  284. {
  285. bitmapInfo.bV4V4Compression = BI_RGB;
  286. }
  287. HDC dc = GetDC (0);
  288. hdc = CreateCompatibleDC (dc);
  289. ReleaseDC (0, dc);
  290. SetMapMode (hdc, MM_TEXT);
  291. hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
  292. (void**) &bitmapData, 0, 0);
  293. previousBitmap = SelectObject (hdc, hBitmap);
  294. if (format == Image::ARGB && clearImage)
  295. zeromem (bitmapData, (size_t) std::abs (h * lineStride));
  296. imageData = bitmapData - (lineStride * (h - 1));
  297. }
  298. ~WindowsBitmapImage()
  299. {
  300. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  301. DeleteDC (hdc);
  302. DeleteObject (hBitmap);
  303. }
  304. ImageType* createType() const override { return new NativeImageType(); }
  305. LowLevelGraphicsContext* createLowLevelContext() override
  306. {
  307. sendDataChangeMessage();
  308. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  309. }
  310. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  311. {
  312. bitmap.data = imageData + x * pixelStride + y * lineStride;
  313. bitmap.pixelFormat = pixelFormat;
  314. bitmap.lineStride = lineStride;
  315. bitmap.pixelStride = pixelStride;
  316. if (mode != Image::BitmapData::readOnly)
  317. sendDataChangeMessage();
  318. }
  319. ImagePixelData* clone() override
  320. {
  321. WindowsBitmapImage* im = new WindowsBitmapImage (pixelFormat, width, height, false);
  322. for (int i = 0; i < height; ++i)
  323. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  324. return im;
  325. }
  326. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  327. const int x, const int y,
  328. const uint8 updateLayeredWindowAlpha) noexcept
  329. {
  330. SetMapMode (dc, MM_TEXT);
  331. if (transparent)
  332. {
  333. RECT windowBounds = getWindowRect (hwnd);
  334. POINT p = { -x, -y };
  335. POINT pos = { windowBounds.left, windowBounds.top };
  336. SIZE size = { windowBounds.right - windowBounds.left,
  337. windowBounds.bottom - windowBounds.top };
  338. BLENDFUNCTION bf;
  339. bf.AlphaFormat = 1 /*AC_SRC_ALPHA*/;
  340. bf.BlendFlags = 0;
  341. bf.BlendOp = AC_SRC_OVER;
  342. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  343. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, 2 /*ULW_ALPHA*/);
  344. }
  345. else
  346. {
  347. StretchDIBits (dc,
  348. x, y, width, height,
  349. 0, 0, width, height,
  350. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  351. DIB_RGB_COLORS, SRCCOPY);
  352. }
  353. }
  354. HBITMAP hBitmap;
  355. HGDIOBJ previousBitmap;
  356. BITMAPV4HEADER bitmapInfo;
  357. HDC hdc;
  358. uint8* bitmapData;
  359. int pixelStride, lineStride;
  360. uint8* imageData;
  361. private:
  362. static bool isGraphicsCard32Bit()
  363. {
  364. HDC dc = GetDC (0);
  365. const int bitsPerPixel = GetDeviceCaps (dc, BITSPIXEL);
  366. ReleaseDC (0, dc);
  367. return bitsPerPixel > 24;
  368. }
  369. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage)
  370. };
  371. //==============================================================================
  372. namespace IconConverters
  373. {
  374. Image createImageFromHBITMAP (HBITMAP bitmap)
  375. {
  376. Image im;
  377. if (bitmap != 0)
  378. {
  379. BITMAP bm;
  380. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  381. && bm.bmWidth > 0 && bm.bmHeight > 0)
  382. {
  383. HDC tempDC = GetDC (0);
  384. HDC dc = CreateCompatibleDC (tempDC);
  385. ReleaseDC (0, tempDC);
  386. SelectObject (dc, bitmap);
  387. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  388. Image::BitmapData imageData (im, Image::BitmapData::writeOnly);
  389. for (int y = bm.bmHeight; --y >= 0;)
  390. {
  391. for (int x = bm.bmWidth; --x >= 0;)
  392. {
  393. COLORREF col = GetPixel (dc, x, y);
  394. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  395. (uint8) GetGValue (col),
  396. (uint8) GetBValue (col)));
  397. }
  398. }
  399. DeleteDC (dc);
  400. }
  401. }
  402. return im;
  403. }
  404. Image createImageFromHICON (HICON icon)
  405. {
  406. ICONINFO info;
  407. if (GetIconInfo (icon, &info))
  408. {
  409. Image mask (createImageFromHBITMAP (info.hbmMask));
  410. Image image (createImageFromHBITMAP (info.hbmColor));
  411. if (mask.isValid() && image.isValid())
  412. {
  413. for (int y = image.getHeight(); --y >= 0;)
  414. {
  415. for (int x = image.getWidth(); --x >= 0;)
  416. {
  417. const float brightness = mask.getPixelAt (x, y).getBrightness();
  418. if (brightness > 0.0f)
  419. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  420. }
  421. }
  422. return image;
  423. }
  424. }
  425. return Image::null;
  426. }
  427. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  428. {
  429. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  430. Image bitmap (nativeBitmap);
  431. {
  432. Graphics g (bitmap);
  433. g.drawImageAt (image, 0, 0);
  434. }
  435. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  436. ICONINFO info;
  437. info.fIcon = isIcon;
  438. info.xHotspot = (DWORD) hotspotX;
  439. info.yHotspot = (DWORD) hotspotY;
  440. info.hbmMask = mask;
  441. info.hbmColor = nativeBitmap->hBitmap;
  442. HICON hi = CreateIconIndirect (&info);
  443. DeleteObject (mask);
  444. return hi;
  445. }
  446. }
  447. //==============================================================================
  448. class HWNDComponentPeer : public ComponentPeer
  449. {
  450. public:
  451. enum RenderingEngineType
  452. {
  453. softwareRenderingEngine = 0,
  454. direct2DRenderingEngine
  455. };
  456. //==============================================================================
  457. HWNDComponentPeer (Component& comp, const int windowStyleFlags, HWND parent, bool nonRepainting)
  458. : ComponentPeer (comp, windowStyleFlags),
  459. dontRepaint (nonRepainting),
  460. parentToAddTo (parent),
  461. currentRenderingEngine (softwareRenderingEngine),
  462. lastPaintTime (0),
  463. lastMagnifySize (0),
  464. fullScreen (false),
  465. isDragging (false),
  466. isMouseOver (false),
  467. hasCreatedCaret (false),
  468. constrainerIsResizing (false),
  469. currentWindowIcon (0),
  470. dropTarget (nullptr),
  471. updateLayeredWindowAlpha (255)
  472. {
  473. callFunctionIfNotLocked (&createWindowCallback, this);
  474. setTitle (component.getName());
  475. if ((windowStyleFlags & windowHasDropShadow) != 0
  476. && Desktop::canUseSemiTransparentWindows()
  477. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  478. {
  479. shadower = component.getLookAndFeel().createDropShadowerForComponent (&component);
  480. if (shadower != nullptr)
  481. shadower->setOwner (&component);
  482. }
  483. }
  484. ~HWNDComponentPeer()
  485. {
  486. shadower = nullptr;
  487. // do this before the next bit to avoid messages arriving for this window
  488. // before it's destroyed
  489. JuceWindowIdentifier::setAsJUCEWindow (hwnd, false);
  490. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  491. if (currentWindowIcon != 0)
  492. DestroyIcon (currentWindowIcon);
  493. if (dropTarget != nullptr)
  494. {
  495. dropTarget->clear();
  496. dropTarget->Release();
  497. dropTarget = nullptr;
  498. }
  499. #if JUCE_DIRECT2D
  500. direct2DContext = nullptr;
  501. #endif
  502. }
  503. //==============================================================================
  504. void* getNativeHandle() const override { return hwnd; }
  505. void setVisible (bool shouldBeVisible) override
  506. {
  507. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  508. if (shouldBeVisible)
  509. InvalidateRect (hwnd, 0, 0);
  510. else
  511. lastPaintTime = 0;
  512. }
  513. void setTitle (const String& title) override
  514. {
  515. // Unfortunately some ancient bits of win32 mean you can only perform this operation from the message thread.
  516. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  517. SetWindowText (hwnd, title.toWideCharPointer());
  518. }
  519. void repaintNowIfTransparent()
  520. {
  521. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  522. handlePaintMessage();
  523. }
  524. void updateBorderSize()
  525. {
  526. WINDOWINFO info;
  527. info.cbSize = sizeof (info);
  528. if (GetWindowInfo (hwnd, &info))
  529. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  530. info.rcClient.left - info.rcWindow.left,
  531. info.rcWindow.bottom - info.rcClient.bottom,
  532. info.rcWindow.right - info.rcClient.right);
  533. #if JUCE_DIRECT2D
  534. if (direct2DContext != nullptr)
  535. direct2DContext->resized();
  536. #endif
  537. }
  538. void setBounds (const Rectangle<int>& bounds, bool isNowFullScreen) override
  539. {
  540. fullScreen = isNowFullScreen;
  541. Rectangle<int> newBounds (windowBorder.addedTo (bounds));
  542. if (isUsingUpdateLayeredWindow())
  543. {
  544. if (HWND parentHwnd = GetParent (hwnd))
  545. {
  546. RECT parentRect = getWindowRect (parentHwnd);
  547. newBounds.translate (parentRect.left, parentRect.top);
  548. }
  549. }
  550. const Rectangle<int> oldBounds (getBounds());
  551. const bool hasMoved = (oldBounds.getPosition() != bounds.getPosition());
  552. const bool hasResized = (oldBounds.getWidth() != bounds.getWidth()
  553. || oldBounds.getHeight() != bounds.getHeight());
  554. DWORD flags = SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER;
  555. if (! hasMoved) flags |= SWP_NOMOVE;
  556. if (! hasResized) flags |= SWP_NOSIZE;
  557. setWindowPos (hwnd, newBounds, flags);
  558. if (hasResized && isValidPeer (this))
  559. {
  560. updateBorderSize();
  561. repaintNowIfTransparent();
  562. }
  563. }
  564. Rectangle<int> getBounds() const override
  565. {
  566. Rectangle<int> bounds (rectangleFromRECT (getWindowRect (hwnd)));
  567. if (HWND parentH = GetParent (hwnd))
  568. {
  569. RECT r = getWindowRect (parentH);
  570. bounds.translate (-r.left, -r.top);
  571. }
  572. return windowBorder.subtractedFrom (bounds);
  573. }
  574. Point<int> getScreenPosition() const
  575. {
  576. RECT r = getWindowRect (hwnd);
  577. return Point<int> (r.left + windowBorder.getLeft(),
  578. r.top + windowBorder.getTop());
  579. }
  580. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition().toFloat(); }
  581. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition().toFloat(); }
  582. void setAlpha (float newAlpha) override
  583. {
  584. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  585. if (component.isOpaque())
  586. {
  587. if (newAlpha < 1.0f)
  588. {
  589. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  590. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  591. }
  592. else
  593. {
  594. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  595. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  596. }
  597. }
  598. else
  599. {
  600. updateLayeredWindowAlpha = intAlpha;
  601. component.repaint();
  602. }
  603. }
  604. void setMinimised (bool shouldBeMinimised) override
  605. {
  606. if (shouldBeMinimised != isMinimised())
  607. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  608. }
  609. bool isMinimised() const override
  610. {
  611. WINDOWPLACEMENT wp;
  612. wp.length = sizeof (WINDOWPLACEMENT);
  613. GetWindowPlacement (hwnd, &wp);
  614. return wp.showCmd == SW_SHOWMINIMIZED;
  615. }
  616. void setFullScreen (bool shouldBeFullScreen) override
  617. {
  618. setMinimised (false);
  619. if (isFullScreen() != shouldBeFullScreen)
  620. {
  621. fullScreen = shouldBeFullScreen;
  622. const WeakReference<Component> deletionChecker (&component);
  623. if (! fullScreen)
  624. {
  625. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  626. if (hasTitleBar())
  627. ShowWindow (hwnd, SW_SHOWNORMAL);
  628. if (! boundsCopy.isEmpty())
  629. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, boundsCopy), false);
  630. }
  631. else
  632. {
  633. if (hasTitleBar())
  634. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  635. else
  636. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  637. }
  638. if (deletionChecker != nullptr)
  639. handleMovedOrResized();
  640. }
  641. }
  642. bool isFullScreen() const override
  643. {
  644. if (! hasTitleBar())
  645. return fullScreen;
  646. WINDOWPLACEMENT wp;
  647. wp.length = sizeof (wp);
  648. GetWindowPlacement (hwnd, &wp);
  649. return wp.showCmd == SW_SHOWMAXIMIZED;
  650. }
  651. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  652. {
  653. RECT r = getWindowRect (hwnd);
  654. if (! (isPositiveAndBelow (localPos.x, (int) (r.right - r.left))
  655. && isPositiveAndBelow (localPos.y, (int) (r.bottom - r.top))))
  656. return false;
  657. POINT p = { localPos.x + r.left + windowBorder.getLeft(),
  658. localPos.y + r.top + windowBorder.getTop() };
  659. HWND w = WindowFromPoint (p);
  660. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  661. }
  662. BorderSize<int> getFrameSize() const override
  663. {
  664. return windowBorder;
  665. }
  666. bool setAlwaysOnTop (bool alwaysOnTop) override
  667. {
  668. const bool oldDeactivate = shouldDeactivateTitleBar;
  669. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  670. setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
  671. shouldDeactivateTitleBar = oldDeactivate;
  672. if (shadower != nullptr)
  673. handleBroughtToFront();
  674. return true;
  675. }
  676. void toFront (bool makeActive) override
  677. {
  678. setMinimised (false);
  679. const bool oldDeactivate = shouldDeactivateTitleBar;
  680. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  681. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  682. shouldDeactivateTitleBar = oldDeactivate;
  683. if (! makeActive)
  684. {
  685. // in this case a broughttofront call won't have occured, so do it now..
  686. handleBroughtToFront();
  687. }
  688. }
  689. void toBehind (ComponentPeer* other) override
  690. {
  691. if (HWNDComponentPeer* const otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
  692. {
  693. setMinimised (false);
  694. // Must be careful not to try to put a topmost window behind a normal one, or Windows
  695. // promotes the normal one to be topmost!
  696. if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
  697. setWindowZOrder (hwnd, otherPeer->hwnd);
  698. else if (otherPeer->getComponent().isAlwaysOnTop())
  699. setWindowZOrder (hwnd, HWND_TOP);
  700. }
  701. else
  702. {
  703. jassertfalse; // wrong type of window?
  704. }
  705. }
  706. bool isFocused() const override
  707. {
  708. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  709. }
  710. void grabFocus() override
  711. {
  712. const bool oldDeactivate = shouldDeactivateTitleBar;
  713. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  714. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  715. shouldDeactivateTitleBar = oldDeactivate;
  716. }
  717. void textInputRequired (Point<int>, TextInputTarget&) override
  718. {
  719. if (! hasCreatedCaret)
  720. {
  721. hasCreatedCaret = true;
  722. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  723. }
  724. ShowCaret (hwnd);
  725. SetCaretPos (0, 0);
  726. }
  727. void dismissPendingTextInput() override
  728. {
  729. imeHandler.handleSetContext (hwnd, false);
  730. }
  731. void repaint (const Rectangle<int>& area) override
  732. {
  733. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  734. InvalidateRect (hwnd, &r, FALSE);
  735. }
  736. void performAnyPendingRepaintsNow() override
  737. {
  738. if (component.isVisible())
  739. {
  740. WeakReference<Component> localRef (&component);
  741. MSG m;
  742. if (isUsingUpdateLayeredWindow() || PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  743. if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
  744. handlePaintMessage();
  745. }
  746. }
  747. //==============================================================================
  748. static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
  749. {
  750. if (h != 0 && JuceWindowIdentifier::isJUCEWindow (h))
  751. return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
  752. return nullptr;
  753. }
  754. //==============================================================================
  755. bool isInside (HWND h) const noexcept
  756. {
  757. return GetAncestor (hwnd, GA_ROOT) == h;
  758. }
  759. //==============================================================================
  760. static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
  761. static void updateKeyModifiers() noexcept
  762. {
  763. int keyMods = 0;
  764. if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
  765. if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
  766. if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
  767. if (isKeyDown (VK_RMENU)) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  768. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  769. }
  770. static void updateModifiersFromWParam (const WPARAM wParam)
  771. {
  772. int mouseMods = 0;
  773. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  774. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  775. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  776. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  777. updateKeyModifiers();
  778. }
  779. //==============================================================================
  780. bool dontRepaint;
  781. static ModifierKeys currentModifiers;
  782. static ModifierKeys modifiersAtLastCallback;
  783. //==============================================================================
  784. class JuceDropTarget : public ComBaseClassHelper<IDropTarget>
  785. {
  786. public:
  787. JuceDropTarget (HWNDComponentPeer& p) : ownerInfo (new OwnerInfo (p)) {}
  788. void clear()
  789. {
  790. ownerInfo = nullptr;
  791. }
  792. JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect)
  793. {
  794. HRESULT hr = updateFileList (pDataObject);
  795. if (FAILED (hr))
  796. return hr;
  797. return DragOver (grfKeyState, mousePos, pdwEffect);
  798. }
  799. JUCE_COMRESULT DragLeave()
  800. {
  801. if (ownerInfo == nullptr)
  802. return S_FALSE;
  803. ownerInfo->owner.handleDragExit (ownerInfo->dragInfo);
  804. return S_OK;
  805. }
  806. JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  807. {
  808. if (ownerInfo == nullptr)
  809. return S_FALSE;
  810. ownerInfo->dragInfo.position = ownerInfo->getMousePos (mousePos).roundToInt();
  811. const bool wasWanted = ownerInfo->owner.handleDragMove (ownerInfo->dragInfo);
  812. *pdwEffect = wasWanted ? (DWORD) DROPEFFECT_COPY : (DWORD) DROPEFFECT_NONE;
  813. return S_OK;
  814. }
  815. JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  816. {
  817. HRESULT hr = updateFileList (pDataObject);
  818. if (SUCCEEDED (hr))
  819. {
  820. ownerInfo->dragInfo.position = ownerInfo->getMousePos (mousePos).roundToInt();
  821. const bool wasWanted = ownerInfo->owner.handleDragDrop (ownerInfo->dragInfo);
  822. *pdwEffect = wasWanted ? (DWORD) DROPEFFECT_COPY : (DWORD) DROPEFFECT_NONE;
  823. hr = S_OK;
  824. }
  825. return hr;
  826. }
  827. private:
  828. struct OwnerInfo
  829. {
  830. OwnerInfo (HWNDComponentPeer& p) : owner (p) {}
  831. Point<float> getMousePos (const POINTL& mousePos) const
  832. {
  833. return owner.globalToLocal (Point<float> (static_cast<float> (mousePos.x),
  834. static_cast<float> (mousePos.y)));
  835. }
  836. template <typename CharType>
  837. void parseFileList (const CharType* names, const SIZE_T totalLen)
  838. {
  839. unsigned int i = 0;
  840. for (;;)
  841. {
  842. unsigned int len = 0;
  843. while (i + len < totalLen && names [i + len] != 0)
  844. ++len;
  845. if (len == 0)
  846. break;
  847. dragInfo.files.add (String (names + i, len));
  848. i += len + 1;
  849. }
  850. }
  851. HWNDComponentPeer& owner;
  852. ComponentPeer::DragInfo dragInfo;
  853. JUCE_DECLARE_NON_COPYABLE (OwnerInfo)
  854. };
  855. ScopedPointer<OwnerInfo> ownerInfo;
  856. struct DroppedData
  857. {
  858. DroppedData (IDataObject* const dataObject, const CLIPFORMAT type)
  859. : data (nullptr)
  860. {
  861. FORMATETC format = { type, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  862. STGMEDIUM resetMedium = { TYMED_HGLOBAL, { 0 }, 0 };
  863. medium = resetMedium;
  864. if (SUCCEEDED (error = dataObject->GetData (&format, &medium)))
  865. {
  866. dataSize = GlobalSize (medium.hGlobal);
  867. data = GlobalLock (medium.hGlobal);
  868. }
  869. }
  870. ~DroppedData()
  871. {
  872. if (data != nullptr)
  873. GlobalUnlock (medium.hGlobal);
  874. }
  875. HRESULT error;
  876. STGMEDIUM medium;
  877. void* data;
  878. SIZE_T dataSize;
  879. };
  880. HRESULT updateFileList (IDataObject* const dataObject)
  881. {
  882. if (ownerInfo == nullptr)
  883. return S_FALSE;
  884. ownerInfo->dragInfo.clear();
  885. DroppedData textData (dataObject, CF_UNICODETEXT);
  886. if (SUCCEEDED (textData.error))
  887. {
  888. ownerInfo->dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
  889. CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
  890. }
  891. else
  892. {
  893. DroppedData fileData (dataObject, CF_HDROP);
  894. if (SUCCEEDED (fileData.error))
  895. {
  896. const LPDROPFILES dropFiles = static_cast<const LPDROPFILES> (fileData.data);
  897. const void* const names = addBytesToPointer (dropFiles, sizeof (DROPFILES));
  898. if (dropFiles->fWide)
  899. ownerInfo->parseFileList (static_cast<const WCHAR*> (names), fileData.dataSize);
  900. else
  901. ownerInfo->parseFileList (static_cast<const char*> (names), fileData.dataSize);
  902. }
  903. else
  904. {
  905. return fileData.error;
  906. }
  907. }
  908. return S_OK;
  909. }
  910. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget)
  911. };
  912. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  913. static bool offerKeyMessageToJUCEWindow (MSG& m)
  914. {
  915. if (m.message == WM_KEYDOWN || m.message == WM_KEYUP)
  916. if (Component::getCurrentlyFocusedComponent() != nullptr)
  917. if (HWNDComponentPeer* h = getOwnerOfWindow (m.hwnd))
  918. if (m.message == WM_KEYDOWN ? h->doKeyDown (m.wParam)
  919. : h->doKeyUp (m.wParam))
  920. return true;
  921. return false;
  922. }
  923. #endif
  924. private:
  925. HWND hwnd, parentToAddTo;
  926. ScopedPointer<DropShadower> shadower;
  927. RenderingEngineType currentRenderingEngine;
  928. #if JUCE_DIRECT2D
  929. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  930. #endif
  931. uint32 lastPaintTime;
  932. ULONGLONG lastMagnifySize;
  933. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  934. BorderSize<int> windowBorder;
  935. HICON currentWindowIcon;
  936. JuceDropTarget* dropTarget;
  937. uint8 updateLayeredWindowAlpha;
  938. MultiTouchMapper<DWORD> currentTouches;
  939. //==============================================================================
  940. class TemporaryImage : public Timer
  941. {
  942. public:
  943. TemporaryImage() {}
  944. Image& getImage (const bool transparent, const int w, const int h)
  945. {
  946. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  947. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  948. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  949. startTimer (3000);
  950. return image;
  951. }
  952. void timerCallback() override
  953. {
  954. stopTimer();
  955. image = Image::null;
  956. }
  957. private:
  958. Image image;
  959. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  960. };
  961. TemporaryImage offscreenImageGenerator;
  962. //==============================================================================
  963. class WindowClassHolder : private DeletedAtShutdown
  964. {
  965. public:
  966. WindowClassHolder()
  967. {
  968. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  969. // get a bit confused (even despite it not being a process-global window class).
  970. String windowClassName ("JUCE_");
  971. windowClassName << String::toHexString (Time::currentTimeMillis());
  972. HINSTANCE moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  973. TCHAR moduleFile [1024] = { 0 };
  974. GetModuleFileName (moduleHandle, moduleFile, 1024);
  975. WORD iconNum = 0;
  976. WNDCLASSEX wcex = { 0 };
  977. wcex.cbSize = sizeof (wcex);
  978. wcex.style = CS_OWNDC;
  979. wcex.lpfnWndProc = (WNDPROC) windowProc;
  980. wcex.lpszClassName = windowClassName.toWideCharPointer();
  981. wcex.cbWndExtra = 32;
  982. wcex.hInstance = moduleHandle;
  983. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  984. iconNum = 1;
  985. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  986. atom = RegisterClassEx (&wcex);
  987. jassert (atom != 0);
  988. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  989. }
  990. ~WindowClassHolder()
  991. {
  992. if (ComponentPeer::getNumPeers() == 0)
  993. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  994. clearSingletonInstance();
  995. }
  996. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) MAKELONG (atom, 0); }
  997. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder)
  998. private:
  999. ATOM atom;
  1000. static bool isHWNDBlockedByModalComponents (HWND h)
  1001. {
  1002. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1003. if (Component* const c = Desktop::getInstance().getComponent (i))
  1004. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  1005. && IsChild ((HWND) c->getWindowHandle(), h))
  1006. return false;
  1007. return true;
  1008. }
  1009. static bool checkEventBlockedByModalComps (const MSG& m)
  1010. {
  1011. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  1012. return false;
  1013. switch (m.message)
  1014. {
  1015. case WM_MOUSEMOVE:
  1016. case WM_NCMOUSEMOVE:
  1017. case 0x020A: /* WM_MOUSEWHEEL */
  1018. case 0x020E: /* WM_MOUSEHWHEEL */
  1019. case WM_KEYUP:
  1020. case WM_SYSKEYUP:
  1021. case WM_CHAR:
  1022. case WM_APPCOMMAND:
  1023. case WM_LBUTTONUP:
  1024. case WM_MBUTTONUP:
  1025. case WM_RBUTTONUP:
  1026. case WM_MOUSEACTIVATE:
  1027. case WM_NCMOUSEHOVER:
  1028. case WM_MOUSEHOVER:
  1029. case WM_TOUCH:
  1030. return isHWNDBlockedByModalComponents (m.hwnd);
  1031. case WM_NCLBUTTONDOWN:
  1032. case WM_NCLBUTTONDBLCLK:
  1033. case WM_NCRBUTTONDOWN:
  1034. case WM_NCRBUTTONDBLCLK:
  1035. case WM_NCMBUTTONDOWN:
  1036. case WM_NCMBUTTONDBLCLK:
  1037. case WM_LBUTTONDOWN:
  1038. case WM_LBUTTONDBLCLK:
  1039. case WM_MBUTTONDOWN:
  1040. case WM_MBUTTONDBLCLK:
  1041. case WM_RBUTTONDOWN:
  1042. case WM_RBUTTONDBLCLK:
  1043. case WM_KEYDOWN:
  1044. case WM_SYSKEYDOWN:
  1045. if (isHWNDBlockedByModalComponents (m.hwnd))
  1046. {
  1047. if (Component* const modal = Component::getCurrentlyModalComponent (0))
  1048. modal->inputAttemptWhenModal();
  1049. return true;
  1050. }
  1051. break;
  1052. default:
  1053. break;
  1054. }
  1055. return false;
  1056. }
  1057. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  1058. };
  1059. //==============================================================================
  1060. static void* createWindowCallback (void* userData)
  1061. {
  1062. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  1063. return nullptr;
  1064. }
  1065. void createWindow()
  1066. {
  1067. DWORD exstyle = 0;
  1068. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  1069. if (hasTitleBar())
  1070. {
  1071. type |= WS_OVERLAPPED;
  1072. if ((styleFlags & windowHasCloseButton) != 0)
  1073. {
  1074. type |= WS_SYSMENU;
  1075. }
  1076. else
  1077. {
  1078. // annoyingly, windows won't let you have a min/max button without a close button
  1079. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  1080. }
  1081. if ((styleFlags & windowIsResizable) != 0)
  1082. type |= WS_THICKFRAME;
  1083. }
  1084. else if (parentToAddTo != 0)
  1085. {
  1086. type |= WS_CHILD;
  1087. }
  1088. else
  1089. {
  1090. type |= WS_POPUP | WS_SYSMENU;
  1091. }
  1092. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1093. exstyle |= WS_EX_TOOLWINDOW;
  1094. else
  1095. exstyle |= WS_EX_APPWINDOW;
  1096. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  1097. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  1098. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  1099. if ((styleFlags & windowIsSemiTransparent) != 0 && Desktop::canUseSemiTransparentWindows())
  1100. exstyle |= WS_EX_LAYERED;
  1101. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  1102. L"", type, 0, 0, 0, 0, parentToAddTo, 0,
  1103. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), 0);
  1104. if (hwnd != 0)
  1105. {
  1106. SetWindowLongPtr (hwnd, 0, 0);
  1107. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  1108. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  1109. if (dropTarget == nullptr)
  1110. {
  1111. HWNDComponentPeer* peer = nullptr;
  1112. if (dontRepaint)
  1113. peer = getOwnerOfWindow (parentToAddTo);
  1114. if (peer == nullptr)
  1115. peer = this;
  1116. dropTarget = new JuceDropTarget (*peer);
  1117. }
  1118. RegisterDragDrop (hwnd, dropTarget);
  1119. if (canUseMultiTouch())
  1120. registerTouchWindow (hwnd, 0);
  1121. setDPIAwareness();
  1122. setMessageFilter();
  1123. updateBorderSize();
  1124. // Calling this function here is (for some reason) necessary to make Windows
  1125. // correctly enable the menu items that we specify in the wm_initmenu message.
  1126. GetSystemMenu (hwnd, false);
  1127. const float alpha = component.getAlpha();
  1128. if (alpha < 1.0f)
  1129. setAlpha (alpha);
  1130. }
  1131. else
  1132. {
  1133. jassertfalse;
  1134. }
  1135. }
  1136. static void* destroyWindowCallback (void* handle)
  1137. {
  1138. RevokeDragDrop ((HWND) handle);
  1139. DestroyWindow ((HWND) handle);
  1140. return nullptr;
  1141. }
  1142. static void* toFrontCallback1 (void* h)
  1143. {
  1144. SetForegroundWindow ((HWND) h);
  1145. return nullptr;
  1146. }
  1147. static void* toFrontCallback2 (void* h)
  1148. {
  1149. setWindowZOrder ((HWND) h, HWND_TOP);
  1150. return nullptr;
  1151. }
  1152. static void* setFocusCallback (void* h)
  1153. {
  1154. SetFocus ((HWND) h);
  1155. return nullptr;
  1156. }
  1157. static void* getFocusCallback (void*)
  1158. {
  1159. return GetFocus();
  1160. }
  1161. bool isUsingUpdateLayeredWindow() const
  1162. {
  1163. return ! component.isOpaque();
  1164. }
  1165. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  1166. void setIcon (const Image& newIcon)
  1167. {
  1168. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  1169. if (hicon != 0)
  1170. {
  1171. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  1172. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  1173. if (currentWindowIcon != 0)
  1174. DestroyIcon (currentWindowIcon);
  1175. currentWindowIcon = hicon;
  1176. }
  1177. }
  1178. void setMessageFilter()
  1179. {
  1180. typedef BOOL (WINAPI* ChangeWindowMessageFilterExFunc) (HWND, UINT, DWORD, PVOID);
  1181. if (ChangeWindowMessageFilterExFunc changeMessageFilter
  1182. = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx"))
  1183. {
  1184. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  1185. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  1186. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  1187. }
  1188. }
  1189. struct ChildWindowClippingInfo
  1190. {
  1191. HDC dc;
  1192. HWNDComponentPeer* peer;
  1193. RectangleList<int>* clip;
  1194. Point<int> origin;
  1195. int savedDC;
  1196. };
  1197. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  1198. {
  1199. if (IsWindowVisible (hwnd))
  1200. {
  1201. ChildWindowClippingInfo& info = *(ChildWindowClippingInfo*) context;
  1202. HWND parent = GetParent (hwnd);
  1203. if (parent == info.peer->hwnd)
  1204. {
  1205. RECT r = getWindowRect (hwnd);
  1206. POINT pos = { r.left, r.top };
  1207. ScreenToClient (GetParent (hwnd), &pos);
  1208. Rectangle<int> clip (Rectangle<int> (pos.x, pos.y,
  1209. r.right - r.left,
  1210. r.bottom - r.top));
  1211. info.clip->subtract (clip - info.origin);
  1212. if (info.savedDC == 0)
  1213. info.savedDC = SaveDC (info.dc);
  1214. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  1215. }
  1216. }
  1217. return TRUE;
  1218. }
  1219. //==============================================================================
  1220. void handlePaintMessage()
  1221. {
  1222. #if JUCE_DIRECT2D
  1223. if (direct2DContext != nullptr)
  1224. {
  1225. RECT r;
  1226. if (GetUpdateRect (hwnd, &r, false))
  1227. {
  1228. direct2DContext->start();
  1229. direct2DContext->clipToRectangle (rectangleFromRECT (r));
  1230. handlePaint (*direct2DContext);
  1231. direct2DContext->end();
  1232. }
  1233. }
  1234. else
  1235. #endif
  1236. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  1237. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  1238. PAINTSTRUCT paintStruct;
  1239. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  1240. // message and become re-entrant, but that's OK
  1241. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  1242. // corrupt the image it's using to paint into, so do a check here.
  1243. static bool reentrant = false;
  1244. if (! reentrant)
  1245. {
  1246. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1247. if (dontRepaint)
  1248. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  1249. else
  1250. performPaint (dc, rgn, regionType, paintStruct);
  1251. }
  1252. DeleteObject (rgn);
  1253. EndPaint (hwnd, &paintStruct);
  1254. #ifndef JUCE_GCC
  1255. _fpreset(); // because some graphics cards can unmask FP exceptions
  1256. #endif
  1257. lastPaintTime = Time::getMillisecondCounter();
  1258. }
  1259. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1260. {
  1261. int x = paintStruct.rcPaint.left;
  1262. int y = paintStruct.rcPaint.top;
  1263. int w = paintStruct.rcPaint.right - x;
  1264. int h = paintStruct.rcPaint.bottom - y;
  1265. const bool transparent = isUsingUpdateLayeredWindow();
  1266. if (transparent)
  1267. {
  1268. // it's not possible to have a transparent window with a title bar at the moment!
  1269. jassert (! hasTitleBar());
  1270. RECT r = getWindowRect (hwnd);
  1271. x = y = 0;
  1272. w = r.right - r.left;
  1273. h = r.bottom - r.top;
  1274. }
  1275. if (w > 0 && h > 0)
  1276. {
  1277. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1278. RectangleList<int> contextClip;
  1279. const Rectangle<int> clipBounds (w, h);
  1280. bool needToPaintAll = true;
  1281. if (regionType == COMPLEXREGION && ! transparent)
  1282. {
  1283. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1284. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1285. DeleteObject (clipRgn);
  1286. char rgnData [8192];
  1287. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1288. if (res > 0 && res <= sizeof (rgnData))
  1289. {
  1290. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1291. if (hdr->iType == RDH_RECTANGLES
  1292. && hdr->rcBound.right - hdr->rcBound.left >= w
  1293. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1294. {
  1295. needToPaintAll = false;
  1296. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1297. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  1298. {
  1299. if (rects->right <= x + w && rects->bottom <= y + h)
  1300. {
  1301. const int cx = jmax (x, (int) rects->left);
  1302. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  1303. rects->right - cx, rects->bottom - rects->top)
  1304. .getIntersection (clipBounds));
  1305. }
  1306. else
  1307. {
  1308. needToPaintAll = true;
  1309. break;
  1310. }
  1311. ++rects;
  1312. }
  1313. }
  1314. }
  1315. }
  1316. if (needToPaintAll)
  1317. {
  1318. contextClip.clear();
  1319. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  1320. }
  1321. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  1322. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  1323. if (! contextClip.isEmpty())
  1324. {
  1325. if (transparent)
  1326. for (const Rectangle<int>* i = contextClip.begin(), * const e = contextClip.end(); i != e; ++i)
  1327. offscreenImage.clear (*i);
  1328. // if the component's not opaque, this won't draw properly unless the platform can support this
  1329. jassert (Desktop::canUseSemiTransparentWindows() || component.isOpaque());
  1330. {
  1331. ScopedPointer<LowLevelGraphicsContext> context (component.getLookAndFeel()
  1332. .createGraphicsContext (offscreenImage, Point<int> (-x, -y), contextClip));
  1333. handlePaint (*context);
  1334. }
  1335. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  1336. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  1337. }
  1338. if (childClipInfo.savedDC != 0)
  1339. RestoreDC (dc, childClipInfo.savedDC);
  1340. }
  1341. }
  1342. //==============================================================================
  1343. void doMouseEvent (Point<float> position)
  1344. {
  1345. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  1346. }
  1347. StringArray getAvailableRenderingEngines() override
  1348. {
  1349. StringArray s ("Software Renderer");
  1350. #if JUCE_DIRECT2D
  1351. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  1352. s.add ("Direct2D");
  1353. #endif
  1354. return s;
  1355. }
  1356. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  1357. #if JUCE_DIRECT2D
  1358. void updateDirect2DContext()
  1359. {
  1360. if (currentRenderingEngine != direct2DRenderingEngine)
  1361. direct2DContext = 0;
  1362. else if (direct2DContext == 0)
  1363. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  1364. }
  1365. #endif
  1366. void setCurrentRenderingEngine (int index) override
  1367. {
  1368. (void) index;
  1369. #if JUCE_DIRECT2D
  1370. if (getAvailableRenderingEngines().size() > 1)
  1371. {
  1372. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  1373. updateDirect2DContext();
  1374. repaint (component.getLocalBounds());
  1375. }
  1376. #endif
  1377. }
  1378. static int getMinTimeBetweenMouseMoves()
  1379. {
  1380. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1381. return 0;
  1382. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  1383. }
  1384. void doMouseMove (Point<float> position)
  1385. {
  1386. if (! isMouseOver)
  1387. {
  1388. isMouseOver = true;
  1389. ModifierKeys::getCurrentModifiersRealtime(); // (This avoids a rare stuck-button problem when focus is lost unexpectedly)
  1390. updateKeyModifiers();
  1391. TRACKMOUSEEVENT tme;
  1392. tme.cbSize = sizeof (tme);
  1393. tme.dwFlags = TME_LEAVE;
  1394. tme.hwndTrack = hwnd;
  1395. tme.dwHoverTime = 0;
  1396. if (! TrackMouseEvent (&tme))
  1397. jassertfalse;
  1398. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1399. }
  1400. else if (! isDragging)
  1401. {
  1402. if (! contains (position.roundToInt(), false))
  1403. return;
  1404. }
  1405. static uint32 lastMouseTime = 0;
  1406. static int minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  1407. const uint32 now = Time::getMillisecondCounter();
  1408. if (now >= lastMouseTime + minTimeBetweenMouses)
  1409. {
  1410. lastMouseTime = now;
  1411. doMouseEvent (position);
  1412. }
  1413. }
  1414. void doMouseDown (Point<float> position, const WPARAM wParam)
  1415. {
  1416. if (GetCapture() != hwnd)
  1417. SetCapture (hwnd);
  1418. doMouseMove (position);
  1419. if (isValidPeer (this))
  1420. {
  1421. updateModifiersFromWParam (wParam);
  1422. isDragging = true;
  1423. doMouseEvent (position);
  1424. }
  1425. }
  1426. void doMouseUp (Point<float> position, const WPARAM wParam)
  1427. {
  1428. updateModifiersFromWParam (wParam);
  1429. const bool wasDragging = isDragging;
  1430. isDragging = false;
  1431. // release the mouse capture if the user has released all buttons
  1432. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  1433. ReleaseCapture();
  1434. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  1435. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  1436. if (wasDragging)
  1437. doMouseEvent (position);
  1438. }
  1439. void doCaptureChanged()
  1440. {
  1441. if (constrainerIsResizing)
  1442. {
  1443. if (constrainer != nullptr)
  1444. constrainer->resizeEnd();
  1445. constrainerIsResizing = false;
  1446. }
  1447. if (isDragging)
  1448. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  1449. }
  1450. void doMouseExit()
  1451. {
  1452. isMouseOver = false;
  1453. doMouseEvent (getCurrentMousePos());
  1454. }
  1455. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  1456. {
  1457. const Point<int> globalPos (getCurrentMousePosGlobal().roundToInt());
  1458. // Because Windows stupidly sends all wheel events to the window with the keyboard
  1459. // focus, we have to redirect them here according to the mouse pos..
  1460. POINT p = { globalPos.x, globalPos.y };
  1461. HWNDComponentPeer* peer = getOwnerOfWindow (WindowFromPoint (p));
  1462. if (peer == nullptr)
  1463. peer = this;
  1464. localPos = peer->globalToLocal (globalPos.toFloat());
  1465. return peer;
  1466. }
  1467. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  1468. {
  1469. updateKeyModifiers();
  1470. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  1471. MouseWheelDetails wheel;
  1472. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  1473. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  1474. wheel.isReversed = false;
  1475. wheel.isSmooth = false;
  1476. Point<float> localPos;
  1477. if (ComponentPeer* const peer = findPeerUnderMouse (localPos))
  1478. peer->handleMouseWheel (0, localPos, getMouseEventTime(), wheel);
  1479. }
  1480. bool doGestureEvent (LPARAM lParam)
  1481. {
  1482. GESTUREINFO gi;
  1483. zerostruct (gi);
  1484. gi.cbSize = sizeof (gi);
  1485. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  1486. {
  1487. updateKeyModifiers();
  1488. Point<float> localPos;
  1489. if (ComponentPeer* const peer = findPeerUnderMouse (localPos))
  1490. {
  1491. switch (gi.dwID)
  1492. {
  1493. case 3: /*GID_ZOOM*/
  1494. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  1495. peer->handleMagnifyGesture (0, localPos, getMouseEventTime(),
  1496. (float) (gi.ullArguments / (double) lastMagnifySize));
  1497. lastMagnifySize = gi.ullArguments;
  1498. return true;
  1499. case 4: /*GID_PAN*/
  1500. case 5: /*GID_ROTATE*/
  1501. case 6: /*GID_TWOFINGERTAP*/
  1502. case 7: /*GID_PRESSANDTAP*/
  1503. default:
  1504. break;
  1505. }
  1506. }
  1507. }
  1508. return false;
  1509. }
  1510. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  1511. {
  1512. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  1513. if (HWNDComponentPeer* const parent = getOwnerOfWindow (GetParent (hwnd)))
  1514. if (parent != this)
  1515. return parent->doTouchEvent (numInputs, eventHandle);
  1516. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  1517. if (getTouchInputInfo (eventHandle, numInputs, inputInfo, sizeof (TOUCHINPUT)))
  1518. {
  1519. for (int i = 0; i < numInputs; ++i)
  1520. {
  1521. const DWORD flags = inputInfo[i].dwFlags;
  1522. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  1523. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_PRIMARY) != 0,
  1524. (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  1525. return 0; // abandon method if this window was deleted by the callback
  1526. }
  1527. }
  1528. closeTouchInputHandle (eventHandle);
  1529. return 0;
  1530. }
  1531. bool handleTouchInput (const TOUCHINPUT& touch, const bool isPrimary, const bool isDown, const bool isUp)
  1532. {
  1533. bool isCancel = false;
  1534. const int touchIndex = currentTouches.getIndexOfTouch (touch.dwID);
  1535. const int64 time = getMouseEventTime();
  1536. const Point<float> pos (globalToLocal (Point<float> (static_cast<float> (TOUCH_COORD_TO_PIXEL (touch.x)),
  1537. static_cast<float> (TOUCH_COORD_TO_PIXEL (touch.y)))));
  1538. ModifierKeys modsToSend (currentModifiers);
  1539. if (isDown)
  1540. {
  1541. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1542. modsToSend = currentModifiers;
  1543. if (! isPrimary)
  1544. {
  1545. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  1546. handleMouseEvent (touchIndex, pos.toFloat(), modsToSend.withoutMouseButtons(), time);
  1547. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1548. return false;
  1549. }
  1550. }
  1551. else if (isUp)
  1552. {
  1553. modsToSend = modsToSend.withoutMouseButtons();
  1554. currentTouches.clearTouch (touchIndex);
  1555. if (! currentTouches.areAnyTouchesActive())
  1556. isCancel = true;
  1557. }
  1558. else
  1559. {
  1560. modsToSend = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1561. }
  1562. if (isCancel)
  1563. {
  1564. currentTouches.clear();
  1565. currentModifiers = currentModifiers.withoutMouseButtons();
  1566. }
  1567. if (! isPrimary)
  1568. {
  1569. handleMouseEvent (touchIndex, pos.toFloat(), modsToSend, time);
  1570. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1571. return false;
  1572. }
  1573. if ((isUp || isCancel) && ! isPrimary)
  1574. {
  1575. handleMouseEvent (touchIndex, Point<float> (-10.0f, -10.0f), currentModifiers, time);
  1576. if (! isValidPeer (this))
  1577. return false;
  1578. }
  1579. return true;
  1580. }
  1581. //==============================================================================
  1582. void sendModifierKeyChangeIfNeeded()
  1583. {
  1584. if (modifiersAtLastCallback != currentModifiers)
  1585. {
  1586. modifiersAtLastCallback = currentModifiers;
  1587. handleModifierKeysChange();
  1588. }
  1589. }
  1590. bool doKeyUp (const WPARAM key)
  1591. {
  1592. updateKeyModifiers();
  1593. switch (key)
  1594. {
  1595. case VK_SHIFT:
  1596. case VK_CONTROL:
  1597. case VK_MENU:
  1598. case VK_CAPITAL:
  1599. case VK_LWIN:
  1600. case VK_RWIN:
  1601. case VK_APPS:
  1602. case VK_NUMLOCK:
  1603. case VK_SCROLL:
  1604. case VK_LSHIFT:
  1605. case VK_RSHIFT:
  1606. case VK_LCONTROL:
  1607. case VK_LMENU:
  1608. case VK_RCONTROL:
  1609. case VK_RMENU:
  1610. sendModifierKeyChangeIfNeeded();
  1611. }
  1612. return handleKeyUpOrDown (false)
  1613. || Component::getCurrentlyModalComponent() != nullptr;
  1614. }
  1615. bool doKeyDown (const WPARAM key)
  1616. {
  1617. updateKeyModifiers();
  1618. bool used = false;
  1619. switch (key)
  1620. {
  1621. case VK_SHIFT:
  1622. case VK_LSHIFT:
  1623. case VK_RSHIFT:
  1624. case VK_CONTROL:
  1625. case VK_LCONTROL:
  1626. case VK_RCONTROL:
  1627. case VK_MENU:
  1628. case VK_LMENU:
  1629. case VK_RMENU:
  1630. case VK_LWIN:
  1631. case VK_RWIN:
  1632. case VK_CAPITAL:
  1633. case VK_NUMLOCK:
  1634. case VK_SCROLL:
  1635. case VK_APPS:
  1636. sendModifierKeyChangeIfNeeded();
  1637. break;
  1638. case VK_LEFT:
  1639. case VK_RIGHT:
  1640. case VK_UP:
  1641. case VK_DOWN:
  1642. case VK_PRIOR:
  1643. case VK_NEXT:
  1644. case VK_HOME:
  1645. case VK_END:
  1646. case VK_DELETE:
  1647. case VK_INSERT:
  1648. case VK_F1:
  1649. case VK_F2:
  1650. case VK_F3:
  1651. case VK_F4:
  1652. case VK_F5:
  1653. case VK_F6:
  1654. case VK_F7:
  1655. case VK_F8:
  1656. case VK_F9:
  1657. case VK_F10:
  1658. case VK_F11:
  1659. case VK_F12:
  1660. case VK_F13:
  1661. case VK_F14:
  1662. case VK_F15:
  1663. case VK_F16:
  1664. used = handleKeyUpOrDown (true);
  1665. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  1666. break;
  1667. default:
  1668. used = handleKeyUpOrDown (true);
  1669. {
  1670. MSG msg;
  1671. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  1672. {
  1673. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  1674. // manually generate the key-press event that matches this key-down.
  1675. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  1676. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  1677. BYTE keyState[256];
  1678. GetKeyboardState (keyState);
  1679. WCHAR text[16] = { 0 };
  1680. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  1681. text[0] = 0;
  1682. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  1683. }
  1684. }
  1685. break;
  1686. }
  1687. return used || (Component::getCurrentlyModalComponent() != nullptr);
  1688. }
  1689. bool doKeyChar (int key, const LPARAM flags)
  1690. {
  1691. updateKeyModifiers();
  1692. juce_wchar textChar = (juce_wchar) key;
  1693. const int virtualScanCode = (flags >> 16) & 0xff;
  1694. if (key >= '0' && key <= '9')
  1695. {
  1696. switch (virtualScanCode) // check for a numeric keypad scan-code
  1697. {
  1698. case 0x52:
  1699. case 0x4f:
  1700. case 0x50:
  1701. case 0x51:
  1702. case 0x4b:
  1703. case 0x4c:
  1704. case 0x4d:
  1705. case 0x47:
  1706. case 0x48:
  1707. case 0x49:
  1708. key = (key - '0') + KeyPress::numberPad0;
  1709. break;
  1710. default:
  1711. break;
  1712. }
  1713. }
  1714. else
  1715. {
  1716. // convert the scan code to an unmodified character code..
  1717. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  1718. UINT keyChar = MapVirtualKey (virtualKey, 2);
  1719. keyChar = LOWORD (keyChar);
  1720. if (keyChar != 0)
  1721. key = (int) keyChar;
  1722. // avoid sending junk text characters for some control-key combinations
  1723. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  1724. textChar = 0;
  1725. }
  1726. return handleKeyPress (key, textChar);
  1727. }
  1728. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  1729. {
  1730. if (HWND parentH = GetParent (hwnd))
  1731. PostMessage (parentH, message, wParam, lParam);
  1732. }
  1733. bool doAppCommand (const LPARAM lParam)
  1734. {
  1735. int key = 0;
  1736. switch (GET_APPCOMMAND_LPARAM (lParam))
  1737. {
  1738. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  1739. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  1740. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  1741. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  1742. default: break;
  1743. }
  1744. if (key != 0)
  1745. {
  1746. updateKeyModifiers();
  1747. if (hwnd == GetActiveWindow())
  1748. {
  1749. handleKeyPress (key, 0);
  1750. return true;
  1751. }
  1752. }
  1753. return false;
  1754. }
  1755. bool isConstrainedNativeWindow() const
  1756. {
  1757. return constrainer != nullptr
  1758. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  1759. && ! isKioskMode();
  1760. }
  1761. Rectangle<int> getCurrentScaledBounds (float scale) const
  1762. {
  1763. return ScalingHelpers::unscaledScreenPosToScaled (scale, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (scale, component.getBounds())));
  1764. }
  1765. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  1766. {
  1767. if (isConstrainedNativeWindow())
  1768. {
  1769. const float scale = getComponent().getDesktopScaleFactor();
  1770. Rectangle<int> pos (ScalingHelpers::unscaledScreenPosToScaled (scale, rectangleFromRECT (r)));
  1771. const Rectangle<int> current (getCurrentScaledBounds (scale));
  1772. constrainer->checkBounds (pos, current,
  1773. Desktop::getInstance().getDisplays().getTotalBounds (true),
  1774. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  1775. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  1776. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  1777. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  1778. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  1779. r.left = pos.getX();
  1780. r.top = pos.getY();
  1781. r.right = pos.getRight();
  1782. r.bottom = pos.getBottom();
  1783. }
  1784. return TRUE;
  1785. }
  1786. LRESULT handlePositionChanging (WINDOWPOS& wp)
  1787. {
  1788. if (isConstrainedNativeWindow())
  1789. {
  1790. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  1791. && ! Component::isMouseButtonDownAnywhere())
  1792. {
  1793. const float scale = getComponent().getDesktopScaleFactor();
  1794. Rectangle<int> pos (ScalingHelpers::unscaledScreenPosToScaled (scale, Rectangle<int> (wp.x, wp.y, wp.cx, wp.cy)));
  1795. const Rectangle<int> current (getCurrentScaledBounds (scale));
  1796. constrainer->checkBounds (pos, current,
  1797. Desktop::getInstance().getDisplays().getTotalBounds (true),
  1798. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  1799. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  1800. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  1801. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  1802. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  1803. wp.x = pos.getX();
  1804. wp.y = pos.getY();
  1805. wp.cx = pos.getWidth();
  1806. wp.cy = pos.getHeight();
  1807. }
  1808. }
  1809. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  1810. component.setVisible (true);
  1811. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  1812. component.setVisible (false);
  1813. return 0;
  1814. }
  1815. bool handlePositionChanged()
  1816. {
  1817. const Point<float> pos (getCurrentMousePos());
  1818. if (contains (pos.roundToInt(), false))
  1819. {
  1820. doMouseEvent (pos);
  1821. if (! isValidPeer (this))
  1822. return true;
  1823. }
  1824. handleMovedOrResized();
  1825. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  1826. }
  1827. void handleAppActivation (const WPARAM wParam)
  1828. {
  1829. modifiersAtLastCallback = -1;
  1830. updateKeyModifiers();
  1831. if (isMinimised())
  1832. {
  1833. component.repaint();
  1834. handleMovedOrResized();
  1835. if (! isValidPeer (this))
  1836. return;
  1837. }
  1838. Component* underMouse = component.getComponentAt (component.getMouseXYRelative());
  1839. if (underMouse == nullptr)
  1840. underMouse = &component;
  1841. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  1842. {
  1843. if (LOWORD (wParam) == WA_CLICKACTIVE)
  1844. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1845. else
  1846. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1847. }
  1848. else
  1849. {
  1850. handleBroughtToFront();
  1851. }
  1852. }
  1853. void handlePowerBroadcast (WPARAM wParam)
  1854. {
  1855. if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
  1856. {
  1857. switch (wParam)
  1858. {
  1859. case PBT_APMSUSPEND: app->suspended(); break;
  1860. case PBT_APMQUERYSUSPENDFAILED:
  1861. case PBT_APMRESUMECRITICAL:
  1862. case PBT_APMRESUMESUSPEND:
  1863. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  1864. default: break;
  1865. }
  1866. }
  1867. }
  1868. void handleLeftClickInNCArea (WPARAM wParam)
  1869. {
  1870. if (! sendInputAttemptWhenModalMessage())
  1871. {
  1872. switch (wParam)
  1873. {
  1874. case HTBOTTOM:
  1875. case HTBOTTOMLEFT:
  1876. case HTBOTTOMRIGHT:
  1877. case HTGROWBOX:
  1878. case HTLEFT:
  1879. case HTRIGHT:
  1880. case HTTOP:
  1881. case HTTOPLEFT:
  1882. case HTTOPRIGHT:
  1883. if (isConstrainedNativeWindow())
  1884. {
  1885. constrainerIsResizing = true;
  1886. constrainer->resizeStart();
  1887. }
  1888. break;
  1889. default:
  1890. break;
  1891. }
  1892. }
  1893. }
  1894. void initialiseSysMenu (HMENU menu) const
  1895. {
  1896. if (! hasTitleBar())
  1897. {
  1898. if (isFullScreen())
  1899. {
  1900. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  1901. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  1902. }
  1903. else if (! isMinimised())
  1904. {
  1905. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  1906. }
  1907. }
  1908. }
  1909. void doSettingChange()
  1910. {
  1911. Desktop& desktop = Desktop::getInstance();
  1912. const_cast<Desktop::Displays&> (desktop.getDisplays()).refresh();
  1913. if (fullScreen && ! isMinimised())
  1914. {
  1915. const Desktop::Displays::Display& display
  1916. = desktop.getDisplays().getDisplayContaining (component.getScreenBounds().getCentre());
  1917. setWindowPos (hwnd, display.userArea * display.scale,
  1918. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  1919. }
  1920. }
  1921. void handleDPIChange() // happens when a window moves to a screen with a different DPI.
  1922. {
  1923. }
  1924. //==============================================================================
  1925. public:
  1926. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1927. {
  1928. if (HWNDComponentPeer* const peer = getOwnerOfWindow (h))
  1929. {
  1930. jassert (isValidPeer (peer));
  1931. return peer->peerWindowProc (h, message, wParam, lParam);
  1932. }
  1933. return DefWindowProcW (h, message, wParam, lParam);
  1934. }
  1935. private:
  1936. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  1937. {
  1938. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  1939. return callback (userData);
  1940. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  1941. }
  1942. static Point<float> getPointFromLParam (LPARAM lParam) noexcept
  1943. {
  1944. return Point<float> (static_cast<float> (GET_X_LPARAM (lParam)),
  1945. static_cast<float> (GET_Y_LPARAM (lParam)));
  1946. }
  1947. static Point<float> getCurrentMousePosGlobal() noexcept
  1948. {
  1949. return getPointFromLParam (GetMessagePos());
  1950. }
  1951. Point<float> getCurrentMousePos() noexcept
  1952. {
  1953. return globalToLocal (getCurrentMousePosGlobal());
  1954. }
  1955. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1956. {
  1957. switch (message)
  1958. {
  1959. //==============================================================================
  1960. case WM_NCHITTEST:
  1961. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  1962. return HTTRANSPARENT;
  1963. if (! hasTitleBar())
  1964. return HTCLIENT;
  1965. break;
  1966. //==============================================================================
  1967. case WM_PAINT:
  1968. handlePaintMessage();
  1969. return 0;
  1970. case WM_NCPAINT:
  1971. if (wParam != 1) // (1 = a repaint of the entire NC region)
  1972. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  1973. if (hasTitleBar())
  1974. break; // let the DefWindowProc handle drawing the frame.
  1975. return 0;
  1976. case WM_ERASEBKGND:
  1977. case WM_NCCALCSIZE:
  1978. if (hasTitleBar())
  1979. break;
  1980. return 1;
  1981. //==============================================================================
  1982. case WM_MOUSEMOVE: doMouseMove (getPointFromLParam (lParam)); return 0;
  1983. case WM_MOUSELEAVE: doMouseExit(); return 0;
  1984. case WM_LBUTTONDOWN:
  1985. case WM_MBUTTONDOWN:
  1986. case WM_RBUTTONDOWN: doMouseDown (getPointFromLParam (lParam), wParam); return 0;
  1987. case WM_LBUTTONUP:
  1988. case WM_MBUTTONUP:
  1989. case WM_RBUTTONUP: doMouseUp (getPointFromLParam (lParam), wParam); return 0;
  1990. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  1991. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  1992. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  1993. case WM_NCMOUSEMOVE:
  1994. if (hasTitleBar())
  1995. break;
  1996. return 0;
  1997. case WM_TOUCH:
  1998. if (getTouchInputInfo != nullptr)
  1999. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2000. break;
  2001. case 0x119: /* WM_GESTURE */
  2002. if (doGestureEvent (lParam))
  2003. return 0;
  2004. break;
  2005. //==============================================================================
  2006. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2007. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2008. case WM_WINDOWPOSCHANGED:
  2009. if (handlePositionChanged())
  2010. return 0;
  2011. break;
  2012. //==============================================================================
  2013. case WM_KEYDOWN:
  2014. case WM_SYSKEYDOWN:
  2015. if (doKeyDown (wParam))
  2016. return 0;
  2017. forwardMessageToParent (message, wParam, lParam);
  2018. break;
  2019. case WM_KEYUP:
  2020. case WM_SYSKEYUP:
  2021. if (doKeyUp (wParam))
  2022. return 0;
  2023. forwardMessageToParent (message, wParam, lParam);
  2024. break;
  2025. case WM_CHAR:
  2026. if (doKeyChar ((int) wParam, lParam))
  2027. return 0;
  2028. forwardMessageToParent (message, wParam, lParam);
  2029. break;
  2030. case WM_APPCOMMAND:
  2031. if (doAppCommand (lParam))
  2032. return TRUE;
  2033. break;
  2034. case WM_MENUCHAR: // triggered when alt+something is pressed
  2035. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2036. //==============================================================================
  2037. case WM_SETFOCUS:
  2038. updateKeyModifiers();
  2039. handleFocusGain();
  2040. break;
  2041. case WM_KILLFOCUS:
  2042. if (hasCreatedCaret)
  2043. {
  2044. hasCreatedCaret = false;
  2045. DestroyCaret();
  2046. }
  2047. handleFocusLoss();
  2048. break;
  2049. case WM_ACTIVATEAPP:
  2050. // Windows does weird things to process priority when you swap apps,
  2051. // so this forces an update when the app is brought to the front
  2052. if (wParam != FALSE)
  2053. juce_repeatLastProcessPriority();
  2054. else
  2055. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2056. juce_checkCurrentlyFocusedTopLevelWindow();
  2057. modifiersAtLastCallback = -1;
  2058. return 0;
  2059. case WM_ACTIVATE:
  2060. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2061. {
  2062. handleAppActivation (wParam);
  2063. return 0;
  2064. }
  2065. break;
  2066. case WM_NCACTIVATE:
  2067. // while a temporary window is being shown, prevent Windows from deactivating the
  2068. // title bars of our main windows.
  2069. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2070. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2071. break;
  2072. case WM_MOUSEACTIVATE:
  2073. if (! component.getMouseClickGrabsKeyboardFocus())
  2074. return MA_NOACTIVATE;
  2075. break;
  2076. case WM_SHOWWINDOW:
  2077. if (wParam != 0)
  2078. {
  2079. component.setVisible (true);
  2080. handleBroughtToFront();
  2081. }
  2082. break;
  2083. case WM_CLOSE:
  2084. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2085. handleUserClosingWindow();
  2086. return 0;
  2087. case WM_QUERYENDSESSION:
  2088. if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
  2089. {
  2090. app->systemRequestedQuit();
  2091. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2092. }
  2093. return TRUE;
  2094. case WM_POWERBROADCAST:
  2095. handlePowerBroadcast (wParam);
  2096. break;
  2097. case WM_SYNCPAINT:
  2098. return 0;
  2099. case WM_DISPLAYCHANGE:
  2100. InvalidateRect (h, 0, 0);
  2101. // intentional fall-through...
  2102. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  2103. doSettingChange();
  2104. break;
  2105. case 0x2e0: // WM_DPICHANGED
  2106. handleDPIChange();
  2107. break;
  2108. case WM_INITMENU:
  2109. initialiseSysMenu ((HMENU) wParam);
  2110. break;
  2111. case WM_SYSCOMMAND:
  2112. switch (wParam & 0xfff0)
  2113. {
  2114. case SC_CLOSE:
  2115. if (sendInputAttemptWhenModalMessage())
  2116. return 0;
  2117. if (hasTitleBar())
  2118. {
  2119. PostMessage (h, WM_CLOSE, 0, 0);
  2120. return 0;
  2121. }
  2122. break;
  2123. case SC_KEYMENU:
  2124. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  2125. // situations that can arise if a modal loop is started from an alt-key keypress).
  2126. if (hasTitleBar() && h == GetCapture())
  2127. ReleaseCapture();
  2128. break;
  2129. case SC_MAXIMIZE:
  2130. if (! sendInputAttemptWhenModalMessage())
  2131. setFullScreen (true);
  2132. return 0;
  2133. case SC_MINIMIZE:
  2134. if (sendInputAttemptWhenModalMessage())
  2135. return 0;
  2136. if (! hasTitleBar())
  2137. {
  2138. setMinimised (true);
  2139. return 0;
  2140. }
  2141. break;
  2142. case SC_RESTORE:
  2143. if (sendInputAttemptWhenModalMessage())
  2144. return 0;
  2145. if (hasTitleBar())
  2146. {
  2147. if (isFullScreen())
  2148. {
  2149. setFullScreen (false);
  2150. return 0;
  2151. }
  2152. }
  2153. else
  2154. {
  2155. if (isMinimised())
  2156. setMinimised (false);
  2157. else if (isFullScreen())
  2158. setFullScreen (false);
  2159. return 0;
  2160. }
  2161. break;
  2162. }
  2163. break;
  2164. case WM_NCLBUTTONDOWN:
  2165. handleLeftClickInNCArea (wParam);
  2166. break;
  2167. case WM_NCRBUTTONDOWN:
  2168. case WM_NCMBUTTONDOWN:
  2169. sendInputAttemptWhenModalMessage();
  2170. break;
  2171. case WM_IME_SETCONTEXT:
  2172. imeHandler.handleSetContext (h, wParam == TRUE);
  2173. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  2174. break;
  2175. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  2176. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  2177. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  2178. case WM_GETDLGCODE:
  2179. return DLGC_WANTALLKEYS;
  2180. default:
  2181. break;
  2182. }
  2183. return DefWindowProcW (h, message, wParam, lParam);
  2184. }
  2185. bool sendInputAttemptWhenModalMessage()
  2186. {
  2187. if (component.isCurrentlyBlockedByAnotherModalComponent())
  2188. {
  2189. if (Component* const current = Component::getCurrentlyModalComponent())
  2190. current->inputAttemptWhenModal();
  2191. return true;
  2192. }
  2193. return false;
  2194. }
  2195. //==============================================================================
  2196. class IMEHandler
  2197. {
  2198. public:
  2199. IMEHandler()
  2200. {
  2201. reset();
  2202. }
  2203. void handleSetContext (HWND hWnd, const bool windowIsActive)
  2204. {
  2205. if (compositionInProgress && ! windowIsActive)
  2206. {
  2207. compositionInProgress = false;
  2208. if (HIMC hImc = ImmGetContext (hWnd))
  2209. {
  2210. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  2211. ImmReleaseContext (hWnd, hImc);
  2212. }
  2213. }
  2214. }
  2215. void handleStartComposition (ComponentPeer& owner)
  2216. {
  2217. reset();
  2218. if (TextInputTarget* const target = owner.findCurrentTextInputTarget())
  2219. target->insertTextAtCaret (String::empty);
  2220. }
  2221. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  2222. {
  2223. if (compositionInProgress)
  2224. {
  2225. // If this occurs, the user has cancelled the composition, so clear their changes..
  2226. if (TextInputTarget* const target = owner.findCurrentTextInputTarget())
  2227. {
  2228. target->setHighlightedRegion (compositionRange);
  2229. target->insertTextAtCaret (String::empty);
  2230. compositionRange.setLength (0);
  2231. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  2232. target->setTemporaryUnderlining (Array<Range<int> >());
  2233. }
  2234. if (HIMC hImc = ImmGetContext (hWnd))
  2235. {
  2236. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  2237. ImmReleaseContext (hWnd, hImc);
  2238. }
  2239. }
  2240. reset();
  2241. }
  2242. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  2243. {
  2244. TextInputTarget* const target = owner.findCurrentTextInputTarget();
  2245. HIMC hImc = ImmGetContext (hWnd);
  2246. if (target == nullptr || hImc == 0)
  2247. return;
  2248. if (compositionRange.getStart() < 0)
  2249. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  2250. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  2251. {
  2252. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  2253. Range<int>::emptyRange (-1));
  2254. reset();
  2255. target->setTemporaryUnderlining (Array<Range<int> >());
  2256. }
  2257. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  2258. {
  2259. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  2260. getCompositionSelection (hImc, lParam));
  2261. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  2262. compositionInProgress = true;
  2263. }
  2264. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  2265. ImmReleaseContext (hWnd, hImc);
  2266. }
  2267. private:
  2268. //==============================================================================
  2269. Range<int> compositionRange; // The range being modified in the TextInputTarget
  2270. bool compositionInProgress;
  2271. //==============================================================================
  2272. void reset()
  2273. {
  2274. compositionRange = Range<int>::emptyRange (-1);
  2275. compositionInProgress = false;
  2276. }
  2277. String getCompositionString (HIMC hImc, const DWORD type) const
  2278. {
  2279. jassert (hImc != 0);
  2280. const int stringSizeBytes = ImmGetCompositionString (hImc, type, 0, 0);
  2281. if (stringSizeBytes > 0)
  2282. {
  2283. HeapBlock<TCHAR> buffer;
  2284. buffer.calloc (stringSizeBytes / sizeof (TCHAR) + 1);
  2285. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  2286. return String (buffer);
  2287. }
  2288. return String::empty;
  2289. }
  2290. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  2291. {
  2292. jassert (hImc != 0);
  2293. if ((lParam & CS_NOMOVECARET) != 0)
  2294. return compositionRange.getStart();
  2295. if ((lParam & GCS_CURSORPOS) != 0)
  2296. {
  2297. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, 0, 0);
  2298. return compositionRange.getStart() + jmax (0, localCaretPos);
  2299. }
  2300. return compositionRange.getStart() + currentIMEString.length();
  2301. }
  2302. // Get selected/highlighted range while doing composition:
  2303. // returned range is relative to beginning of TextInputTarget, not composition string
  2304. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  2305. {
  2306. jassert (hImc != 0);
  2307. int selectionStart = 0;
  2308. int selectionEnd = 0;
  2309. if ((lParam & GCS_COMPATTR) != 0)
  2310. {
  2311. // Get size of attributes array:
  2312. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, 0, 0);
  2313. if (attributeSizeBytes > 0)
  2314. {
  2315. // Get attributes (8 bit flag per character):
  2316. HeapBlock<char> attributes ((size_t) attributeSizeBytes);
  2317. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  2318. selectionStart = 0;
  2319. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  2320. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  2321. break;
  2322. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  2323. if (attributes [selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  2324. break;
  2325. }
  2326. }
  2327. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  2328. }
  2329. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  2330. {
  2331. if (compositionInProgress)
  2332. target->setHighlightedRegion (compositionRange);
  2333. target->insertTextAtCaret (newContent);
  2334. compositionRange.setLength (newContent.length());
  2335. if (newSelection.getStart() < 0)
  2336. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  2337. target->setHighlightedRegion (newSelection);
  2338. }
  2339. Array<Range<int> > getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  2340. {
  2341. Array<Range<int> > result;
  2342. if (hImc != 0 && (lParam & GCS_COMPCLAUSE) != 0)
  2343. {
  2344. const int clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, 0, 0);
  2345. if (clauseDataSizeBytes > 0)
  2346. {
  2347. const size_t numItems = clauseDataSizeBytes / sizeof (uint32);
  2348. HeapBlock<uint32> clauseData (numItems);
  2349. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  2350. for (size_t i = 0; i + 1 < numItems; ++i)
  2351. result.add (Range<int> ((int) clauseData [i], (int) clauseData [i + 1]) + compositionRange.getStart());
  2352. }
  2353. }
  2354. return result;
  2355. }
  2356. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  2357. {
  2358. if (Component* const targetComp = dynamic_cast<Component*> (target))
  2359. {
  2360. const Rectangle<int> area (peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle()));
  2361. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  2362. ImmSetCandidateWindow (hImc, &pos);
  2363. }
  2364. }
  2365. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  2366. };
  2367. IMEHandler imeHandler;
  2368. //==============================================================================
  2369. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  2370. };
  2371. ModifierKeys HWNDComponentPeer::currentModifiers;
  2372. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  2373. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  2374. {
  2375. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  2376. }
  2377. ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  2378. {
  2379. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  2380. (HWND) parentHWND, true);
  2381. }
  2382. juce_ImplementSingleton_SingleThreaded (HWNDComponentPeer::WindowClassHolder)
  2383. //==============================================================================
  2384. void ModifierKeys::updateCurrentModifiers() noexcept
  2385. {
  2386. currentModifiers = HWNDComponentPeer::currentModifiers;
  2387. }
  2388. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2389. {
  2390. HWNDComponentPeer::updateKeyModifiers();
  2391. int mouseMods = 0;
  2392. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  2393. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  2394. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  2395. HWNDComponentPeer::currentModifiers
  2396. = HWNDComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2397. return HWNDComponentPeer::currentModifiers;
  2398. }
  2399. //==============================================================================
  2400. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  2401. {
  2402. SHORT k = (SHORT) keyCode;
  2403. if ((keyCode & extendedKeyModifier) == 0
  2404. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  2405. k += (SHORT) 'A' - (SHORT) 'a';
  2406. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  2407. (SHORT) '+', VK_OEM_PLUS,
  2408. (SHORT) '-', VK_OEM_MINUS,
  2409. (SHORT) '.', VK_OEM_PERIOD,
  2410. (SHORT) ';', VK_OEM_1,
  2411. (SHORT) ':', VK_OEM_1,
  2412. (SHORT) '/', VK_OEM_2,
  2413. (SHORT) '?', VK_OEM_2,
  2414. (SHORT) '[', VK_OEM_4,
  2415. (SHORT) ']', VK_OEM_6 };
  2416. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  2417. if (k == translatedValues [i])
  2418. k = translatedValues [i + 1];
  2419. return HWNDComponentPeer::isKeyDown (k);
  2420. }
  2421. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2422. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  2423. #endif
  2424. //==============================================================================
  2425. bool JUCE_CALLTYPE Process::isForegroundProcess()
  2426. {
  2427. HWND fg = GetForegroundWindow();
  2428. if (fg == 0)
  2429. return true;
  2430. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  2431. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  2432. // have to see if any of our windows are children of the foreground window
  2433. fg = GetAncestor (fg, GA_ROOT);
  2434. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2435. if (HWNDComponentPeer* const wp = dynamic_cast<HWNDComponentPeer*> (ComponentPeer::getPeer (i)))
  2436. if (wp->isInside (fg))
  2437. return true;
  2438. return false;
  2439. }
  2440. // N/A on Windows as far as I know.
  2441. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2442. void JUCE_CALLTYPE Process::hide() {}
  2443. //==============================================================================
  2444. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  2445. {
  2446. if (IsWindowVisible (hwnd))
  2447. {
  2448. DWORD processID = 0;
  2449. GetWindowThreadProcessId (hwnd, &processID);
  2450. if (processID == GetCurrentProcessId())
  2451. {
  2452. WINDOWINFO info;
  2453. if (GetWindowInfo (hwnd, &info)
  2454. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  2455. {
  2456. *reinterpret_cast<bool*> (lParam) = true;
  2457. return FALSE;
  2458. }
  2459. }
  2460. }
  2461. return TRUE;
  2462. }
  2463. bool juce_areThereAnyAlwaysOnTopWindows()
  2464. {
  2465. bool anyAlwaysOnTopFound = false;
  2466. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  2467. return anyAlwaysOnTopFound;
  2468. }
  2469. //==============================================================================
  2470. class WindowsMessageBox : public AsyncUpdater
  2471. {
  2472. public:
  2473. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  2474. const String& boxTitle, const String& m,
  2475. Component* associatedComponent, UINT extraFlags,
  2476. ModalComponentManager::Callback* cb, const bool runAsync)
  2477. : flags (extraFlags | getMessageBoxFlags (iconType)),
  2478. owner (getWindowForMessageBox (associatedComponent)),
  2479. title (boxTitle), message (m), callback (cb)
  2480. {
  2481. if (runAsync)
  2482. triggerAsyncUpdate();
  2483. }
  2484. int getResult() const
  2485. {
  2486. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  2487. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO ? 2 : 0);
  2488. }
  2489. void handleAsyncUpdate() override
  2490. {
  2491. const int result = getResult();
  2492. if (callback != nullptr)
  2493. callback->modalStateFinished (result);
  2494. delete this;
  2495. }
  2496. private:
  2497. UINT flags;
  2498. HWND owner;
  2499. String title, message;
  2500. ScopedPointer<ModalComponentManager::Callback> callback;
  2501. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  2502. {
  2503. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  2504. switch (iconType)
  2505. {
  2506. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  2507. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  2508. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  2509. default: break;
  2510. }
  2511. return flags;
  2512. }
  2513. static HWND getWindowForMessageBox (Component* associatedComponent)
  2514. {
  2515. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : 0;
  2516. }
  2517. };
  2518. #if JUCE_MODAL_LOOPS_PERMITTED
  2519. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2520. const String& title, const String& message,
  2521. Component* associatedComponent)
  2522. {
  2523. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, 0, false);
  2524. (void) box.getResult();
  2525. }
  2526. #endif
  2527. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2528. const String& title, const String& message,
  2529. Component* associatedComponent,
  2530. ModalComponentManager::Callback* callback)
  2531. {
  2532. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  2533. }
  2534. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2535. const String& title, const String& message,
  2536. Component* associatedComponent,
  2537. ModalComponentManager::Callback* callback)
  2538. {
  2539. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  2540. MB_OKCANCEL, callback, callback != nullptr));
  2541. if (callback == nullptr)
  2542. return mb->getResult() != 0;
  2543. mb.release();
  2544. return false;
  2545. }
  2546. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2547. const String& title, const String& message,
  2548. Component* associatedComponent,
  2549. ModalComponentManager::Callback* callback)
  2550. {
  2551. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  2552. MB_YESNOCANCEL, callback, callback != nullptr));
  2553. if (callback == nullptr)
  2554. return mb->getResult();
  2555. mb.release();
  2556. return 0;
  2557. }
  2558. //==============================================================================
  2559. bool MouseInputSource::SourceList::addSource()
  2560. {
  2561. const int numSources = sources.size();
  2562. if (numSources == 0 || canUseMultiTouch())
  2563. {
  2564. addSource (numSources, numSources == 0);
  2565. return true;
  2566. }
  2567. return false;
  2568. }
  2569. Point<float> MouseInputSource::getCurrentRawMousePosition()
  2570. {
  2571. POINT mousePos;
  2572. GetCursorPos (&mousePos);
  2573. return Point<float> ((float) mousePos.x, (float) mousePos.y);
  2574. }
  2575. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  2576. {
  2577. SetCursorPos (roundToInt (newPosition.x),
  2578. roundToInt (newPosition.y));
  2579. }
  2580. //==============================================================================
  2581. class ScreenSaverDefeater : public Timer
  2582. {
  2583. public:
  2584. ScreenSaverDefeater()
  2585. {
  2586. startTimer (10000);
  2587. timerCallback();
  2588. }
  2589. void timerCallback() override
  2590. {
  2591. if (Process::isForegroundProcess())
  2592. {
  2593. INPUT input = { 0 };
  2594. input.type = INPUT_MOUSE;
  2595. input.mi.mouseData = MOUSEEVENTF_MOVE;
  2596. SendInput (1, &input, sizeof (INPUT));
  2597. }
  2598. }
  2599. };
  2600. static ScopedPointer<ScreenSaverDefeater> screenSaverDefeater;
  2601. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2602. {
  2603. if (isEnabled)
  2604. screenSaverDefeater = nullptr;
  2605. else if (screenSaverDefeater == nullptr)
  2606. screenSaverDefeater = new ScreenSaverDefeater();
  2607. }
  2608. bool Desktop::isScreenSaverEnabled()
  2609. {
  2610. return screenSaverDefeater == nullptr;
  2611. }
  2612. //==============================================================================
  2613. void LookAndFeel::playAlertSound()
  2614. {
  2615. MessageBeep (MB_OK);
  2616. }
  2617. //==============================================================================
  2618. void SystemClipboard::copyTextToClipboard (const String& text)
  2619. {
  2620. if (OpenClipboard (0) != 0)
  2621. {
  2622. if (EmptyClipboard() != 0)
  2623. {
  2624. const size_t bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  2625. if (bytesNeeded > 0)
  2626. {
  2627. if (HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  2628. {
  2629. if (WCHAR* const data = static_cast<WCHAR*> (GlobalLock (bufH)))
  2630. {
  2631. text.copyToUTF16 (data, bytesNeeded);
  2632. GlobalUnlock (bufH);
  2633. SetClipboardData (CF_UNICODETEXT, bufH);
  2634. }
  2635. }
  2636. }
  2637. }
  2638. CloseClipboard();
  2639. }
  2640. }
  2641. String SystemClipboard::getTextFromClipboard()
  2642. {
  2643. String result;
  2644. if (OpenClipboard (0) != 0)
  2645. {
  2646. if (HANDLE bufH = GetClipboardData (CF_UNICODETEXT))
  2647. {
  2648. if (const WCHAR* const data = (const WCHAR*) GlobalLock (bufH))
  2649. {
  2650. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  2651. GlobalUnlock (bufH);
  2652. }
  2653. }
  2654. CloseClipboard();
  2655. }
  2656. return result;
  2657. }
  2658. //==============================================================================
  2659. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  2660. {
  2661. if (TopLevelWindow* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComponent))
  2662. tlw->setUsingNativeTitleBar (! enableOrDisable);
  2663. if (enableOrDisable)
  2664. kioskModeComponent->setBounds (getDisplays().getMainDisplay().totalArea);
  2665. }
  2666. //==============================================================================
  2667. struct MonitorInfo
  2668. {
  2669. MonitorInfo (Rectangle<int> rect, bool main, double d) noexcept
  2670. : bounds (rect), dpi (d), isMain (main) {}
  2671. Rectangle<int> bounds;
  2672. double dpi;
  2673. bool isMain;
  2674. };
  2675. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  2676. {
  2677. MONITORINFO info = { 0 };
  2678. info.cbSize = sizeof (info);
  2679. GetMonitorInfo (hm, &info);
  2680. const bool isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  2681. double dpi = 0;
  2682. if (getDPIForMonitor != nullptr)
  2683. {
  2684. UINT dpiX = 0, dpiY = 0;
  2685. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  2686. dpi = (dpiX + dpiY) / 2.0;
  2687. }
  2688. ((Array<MonitorInfo>*) userInfo)->add (MonitorInfo (rectangleFromRECT (*r), isMain, dpi));
  2689. return TRUE;
  2690. }
  2691. void Desktop::Displays::findDisplays (float masterScale)
  2692. {
  2693. setDPIAwareness();
  2694. Array<MonitorInfo> monitors;
  2695. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitors);
  2696. const double globalDPI = getGlobalDPI();
  2697. if (monitors.size() == 0)
  2698. monitors.add (MonitorInfo (rectangleFromRECT (getWindowRect (GetDesktopWindow())), true, globalDPI));
  2699. // make sure the first in the list is the main monitor
  2700. for (int i = 1; i < monitors.size(); ++i)
  2701. if (monitors.getReference(i).isMain)
  2702. monitors.swap (i, 0);
  2703. RECT workArea;
  2704. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  2705. for (int i = 0; i < monitors.size(); ++i)
  2706. {
  2707. Display d;
  2708. d.userArea = d.totalArea = monitors.getReference(i).bounds / masterScale;
  2709. d.isMain = monitors.getReference(i).isMain;
  2710. d.dpi = monitors.getReference(i).dpi;
  2711. if (d.dpi == 0)
  2712. {
  2713. d.scale = masterScale;
  2714. d.dpi = globalDPI;
  2715. }
  2716. else
  2717. {
  2718. d.scale = d.dpi / 96.0;
  2719. }
  2720. if (d.isMain)
  2721. d.userArea = d.userArea.getIntersection (rectangleFromRECT (workArea) / masterScale);
  2722. displays.add (d);
  2723. }
  2724. }
  2725. //==============================================================================
  2726. static HICON extractFileHICON (const File& file)
  2727. {
  2728. WORD iconNum = 0;
  2729. WCHAR name [MAX_PATH * 2];
  2730. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  2731. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  2732. name, &iconNum);
  2733. }
  2734. Image juce_createIconForFile (const File& file)
  2735. {
  2736. Image image;
  2737. if (HICON icon = extractFileHICON (file))
  2738. {
  2739. image = IconConverters::createImageFromHICON (icon);
  2740. DestroyIcon (icon);
  2741. }
  2742. return image;
  2743. }
  2744. //==============================================================================
  2745. void* CustomMouseCursorInfo::create() const
  2746. {
  2747. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  2748. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  2749. Image im (image);
  2750. int hotspotX = hotspot.x;
  2751. int hotspotY = hotspot.y;
  2752. if (im.getWidth() > maxW || im.getHeight() > maxH)
  2753. {
  2754. im = im.rescaled (maxW, maxH);
  2755. hotspotX = (hotspotX * maxW) / image.getWidth();
  2756. hotspotY = (hotspotY * maxH) / image.getHeight();
  2757. }
  2758. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  2759. }
  2760. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  2761. {
  2762. if (cursorHandle != nullptr && ! isStandard)
  2763. DestroyCursor ((HCURSOR) cursorHandle);
  2764. }
  2765. enum
  2766. {
  2767. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  2768. };
  2769. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  2770. {
  2771. LPCTSTR cursorName = IDC_ARROW;
  2772. switch (type)
  2773. {
  2774. case NormalCursor:
  2775. case ParentCursor: break;
  2776. case NoCursor: return (void*) hiddenMouseCursorHandle;
  2777. case WaitCursor: cursorName = IDC_WAIT; break;
  2778. case IBeamCursor: cursorName = IDC_IBEAM; break;
  2779. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  2780. case CrosshairCursor: cursorName = IDC_CROSS; break;
  2781. case CopyingCursor: break; // can't seem to find one of these in the system list..
  2782. case LeftRightResizeCursor:
  2783. case LeftEdgeResizeCursor:
  2784. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  2785. case UpDownResizeCursor:
  2786. case TopEdgeResizeCursor:
  2787. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  2788. case TopLeftCornerResizeCursor:
  2789. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  2790. case TopRightCornerResizeCursor:
  2791. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  2792. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  2793. case DraggingHandCursor:
  2794. {
  2795. static void* dragHandCursor = nullptr;
  2796. if (dragHandCursor == nullptr)
  2797. {
  2798. static const unsigned char dragHandData[] =
  2799. { 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,
  2800. 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,
  2801. 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 };
  2802. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7).create();
  2803. }
  2804. return dragHandCursor;
  2805. }
  2806. default:
  2807. jassertfalse; break;
  2808. }
  2809. HCURSOR cursorH = LoadCursor (0, cursorName);
  2810. if (cursorH == 0)
  2811. cursorH = LoadCursor (0, IDC_ARROW);
  2812. return cursorH;
  2813. }
  2814. //==============================================================================
  2815. void MouseCursor::showInWindow (ComponentPeer*) const
  2816. {
  2817. HCURSOR c = (HCURSOR) getHandle();
  2818. if (c == 0)
  2819. c = LoadCursor (0, IDC_ARROW);
  2820. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  2821. c = 0;
  2822. SetCursor (c);
  2823. }
  2824. void MouseCursor::showInAllWindows() const
  2825. {
  2826. showInWindow (nullptr);
  2827. }