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.

3026 lines
98KB

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