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

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