The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

3106 lines
101KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  19. // compiled on its own).
  20. #if JUCE_INCLUDED_FILE
  21. //==============================================================================
  22. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  23. // these are in the windows SDK, but need to be repeated here for GCC..
  24. #ifndef GET_APPCOMMAND_LPARAM
  25. #define FAPPCOMMAND_MASK 0xF000
  26. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  27. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  28. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  29. #define APPCOMMAND_MEDIA_STOP 13
  30. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  31. #define WM_APPCOMMAND 0x0319
  32. #endif
  33. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  34. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  35. extern bool juce_IsRunningInWine() throw();
  36. #ifndef ULW_ALPHA
  37. #define ULW_ALPHA 0x00000002
  38. #endif
  39. #ifndef AC_SRC_ALPHA
  40. #define AC_SRC_ALPHA 0x01
  41. #endif
  42. #define DEBUG_REPAINT_TIMES 0
  43. static HPALETTE palette = 0;
  44. static bool createPaletteIfNeeded = true;
  45. static bool shouldDeactivateTitleBar = true;
  46. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  47. #define WM_TRAYNOTIFY WM_USER + 100
  48. using ::abs;
  49. //==============================================================================
  50. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  51. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  52. bool Desktop::canUseSemiTransparentWindows() throw()
  53. {
  54. if (updateLayeredWindow == 0)
  55. {
  56. if (! juce_IsRunningInWine())
  57. {
  58. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  59. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  60. }
  61. }
  62. return updateLayeredWindow != 0;
  63. }
  64. //==============================================================================
  65. #undef DefWindowProc
  66. #define DefWindowProc DefWindowProcW
  67. //==============================================================================
  68. const int extendedKeyModifier = 0x10000;
  69. const int KeyPress::spaceKey = VK_SPACE;
  70. const int KeyPress::returnKey = VK_RETURN;
  71. const int KeyPress::escapeKey = VK_ESCAPE;
  72. const int KeyPress::backspaceKey = VK_BACK;
  73. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  74. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  75. const int KeyPress::tabKey = VK_TAB;
  76. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  77. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  78. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  79. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  80. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  81. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  82. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  83. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  84. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  85. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  86. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  87. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  88. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  89. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  90. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  91. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  92. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  93. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  94. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  95. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  96. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  97. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  98. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  99. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  100. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  101. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  102. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  103. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  104. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  105. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  106. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  107. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  108. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  109. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  110. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  111. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  112. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  113. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  114. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  115. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  116. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  117. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  118. const int KeyPress::playKey = 0x30000;
  119. const int KeyPress::stopKey = 0x30001;
  120. const int KeyPress::fastForwardKey = 0x30002;
  121. const int KeyPress::rewindKey = 0x30003;
  122. //==============================================================================
  123. class WindowsBitmapImage : public Image
  124. {
  125. public:
  126. //==============================================================================
  127. HBITMAP hBitmap;
  128. BITMAPV4HEADER bitmapInfo;
  129. HDC hdc;
  130. unsigned char* bitmapData;
  131. //==============================================================================
  132. WindowsBitmapImage (const PixelFormat format_,
  133. const int w, const int h, const bool clearImage)
  134. : Image (format_, w, h)
  135. {
  136. jassert (format_ == RGB || format_ == ARGB);
  137. pixelStride = (format_ == RGB) ? 3 : 4;
  138. zerostruct (bitmapInfo);
  139. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  140. bitmapInfo.bV4Width = w;
  141. bitmapInfo.bV4Height = h;
  142. bitmapInfo.bV4Planes = 1;
  143. bitmapInfo.bV4CSType = 1;
  144. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  145. if (format_ == ARGB)
  146. {
  147. bitmapInfo.bV4AlphaMask = 0xff000000;
  148. bitmapInfo.bV4RedMask = 0xff0000;
  149. bitmapInfo.bV4GreenMask = 0xff00;
  150. bitmapInfo.bV4BlueMask = 0xff;
  151. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  152. }
  153. else
  154. {
  155. bitmapInfo.bV4V4Compression = BI_RGB;
  156. }
  157. lineStride = -((w * pixelStride + 3) & ~3);
  158. HDC dc = GetDC (0);
  159. hdc = CreateCompatibleDC (dc);
  160. ReleaseDC (0, dc);
  161. SetMapMode (hdc, MM_TEXT);
  162. hBitmap = CreateDIBSection (hdc,
  163. (BITMAPINFO*) &(bitmapInfo),
  164. DIB_RGB_COLORS,
  165. (void**) &bitmapData,
  166. 0, 0);
  167. SelectObject (hdc, hBitmap);
  168. if (format_ == ARGB && clearImage)
  169. zeromem (bitmapData, abs (h * lineStride));
  170. imageData = bitmapData - (lineStride * (h - 1));
  171. }
  172. ~WindowsBitmapImage()
  173. {
  174. DeleteDC (hdc);
  175. DeleteObject (hBitmap);
  176. imageData = 0; // to stop the base class freeing this
  177. }
  178. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  179. const int x, const int y,
  180. const RectangleList& maskedRegion) throw()
  181. {
  182. static HDRAWDIB hdd = 0;
  183. static bool needToCreateDrawDib = true;
  184. if (needToCreateDrawDib)
  185. {
  186. needToCreateDrawDib = false;
  187. HDC dc = GetDC (0);
  188. const int n = GetDeviceCaps (dc, BITSPIXEL);
  189. ReleaseDC (0, dc);
  190. // only open if we're not palettised
  191. if (n > 8)
  192. hdd = DrawDibOpen();
  193. }
  194. if (createPaletteIfNeeded)
  195. {
  196. HDC dc = GetDC (0);
  197. const int n = GetDeviceCaps (dc, BITSPIXEL);
  198. ReleaseDC (0, dc);
  199. if (n <= 8)
  200. palette = CreateHalftonePalette (dc);
  201. createPaletteIfNeeded = false;
  202. }
  203. if (palette != 0)
  204. {
  205. SelectPalette (dc, palette, FALSE);
  206. RealizePalette (dc);
  207. SetStretchBltMode (dc, HALFTONE);
  208. }
  209. SetMapMode (dc, MM_TEXT);
  210. if (transparent)
  211. {
  212. POINT p, pos;
  213. SIZE size;
  214. RECT windowBounds;
  215. GetWindowRect (hwnd, &windowBounds);
  216. p.x = -x;
  217. p.y = -y;
  218. pos.x = windowBounds.left;
  219. pos.y = windowBounds.top;
  220. size.cx = windowBounds.right - windowBounds.left;
  221. size.cy = windowBounds.bottom - windowBounds.top;
  222. BLENDFUNCTION bf;
  223. bf.AlphaFormat = AC_SRC_ALPHA;
  224. bf.BlendFlags = 0;
  225. bf.BlendOp = AC_SRC_OVER;
  226. bf.SourceConstantAlpha = 0xff;
  227. if (! maskedRegion.isEmpty())
  228. {
  229. for (RectangleList::Iterator i (maskedRegion); i.next();)
  230. {
  231. const Rectangle& r = *i.getRectangle();
  232. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  233. }
  234. }
  235. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  236. }
  237. else
  238. {
  239. int savedDC = 0;
  240. if (! maskedRegion.isEmpty())
  241. {
  242. savedDC = SaveDC (dc);
  243. for (RectangleList::Iterator i (maskedRegion); i.next();)
  244. {
  245. const Rectangle& r = *i.getRectangle();
  246. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  247. }
  248. }
  249. const int w = getWidth();
  250. const int h = getHeight();
  251. if (hdd == 0)
  252. {
  253. StretchDIBits (dc,
  254. x, y, w, h,
  255. 0, 0, w, h,
  256. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  257. DIB_RGB_COLORS, SRCCOPY);
  258. }
  259. else
  260. {
  261. DrawDibDraw (hdd, dc, x, y, -1, -1,
  262. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  263. 0, 0, w, h, 0);
  264. }
  265. if (! maskedRegion.isEmpty())
  266. RestoreDC (dc, savedDC);
  267. }
  268. }
  269. juce_UseDebuggingNewOperator
  270. private:
  271. WindowsBitmapImage (const WindowsBitmapImage&);
  272. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  273. };
  274. //==============================================================================
  275. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  276. //==============================================================================
  277. static int currentModifiers = 0;
  278. static int modifiersAtLastCallback = 0;
  279. static void updateKeyModifiers() throw()
  280. {
  281. currentModifiers &= ~(ModifierKeys::shiftModifier
  282. | ModifierKeys::ctrlModifier
  283. | ModifierKeys::altModifier);
  284. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  285. currentModifiers |= ModifierKeys::shiftModifier;
  286. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  287. currentModifiers |= ModifierKeys::ctrlModifier;
  288. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  289. currentModifiers |= ModifierKeys::altModifier;
  290. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  291. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  292. }
  293. void ModifierKeys::updateCurrentModifiers() throw()
  294. {
  295. currentModifierFlags = currentModifiers;
  296. }
  297. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  298. {
  299. SHORT k = (SHORT) keyCode;
  300. if ((keyCode & extendedKeyModifier) == 0
  301. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  302. k += (SHORT) T('A') - (SHORT) T('a');
  303. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  304. (SHORT) '+', VK_OEM_PLUS,
  305. (SHORT) '-', VK_OEM_MINUS,
  306. (SHORT) '.', VK_OEM_PERIOD,
  307. (SHORT) ';', VK_OEM_1,
  308. (SHORT) ':', VK_OEM_1,
  309. (SHORT) '/', VK_OEM_2,
  310. (SHORT) '?', VK_OEM_2,
  311. (SHORT) '[', VK_OEM_4,
  312. (SHORT) ']', VK_OEM_6 };
  313. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  314. if (k == translatedValues [i])
  315. k = translatedValues [i + 1];
  316. return (GetKeyState (k) & 0x8000) != 0;
  317. }
  318. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  319. {
  320. updateKeyModifiers();
  321. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  322. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  323. currentModifiers |= ModifierKeys::leftButtonModifier;
  324. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  325. currentModifiers |= ModifierKeys::rightButtonModifier;
  326. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  327. currentModifiers |= ModifierKeys::middleButtonModifier;
  328. return ModifierKeys (currentModifiers);
  329. }
  330. static int64 getMouseEventTime() throw()
  331. {
  332. static int64 eventTimeOffset = 0;
  333. static DWORD lastMessageTime = 0;
  334. const DWORD thisMessageTime = GetMessageTime();
  335. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  336. {
  337. lastMessageTime = thisMessageTime;
  338. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  339. }
  340. return eventTimeOffset + thisMessageTime;
  341. }
  342. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  343. {
  344. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  345. return callback (userData);
  346. else
  347. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  348. }
  349. //==============================================================================
  350. class Win32ComponentPeer : public ComponentPeer
  351. {
  352. public:
  353. //==============================================================================
  354. Win32ComponentPeer (Component* const component,
  355. const int windowStyleFlags)
  356. : ComponentPeer (component, windowStyleFlags),
  357. dontRepaint (false),
  358. fullScreen (false),
  359. isDragging (false),
  360. isMouseOver (false),
  361. hasCreatedCaret (false),
  362. currentWindowIcon (0),
  363. taskBarIcon (0),
  364. dropTarget (0)
  365. {
  366. callFunctionIfNotLocked (&createWindowCallback, (void*) this);
  367. setTitle (component->getName());
  368. if ((windowStyleFlags & windowHasDropShadow) != 0
  369. && Desktop::canUseSemiTransparentWindows())
  370. {
  371. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  372. if (shadower != 0)
  373. shadower->setOwner (component);
  374. }
  375. else
  376. {
  377. shadower = 0;
  378. }
  379. }
  380. ~Win32ComponentPeer()
  381. {
  382. setTaskBarIcon (0);
  383. deleteAndZero (shadower);
  384. // do this before the next bit to avoid messages arriving for this window
  385. // before it's destroyed
  386. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  387. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  388. if (currentWindowIcon != 0)
  389. DestroyIcon (currentWindowIcon);
  390. if (dropTarget != 0)
  391. {
  392. dropTarget->Release();
  393. dropTarget = 0;
  394. }
  395. }
  396. //==============================================================================
  397. void* getNativeHandle() const
  398. {
  399. return (void*) hwnd;
  400. }
  401. void setVisible (bool shouldBeVisible)
  402. {
  403. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  404. if (shouldBeVisible)
  405. InvalidateRect (hwnd, 0, 0);
  406. else
  407. lastPaintTime = 0;
  408. }
  409. void setTitle (const String& title)
  410. {
  411. SetWindowText (hwnd, title);
  412. }
  413. void setPosition (int x, int y)
  414. {
  415. offsetWithinParent (x, y);
  416. SetWindowPos (hwnd, 0,
  417. x - windowBorder.getLeft(),
  418. y - windowBorder.getTop(),
  419. 0, 0,
  420. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  421. }
  422. void repaintNowIfTransparent()
  423. {
  424. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  425. handlePaintMessage();
  426. }
  427. void updateBorderSize()
  428. {
  429. WINDOWINFO info;
  430. info.cbSize = sizeof (info);
  431. if (GetWindowInfo (hwnd, &info))
  432. {
  433. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  434. info.rcClient.left - info.rcWindow.left,
  435. info.rcWindow.bottom - info.rcClient.bottom,
  436. info.rcWindow.right - info.rcClient.right);
  437. }
  438. }
  439. void setSize (int w, int h)
  440. {
  441. SetWindowPos (hwnd, 0, 0, 0,
  442. w + windowBorder.getLeftAndRight(),
  443. h + windowBorder.getTopAndBottom(),
  444. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  445. updateBorderSize();
  446. repaintNowIfTransparent();
  447. }
  448. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  449. {
  450. fullScreen = isNowFullScreen;
  451. offsetWithinParent (x, y);
  452. SetWindowPos (hwnd, 0,
  453. x - windowBorder.getLeft(),
  454. y - windowBorder.getTop(),
  455. w + windowBorder.getLeftAndRight(),
  456. h + windowBorder.getTopAndBottom(),
  457. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  458. updateBorderSize();
  459. repaintNowIfTransparent();
  460. }
  461. void getBounds (int& x, int& y, int& w, int& h) const
  462. {
  463. RECT r;
  464. GetWindowRect (hwnd, &r);
  465. x = r.left;
  466. y = r.top;
  467. w = r.right - x;
  468. h = r.bottom - y;
  469. HWND parentH = GetParent (hwnd);
  470. if (parentH != 0)
  471. {
  472. GetWindowRect (parentH, &r);
  473. x -= r.left;
  474. y -= r.top;
  475. }
  476. x += windowBorder.getLeft();
  477. y += windowBorder.getTop();
  478. w -= windowBorder.getLeftAndRight();
  479. h -= windowBorder.getTopAndBottom();
  480. }
  481. int getScreenX() const
  482. {
  483. RECT r;
  484. GetWindowRect (hwnd, &r);
  485. return r.left + windowBorder.getLeft();
  486. }
  487. int getScreenY() const
  488. {
  489. RECT r;
  490. GetWindowRect (hwnd, &r);
  491. return r.top + windowBorder.getTop();
  492. }
  493. void relativePositionToGlobal (int& x, int& y)
  494. {
  495. RECT r;
  496. GetWindowRect (hwnd, &r);
  497. x += r.left + windowBorder.getLeft();
  498. y += r.top + windowBorder.getTop();
  499. }
  500. void globalPositionToRelative (int& x, int& y)
  501. {
  502. RECT r;
  503. GetWindowRect (hwnd, &r);
  504. x -= r.left + windowBorder.getLeft();
  505. y -= r.top + windowBorder.getTop();
  506. }
  507. void setMinimised (bool shouldBeMinimised)
  508. {
  509. if (shouldBeMinimised != isMinimised())
  510. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  511. }
  512. bool isMinimised() const
  513. {
  514. WINDOWPLACEMENT wp;
  515. wp.length = sizeof (WINDOWPLACEMENT);
  516. GetWindowPlacement (hwnd, &wp);
  517. return wp.showCmd == SW_SHOWMINIMIZED;
  518. }
  519. void setFullScreen (bool shouldBeFullScreen)
  520. {
  521. setMinimised (false);
  522. if (fullScreen != shouldBeFullScreen)
  523. {
  524. fullScreen = shouldBeFullScreen;
  525. const ComponentDeletionWatcher deletionChecker (component);
  526. if (! fullScreen)
  527. {
  528. const Rectangle boundsCopy (lastNonFullscreenBounds);
  529. if (hasTitleBar())
  530. ShowWindow (hwnd, SW_SHOWNORMAL);
  531. if (! boundsCopy.isEmpty())
  532. {
  533. setBounds (boundsCopy.getX(),
  534. boundsCopy.getY(),
  535. boundsCopy.getWidth(),
  536. boundsCopy.getHeight(),
  537. false);
  538. }
  539. }
  540. else
  541. {
  542. if (hasTitleBar())
  543. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  544. else
  545. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  546. }
  547. if (! deletionChecker.hasBeenDeleted())
  548. handleMovedOrResized();
  549. }
  550. }
  551. bool isFullScreen() const
  552. {
  553. if (! hasTitleBar())
  554. return fullScreen;
  555. WINDOWPLACEMENT wp;
  556. wp.length = sizeof (wp);
  557. GetWindowPlacement (hwnd, &wp);
  558. return wp.showCmd == SW_SHOWMAXIMIZED;
  559. }
  560. bool contains (int x, int y, bool trueIfInAChildWindow) const
  561. {
  562. RECT r;
  563. GetWindowRect (hwnd, &r);
  564. POINT p;
  565. p.x = x + r.left + windowBorder.getLeft();
  566. p.y = y + r.top + windowBorder.getTop();
  567. HWND w = WindowFromPoint (p);
  568. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  569. }
  570. const BorderSize getFrameSize() const
  571. {
  572. return windowBorder;
  573. }
  574. bool setAlwaysOnTop (bool alwaysOnTop)
  575. {
  576. const bool oldDeactivate = shouldDeactivateTitleBar;
  577. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  578. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  579. 0, 0, 0, 0,
  580. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  581. shouldDeactivateTitleBar = oldDeactivate;
  582. if (shadower != 0)
  583. shadower->componentBroughtToFront (*component);
  584. return true;
  585. }
  586. void toFront (bool makeActive)
  587. {
  588. setMinimised (false);
  589. const bool oldDeactivate = shouldDeactivateTitleBar;
  590. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  591. callFunctionIfNotLocked (makeActive ? &toFrontCallback1
  592. : &toFrontCallback2,
  593. (void*) hwnd);
  594. shouldDeactivateTitleBar = oldDeactivate;
  595. if (! makeActive)
  596. {
  597. // in this case a broughttofront call won't have occured, so do it now..
  598. handleBroughtToFront();
  599. }
  600. }
  601. void toBehind (ComponentPeer* other)
  602. {
  603. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  604. jassert (otherPeer != 0); // wrong type of window?
  605. if (otherPeer != 0)
  606. {
  607. setMinimised (false);
  608. // must be careful not to try to put a topmost window behind a normal one, or win32
  609. // promotes the normal one to be topmost!
  610. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  611. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  612. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  613. else if (otherPeer->getComponent()->isAlwaysOnTop())
  614. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  615. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  616. }
  617. }
  618. bool isFocused() const
  619. {
  620. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  621. }
  622. void grabFocus()
  623. {
  624. const bool oldDeactivate = shouldDeactivateTitleBar;
  625. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  626. callFunctionIfNotLocked (&setFocusCallback, (void*) hwnd);
  627. shouldDeactivateTitleBar = oldDeactivate;
  628. }
  629. void textInputRequired (int /*x*/, int /*y*/)
  630. {
  631. if (! hasCreatedCaret)
  632. {
  633. hasCreatedCaret = true;
  634. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  635. }
  636. ShowCaret (hwnd);
  637. SetCaretPos (0, 0);
  638. }
  639. void repaint (int x, int y, int w, int h)
  640. {
  641. const RECT r = { x, y, x + w, y + h };
  642. InvalidateRect (hwnd, &r, FALSE);
  643. }
  644. void performAnyPendingRepaintsNow()
  645. {
  646. MSG m;
  647. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  648. DispatchMessage (&m);
  649. }
  650. //==============================================================================
  651. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  652. {
  653. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  654. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  655. return 0;
  656. }
  657. //==============================================================================
  658. void setTaskBarIcon (const Image* const image)
  659. {
  660. if (image != 0)
  661. {
  662. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  663. if (taskBarIcon == 0)
  664. {
  665. taskBarIcon = new NOTIFYICONDATA();
  666. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  667. taskBarIcon->hWnd = (HWND) hwnd;
  668. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  669. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  670. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  671. taskBarIcon->hIcon = hicon;
  672. taskBarIcon->szTip[0] = 0;
  673. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  674. }
  675. else
  676. {
  677. HICON oldIcon = taskBarIcon->hIcon;
  678. taskBarIcon->hIcon = hicon;
  679. taskBarIcon->uFlags = NIF_ICON;
  680. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  681. DestroyIcon (oldIcon);
  682. }
  683. DestroyIcon (hicon);
  684. }
  685. else if (taskBarIcon != 0)
  686. {
  687. taskBarIcon->uFlags = 0;
  688. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  689. DestroyIcon (taskBarIcon->hIcon);
  690. deleteAndZero (taskBarIcon);
  691. }
  692. }
  693. void setTaskBarIconToolTip (const String& toolTip) const
  694. {
  695. if (taskBarIcon != 0)
  696. {
  697. taskBarIcon->uFlags = NIF_TIP;
  698. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  699. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  700. }
  701. }
  702. bool isInside (HWND h) const
  703. {
  704. return GetAncestor (hwnd, GA_ROOT) == h;
  705. }
  706. //==============================================================================
  707. juce_UseDebuggingNewOperator
  708. bool dontRepaint;
  709. private:
  710. HWND hwnd;
  711. DropShadower* shadower;
  712. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  713. BorderSize windowBorder;
  714. HICON currentWindowIcon;
  715. NOTIFYICONDATA* taskBarIcon;
  716. IDropTarget* dropTarget;
  717. //==============================================================================
  718. class TemporaryImage : public Timer
  719. {
  720. public:
  721. //==============================================================================
  722. TemporaryImage()
  723. : image (0)
  724. {
  725. }
  726. ~TemporaryImage()
  727. {
  728. delete image;
  729. }
  730. //==============================================================================
  731. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  732. {
  733. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  734. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  735. {
  736. delete image;
  737. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  738. }
  739. startTimer (3000);
  740. return image;
  741. }
  742. //==============================================================================
  743. void timerCallback()
  744. {
  745. stopTimer();
  746. deleteAndZero (image);
  747. }
  748. private:
  749. WindowsBitmapImage* image;
  750. TemporaryImage (const TemporaryImage&);
  751. const TemporaryImage& operator= (const TemporaryImage&);
  752. };
  753. TemporaryImage offscreenImageGenerator;
  754. //==============================================================================
  755. class WindowClassHolder : public DeletedAtShutdown
  756. {
  757. public:
  758. WindowClassHolder()
  759. : windowClassName ("JUCE_")
  760. {
  761. // this name has to be different for each app/dll instance because otherwise
  762. // poor old Win32 can get a bit confused (even despite it not being a process-global
  763. // window class).
  764. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  765. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  766. TCHAR moduleFile [1024];
  767. moduleFile[0] = 0;
  768. GetModuleFileName (moduleHandle, moduleFile, 1024);
  769. WORD iconNum = 0;
  770. WNDCLASSEX wcex;
  771. wcex.cbSize = sizeof (wcex);
  772. wcex.style = CS_OWNDC;
  773. wcex.lpfnWndProc = (WNDPROC) windowProc;
  774. wcex.lpszClassName = windowClassName;
  775. wcex.cbClsExtra = 0;
  776. wcex.cbWndExtra = 32;
  777. wcex.hInstance = moduleHandle;
  778. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  779. iconNum = 1;
  780. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  781. wcex.hCursor = 0;
  782. wcex.hbrBackground = 0;
  783. wcex.lpszMenuName = 0;
  784. RegisterClassEx (&wcex);
  785. }
  786. ~WindowClassHolder()
  787. {
  788. if (ComponentPeer::getNumPeers() == 0)
  789. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  790. clearSingletonInstance();
  791. }
  792. String windowClassName;
  793. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  794. };
  795. //==============================================================================
  796. static void* createWindowCallback (void* userData)
  797. {
  798. ((Win32ComponentPeer*) userData)->createWindow();
  799. return 0;
  800. }
  801. void createWindow()
  802. {
  803. DWORD exstyle = WS_EX_ACCEPTFILES;
  804. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  805. if (hasTitleBar())
  806. {
  807. type |= WS_OVERLAPPED;
  808. exstyle |= WS_EX_APPWINDOW;
  809. if ((styleFlags & windowHasCloseButton) != 0)
  810. {
  811. type |= WS_SYSMENU;
  812. }
  813. else
  814. {
  815. // annoyingly, windows won't let you have a min/max button without a close button
  816. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  817. }
  818. if ((styleFlags & windowIsResizable) != 0)
  819. type |= WS_THICKFRAME;
  820. }
  821. else
  822. {
  823. type |= WS_POPUP | WS_SYSMENU;
  824. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  825. exstyle |= WS_EX_TOOLWINDOW;
  826. else
  827. exstyle |= WS_EX_APPWINDOW;
  828. }
  829. if ((styleFlags & windowHasMinimiseButton) != 0)
  830. type |= WS_MINIMIZEBOX;
  831. if ((styleFlags & windowHasMaximiseButton) != 0)
  832. type |= WS_MAXIMIZEBOX;
  833. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  834. exstyle |= WS_EX_TRANSPARENT;
  835. if ((styleFlags & windowIsSemiTransparent) != 0
  836. && Desktop::canUseSemiTransparentWindows())
  837. exstyle |= WS_EX_LAYERED;
  838. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  839. if (hwnd != 0)
  840. {
  841. SetWindowLongPtr (hwnd, 0, 0);
  842. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  843. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  844. if (dropTarget == 0)
  845. dropTarget = new JuceDropTarget (this);
  846. RegisterDragDrop (hwnd, dropTarget);
  847. updateBorderSize();
  848. // Calling this function here is (for some reason) necessary to make Windows
  849. // correctly enable the menu items that we specify in the wm_initmenu message.
  850. GetSystemMenu (hwnd, false);
  851. }
  852. else
  853. {
  854. jassertfalse
  855. }
  856. }
  857. static void* destroyWindowCallback (void* handle)
  858. {
  859. RevokeDragDrop ((HWND) handle);
  860. DestroyWindow ((HWND) handle);
  861. return 0;
  862. }
  863. static void* toFrontCallback1 (void* h)
  864. {
  865. SetForegroundWindow ((HWND) h);
  866. return 0;
  867. }
  868. static void* toFrontCallback2 (void* h)
  869. {
  870. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  871. return 0;
  872. }
  873. static void* setFocusCallback (void* h)
  874. {
  875. SetFocus ((HWND) h);
  876. return 0;
  877. }
  878. static void* getFocusCallback (void*)
  879. {
  880. return (void*) GetFocus();
  881. }
  882. void offsetWithinParent (int& x, int& y) const
  883. {
  884. if (isTransparent())
  885. {
  886. HWND parentHwnd = GetParent (hwnd);
  887. if (parentHwnd != 0)
  888. {
  889. RECT parentRect;
  890. GetWindowRect (parentHwnd, &parentRect);
  891. x += parentRect.left;
  892. y += parentRect.top;
  893. }
  894. }
  895. }
  896. bool isTransparent() const
  897. {
  898. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  899. }
  900. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  901. void setIcon (const Image& newIcon)
  902. {
  903. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  904. if (hicon != 0)
  905. {
  906. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  907. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  908. if (currentWindowIcon != 0)
  909. DestroyIcon (currentWindowIcon);
  910. currentWindowIcon = hicon;
  911. }
  912. }
  913. //==============================================================================
  914. void handlePaintMessage()
  915. {
  916. #if DEBUG_REPAINT_TIMES
  917. const double paintStart = Time::getMillisecondCounterHiRes();
  918. #endif
  919. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  920. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  921. PAINTSTRUCT paintStruct;
  922. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  923. // message and become re-entrant, but that's OK
  924. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  925. // corrupt the image it's using to paint into, so do a check here.
  926. static bool reentrant = false;
  927. if (reentrant)
  928. {
  929. DeleteObject (rgn);
  930. EndPaint (hwnd, &paintStruct);
  931. return;
  932. }
  933. reentrant = true;
  934. // this is the rectangle to update..
  935. int x = paintStruct.rcPaint.left;
  936. int y = paintStruct.rcPaint.top;
  937. int w = paintStruct.rcPaint.right - x;
  938. int h = paintStruct.rcPaint.bottom - y;
  939. const bool transparent = isTransparent();
  940. if (transparent)
  941. {
  942. // it's not possible to have a transparent window with a title bar at the moment!
  943. jassert (! hasTitleBar());
  944. RECT r;
  945. GetWindowRect (hwnd, &r);
  946. x = y = 0;
  947. w = r.right - r.left;
  948. h = r.bottom - r.top;
  949. }
  950. if (w > 0 && h > 0)
  951. {
  952. clearMaskedRegion();
  953. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  954. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  955. RectangleList* const contextClip = context.getRawClipRegion();
  956. contextClip->clear();
  957. context.setOrigin (-x, -y);
  958. bool needToPaintAll = true;
  959. if (regionType == COMPLEXREGION && ! transparent)
  960. {
  961. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  962. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  963. DeleteObject (clipRgn);
  964. char rgnData [8192];
  965. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  966. if (res > 0 && res <= sizeof (rgnData))
  967. {
  968. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  969. if (hdr->iType == RDH_RECTANGLES
  970. && hdr->rcBound.right - hdr->rcBound.left >= w
  971. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  972. {
  973. needToPaintAll = false;
  974. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  975. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  976. while (--num >= 0)
  977. {
  978. // (need to move this one pixel to the left because of a win32 bug)
  979. const int cx = jmax (x, rects->left - 1);
  980. const int cy = rects->top;
  981. const int cw = rects->right - cx;
  982. const int ch = rects->bottom - rects->top;
  983. if (cx + cw - x <= w && cy + ch - y <= h)
  984. {
  985. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  986. }
  987. else
  988. {
  989. needToPaintAll = true;
  990. break;
  991. }
  992. ++rects;
  993. }
  994. }
  995. }
  996. }
  997. if (needToPaintAll)
  998. {
  999. contextClip->clear();
  1000. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  1001. }
  1002. if (transparent)
  1003. {
  1004. RectangleList::Iterator i (*contextClip);
  1005. while (i.next())
  1006. {
  1007. const Rectangle& r = *i.getRectangle();
  1008. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  1009. }
  1010. }
  1011. // if the component's not opaque, this won't draw properly unless the platform can support this
  1012. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  1013. updateCurrentModifiers();
  1014. handlePaint (context);
  1015. if (! dontRepaint)
  1016. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  1017. }
  1018. DeleteObject (rgn);
  1019. EndPaint (hwnd, &paintStruct);
  1020. reentrant = false;
  1021. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  1022. _fpreset(); // because some graphics cards can unmask FP exceptions
  1023. #endif
  1024. lastPaintTime = Time::getMillisecondCounter();
  1025. #if DEBUG_REPAINT_TIMES
  1026. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  1027. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  1028. #endif
  1029. }
  1030. //==============================================================================
  1031. void doMouseMove (const int x, const int y)
  1032. {
  1033. static uint32 lastMouseTime = 0;
  1034. // this can be set to throttle the mouse-messages to less than a
  1035. // certain number per second, as things can get unresponsive
  1036. // if each drag or move callback has to do a lot of work.
  1037. const int maxMouseMovesPerSecond = 60;
  1038. const int64 mouseEventTime = getMouseEventTime();
  1039. if (! isMouseOver)
  1040. {
  1041. isMouseOver = true;
  1042. TRACKMOUSEEVENT tme;
  1043. tme.cbSize = sizeof (tme);
  1044. tme.dwFlags = TME_LEAVE;
  1045. tme.hwndTrack = hwnd;
  1046. tme.dwHoverTime = 0;
  1047. if (! TrackMouseEvent (&tme))
  1048. {
  1049. jassertfalse;
  1050. }
  1051. updateKeyModifiers();
  1052. handleMouseEnter (x, y, mouseEventTime);
  1053. }
  1054. else if (! isDragging)
  1055. {
  1056. if (((unsigned int) x) < (unsigned int) component->getWidth()
  1057. && ((unsigned int) y) < (unsigned int) component->getHeight())
  1058. {
  1059. RECT r;
  1060. GetWindowRect (hwnd, &r);
  1061. POINT p;
  1062. p.x = x + r.left + windowBorder.getLeft();
  1063. p.y = y + r.top + windowBorder.getTop();
  1064. if (WindowFromPoint (p) == hwnd)
  1065. {
  1066. const uint32 now = Time::getMillisecondCounter();
  1067. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  1068. {
  1069. lastMouseTime = now;
  1070. handleMouseMove (x, y, mouseEventTime);
  1071. }
  1072. }
  1073. }
  1074. }
  1075. else
  1076. {
  1077. const uint32 now = Time::getMillisecondCounter();
  1078. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  1079. {
  1080. lastMouseTime = now;
  1081. handleMouseDrag (x, y, mouseEventTime);
  1082. }
  1083. }
  1084. }
  1085. void doMouseDown (const int x, const int y, const WPARAM wParam)
  1086. {
  1087. if (GetCapture() != hwnd)
  1088. SetCapture (hwnd);
  1089. doMouseMove (x, y);
  1090. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  1091. if ((wParam & MK_LBUTTON) != 0)
  1092. currentModifiers |= ModifierKeys::leftButtonModifier;
  1093. if ((wParam & MK_RBUTTON) != 0)
  1094. currentModifiers |= ModifierKeys::rightButtonModifier;
  1095. if ((wParam & MK_MBUTTON) != 0)
  1096. currentModifiers |= ModifierKeys::middleButtonModifier;
  1097. updateKeyModifiers();
  1098. isDragging = true;
  1099. handleMouseDown (x, y, getMouseEventTime());
  1100. }
  1101. void doMouseUp (const int x, const int y, const WPARAM wParam)
  1102. {
  1103. int numButtons = 0;
  1104. if ((wParam & MK_LBUTTON) != 0)
  1105. ++numButtons;
  1106. if ((wParam & MK_RBUTTON) != 0)
  1107. ++numButtons;
  1108. if ((wParam & MK_MBUTTON) != 0)
  1109. ++numButtons;
  1110. const int oldModifiers = currentModifiers;
  1111. // update the currentmodifiers only after the callback, so the callback
  1112. // knows which button was released.
  1113. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  1114. if ((wParam & MK_LBUTTON) != 0)
  1115. currentModifiers |= ModifierKeys::leftButtonModifier;
  1116. if ((wParam & MK_RBUTTON) != 0)
  1117. currentModifiers |= ModifierKeys::rightButtonModifier;
  1118. if ((wParam & MK_MBUTTON) != 0)
  1119. currentModifiers |= ModifierKeys::middleButtonModifier;
  1120. updateKeyModifiers();
  1121. isDragging = false;
  1122. // release the mouse capture if the user's not still got a button down
  1123. if (numButtons == 0 && hwnd == GetCapture())
  1124. ReleaseCapture();
  1125. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  1126. }
  1127. void doCaptureChanged()
  1128. {
  1129. if (isDragging)
  1130. {
  1131. RECT wr;
  1132. GetWindowRect (hwnd, &wr);
  1133. const DWORD mp = GetMessagePos();
  1134. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  1135. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  1136. (WPARAM) getMouseEventTime());
  1137. }
  1138. }
  1139. void doMouseExit()
  1140. {
  1141. if (isMouseOver)
  1142. {
  1143. isMouseOver = false;
  1144. RECT wr;
  1145. GetWindowRect (hwnd, &wr);
  1146. const DWORD mp = GetMessagePos();
  1147. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  1148. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  1149. getMouseEventTime());
  1150. }
  1151. }
  1152. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  1153. {
  1154. updateKeyModifiers();
  1155. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  1156. handleMouseWheel (isVertical ? 0 : amount,
  1157. isVertical ? amount : 0,
  1158. getMouseEventTime());
  1159. }
  1160. //==============================================================================
  1161. void sendModifierKeyChangeIfNeeded()
  1162. {
  1163. if (modifiersAtLastCallback != currentModifiers)
  1164. {
  1165. modifiersAtLastCallback = currentModifiers;
  1166. handleModifierKeysChange();
  1167. }
  1168. }
  1169. bool doKeyUp (const WPARAM key)
  1170. {
  1171. updateKeyModifiers();
  1172. switch (key)
  1173. {
  1174. case VK_SHIFT:
  1175. case VK_CONTROL:
  1176. case VK_MENU:
  1177. case VK_CAPITAL:
  1178. case VK_LWIN:
  1179. case VK_RWIN:
  1180. case VK_APPS:
  1181. case VK_NUMLOCK:
  1182. case VK_SCROLL:
  1183. case VK_LSHIFT:
  1184. case VK_RSHIFT:
  1185. case VK_LCONTROL:
  1186. case VK_LMENU:
  1187. case VK_RCONTROL:
  1188. case VK_RMENU:
  1189. sendModifierKeyChangeIfNeeded();
  1190. }
  1191. return handleKeyUpOrDown (false)
  1192. || Component::getCurrentlyModalComponent() != 0;
  1193. }
  1194. bool doKeyDown (const WPARAM key)
  1195. {
  1196. updateKeyModifiers();
  1197. bool used = false;
  1198. switch (key)
  1199. {
  1200. case VK_SHIFT:
  1201. case VK_LSHIFT:
  1202. case VK_RSHIFT:
  1203. case VK_CONTROL:
  1204. case VK_LCONTROL:
  1205. case VK_RCONTROL:
  1206. case VK_MENU:
  1207. case VK_LMENU:
  1208. case VK_RMENU:
  1209. case VK_LWIN:
  1210. case VK_RWIN:
  1211. case VK_CAPITAL:
  1212. case VK_NUMLOCK:
  1213. case VK_SCROLL:
  1214. case VK_APPS:
  1215. sendModifierKeyChangeIfNeeded();
  1216. break;
  1217. case VK_LEFT:
  1218. case VK_RIGHT:
  1219. case VK_UP:
  1220. case VK_DOWN:
  1221. case VK_PRIOR:
  1222. case VK_NEXT:
  1223. case VK_HOME:
  1224. case VK_END:
  1225. case VK_DELETE:
  1226. case VK_INSERT:
  1227. case VK_F1:
  1228. case VK_F2:
  1229. case VK_F3:
  1230. case VK_F4:
  1231. case VK_F5:
  1232. case VK_F6:
  1233. case VK_F7:
  1234. case VK_F8:
  1235. case VK_F9:
  1236. case VK_F10:
  1237. case VK_F11:
  1238. case VK_F12:
  1239. case VK_F13:
  1240. case VK_F14:
  1241. case VK_F15:
  1242. case VK_F16:
  1243. used = handleKeyUpOrDown (true);
  1244. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  1245. break;
  1246. case VK_ADD:
  1247. case VK_SUBTRACT:
  1248. case VK_MULTIPLY:
  1249. case VK_DIVIDE:
  1250. case VK_SEPARATOR:
  1251. case VK_DECIMAL:
  1252. used = handleKeyUpOrDown (true);
  1253. break;
  1254. default:
  1255. used = handleKeyUpOrDown (true);
  1256. {
  1257. MSG msg;
  1258. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  1259. {
  1260. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  1261. // manually generate the key-press event that matches this key-down.
  1262. const UINT keyChar = MapVirtualKey (key, 2);
  1263. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  1264. }
  1265. }
  1266. break;
  1267. }
  1268. if (Component::getCurrentlyModalComponent() != 0)
  1269. used = true;
  1270. return used;
  1271. }
  1272. bool doKeyChar (int key, const LPARAM flags)
  1273. {
  1274. updateKeyModifiers();
  1275. juce_wchar textChar = (juce_wchar) key;
  1276. const int virtualScanCode = (flags >> 16) & 0xff;
  1277. if (key >= '0' && key <= '9')
  1278. {
  1279. switch (virtualScanCode) // check for a numeric keypad scan-code
  1280. {
  1281. case 0x52:
  1282. case 0x4f:
  1283. case 0x50:
  1284. case 0x51:
  1285. case 0x4b:
  1286. case 0x4c:
  1287. case 0x4d:
  1288. case 0x47:
  1289. case 0x48:
  1290. case 0x49:
  1291. key = (key - '0') + KeyPress::numberPad0;
  1292. break;
  1293. default:
  1294. break;
  1295. }
  1296. }
  1297. else
  1298. {
  1299. // convert the scan code to an unmodified character code..
  1300. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  1301. UINT keyChar = MapVirtualKey (virtualKey, 2);
  1302. keyChar = LOWORD (keyChar);
  1303. if (keyChar != 0)
  1304. key = (int) keyChar;
  1305. // avoid sending junk text characters for some control-key combinations
  1306. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  1307. textChar = 0;
  1308. }
  1309. return handleKeyPress (key, textChar);
  1310. }
  1311. bool doAppCommand (const LPARAM lParam)
  1312. {
  1313. int key = 0;
  1314. switch (GET_APPCOMMAND_LPARAM (lParam))
  1315. {
  1316. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  1317. key = KeyPress::playKey;
  1318. break;
  1319. case APPCOMMAND_MEDIA_STOP:
  1320. key = KeyPress::stopKey;
  1321. break;
  1322. case APPCOMMAND_MEDIA_NEXTTRACK:
  1323. key = KeyPress::fastForwardKey;
  1324. break;
  1325. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  1326. key = KeyPress::rewindKey;
  1327. break;
  1328. }
  1329. if (key != 0)
  1330. {
  1331. updateKeyModifiers();
  1332. if (hwnd == GetActiveWindow())
  1333. {
  1334. handleKeyPress (key, 0);
  1335. return true;
  1336. }
  1337. }
  1338. return false;
  1339. }
  1340. //==============================================================================
  1341. class JuceDropTarget : public IDropTarget
  1342. {
  1343. public:
  1344. JuceDropTarget (Win32ComponentPeer* const owner_)
  1345. : owner (owner_),
  1346. refCount (1)
  1347. {
  1348. }
  1349. virtual ~JuceDropTarget()
  1350. {
  1351. jassert (refCount == 0);
  1352. }
  1353. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  1354. {
  1355. if (id == IID_IUnknown || id == IID_IDropTarget)
  1356. {
  1357. AddRef();
  1358. *result = this;
  1359. return S_OK;
  1360. }
  1361. *result = 0;
  1362. return E_NOINTERFACE;
  1363. }
  1364. ULONG __stdcall AddRef() { return ++refCount; }
  1365. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  1366. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1367. {
  1368. updateFileList (pDataObject);
  1369. int x = mousePos.x, y = mousePos.y;
  1370. owner->globalPositionToRelative (x, y);
  1371. owner->handleFileDragMove (files, x, y);
  1372. *pdwEffect = DROPEFFECT_COPY;
  1373. return S_OK;
  1374. }
  1375. HRESULT __stdcall DragLeave()
  1376. {
  1377. owner->handleFileDragExit (files);
  1378. return S_OK;
  1379. }
  1380. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1381. {
  1382. int x = mousePos.x, y = mousePos.y;
  1383. owner->globalPositionToRelative (x, y);
  1384. owner->handleFileDragMove (files, x, y);
  1385. *pdwEffect = DROPEFFECT_COPY;
  1386. return S_OK;
  1387. }
  1388. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1389. {
  1390. updateFileList (pDataObject);
  1391. int x = mousePos.x, y = mousePos.y;
  1392. owner->globalPositionToRelative (x, y);
  1393. owner->handleFileDragDrop (files, x, y);
  1394. *pdwEffect = DROPEFFECT_COPY;
  1395. return S_OK;
  1396. }
  1397. private:
  1398. Win32ComponentPeer* const owner;
  1399. int refCount;
  1400. StringArray files;
  1401. void updateFileList (IDataObject* const pDataObject)
  1402. {
  1403. files.clear();
  1404. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1405. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  1406. if (pDataObject->GetData (&format, &medium) == S_OK)
  1407. {
  1408. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  1409. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  1410. unsigned int i = 0;
  1411. if (pDropFiles->fWide)
  1412. {
  1413. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  1414. for (;;)
  1415. {
  1416. unsigned int len = 0;
  1417. while (i + len < totalLen && fname [i + len] != 0)
  1418. ++len;
  1419. if (len == 0)
  1420. break;
  1421. files.add (String (fname + i, len));
  1422. i += len + 1;
  1423. }
  1424. }
  1425. else
  1426. {
  1427. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  1428. for (;;)
  1429. {
  1430. unsigned int len = 0;
  1431. while (i + len < totalLen && fname [i + len] != 0)
  1432. ++len;
  1433. if (len == 0)
  1434. break;
  1435. files.add (String (fname + i, len));
  1436. i += len + 1;
  1437. }
  1438. }
  1439. GlobalUnlock (medium.hGlobal);
  1440. }
  1441. }
  1442. JuceDropTarget (const JuceDropTarget&);
  1443. const JuceDropTarget& operator= (const JuceDropTarget&);
  1444. };
  1445. void doSettingChange()
  1446. {
  1447. Desktop::getInstance().refreshMonitorSizes();
  1448. if (fullScreen && ! isMinimised())
  1449. {
  1450. const Rectangle r (component->getParentMonitorArea());
  1451. SetWindowPos (hwnd, 0,
  1452. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  1453. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  1454. }
  1455. }
  1456. //==============================================================================
  1457. public:
  1458. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1459. {
  1460. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  1461. if (peer != 0)
  1462. return peer->peerWindowProc (h, message, wParam, lParam);
  1463. return DefWindowProc (h, message, wParam, lParam);
  1464. }
  1465. private:
  1466. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1467. {
  1468. {
  1469. if (isValidPeer (this))
  1470. {
  1471. switch (message)
  1472. {
  1473. case WM_NCHITTEST:
  1474. if (hasTitleBar())
  1475. break;
  1476. return HTCLIENT;
  1477. //==============================================================================
  1478. case WM_PAINT:
  1479. handlePaintMessage();
  1480. return 0;
  1481. case WM_NCPAINT:
  1482. if (wParam != 1)
  1483. handlePaintMessage();
  1484. if (hasTitleBar())
  1485. break;
  1486. return 0;
  1487. case WM_ERASEBKGND:
  1488. case WM_NCCALCSIZE:
  1489. if (hasTitleBar())
  1490. break;
  1491. return 1;
  1492. //==============================================================================
  1493. case WM_MOUSEMOVE:
  1494. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  1495. return 0;
  1496. case WM_MOUSELEAVE:
  1497. doMouseExit();
  1498. return 0;
  1499. case WM_LBUTTONDOWN:
  1500. case WM_MBUTTONDOWN:
  1501. case WM_RBUTTONDOWN:
  1502. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1503. return 0;
  1504. case WM_LBUTTONUP:
  1505. case WM_MBUTTONUP:
  1506. case WM_RBUTTONUP:
  1507. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1508. return 0;
  1509. case WM_CAPTURECHANGED:
  1510. doCaptureChanged();
  1511. return 0;
  1512. case WM_NCMOUSEMOVE:
  1513. if (hasTitleBar())
  1514. break;
  1515. return 0;
  1516. case 0x020A: /* WM_MOUSEWHEEL */
  1517. doMouseWheel (wParam, true);
  1518. return 0;
  1519. case 0x020E: /* WM_MOUSEHWHEEL */
  1520. doMouseWheel (wParam, false);
  1521. return 0;
  1522. //==============================================================================
  1523. case WM_WINDOWPOSCHANGING:
  1524. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  1525. {
  1526. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  1527. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  1528. {
  1529. if (constrainer != 0)
  1530. {
  1531. const Rectangle current (component->getX() - windowBorder.getLeft(),
  1532. component->getY() - windowBorder.getTop(),
  1533. component->getWidth() + windowBorder.getLeftAndRight(),
  1534. component->getHeight() + windowBorder.getTopAndBottom());
  1535. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  1536. current,
  1537. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  1538. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  1539. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  1540. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  1541. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  1542. }
  1543. }
  1544. }
  1545. return 0;
  1546. case WM_WINDOWPOSCHANGED:
  1547. handleMovedOrResized();
  1548. if (dontRepaint)
  1549. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  1550. else
  1551. return 0;
  1552. //==============================================================================
  1553. case WM_KEYDOWN:
  1554. case WM_SYSKEYDOWN:
  1555. if (doKeyDown (wParam))
  1556. return 0;
  1557. break;
  1558. case WM_KEYUP:
  1559. case WM_SYSKEYUP:
  1560. if (doKeyUp (wParam))
  1561. return 0;
  1562. break;
  1563. case WM_CHAR:
  1564. if (doKeyChar ((int) wParam, lParam))
  1565. return 0;
  1566. break;
  1567. case WM_APPCOMMAND:
  1568. if (doAppCommand (lParam))
  1569. return TRUE;
  1570. break;
  1571. //==============================================================================
  1572. case WM_SETFOCUS:
  1573. updateKeyModifiers();
  1574. handleFocusGain();
  1575. break;
  1576. case WM_KILLFOCUS:
  1577. if (hasCreatedCaret)
  1578. {
  1579. hasCreatedCaret = false;
  1580. DestroyCaret();
  1581. }
  1582. handleFocusLoss();
  1583. break;
  1584. case WM_ACTIVATEAPP:
  1585. // Windows does weird things to process priority when you swap apps,
  1586. // so this forces an update when the app is brought to the front
  1587. if (wParam != FALSE)
  1588. juce_repeatLastProcessPriority();
  1589. else
  1590. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  1591. juce_CheckCurrentlyFocusedTopLevelWindow();
  1592. modifiersAtLastCallback = -1;
  1593. return 0;
  1594. case WM_ACTIVATE:
  1595. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  1596. {
  1597. modifiersAtLastCallback = -1;
  1598. updateKeyModifiers();
  1599. if (isMinimised())
  1600. {
  1601. component->repaint();
  1602. handleMovedOrResized();
  1603. if (! isValidMessageListener())
  1604. return 0;
  1605. }
  1606. if (LOWORD (wParam) == WA_CLICKACTIVE
  1607. && component->isCurrentlyBlockedByAnotherModalComponent())
  1608. {
  1609. int mx, my;
  1610. component->getMouseXYRelative (mx, my);
  1611. Component* const underMouse = component->getComponentAt (mx, my);
  1612. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  1613. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1614. return 0;
  1615. }
  1616. handleBroughtToFront();
  1617. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1618. Component::getCurrentlyModalComponent()->toFront (true);
  1619. return 0;
  1620. }
  1621. break;
  1622. case WM_NCACTIVATE:
  1623. // while a temporary window is being shown, prevent Windows from deactivating the
  1624. // title bars of our main windows.
  1625. if (wParam == 0 && ! shouldDeactivateTitleBar)
  1626. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  1627. break;
  1628. case WM_MOUSEACTIVATE:
  1629. if (! component->getMouseClickGrabsKeyboardFocus())
  1630. return MA_NOACTIVATE;
  1631. break;
  1632. case WM_SHOWWINDOW:
  1633. if (wParam != 0)
  1634. handleBroughtToFront();
  1635. break;
  1636. case WM_CLOSE:
  1637. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  1638. handleUserClosingWindow();
  1639. return 0;
  1640. case WM_QUIT:
  1641. if (JUCEApplication::getInstance() != 0)
  1642. JUCEApplication::getInstance()->systemRequestedQuit();
  1643. return 0;
  1644. case WM_QUERYENDSESSION:
  1645. if (JUCEApplication::getInstance() != 0)
  1646. {
  1647. JUCEApplication::getInstance()->systemRequestedQuit();
  1648. return MessageManager::getInstance()->hasStopMessageBeenSent();
  1649. }
  1650. return TRUE;
  1651. //==============================================================================
  1652. case WM_TRAYNOTIFY:
  1653. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1654. {
  1655. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  1656. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1657. {
  1658. Component* const current = Component::getCurrentlyModalComponent();
  1659. if (current != 0)
  1660. current->inputAttemptWhenModal();
  1661. }
  1662. }
  1663. else
  1664. {
  1665. const int oldModifiers = currentModifiers;
  1666. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  1667. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  1668. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  1669. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  1670. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  1671. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  1672. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  1673. {
  1674. SetFocus (hwnd);
  1675. SetForegroundWindow (hwnd);
  1676. component->mouseDown (e);
  1677. }
  1678. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  1679. {
  1680. e.mods = ModifierKeys (oldModifiers);
  1681. component->mouseUp (e);
  1682. }
  1683. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1684. {
  1685. e.mods = ModifierKeys (oldModifiers);
  1686. component->mouseDoubleClick (e);
  1687. }
  1688. else if (lParam == WM_MOUSEMOVE)
  1689. {
  1690. component->mouseMove (e);
  1691. }
  1692. }
  1693. break;
  1694. //==============================================================================
  1695. case WM_SYNCPAINT:
  1696. return 0;
  1697. case WM_PALETTECHANGED:
  1698. InvalidateRect (h, 0, 0);
  1699. break;
  1700. case WM_DISPLAYCHANGE:
  1701. InvalidateRect (h, 0, 0);
  1702. createPaletteIfNeeded = true;
  1703. // intentional fall-through...
  1704. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  1705. doSettingChange();
  1706. break;
  1707. case WM_INITMENU:
  1708. if (! hasTitleBar())
  1709. {
  1710. if (isFullScreen())
  1711. {
  1712. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  1713. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  1714. }
  1715. else if (! isMinimised())
  1716. {
  1717. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  1718. }
  1719. }
  1720. break;
  1721. case WM_SYSCOMMAND:
  1722. switch (wParam & 0xfff0)
  1723. {
  1724. case SC_CLOSE:
  1725. if (sendInputAttemptWhenModalMessage())
  1726. return 0;
  1727. if (hasTitleBar())
  1728. {
  1729. PostMessage (h, WM_CLOSE, 0, 0);
  1730. return 0;
  1731. }
  1732. break;
  1733. case SC_KEYMENU:
  1734. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  1735. // obscure situations that can arise if a modal loop is started from an alt-key
  1736. // keypress).
  1737. if (hasTitleBar() && h == GetCapture())
  1738. ReleaseCapture();
  1739. break;
  1740. case SC_MAXIMIZE:
  1741. if (sendInputAttemptWhenModalMessage())
  1742. return 0;
  1743. setFullScreen (true);
  1744. return 0;
  1745. case SC_MINIMIZE:
  1746. if (sendInputAttemptWhenModalMessage())
  1747. return 0;
  1748. if (! hasTitleBar())
  1749. {
  1750. setMinimised (true);
  1751. return 0;
  1752. }
  1753. break;
  1754. case SC_RESTORE:
  1755. if (sendInputAttemptWhenModalMessage())
  1756. return 0;
  1757. if (hasTitleBar())
  1758. {
  1759. if (isFullScreen())
  1760. {
  1761. setFullScreen (false);
  1762. return 0;
  1763. }
  1764. }
  1765. else
  1766. {
  1767. if (isMinimised())
  1768. setMinimised (false);
  1769. else if (isFullScreen())
  1770. setFullScreen (false);
  1771. return 0;
  1772. }
  1773. break;
  1774. }
  1775. break;
  1776. case WM_NCLBUTTONDOWN:
  1777. case WM_NCRBUTTONDOWN:
  1778. case WM_NCMBUTTONDOWN:
  1779. sendInputAttemptWhenModalMessage();
  1780. break;
  1781. //case WM_IME_STARTCOMPOSITION;
  1782. // return 0;
  1783. case WM_GETDLGCODE:
  1784. return DLGC_WANTALLKEYS;
  1785. default:
  1786. break;
  1787. }
  1788. }
  1789. }
  1790. // (the message manager lock exits before calling this, to avoid deadlocks if
  1791. // this calls into non-juce windows)
  1792. return DefWindowProc (h, message, wParam, lParam);
  1793. }
  1794. bool sendInputAttemptWhenModalMessage()
  1795. {
  1796. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1797. {
  1798. Component* const current = Component::getCurrentlyModalComponent();
  1799. if (current != 0)
  1800. current->inputAttemptWhenModal();
  1801. return true;
  1802. }
  1803. return false;
  1804. }
  1805. Win32ComponentPeer (const Win32ComponentPeer&);
  1806. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  1807. };
  1808. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  1809. {
  1810. return new Win32ComponentPeer (this, styleFlags);
  1811. }
  1812. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  1813. //==============================================================================
  1814. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  1815. {
  1816. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1817. if (wp != 0)
  1818. wp->setTaskBarIcon (&newImage);
  1819. }
  1820. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  1821. {
  1822. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1823. if (wp != 0)
  1824. wp->setTaskBarIconToolTip (tooltip);
  1825. }
  1826. //==============================================================================
  1827. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  1828. {
  1829. DWORD val = GetWindowLong (h, styleType);
  1830. if (bitIsSet)
  1831. val |= feature;
  1832. else
  1833. val &= ~feature;
  1834. SetWindowLongPtr (h, styleType, val);
  1835. SetWindowPos (h, 0, 0, 0, 0, 0,
  1836. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  1837. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  1838. }
  1839. //==============================================================================
  1840. bool Process::isForegroundProcess() throw()
  1841. {
  1842. HWND fg = GetForegroundWindow();
  1843. if (fg == 0)
  1844. return true;
  1845. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  1846. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  1847. // have to see if any of our windows are children of the foreground window
  1848. fg = GetAncestor (fg, GA_ROOT);
  1849. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1850. {
  1851. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  1852. if (wp != 0 && wp->isInside (fg))
  1853. return true;
  1854. }
  1855. return false;
  1856. }
  1857. //==============================================================================
  1858. bool AlertWindow::showNativeDialogBox (const String& title,
  1859. const String& bodyText,
  1860. bool isOkCancel)
  1861. {
  1862. return MessageBox (0, bodyText, title,
  1863. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  1864. : MB_OK)) == IDOK;
  1865. }
  1866. //==============================================================================
  1867. void Desktop::getMousePosition (int& x, int& y) throw()
  1868. {
  1869. POINT mousePos;
  1870. GetCursorPos (&mousePos);
  1871. x = mousePos.x;
  1872. y = mousePos.y;
  1873. }
  1874. void Desktop::setMousePosition (int x, int y) throw()
  1875. {
  1876. SetCursorPos (x, y);
  1877. }
  1878. //==============================================================================
  1879. class ScreenSaverDefeater : public Timer,
  1880. public DeletedAtShutdown
  1881. {
  1882. public:
  1883. ScreenSaverDefeater() throw()
  1884. {
  1885. startTimer (10000);
  1886. timerCallback();
  1887. }
  1888. ~ScreenSaverDefeater() {}
  1889. void timerCallback()
  1890. {
  1891. if (Process::isForegroundProcess())
  1892. {
  1893. // simulate a shift key getting pressed..
  1894. INPUT input[2];
  1895. input[0].type = INPUT_KEYBOARD;
  1896. input[0].ki.wVk = VK_SHIFT;
  1897. input[0].ki.dwFlags = 0;
  1898. input[0].ki.dwExtraInfo = 0;
  1899. input[1].type = INPUT_KEYBOARD;
  1900. input[1].ki.wVk = VK_SHIFT;
  1901. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  1902. input[1].ki.dwExtraInfo = 0;
  1903. SendInput (2, input, sizeof (INPUT));
  1904. }
  1905. }
  1906. };
  1907. static ScreenSaverDefeater* screenSaverDefeater = 0;
  1908. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1909. {
  1910. if (isEnabled)
  1911. {
  1912. deleteAndZero (screenSaverDefeater);
  1913. }
  1914. else if (screenSaverDefeater == 0)
  1915. {
  1916. screenSaverDefeater = new ScreenSaverDefeater();
  1917. }
  1918. }
  1919. bool Desktop::isScreenSaverEnabled() throw()
  1920. {
  1921. return screenSaverDefeater == 0;
  1922. }
  1923. /* (The code below is the "correct" way to disable the screen saver, but it
  1924. completely fails on winXP when the saver is password-protected...)
  1925. static bool juce_screenSaverEnabled = true;
  1926. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1927. {
  1928. juce_screenSaverEnabled = isEnabled;
  1929. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  1930. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  1931. }
  1932. bool Desktop::isScreenSaverEnabled() throw()
  1933. {
  1934. return juce_screenSaverEnabled;
  1935. }
  1936. */
  1937. //==============================================================================
  1938. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  1939. {
  1940. if (enableOrDisable)
  1941. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  1942. }
  1943. //==============================================================================
  1944. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  1945. {
  1946. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  1947. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  1948. return TRUE;
  1949. }
  1950. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1951. {
  1952. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  1953. // make sure the first in the list is the main monitor
  1954. for (int i = 1; i < monitorCoords.size(); ++i)
  1955. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  1956. monitorCoords.swap (i, 0);
  1957. if (monitorCoords.size() == 0)
  1958. {
  1959. RECT r;
  1960. GetWindowRect (GetDesktopWindow(), &r);
  1961. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  1962. }
  1963. if (clipToWorkArea)
  1964. {
  1965. // clip the main monitor to the active non-taskbar area
  1966. RECT r;
  1967. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  1968. Rectangle& screen = monitorCoords.getReference (0);
  1969. screen.setPosition (jmax (screen.getX(), r.left),
  1970. jmax (screen.getY(), r.top));
  1971. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  1972. jmin (screen.getBottom(), r.bottom) - screen.getY());
  1973. }
  1974. }
  1975. //==============================================================================
  1976. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  1977. {
  1978. Image* im = 0;
  1979. if (bitmap != 0)
  1980. {
  1981. BITMAP bm;
  1982. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  1983. && bm.bmWidth > 0 && bm.bmHeight > 0)
  1984. {
  1985. HDC tempDC = GetDC (0);
  1986. HDC dc = CreateCompatibleDC (tempDC);
  1987. ReleaseDC (0, tempDC);
  1988. SelectObject (dc, bitmap);
  1989. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  1990. for (int y = bm.bmHeight; --y >= 0;)
  1991. {
  1992. for (int x = bm.bmWidth; --x >= 0;)
  1993. {
  1994. COLORREF col = GetPixel (dc, x, y);
  1995. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  1996. (uint8) GetGValue (col),
  1997. (uint8) GetBValue (col)));
  1998. }
  1999. }
  2000. DeleteDC (dc);
  2001. }
  2002. }
  2003. return im;
  2004. }
  2005. static Image* createImageFromHICON (HICON icon) throw()
  2006. {
  2007. ICONINFO info;
  2008. if (GetIconInfo (icon, &info))
  2009. {
  2010. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  2011. if (mask == 0)
  2012. return 0;
  2013. Image* const image = createImageFromHBITMAP (info.hbmColor);
  2014. if (image == 0)
  2015. return mask;
  2016. for (int y = image->getHeight(); --y >= 0;)
  2017. {
  2018. for (int x = image->getWidth(); --x >= 0;)
  2019. {
  2020. const float brightness = mask->getPixelAt (x, y).getBrightness();
  2021. if (brightness > 0.0f)
  2022. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  2023. }
  2024. }
  2025. delete mask;
  2026. return image;
  2027. }
  2028. return 0;
  2029. }
  2030. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  2031. {
  2032. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  2033. ICONINFO info;
  2034. info.fIcon = isIcon;
  2035. info.xHotspot = hotspotX;
  2036. info.yHotspot = hotspotY;
  2037. info.hbmMask = mask;
  2038. HICON hi = 0;
  2039. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  2040. {
  2041. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  2042. Graphics g (bitmap);
  2043. g.drawImageAt (&image, 0, 0);
  2044. info.hbmColor = bitmap.hBitmap;
  2045. hi = CreateIconIndirect (&info);
  2046. }
  2047. else
  2048. {
  2049. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  2050. HDC colDC = CreateCompatibleDC (GetDC (0));
  2051. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  2052. SelectObject (colDC, colour);
  2053. SelectObject (alphaDC, mask);
  2054. for (int y = image.getHeight(); --y >= 0;)
  2055. {
  2056. for (int x = image.getWidth(); --x >= 0;)
  2057. {
  2058. const Colour c (image.getPixelAt (x, y));
  2059. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  2060. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  2061. }
  2062. }
  2063. DeleteDC (colDC);
  2064. DeleteDC (alphaDC);
  2065. info.hbmColor = colour;
  2066. hi = CreateIconIndirect (&info);
  2067. DeleteObject (colour);
  2068. }
  2069. DeleteObject (mask);
  2070. return hi;
  2071. }
  2072. Image* juce_createIconForFile (const File& file)
  2073. {
  2074. Image* image = 0;
  2075. TCHAR filename [1024];
  2076. file.getFullPathName().copyToBuffer (filename, 1023);
  2077. WORD iconNum = 0;
  2078. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  2079. filename, &iconNum);
  2080. if (icon != 0)
  2081. {
  2082. image = createImageFromHICON (icon);
  2083. DestroyIcon (icon);
  2084. }
  2085. return image;
  2086. }
  2087. //==============================================================================
  2088. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  2089. {
  2090. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  2091. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  2092. const Image* im = &image;
  2093. Image* newIm = 0;
  2094. if (image.getWidth() > maxW || image.getHeight() > maxH)
  2095. {
  2096. im = newIm = image.createCopy (maxW, maxH);
  2097. hotspotX = (hotspotX * maxW) / image.getWidth();
  2098. hotspotY = (hotspotY * maxH) / image.getHeight();
  2099. }
  2100. void* cursorH = 0;
  2101. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  2102. if (os == SystemStats::WinXP)
  2103. {
  2104. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  2105. }
  2106. else
  2107. {
  2108. const int stride = (maxW + 7) >> 3;
  2109. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  2110. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  2111. int index = 0;
  2112. for (int y = 0; y < maxH; ++y)
  2113. {
  2114. for (int x = 0; x < maxW; ++x)
  2115. {
  2116. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  2117. const Colour pixelColour (im->getPixelAt (x, y));
  2118. if (pixelColour.getAlpha() < 127)
  2119. andPlane [index + (x >> 3)] |= bit;
  2120. else if (pixelColour.getBrightness() >= 0.5f)
  2121. xorPlane [index + (x >> 3)] |= bit;
  2122. }
  2123. index += stride;
  2124. }
  2125. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  2126. juce_free (andPlane);
  2127. juce_free (xorPlane);
  2128. }
  2129. delete newIm;
  2130. return cursorH;
  2131. }
  2132. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2133. {
  2134. if (cursorHandle != 0 && ! isStandard)
  2135. DestroyCursor ((HCURSOR) cursorHandle);
  2136. }
  2137. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  2138. {
  2139. LPCTSTR cursorName = IDC_ARROW;
  2140. switch (type)
  2141. {
  2142. case MouseCursor::NormalCursor:
  2143. cursorName = IDC_ARROW;
  2144. break;
  2145. case MouseCursor::NoCursor:
  2146. return 0;
  2147. case MouseCursor::DraggingHandCursor:
  2148. {
  2149. static void* dragHandCursor = 0;
  2150. if (dragHandCursor == 0)
  2151. {
  2152. static const unsigned char dragHandData[] =
  2153. { 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,
  2154. 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,
  2155. 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 };
  2156. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  2157. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  2158. delete image;
  2159. }
  2160. return dragHandCursor;
  2161. }
  2162. case MouseCursor::WaitCursor:
  2163. cursorName = IDC_WAIT;
  2164. break;
  2165. case MouseCursor::IBeamCursor:
  2166. cursorName = IDC_IBEAM;
  2167. break;
  2168. case MouseCursor::PointingHandCursor:
  2169. cursorName = MAKEINTRESOURCE(32649);
  2170. break;
  2171. case MouseCursor::LeftRightResizeCursor:
  2172. case MouseCursor::LeftEdgeResizeCursor:
  2173. case MouseCursor::RightEdgeResizeCursor:
  2174. cursorName = IDC_SIZEWE;
  2175. break;
  2176. case MouseCursor::UpDownResizeCursor:
  2177. case MouseCursor::TopEdgeResizeCursor:
  2178. case MouseCursor::BottomEdgeResizeCursor:
  2179. cursorName = IDC_SIZENS;
  2180. break;
  2181. case MouseCursor::TopLeftCornerResizeCursor:
  2182. case MouseCursor::BottomRightCornerResizeCursor:
  2183. cursorName = IDC_SIZENWSE;
  2184. break;
  2185. case MouseCursor::TopRightCornerResizeCursor:
  2186. case MouseCursor::BottomLeftCornerResizeCursor:
  2187. cursorName = IDC_SIZENESW;
  2188. break;
  2189. case MouseCursor::UpDownLeftRightResizeCursor:
  2190. cursorName = IDC_SIZEALL;
  2191. break;
  2192. case MouseCursor::CrosshairCursor:
  2193. cursorName = IDC_CROSS;
  2194. break;
  2195. case MouseCursor::CopyingCursor:
  2196. // can't seem to find one of these in the win32 list..
  2197. break;
  2198. }
  2199. HCURSOR cursorH = LoadCursor (0, cursorName);
  2200. if (cursorH == 0)
  2201. cursorH = LoadCursor (0, IDC_ARROW);
  2202. return (void*) cursorH;
  2203. }
  2204. //==============================================================================
  2205. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2206. {
  2207. SetCursor ((HCURSOR) getHandle());
  2208. }
  2209. void MouseCursor::showInAllWindows() const throw()
  2210. {
  2211. showInWindow (0);
  2212. }
  2213. //==============================================================================
  2214. //==============================================================================
  2215. class JuceDropSource : public IDropSource
  2216. {
  2217. int refCount;
  2218. public:
  2219. JuceDropSource()
  2220. : refCount (1)
  2221. {
  2222. }
  2223. virtual ~JuceDropSource()
  2224. {
  2225. jassert (refCount == 0);
  2226. }
  2227. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2228. {
  2229. if (id == IID_IUnknown || id == IID_IDropSource)
  2230. {
  2231. AddRef();
  2232. *result = this;
  2233. return S_OK;
  2234. }
  2235. *result = 0;
  2236. return E_NOINTERFACE;
  2237. }
  2238. ULONG __stdcall AddRef() { return ++refCount; }
  2239. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2240. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  2241. {
  2242. if (escapePressed)
  2243. return DRAGDROP_S_CANCEL;
  2244. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  2245. return DRAGDROP_S_DROP;
  2246. return S_OK;
  2247. }
  2248. HRESULT __stdcall GiveFeedback (DWORD)
  2249. {
  2250. return DRAGDROP_S_USEDEFAULTCURSORS;
  2251. }
  2252. };
  2253. class JuceEnumFormatEtc : public IEnumFORMATETC
  2254. {
  2255. public:
  2256. JuceEnumFormatEtc (const FORMATETC* const format_)
  2257. : refCount (1),
  2258. format (format_),
  2259. index (0)
  2260. {
  2261. }
  2262. virtual ~JuceEnumFormatEtc()
  2263. {
  2264. jassert (refCount == 0);
  2265. }
  2266. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2267. {
  2268. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  2269. {
  2270. AddRef();
  2271. *result = this;
  2272. return S_OK;
  2273. }
  2274. *result = 0;
  2275. return E_NOINTERFACE;
  2276. }
  2277. ULONG __stdcall AddRef() { return ++refCount; }
  2278. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2279. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  2280. {
  2281. if (result == 0)
  2282. return E_POINTER;
  2283. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  2284. newOne->index = index;
  2285. *result = newOne;
  2286. return S_OK;
  2287. }
  2288. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  2289. {
  2290. if (pceltFetched != 0)
  2291. *pceltFetched = 0;
  2292. else if (celt != 1)
  2293. return S_FALSE;
  2294. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  2295. {
  2296. copyFormatEtc (lpFormatEtc [0], *format);
  2297. ++index;
  2298. if (pceltFetched != 0)
  2299. *pceltFetched = 1;
  2300. return S_OK;
  2301. }
  2302. return S_FALSE;
  2303. }
  2304. HRESULT __stdcall Skip (ULONG celt)
  2305. {
  2306. if (index + (int) celt >= 1)
  2307. return S_FALSE;
  2308. index += celt;
  2309. return S_OK;
  2310. }
  2311. HRESULT __stdcall Reset()
  2312. {
  2313. index = 0;
  2314. return S_OK;
  2315. }
  2316. private:
  2317. int refCount;
  2318. const FORMATETC* const format;
  2319. int index;
  2320. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  2321. {
  2322. dest = source;
  2323. if (source.ptd != 0)
  2324. {
  2325. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  2326. *(dest.ptd) = *(source.ptd);
  2327. }
  2328. }
  2329. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  2330. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  2331. };
  2332. class JuceDataObject : public IDataObject
  2333. {
  2334. JuceDropSource* const dropSource;
  2335. const FORMATETC* const format;
  2336. const STGMEDIUM* const medium;
  2337. int refCount;
  2338. JuceDataObject (const JuceDataObject&);
  2339. const JuceDataObject& operator= (const JuceDataObject&);
  2340. public:
  2341. JuceDataObject (JuceDropSource* const dropSource_,
  2342. const FORMATETC* const format_,
  2343. const STGMEDIUM* const medium_)
  2344. : dropSource (dropSource_),
  2345. format (format_),
  2346. medium (medium_),
  2347. refCount (1)
  2348. {
  2349. }
  2350. virtual ~JuceDataObject()
  2351. {
  2352. jassert (refCount == 0);
  2353. }
  2354. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2355. {
  2356. if (id == IID_IUnknown || id == IID_IDataObject)
  2357. {
  2358. AddRef();
  2359. *result = this;
  2360. return S_OK;
  2361. }
  2362. *result = 0;
  2363. return E_NOINTERFACE;
  2364. }
  2365. ULONG __stdcall AddRef() { return ++refCount; }
  2366. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2367. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  2368. {
  2369. if (pFormatEtc->tymed == format->tymed
  2370. && pFormatEtc->cfFormat == format->cfFormat
  2371. && pFormatEtc->dwAspect == format->dwAspect)
  2372. {
  2373. pMedium->tymed = format->tymed;
  2374. pMedium->pUnkForRelease = 0;
  2375. if (format->tymed == TYMED_HGLOBAL)
  2376. {
  2377. const SIZE_T len = GlobalSize (medium->hGlobal);
  2378. void* const src = GlobalLock (medium->hGlobal);
  2379. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  2380. memcpy (dst, src, len);
  2381. GlobalUnlock (medium->hGlobal);
  2382. pMedium->hGlobal = dst;
  2383. return S_OK;
  2384. }
  2385. }
  2386. return DV_E_FORMATETC;
  2387. }
  2388. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  2389. {
  2390. if (f == 0)
  2391. return E_INVALIDARG;
  2392. if (f->tymed == format->tymed
  2393. && f->cfFormat == format->cfFormat
  2394. && f->dwAspect == format->dwAspect)
  2395. return S_OK;
  2396. return DV_E_FORMATETC;
  2397. }
  2398. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  2399. {
  2400. pFormatEtcOut->ptd = 0;
  2401. return E_NOTIMPL;
  2402. }
  2403. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  2404. {
  2405. if (result == 0)
  2406. return E_POINTER;
  2407. if (direction == DATADIR_GET)
  2408. {
  2409. *result = new JuceEnumFormatEtc (format);
  2410. return S_OK;
  2411. }
  2412. *result = 0;
  2413. return E_NOTIMPL;
  2414. }
  2415. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  2416. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  2417. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  2418. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  2419. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  2420. };
  2421. static HDROP createHDrop (const StringArray& fileNames) throw()
  2422. {
  2423. int totalChars = 0;
  2424. for (int i = fileNames.size(); --i >= 0;)
  2425. totalChars += fileNames[i].length() + 1;
  2426. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  2427. sizeof (DROPFILES)
  2428. + sizeof (WCHAR) * (totalChars + 2));
  2429. if (hDrop != 0)
  2430. {
  2431. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  2432. pDropFiles->pFiles = sizeof (DROPFILES);
  2433. pDropFiles->fWide = true;
  2434. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  2435. for (int i = 0; i < fileNames.size(); ++i)
  2436. {
  2437. fileNames[i].copyToBuffer (fname, 2048);
  2438. fname += fileNames[i].length() + 1;
  2439. }
  2440. *fname = 0;
  2441. GlobalUnlock (hDrop);
  2442. }
  2443. return hDrop;
  2444. }
  2445. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  2446. {
  2447. JuceDropSource* const source = new JuceDropSource();
  2448. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  2449. DWORD effect;
  2450. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  2451. data->Release();
  2452. source->Release();
  2453. return res == DRAGDROP_S_DROP;
  2454. }
  2455. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  2456. {
  2457. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2458. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2459. medium.hGlobal = createHDrop (files);
  2460. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  2461. : DROPEFFECT_COPY);
  2462. }
  2463. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2464. {
  2465. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2466. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2467. const int numChars = text.length();
  2468. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  2469. char* d = (char*) GlobalLock (medium.hGlobal);
  2470. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  2471. format.cfFormat = CF_UNICODETEXT;
  2472. GlobalUnlock (medium.hGlobal);
  2473. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  2474. }
  2475. #endif