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.

3078 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. const MessageManagerLock messLock;
  1460. if (isValidPeer (this))
  1461. {
  1462. switch (message)
  1463. {
  1464. case WM_NCHITTEST:
  1465. if (hasTitleBar())
  1466. break;
  1467. return HTCLIENT;
  1468. //==============================================================================
  1469. case WM_PAINT:
  1470. handlePaintMessage();
  1471. return 0;
  1472. case WM_NCPAINT:
  1473. if (wParam != 1)
  1474. handlePaintMessage();
  1475. if (hasTitleBar())
  1476. break;
  1477. return 0;
  1478. case WM_ERASEBKGND:
  1479. case WM_NCCALCSIZE:
  1480. if (hasTitleBar())
  1481. break;
  1482. return 1;
  1483. //==============================================================================
  1484. case WM_MOUSEMOVE:
  1485. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  1486. return 0;
  1487. case WM_MOUSELEAVE:
  1488. doMouseExit();
  1489. return 0;
  1490. case WM_LBUTTONDOWN:
  1491. case WM_MBUTTONDOWN:
  1492. case WM_RBUTTONDOWN:
  1493. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1494. return 0;
  1495. case WM_LBUTTONUP:
  1496. case WM_MBUTTONUP:
  1497. case WM_RBUTTONUP:
  1498. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1499. return 0;
  1500. case WM_CAPTURECHANGED:
  1501. doCaptureChanged();
  1502. return 0;
  1503. case WM_NCMOUSEMOVE:
  1504. if (hasTitleBar())
  1505. break;
  1506. return 0;
  1507. case 0x020A: /* WM_MOUSEWHEEL */
  1508. doMouseWheel (wParam, true);
  1509. return 0;
  1510. case 0x020E: /* WM_MOUSEHWHEEL */
  1511. doMouseWheel (wParam, false);
  1512. return 0;
  1513. //==============================================================================
  1514. case WM_WINDOWPOSCHANGING:
  1515. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  1516. {
  1517. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  1518. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  1519. {
  1520. if (constrainer != 0)
  1521. {
  1522. const Rectangle current (component->getX() - windowBorder.getLeft(),
  1523. component->getY() - windowBorder.getTop(),
  1524. component->getWidth() + windowBorder.getLeftAndRight(),
  1525. component->getHeight() + windowBorder.getTopAndBottom());
  1526. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  1527. current,
  1528. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  1529. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  1530. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  1531. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  1532. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  1533. }
  1534. }
  1535. }
  1536. return 0;
  1537. case WM_WINDOWPOSCHANGED:
  1538. handleMovedOrResized();
  1539. if (dontRepaint)
  1540. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  1541. else
  1542. return 0;
  1543. //==============================================================================
  1544. case WM_KEYDOWN:
  1545. case WM_SYSKEYDOWN:
  1546. if (doKeyDown (wParam))
  1547. return 0;
  1548. break;
  1549. case WM_KEYUP:
  1550. case WM_SYSKEYUP:
  1551. if (doKeyUp (wParam))
  1552. return 0;
  1553. break;
  1554. case WM_CHAR:
  1555. if (doKeyChar ((int) wParam, lParam))
  1556. return 0;
  1557. break;
  1558. case WM_APPCOMMAND:
  1559. if (doAppCommand (lParam))
  1560. return TRUE;
  1561. break;
  1562. //==============================================================================
  1563. case WM_SETFOCUS:
  1564. updateKeyModifiers();
  1565. handleFocusGain();
  1566. break;
  1567. case WM_KILLFOCUS:
  1568. if (hasCreatedCaret)
  1569. {
  1570. hasCreatedCaret = false;
  1571. DestroyCaret();
  1572. }
  1573. handleFocusLoss();
  1574. break;
  1575. case WM_ACTIVATEAPP:
  1576. // Windows does weird things to process priority when you swap apps,
  1577. // so this forces an update when the app is brought to the front
  1578. if (wParam != FALSE)
  1579. juce_repeatLastProcessPriority();
  1580. else
  1581. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  1582. juce_CheckCurrentlyFocusedTopLevelWindow();
  1583. modifiersAtLastCallback = -1;
  1584. return 0;
  1585. case WM_ACTIVATE:
  1586. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  1587. {
  1588. modifiersAtLastCallback = -1;
  1589. updateKeyModifiers();
  1590. if (isMinimised())
  1591. {
  1592. component->repaint();
  1593. handleMovedOrResized();
  1594. if (! isValidMessageListener())
  1595. return 0;
  1596. }
  1597. if (LOWORD (wParam) == WA_CLICKACTIVE
  1598. && component->isCurrentlyBlockedByAnotherModalComponent())
  1599. {
  1600. int mx, my;
  1601. component->getMouseXYRelative (mx, my);
  1602. Component* const underMouse = component->getComponentAt (mx, my);
  1603. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  1604. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1605. return 0;
  1606. }
  1607. handleBroughtToFront();
  1608. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1609. Component::getCurrentlyModalComponent()->toFront (true);
  1610. return 0;
  1611. }
  1612. break;
  1613. case WM_NCACTIVATE:
  1614. // while a temporary window is being shown, prevent Windows from deactivating the
  1615. // title bars of our main windows.
  1616. if (wParam == 0 && ! shouldDeactivateTitleBar)
  1617. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  1618. break;
  1619. case WM_MOUSEACTIVATE:
  1620. if (! component->getMouseClickGrabsKeyboardFocus())
  1621. return MA_NOACTIVATE;
  1622. break;
  1623. case WM_SHOWWINDOW:
  1624. if (wParam != 0)
  1625. handleBroughtToFront();
  1626. break;
  1627. case WM_CLOSE:
  1628. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  1629. handleUserClosingWindow();
  1630. return 0;
  1631. case WM_QUIT:
  1632. JUCEApplication::quit();
  1633. return 0;
  1634. //==============================================================================
  1635. case WM_TRAYNOTIFY:
  1636. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1637. {
  1638. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  1639. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1640. {
  1641. Component* const current = Component::getCurrentlyModalComponent();
  1642. if (current != 0)
  1643. current->inputAttemptWhenModal();
  1644. }
  1645. }
  1646. else
  1647. {
  1648. const int oldModifiers = currentModifiers;
  1649. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  1650. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  1651. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  1652. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  1653. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  1654. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  1655. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  1656. {
  1657. SetFocus (hwnd);
  1658. SetForegroundWindow (hwnd);
  1659. component->mouseDown (e);
  1660. }
  1661. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  1662. {
  1663. e.mods = ModifierKeys (oldModifiers);
  1664. component->mouseUp (e);
  1665. }
  1666. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1667. {
  1668. e.mods = ModifierKeys (oldModifiers);
  1669. component->mouseDoubleClick (e);
  1670. }
  1671. else if (lParam == WM_MOUSEMOVE)
  1672. {
  1673. component->mouseMove (e);
  1674. }
  1675. }
  1676. break;
  1677. //==============================================================================
  1678. case WM_SYNCPAINT:
  1679. return 0;
  1680. case WM_PALETTECHANGED:
  1681. InvalidateRect (h, 0, 0);
  1682. break;
  1683. case WM_DISPLAYCHANGE:
  1684. InvalidateRect (h, 0, 0);
  1685. createPaletteIfNeeded = true;
  1686. // intentional fall-through...
  1687. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  1688. doSettingChange();
  1689. break;
  1690. case WM_INITMENU:
  1691. if (! hasTitleBar())
  1692. {
  1693. if (isFullScreen())
  1694. {
  1695. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  1696. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  1697. }
  1698. else if (! isMinimised())
  1699. {
  1700. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  1701. }
  1702. }
  1703. break;
  1704. case WM_SYSCOMMAND:
  1705. switch (wParam & 0xfff0)
  1706. {
  1707. case SC_CLOSE:
  1708. if (sendInputAttemptWhenModalMessage())
  1709. return 0;
  1710. if (hasTitleBar())
  1711. {
  1712. PostMessage (h, WM_CLOSE, 0, 0);
  1713. return 0;
  1714. }
  1715. break;
  1716. case SC_KEYMENU:
  1717. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  1718. // obscure situations that can arise if a modal loop is started from an alt-key
  1719. // keypress).
  1720. if (hasTitleBar() && h == GetCapture())
  1721. ReleaseCapture();
  1722. break;
  1723. case SC_MAXIMIZE:
  1724. if (sendInputAttemptWhenModalMessage())
  1725. return 0;
  1726. setFullScreen (true);
  1727. return 0;
  1728. case SC_MINIMIZE:
  1729. if (sendInputAttemptWhenModalMessage())
  1730. return 0;
  1731. if (! hasTitleBar())
  1732. {
  1733. setMinimised (true);
  1734. return 0;
  1735. }
  1736. break;
  1737. case SC_RESTORE:
  1738. if (sendInputAttemptWhenModalMessage())
  1739. return 0;
  1740. if (hasTitleBar())
  1741. {
  1742. if (isFullScreen())
  1743. {
  1744. setFullScreen (false);
  1745. return 0;
  1746. }
  1747. }
  1748. else
  1749. {
  1750. if (isMinimised())
  1751. setMinimised (false);
  1752. else if (isFullScreen())
  1753. setFullScreen (false);
  1754. return 0;
  1755. }
  1756. break;
  1757. }
  1758. break;
  1759. case WM_NCLBUTTONDOWN:
  1760. case WM_NCRBUTTONDOWN:
  1761. case WM_NCMBUTTONDOWN:
  1762. sendInputAttemptWhenModalMessage();
  1763. break;
  1764. //case WM_IME_STARTCOMPOSITION;
  1765. // return 0;
  1766. case WM_GETDLGCODE:
  1767. return DLGC_WANTALLKEYS;
  1768. default:
  1769. break;
  1770. }
  1771. }
  1772. }
  1773. // (the message manager lock exits before calling this, to avoid deadlocks if
  1774. // this calls into non-juce windows)
  1775. return DefWindowProc (h, message, wParam, lParam);
  1776. }
  1777. bool sendInputAttemptWhenModalMessage()
  1778. {
  1779. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1780. {
  1781. Component* const current = Component::getCurrentlyModalComponent();
  1782. if (current != 0)
  1783. current->inputAttemptWhenModal();
  1784. return true;
  1785. }
  1786. return false;
  1787. }
  1788. Win32ComponentPeer (const Win32ComponentPeer&);
  1789. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  1790. };
  1791. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  1792. {
  1793. return new Win32ComponentPeer (this, styleFlags);
  1794. }
  1795. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  1796. //==============================================================================
  1797. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  1798. {
  1799. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1800. if (wp != 0)
  1801. wp->setTaskBarIcon (&newImage);
  1802. }
  1803. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  1804. {
  1805. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1806. if (wp != 0)
  1807. wp->setTaskBarIconToolTip (tooltip);
  1808. }
  1809. //==============================================================================
  1810. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  1811. {
  1812. DWORD val = GetWindowLong (h, styleType);
  1813. if (bitIsSet)
  1814. val |= feature;
  1815. else
  1816. val &= ~feature;
  1817. SetWindowLongPtr (h, styleType, val);
  1818. SetWindowPos (h, 0, 0, 0, 0, 0,
  1819. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  1820. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  1821. }
  1822. //==============================================================================
  1823. bool Process::isForegroundProcess() throw()
  1824. {
  1825. HWND fg = GetForegroundWindow();
  1826. if (fg == 0)
  1827. return true;
  1828. DWORD processId = 0;
  1829. GetWindowThreadProcessId (fg, &processId);
  1830. return processId == GetCurrentProcessId();
  1831. }
  1832. //==============================================================================
  1833. bool AlertWindow::showNativeDialogBox (const String& title,
  1834. const String& bodyText,
  1835. bool isOkCancel)
  1836. {
  1837. return MessageBox (0, bodyText, title,
  1838. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  1839. : MB_OK)) == IDOK;
  1840. }
  1841. //==============================================================================
  1842. void Desktop::getMousePosition (int& x, int& y) throw()
  1843. {
  1844. POINT mousePos;
  1845. GetCursorPos (&mousePos);
  1846. x = mousePos.x;
  1847. y = mousePos.y;
  1848. }
  1849. void Desktop::setMousePosition (int x, int y) throw()
  1850. {
  1851. SetCursorPos (x, y);
  1852. }
  1853. //==============================================================================
  1854. class ScreenSaverDefeater : public Timer,
  1855. public DeletedAtShutdown
  1856. {
  1857. public:
  1858. ScreenSaverDefeater() throw()
  1859. {
  1860. startTimer (10000);
  1861. timerCallback();
  1862. }
  1863. ~ScreenSaverDefeater() {}
  1864. void timerCallback()
  1865. {
  1866. if (Process::isForegroundProcess())
  1867. {
  1868. // simulate a shift key getting pressed..
  1869. INPUT input[2];
  1870. input[0].type = INPUT_KEYBOARD;
  1871. input[0].ki.wVk = VK_SHIFT;
  1872. input[0].ki.dwFlags = 0;
  1873. input[0].ki.dwExtraInfo = 0;
  1874. input[1].type = INPUT_KEYBOARD;
  1875. input[1].ki.wVk = VK_SHIFT;
  1876. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  1877. input[1].ki.dwExtraInfo = 0;
  1878. SendInput (2, input, sizeof (INPUT));
  1879. }
  1880. }
  1881. };
  1882. static ScreenSaverDefeater* screenSaverDefeater = 0;
  1883. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1884. {
  1885. if (isEnabled)
  1886. {
  1887. deleteAndZero (screenSaverDefeater);
  1888. }
  1889. else if (screenSaverDefeater == 0)
  1890. {
  1891. screenSaverDefeater = new ScreenSaverDefeater();
  1892. }
  1893. }
  1894. bool Desktop::isScreenSaverEnabled() throw()
  1895. {
  1896. return screenSaverDefeater == 0;
  1897. }
  1898. /* (The code below is the "correct" way to disable the screen saver, but it
  1899. completely fails on winXP when the saver is password-protected...)
  1900. static bool juce_screenSaverEnabled = true;
  1901. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1902. {
  1903. juce_screenSaverEnabled = isEnabled;
  1904. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  1905. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  1906. }
  1907. bool Desktop::isScreenSaverEnabled() throw()
  1908. {
  1909. return juce_screenSaverEnabled;
  1910. }
  1911. */
  1912. //==============================================================================
  1913. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable)
  1914. {
  1915. if (enableOrDisable)
  1916. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  1917. }
  1918. //==============================================================================
  1919. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  1920. {
  1921. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  1922. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  1923. return TRUE;
  1924. }
  1925. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1926. {
  1927. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  1928. // make sure the first in the list is the main monitor
  1929. for (int i = 1; i < monitorCoords.size(); ++i)
  1930. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  1931. monitorCoords.swap (i, 0);
  1932. if (monitorCoords.size() == 0)
  1933. {
  1934. RECT r;
  1935. GetWindowRect (GetDesktopWindow(), &r);
  1936. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  1937. }
  1938. if (clipToWorkArea)
  1939. {
  1940. // clip the main monitor to the active non-taskbar area
  1941. RECT r;
  1942. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  1943. Rectangle& screen = monitorCoords.getReference (0);
  1944. screen.setPosition (jmax (screen.getX(), r.left),
  1945. jmax (screen.getY(), r.top));
  1946. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  1947. jmin (screen.getBottom(), r.bottom) - screen.getY());
  1948. }
  1949. }
  1950. //==============================================================================
  1951. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  1952. {
  1953. Image* im = 0;
  1954. if (bitmap != 0)
  1955. {
  1956. BITMAP bm;
  1957. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  1958. && bm.bmWidth > 0 && bm.bmHeight > 0)
  1959. {
  1960. HDC tempDC = GetDC (0);
  1961. HDC dc = CreateCompatibleDC (tempDC);
  1962. ReleaseDC (0, tempDC);
  1963. SelectObject (dc, bitmap);
  1964. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  1965. for (int y = bm.bmHeight; --y >= 0;)
  1966. {
  1967. for (int x = bm.bmWidth; --x >= 0;)
  1968. {
  1969. COLORREF col = GetPixel (dc, x, y);
  1970. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  1971. (uint8) GetGValue (col),
  1972. (uint8) GetBValue (col)));
  1973. }
  1974. }
  1975. DeleteDC (dc);
  1976. }
  1977. }
  1978. return im;
  1979. }
  1980. static Image* createImageFromHICON (HICON icon) throw()
  1981. {
  1982. ICONINFO info;
  1983. if (GetIconInfo (icon, &info))
  1984. {
  1985. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  1986. if (mask == 0)
  1987. return 0;
  1988. Image* const image = createImageFromHBITMAP (info.hbmColor);
  1989. if (image == 0)
  1990. return mask;
  1991. for (int y = image->getHeight(); --y >= 0;)
  1992. {
  1993. for (int x = image->getWidth(); --x >= 0;)
  1994. {
  1995. const float brightness = mask->getPixelAt (x, y).getBrightness();
  1996. if (brightness > 0.0f)
  1997. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  1998. }
  1999. }
  2000. delete mask;
  2001. return image;
  2002. }
  2003. return 0;
  2004. }
  2005. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  2006. {
  2007. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  2008. ICONINFO info;
  2009. info.fIcon = isIcon;
  2010. info.xHotspot = hotspotX;
  2011. info.yHotspot = hotspotY;
  2012. info.hbmMask = mask;
  2013. HICON hi = 0;
  2014. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  2015. {
  2016. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  2017. Graphics g (bitmap);
  2018. g.drawImageAt (&image, 0, 0);
  2019. info.hbmColor = bitmap.hBitmap;
  2020. hi = CreateIconIndirect (&info);
  2021. }
  2022. else
  2023. {
  2024. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  2025. HDC colDC = CreateCompatibleDC (GetDC (0));
  2026. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  2027. SelectObject (colDC, colour);
  2028. SelectObject (alphaDC, mask);
  2029. for (int y = image.getHeight(); --y >= 0;)
  2030. {
  2031. for (int x = image.getWidth(); --x >= 0;)
  2032. {
  2033. const Colour c (image.getPixelAt (x, y));
  2034. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  2035. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  2036. }
  2037. }
  2038. DeleteDC (colDC);
  2039. DeleteDC (alphaDC);
  2040. info.hbmColor = colour;
  2041. hi = CreateIconIndirect (&info);
  2042. DeleteObject (colour);
  2043. }
  2044. DeleteObject (mask);
  2045. return hi;
  2046. }
  2047. Image* juce_createIconForFile (const File& file)
  2048. {
  2049. Image* image = 0;
  2050. TCHAR filename [1024];
  2051. file.getFullPathName().copyToBuffer (filename, 1023);
  2052. WORD iconNum = 0;
  2053. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  2054. filename, &iconNum);
  2055. if (icon != 0)
  2056. {
  2057. image = createImageFromHICON (icon);
  2058. DestroyIcon (icon);
  2059. }
  2060. return image;
  2061. }
  2062. //==============================================================================
  2063. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  2064. {
  2065. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  2066. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  2067. const Image* im = &image;
  2068. Image* newIm = 0;
  2069. if (image.getWidth() > maxW || image.getHeight() > maxH)
  2070. {
  2071. im = newIm = image.createCopy (maxW, maxH);
  2072. hotspotX = (hotspotX * maxW) / image.getWidth();
  2073. hotspotY = (hotspotY * maxH) / image.getHeight();
  2074. }
  2075. void* cursorH = 0;
  2076. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  2077. if (os == SystemStats::WinXP)
  2078. {
  2079. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  2080. }
  2081. else
  2082. {
  2083. const int stride = (maxW + 7) >> 3;
  2084. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  2085. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  2086. int index = 0;
  2087. for (int y = 0; y < maxH; ++y)
  2088. {
  2089. for (int x = 0; x < maxW; ++x)
  2090. {
  2091. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  2092. const Colour pixelColour (im->getPixelAt (x, y));
  2093. if (pixelColour.getAlpha() < 127)
  2094. andPlane [index + (x >> 3)] |= bit;
  2095. else if (pixelColour.getBrightness() >= 0.5f)
  2096. xorPlane [index + (x >> 3)] |= bit;
  2097. }
  2098. index += stride;
  2099. }
  2100. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  2101. juce_free (andPlane);
  2102. juce_free (xorPlane);
  2103. }
  2104. delete newIm;
  2105. return cursorH;
  2106. }
  2107. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2108. {
  2109. if (cursorHandle != 0 && ! isStandard)
  2110. DestroyCursor ((HCURSOR) cursorHandle);
  2111. }
  2112. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  2113. {
  2114. LPCTSTR cursorName = IDC_ARROW;
  2115. switch (type)
  2116. {
  2117. case MouseCursor::NormalCursor:
  2118. cursorName = IDC_ARROW;
  2119. break;
  2120. case MouseCursor::NoCursor:
  2121. return 0;
  2122. case MouseCursor::DraggingHandCursor:
  2123. {
  2124. static void* dragHandCursor = 0;
  2125. if (dragHandCursor == 0)
  2126. {
  2127. static const unsigned char dragHandData[] =
  2128. { 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,
  2129. 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,
  2130. 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 };
  2131. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  2132. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  2133. delete image;
  2134. }
  2135. return dragHandCursor;
  2136. }
  2137. case MouseCursor::WaitCursor:
  2138. cursorName = IDC_WAIT;
  2139. break;
  2140. case MouseCursor::IBeamCursor:
  2141. cursorName = IDC_IBEAM;
  2142. break;
  2143. case MouseCursor::PointingHandCursor:
  2144. cursorName = MAKEINTRESOURCE(32649);
  2145. break;
  2146. case MouseCursor::LeftRightResizeCursor:
  2147. case MouseCursor::LeftEdgeResizeCursor:
  2148. case MouseCursor::RightEdgeResizeCursor:
  2149. cursorName = IDC_SIZEWE;
  2150. break;
  2151. case MouseCursor::UpDownResizeCursor:
  2152. case MouseCursor::TopEdgeResizeCursor:
  2153. case MouseCursor::BottomEdgeResizeCursor:
  2154. cursorName = IDC_SIZENS;
  2155. break;
  2156. case MouseCursor::TopLeftCornerResizeCursor:
  2157. case MouseCursor::BottomRightCornerResizeCursor:
  2158. cursorName = IDC_SIZENWSE;
  2159. break;
  2160. case MouseCursor::TopRightCornerResizeCursor:
  2161. case MouseCursor::BottomLeftCornerResizeCursor:
  2162. cursorName = IDC_SIZENESW;
  2163. break;
  2164. case MouseCursor::UpDownLeftRightResizeCursor:
  2165. cursorName = IDC_SIZEALL;
  2166. break;
  2167. case MouseCursor::CrosshairCursor:
  2168. cursorName = IDC_CROSS;
  2169. break;
  2170. case MouseCursor::CopyingCursor:
  2171. // can't seem to find one of these in the win32 list..
  2172. break;
  2173. }
  2174. HCURSOR cursorH = LoadCursor (0, cursorName);
  2175. if (cursorH == 0)
  2176. cursorH = LoadCursor (0, IDC_ARROW);
  2177. return (void*) cursorH;
  2178. }
  2179. //==============================================================================
  2180. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2181. {
  2182. SetCursor ((HCURSOR) getHandle());
  2183. }
  2184. void MouseCursor::showInAllWindows() const throw()
  2185. {
  2186. showInWindow (0);
  2187. }
  2188. //==============================================================================
  2189. //==============================================================================
  2190. class JuceDropSource : public IDropSource
  2191. {
  2192. int refCount;
  2193. public:
  2194. JuceDropSource()
  2195. : refCount (1)
  2196. {
  2197. }
  2198. virtual ~JuceDropSource()
  2199. {
  2200. jassert (refCount == 0);
  2201. }
  2202. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2203. {
  2204. if (id == IID_IUnknown || id == IID_IDropSource)
  2205. {
  2206. AddRef();
  2207. *result = this;
  2208. return S_OK;
  2209. }
  2210. *result = 0;
  2211. return E_NOINTERFACE;
  2212. }
  2213. ULONG __stdcall AddRef() { return ++refCount; }
  2214. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2215. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  2216. {
  2217. if (escapePressed)
  2218. return DRAGDROP_S_CANCEL;
  2219. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  2220. return DRAGDROP_S_DROP;
  2221. return S_OK;
  2222. }
  2223. HRESULT __stdcall GiveFeedback (DWORD)
  2224. {
  2225. return DRAGDROP_S_USEDEFAULTCURSORS;
  2226. }
  2227. };
  2228. class JuceEnumFormatEtc : public IEnumFORMATETC
  2229. {
  2230. public:
  2231. JuceEnumFormatEtc (const FORMATETC* const format_)
  2232. : refCount (1),
  2233. format (format_),
  2234. index (0)
  2235. {
  2236. }
  2237. virtual ~JuceEnumFormatEtc()
  2238. {
  2239. jassert (refCount == 0);
  2240. }
  2241. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2242. {
  2243. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  2244. {
  2245. AddRef();
  2246. *result = this;
  2247. return S_OK;
  2248. }
  2249. *result = 0;
  2250. return E_NOINTERFACE;
  2251. }
  2252. ULONG __stdcall AddRef() { return ++refCount; }
  2253. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2254. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  2255. {
  2256. if (result == 0)
  2257. return E_POINTER;
  2258. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  2259. newOne->index = index;
  2260. *result = newOne;
  2261. return S_OK;
  2262. }
  2263. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  2264. {
  2265. if (pceltFetched != 0)
  2266. *pceltFetched = 0;
  2267. else if (celt != 1)
  2268. return S_FALSE;
  2269. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  2270. {
  2271. copyFormatEtc (lpFormatEtc [0], *format);
  2272. ++index;
  2273. if (pceltFetched != 0)
  2274. *pceltFetched = 1;
  2275. return S_OK;
  2276. }
  2277. return S_FALSE;
  2278. }
  2279. HRESULT __stdcall Skip (ULONG celt)
  2280. {
  2281. if (index + (int) celt >= 1)
  2282. return S_FALSE;
  2283. index += celt;
  2284. return S_OK;
  2285. }
  2286. HRESULT __stdcall Reset()
  2287. {
  2288. index = 0;
  2289. return S_OK;
  2290. }
  2291. private:
  2292. int refCount;
  2293. const FORMATETC* const format;
  2294. int index;
  2295. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  2296. {
  2297. dest = source;
  2298. if (source.ptd != 0)
  2299. {
  2300. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  2301. *(dest.ptd) = *(source.ptd);
  2302. }
  2303. }
  2304. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  2305. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  2306. };
  2307. class JuceDataObject : public IDataObject
  2308. {
  2309. JuceDropSource* const dropSource;
  2310. const FORMATETC* const format;
  2311. const STGMEDIUM* const medium;
  2312. int refCount;
  2313. JuceDataObject (const JuceDataObject&);
  2314. const JuceDataObject& operator= (const JuceDataObject&);
  2315. public:
  2316. JuceDataObject (JuceDropSource* const dropSource_,
  2317. const FORMATETC* const format_,
  2318. const STGMEDIUM* const medium_)
  2319. : dropSource (dropSource_),
  2320. format (format_),
  2321. medium (medium_),
  2322. refCount (1)
  2323. {
  2324. }
  2325. virtual ~JuceDataObject()
  2326. {
  2327. jassert (refCount == 0);
  2328. }
  2329. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2330. {
  2331. if (id == IID_IUnknown || id == IID_IDataObject)
  2332. {
  2333. AddRef();
  2334. *result = this;
  2335. return S_OK;
  2336. }
  2337. *result = 0;
  2338. return E_NOINTERFACE;
  2339. }
  2340. ULONG __stdcall AddRef() { return ++refCount; }
  2341. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2342. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  2343. {
  2344. if (pFormatEtc->tymed == format->tymed
  2345. && pFormatEtc->cfFormat == format->cfFormat
  2346. && pFormatEtc->dwAspect == format->dwAspect)
  2347. {
  2348. pMedium->tymed = format->tymed;
  2349. pMedium->pUnkForRelease = 0;
  2350. if (format->tymed == TYMED_HGLOBAL)
  2351. {
  2352. const SIZE_T len = GlobalSize (medium->hGlobal);
  2353. void* const src = GlobalLock (medium->hGlobal);
  2354. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  2355. memcpy (dst, src, len);
  2356. GlobalUnlock (medium->hGlobal);
  2357. pMedium->hGlobal = dst;
  2358. return S_OK;
  2359. }
  2360. }
  2361. return DV_E_FORMATETC;
  2362. }
  2363. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  2364. {
  2365. if (f == 0)
  2366. return E_INVALIDARG;
  2367. if (f->tymed == format->tymed
  2368. && f->cfFormat == format->cfFormat
  2369. && f->dwAspect == format->dwAspect)
  2370. return S_OK;
  2371. return DV_E_FORMATETC;
  2372. }
  2373. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  2374. {
  2375. pFormatEtcOut->ptd = 0;
  2376. return E_NOTIMPL;
  2377. }
  2378. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  2379. {
  2380. if (result == 0)
  2381. return E_POINTER;
  2382. if (direction == DATADIR_GET)
  2383. {
  2384. *result = new JuceEnumFormatEtc (format);
  2385. return S_OK;
  2386. }
  2387. *result = 0;
  2388. return E_NOTIMPL;
  2389. }
  2390. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  2391. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  2392. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  2393. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  2394. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  2395. };
  2396. static HDROP createHDrop (const StringArray& fileNames) throw()
  2397. {
  2398. int totalChars = 0;
  2399. for (int i = fileNames.size(); --i >= 0;)
  2400. totalChars += fileNames[i].length() + 1;
  2401. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  2402. sizeof (DROPFILES)
  2403. + sizeof (WCHAR) * (totalChars + 2));
  2404. if (hDrop != 0)
  2405. {
  2406. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  2407. pDropFiles->pFiles = sizeof (DROPFILES);
  2408. pDropFiles->fWide = true;
  2409. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  2410. for (int i = 0; i < fileNames.size(); ++i)
  2411. {
  2412. fileNames[i].copyToBuffer (fname, 2048);
  2413. fname += fileNames[i].length() + 1;
  2414. }
  2415. *fname = 0;
  2416. GlobalUnlock (hDrop);
  2417. }
  2418. return hDrop;
  2419. }
  2420. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  2421. {
  2422. JuceDropSource* const source = new JuceDropSource();
  2423. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  2424. DWORD effect;
  2425. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  2426. data->Release();
  2427. source->Release();
  2428. return res == DRAGDROP_S_DROP;
  2429. }
  2430. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  2431. {
  2432. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2433. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2434. medium.hGlobal = createHDrop (files);
  2435. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  2436. : DROPEFFECT_COPY);
  2437. }
  2438. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2439. {
  2440. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2441. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2442. const int numChars = text.length();
  2443. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  2444. char* d = (char*) GlobalLock (medium.hGlobal);
  2445. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  2446. format.cfFormat = CF_UNICODETEXT;
  2447. GlobalUnlock (medium.hGlobal);
  2448. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  2449. }
  2450. #endif