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.

3112 lines
101KB

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