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.

3085 lines
100KB

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