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.

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