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 115KB

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