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

juce_win32_Windowing.cpp 122KB

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