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.

3097 lines
101KB

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