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.

4036 lines
134KB

  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. #ifdef _MSC_VER
  24. #pragma warning (disable: 4514)
  25. #pragma warning (push)
  26. #endif
  27. #include "win32_headers.h"
  28. #include <float.h>
  29. #include <windowsx.h>
  30. #include <shlobj.h>
  31. #if JUCE_OPENGL
  32. #include <gl/gl.h>
  33. #endif
  34. #ifdef _MSC_VER
  35. #pragma warning (pop)
  36. #pragma warning (disable: 4312 4244)
  37. #endif
  38. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  39. // these are in the windows SDK, but need to be repeated here for GCC..
  40. #ifndef GET_APPCOMMAND_LPARAM
  41. #define FAPPCOMMAND_MASK 0xF000
  42. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  43. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  44. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  45. #define APPCOMMAND_MEDIA_STOP 13
  46. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  47. #define WM_APPCOMMAND 0x0319
  48. #endif
  49. #include "../../../src/juce_core/basics/juce_StandardHeader.h"
  50. BEGIN_JUCE_NAMESPACE
  51. #include "../../../src/juce_core/text/juce_StringArray.h"
  52. #include "../../../src/juce_core/basics/juce_SystemStats.h"
  53. #include "../../../src/juce_core/basics/juce_Singleton.h"
  54. #include "../../../src/juce_core/threads/juce_Process.h"
  55. #include "../../../src/juce_core/misc/juce_PlatformUtilities.h"
  56. #include "../../../src/juce_appframework/events/juce_Timer.h"
  57. #include "../../../src/juce_appframework/events/juce_MessageManager.h"
  58. #include "../../../src/juce_appframework/application/juce_DeletedAtShutdown.h"
  59. #include "../../../src/juce_appframework/gui/components/keyboard/juce_KeyPress.h"
  60. #include "../../../src/juce_appframework/gui/components/mouse/juce_DragAndDropContainer.h"
  61. #include "../../../src/juce_appframework/gui/components/juce_Desktop.h"
  62. #include "../../../src/juce_appframework/gui/components/lookandfeel/juce_LookAndFeel.h"
  63. #include "../../../src/juce_appframework/gui/components/special/juce_OpenGLComponent.h"
  64. #include "../../../src/juce_appframework/gui/components/special/juce_DropShadower.h"
  65. #include "../../../src/juce_appframework/gui/components/special/juce_ActiveXControlComponent.h"
  66. #include "../../../src/juce_appframework/gui/components/special/juce_SystemTrayIconComponent.h"
  67. #include "../../../src/juce_appframework/gui/components/juce_ComponentDeletionWatcher.h"
  68. #include "../../../src/juce_appframework/gui/components/layout/juce_ComponentBoundsConstrainer.h"
  69. #include "../../../src/juce_appframework/gui/graphics/imaging/juce_ImageFileFormat.h"
  70. #include "../../../src/juce_appframework/gui/graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.h"
  71. #include "../../../src/juce_appframework/gui/graphics/geometry/juce_PathIterator.h"
  72. #include "../../../src/juce_appframework/gui/components/layout/juce_ComponentMovementWatcher.h"
  73. #include "../../../src/juce_appframework/application/juce_Application.h"
  74. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  75. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  76. extern bool juce_IsRunningInWine() throw();
  77. #ifndef ULW_ALPHA
  78. #define ULW_ALPHA 0x00000002
  79. #endif
  80. #ifndef AC_SRC_ALPHA
  81. #define AC_SRC_ALPHA 0x01
  82. #endif
  83. #define DEBUG_REPAINT_TIMES 0
  84. static HPALETTE palette = 0;
  85. static bool createPaletteIfNeeded = true;
  86. static bool shouldDeactivateTitleBar = true;
  87. static bool screenSaverAllowed = true;
  88. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  89. #define WM_TRAYNOTIFY WM_USER + 100
  90. using ::abs;
  91. //==============================================================================
  92. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  93. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  94. bool Desktop::canUseSemiTransparentWindows() throw()
  95. {
  96. if (updateLayeredWindow == 0)
  97. {
  98. if (! juce_IsRunningInWine())
  99. {
  100. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  101. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  102. }
  103. }
  104. return updateLayeredWindow != 0;
  105. }
  106. //==============================================================================
  107. #undef DefWindowProc
  108. #define DefWindowProc DefWindowProcW
  109. //==============================================================================
  110. const int extendedKeyModifier = 0x10000;
  111. const int KeyPress::spaceKey = VK_SPACE;
  112. const int KeyPress::returnKey = VK_RETURN;
  113. const int KeyPress::escapeKey = VK_ESCAPE;
  114. const int KeyPress::backspaceKey = VK_BACK;
  115. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  116. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  117. const int KeyPress::tabKey = VK_TAB;
  118. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  119. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  120. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  121. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  122. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  123. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  124. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  125. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  126. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  127. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  128. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  129. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  130. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  131. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  132. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  133. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  134. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  135. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  136. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  137. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  138. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  139. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  140. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  141. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  142. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  143. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  144. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  145. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  146. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  147. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  148. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  149. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  150. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  151. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  152. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  153. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  154. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  155. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  156. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  157. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  158. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  159. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  160. const int KeyPress::playKey = 0x30000;
  161. const int KeyPress::stopKey = 0x30001;
  162. const int KeyPress::fastForwardKey = 0x30002;
  163. const int KeyPress::rewindKey = 0x30003;
  164. //==============================================================================
  165. class WindowsBitmapImage : public Image
  166. {
  167. public:
  168. //==============================================================================
  169. HBITMAP hBitmap;
  170. BITMAPV4HEADER bitmapInfo;
  171. HDC hdc;
  172. unsigned char* bitmapData;
  173. //==============================================================================
  174. WindowsBitmapImage (const PixelFormat format_,
  175. const int w, const int h, const bool clearImage)
  176. : Image (format_, w, h)
  177. {
  178. jassert (format_ == RGB || format_ == ARGB);
  179. pixelStride = (format_ == RGB) ? 3 : 4;
  180. zerostruct (bitmapInfo);
  181. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  182. bitmapInfo.bV4Width = w;
  183. bitmapInfo.bV4Height = h;
  184. bitmapInfo.bV4Planes = 1;
  185. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  186. if (format_ == ARGB)
  187. {
  188. bitmapInfo.bV4AlphaMask = 0xff000000;
  189. bitmapInfo.bV4RedMask = 0xff0000;
  190. bitmapInfo.bV4GreenMask = 0xff00;
  191. bitmapInfo.bV4BlueMask = 0xff;
  192. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  193. }
  194. else
  195. {
  196. bitmapInfo.bV4V4Compression = BI_RGB;
  197. }
  198. lineStride = -((w * pixelStride + 3) & ~3);
  199. HDC dc = GetDC (0);
  200. hdc = CreateCompatibleDC (dc);
  201. ReleaseDC (0, dc);
  202. SetMapMode (hdc, MM_TEXT);
  203. hBitmap = CreateDIBSection (hdc,
  204. (BITMAPINFO*) &(bitmapInfo),
  205. DIB_RGB_COLORS,
  206. (void**) &bitmapData,
  207. 0, 0);
  208. SelectObject (hdc, hBitmap);
  209. if (format_ == ARGB && clearImage)
  210. zeromem (bitmapData, abs (h * lineStride));
  211. imageData = bitmapData - (lineStride * (h - 1));
  212. }
  213. ~WindowsBitmapImage()
  214. {
  215. DeleteDC (hdc);
  216. DeleteObject (hBitmap);
  217. imageData = 0; // to stop the base class freeing this
  218. }
  219. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  220. const int x, const int y,
  221. const RectangleList& maskedRegion) throw()
  222. {
  223. static HDRAWDIB hdd = 0;
  224. static bool needToCreateDrawDib = true;
  225. if (needToCreateDrawDib)
  226. {
  227. needToCreateDrawDib = false;
  228. HDC dc = GetDC (0);
  229. const int n = GetDeviceCaps (dc, BITSPIXEL);
  230. ReleaseDC (0, dc);
  231. // only open if we're not palettised
  232. if (n > 8)
  233. hdd = DrawDibOpen();
  234. }
  235. if (createPaletteIfNeeded)
  236. {
  237. HDC dc = GetDC (0);
  238. const int n = GetDeviceCaps (dc, BITSPIXEL);
  239. ReleaseDC (0, dc);
  240. if (n <= 8)
  241. palette = CreateHalftonePalette (dc);
  242. createPaletteIfNeeded = false;
  243. }
  244. if (palette != 0)
  245. {
  246. SelectPalette (dc, palette, FALSE);
  247. RealizePalette (dc);
  248. SetStretchBltMode (dc, HALFTONE);
  249. }
  250. SetMapMode (dc, MM_TEXT);
  251. if (transparent)
  252. {
  253. POINT p, pos;
  254. SIZE size;
  255. RECT windowBounds;
  256. GetWindowRect (hwnd, &windowBounds);
  257. p.x = -x;
  258. p.y = -y;
  259. pos.x = windowBounds.left;
  260. pos.y = windowBounds.top;
  261. size.cx = windowBounds.right - windowBounds.left;
  262. size.cy = windowBounds.bottom - windowBounds.top;
  263. BLENDFUNCTION bf;
  264. bf.AlphaFormat = AC_SRC_ALPHA;
  265. bf.BlendFlags = 0;
  266. bf.BlendOp = AC_SRC_OVER;
  267. bf.SourceConstantAlpha = 0xff;
  268. if (! maskedRegion.isEmpty())
  269. {
  270. for (RectangleList::Iterator i (maskedRegion); i.next();)
  271. {
  272. const Rectangle& r = *i.getRectangle();
  273. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  274. }
  275. }
  276. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  277. }
  278. else
  279. {
  280. int savedDC = 0;
  281. if (! maskedRegion.isEmpty())
  282. {
  283. savedDC = SaveDC (dc);
  284. for (RectangleList::Iterator i (maskedRegion); i.next();)
  285. {
  286. const Rectangle& r = *i.getRectangle();
  287. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  288. }
  289. }
  290. const int w = getWidth();
  291. const int h = getHeight();
  292. if (hdd == 0)
  293. {
  294. StretchDIBits (dc,
  295. x, y, w, h,
  296. 0, 0, w, h,
  297. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  298. DIB_RGB_COLORS, SRCCOPY);
  299. }
  300. else
  301. {
  302. DrawDibDraw (hdd, dc, x, y, -1, -1,
  303. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  304. 0, 0, w, h, 0);
  305. }
  306. if (! maskedRegion.isEmpty())
  307. RestoreDC (dc, savedDC);
  308. }
  309. }
  310. juce_UseDebuggingNewOperator
  311. private:
  312. WindowsBitmapImage (const WindowsBitmapImage&);
  313. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  314. };
  315. //==============================================================================
  316. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  317. //==============================================================================
  318. static int currentModifiers = 0;
  319. static int modifiersAtLastCallback = 0;
  320. static void updateKeyModifiers() throw()
  321. {
  322. currentModifiers &= ~(ModifierKeys::shiftModifier
  323. | ModifierKeys::ctrlModifier
  324. | ModifierKeys::altModifier);
  325. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  326. currentModifiers |= ModifierKeys::shiftModifier;
  327. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  328. currentModifiers |= ModifierKeys::ctrlModifier;
  329. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  330. currentModifiers |= ModifierKeys::altModifier;
  331. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  332. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  333. }
  334. void ModifierKeys::updateCurrentModifiers() throw()
  335. {
  336. currentModifierFlags = currentModifiers;
  337. }
  338. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  339. {
  340. SHORT k = (SHORT) keyCode;
  341. if ((keyCode & extendedKeyModifier) == 0
  342. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  343. k += (SHORT) T('A') - (SHORT) T('a');
  344. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  345. (SHORT) '+', VK_OEM_PLUS,
  346. (SHORT) '-', VK_OEM_MINUS,
  347. (SHORT) '.', VK_OEM_PERIOD,
  348. (SHORT) ';', VK_OEM_1,
  349. (SHORT) ':', VK_OEM_1,
  350. (SHORT) '/', VK_OEM_2,
  351. (SHORT) '?', VK_OEM_2,
  352. (SHORT) '[', VK_OEM_4,
  353. (SHORT) ']', VK_OEM_6 };
  354. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  355. if (k == translatedValues [i])
  356. k = translatedValues [i + 1];
  357. return (GetKeyState (k) & 0x8000) != 0;
  358. }
  359. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  360. {
  361. updateKeyModifiers();
  362. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  363. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  364. currentModifiers |= ModifierKeys::leftButtonModifier;
  365. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  366. currentModifiers |= ModifierKeys::rightButtonModifier;
  367. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  368. currentModifiers |= ModifierKeys::middleButtonModifier;
  369. return ModifierKeys (currentModifiers);
  370. }
  371. static int64 getMouseEventTime() throw()
  372. {
  373. static int64 eventTimeOffset = 0;
  374. static DWORD lastMessageTime = 0;
  375. const DWORD thisMessageTime = GetMessageTime();
  376. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  377. {
  378. lastMessageTime = thisMessageTime;
  379. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  380. }
  381. return eventTimeOffset + thisMessageTime;
  382. }
  383. //==============================================================================
  384. class Win32ComponentPeer : public ComponentPeer
  385. {
  386. public:
  387. //==============================================================================
  388. Win32ComponentPeer (Component* const component,
  389. const int windowStyleFlags)
  390. : ComponentPeer (component, windowStyleFlags),
  391. dontRepaint (false),
  392. fullScreen (false),
  393. isDragging (false),
  394. isMouseOver (false),
  395. hasCreatedCaret (false),
  396. currentWindowIcon (0),
  397. taskBarIcon (0),
  398. dropTarget (0)
  399. {
  400. MessageManager::getInstance()
  401. ->callFunctionOnMessageThread (&createWindowCallback, (void*) this);
  402. setTitle (component->getName());
  403. if ((windowStyleFlags & windowHasDropShadow) != 0
  404. && Desktop::canUseSemiTransparentWindows())
  405. {
  406. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  407. if (shadower != 0)
  408. shadower->setOwner (component);
  409. }
  410. else
  411. {
  412. shadower = 0;
  413. }
  414. }
  415. ~Win32ComponentPeer()
  416. {
  417. setTaskBarIcon (0);
  418. deleteAndZero (shadower);
  419. // do this before the next bit to avoid messages arriving for this window
  420. // before it's destroyed
  421. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  422. MessageManager::getInstance()
  423. ->callFunctionOnMessageThread (&destroyWindowCallback, (void*) hwnd);
  424. if (currentWindowIcon != 0)
  425. DestroyIcon (currentWindowIcon);
  426. if (dropTarget != 0)
  427. {
  428. dropTarget->Release();
  429. dropTarget = 0;
  430. }
  431. }
  432. //==============================================================================
  433. void* getNativeHandle() const
  434. {
  435. return (void*) hwnd;
  436. }
  437. void setVisible (bool shouldBeVisible)
  438. {
  439. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  440. if (shouldBeVisible)
  441. InvalidateRect (hwnd, 0, 0);
  442. else
  443. lastPaintTime = 0;
  444. }
  445. void setTitle (const String& title)
  446. {
  447. SetWindowText (hwnd, title);
  448. }
  449. void setPosition (int x, int y)
  450. {
  451. offsetWithinParent (x, y);
  452. SetWindowPos (hwnd, 0,
  453. x - windowBorder.getLeft(),
  454. y - windowBorder.getTop(),
  455. 0, 0,
  456. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  457. }
  458. void repaintNowIfTransparent()
  459. {
  460. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  461. handlePaintMessage();
  462. }
  463. void updateBorderSize()
  464. {
  465. WINDOWINFO info;
  466. info.cbSize = sizeof (info);
  467. if (GetWindowInfo (hwnd, &info))
  468. {
  469. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  470. info.rcClient.left - info.rcWindow.left,
  471. info.rcWindow.bottom - info.rcClient.bottom,
  472. info.rcWindow.right - info.rcClient.right);
  473. }
  474. }
  475. void setSize (int w, int h)
  476. {
  477. SetWindowPos (hwnd, 0, 0, 0,
  478. w + windowBorder.getLeftAndRight(),
  479. h + windowBorder.getTopAndBottom(),
  480. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  481. updateBorderSize();
  482. repaintNowIfTransparent();
  483. }
  484. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  485. {
  486. fullScreen = isNowFullScreen;
  487. offsetWithinParent (x, y);
  488. SetWindowPos (hwnd, 0,
  489. x - windowBorder.getLeft(),
  490. y - windowBorder.getTop(),
  491. w + windowBorder.getLeftAndRight(),
  492. h + windowBorder.getTopAndBottom(),
  493. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  494. updateBorderSize();
  495. repaintNowIfTransparent();
  496. }
  497. void getBounds (int& x, int& y, int& w, int& h) const
  498. {
  499. RECT r;
  500. GetWindowRect (hwnd, &r);
  501. x = r.left;
  502. y = r.top;
  503. w = r.right - x;
  504. h = r.bottom - y;
  505. HWND parentH = GetParent (hwnd);
  506. if (parentH != 0)
  507. {
  508. GetWindowRect (parentH, &r);
  509. x -= r.left;
  510. y -= r.top;
  511. }
  512. x += windowBorder.getLeft();
  513. y += windowBorder.getTop();
  514. w -= windowBorder.getLeftAndRight();
  515. h -= windowBorder.getTopAndBottom();
  516. }
  517. int getScreenX() const
  518. {
  519. RECT r;
  520. GetWindowRect (hwnd, &r);
  521. return r.left + windowBorder.getLeft();
  522. }
  523. int getScreenY() const
  524. {
  525. RECT r;
  526. GetWindowRect (hwnd, &r);
  527. return r.top + windowBorder.getTop();
  528. }
  529. void relativePositionToGlobal (int& x, int& y)
  530. {
  531. RECT r;
  532. GetWindowRect (hwnd, &r);
  533. x += r.left + windowBorder.getLeft();
  534. y += r.top + windowBorder.getTop();
  535. }
  536. void globalPositionToRelative (int& x, int& y)
  537. {
  538. RECT r;
  539. GetWindowRect (hwnd, &r);
  540. x -= r.left + windowBorder.getLeft();
  541. y -= r.top + windowBorder.getTop();
  542. }
  543. void setMinimised (bool shouldBeMinimised)
  544. {
  545. if (shouldBeMinimised != isMinimised())
  546. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  547. }
  548. bool isMinimised() const
  549. {
  550. WINDOWPLACEMENT wp;
  551. wp.length = sizeof (WINDOWPLACEMENT);
  552. GetWindowPlacement (hwnd, &wp);
  553. return wp.showCmd == SW_SHOWMINIMIZED;
  554. }
  555. void setFullScreen (bool shouldBeFullScreen)
  556. {
  557. setMinimised (false);
  558. if (fullScreen != shouldBeFullScreen)
  559. {
  560. fullScreen = shouldBeFullScreen;
  561. const ComponentDeletionWatcher deletionChecker (component);
  562. if (! fullScreen)
  563. {
  564. const Rectangle boundsCopy (lastNonFullscreenBounds);
  565. if (hasTitleBar())
  566. ShowWindow (hwnd, SW_SHOWNORMAL);
  567. if (! boundsCopy.isEmpty())
  568. {
  569. setBounds (boundsCopy.getX(),
  570. boundsCopy.getY(),
  571. boundsCopy.getWidth(),
  572. boundsCopy.getHeight(),
  573. false);
  574. }
  575. }
  576. else
  577. {
  578. if (hasTitleBar())
  579. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  580. else
  581. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  582. }
  583. if (! deletionChecker.hasBeenDeleted())
  584. handleMovedOrResized();
  585. }
  586. }
  587. bool isFullScreen() const
  588. {
  589. if (! hasTitleBar())
  590. return fullScreen;
  591. WINDOWPLACEMENT wp;
  592. wp.length = sizeof (wp);
  593. GetWindowPlacement (hwnd, &wp);
  594. return wp.showCmd == SW_SHOWMAXIMIZED;
  595. }
  596. bool contains (int x, int y, bool trueIfInAChildWindow) const
  597. {
  598. RECT r;
  599. GetWindowRect (hwnd, &r);
  600. POINT p;
  601. p.x = x + r.left + windowBorder.getLeft();
  602. p.y = y + r.top + windowBorder.getTop();
  603. HWND w = WindowFromPoint (p);
  604. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  605. }
  606. const BorderSize getFrameSize() const
  607. {
  608. return windowBorder;
  609. }
  610. bool setAlwaysOnTop (bool alwaysOnTop)
  611. {
  612. const bool oldDeactivate = shouldDeactivateTitleBar;
  613. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  614. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  615. 0, 0, 0, 0,
  616. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  617. shouldDeactivateTitleBar = oldDeactivate;
  618. if (shadower != 0)
  619. shadower->componentBroughtToFront (*component);
  620. return true;
  621. }
  622. void toFront (bool makeActive)
  623. {
  624. setMinimised (false);
  625. const bool oldDeactivate = shouldDeactivateTitleBar;
  626. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  627. MessageManager::getInstance()
  628. ->callFunctionOnMessageThread (makeActive ? &toFrontCallback1
  629. : &toFrontCallback2,
  630. (void*) hwnd);
  631. shouldDeactivateTitleBar = oldDeactivate;
  632. if (! makeActive)
  633. {
  634. // in this case a broughttofront call won't have occured, so do it now..
  635. handleBroughtToFront();
  636. }
  637. }
  638. void toBehind (ComponentPeer* other)
  639. {
  640. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  641. jassert (otherPeer != 0); // wrong type of window?
  642. if (otherPeer != 0)
  643. {
  644. setMinimised (false);
  645. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  646. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  647. }
  648. }
  649. bool isFocused() const
  650. {
  651. return MessageManager::getInstance()
  652. ->callFunctionOnMessageThread (&getFocusCallback, 0) == (void*) hwnd;
  653. }
  654. void grabFocus()
  655. {
  656. const bool oldDeactivate = shouldDeactivateTitleBar;
  657. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  658. MessageManager::getInstance()
  659. ->callFunctionOnMessageThread (&setFocusCallback, (void*) hwnd);
  660. shouldDeactivateTitleBar = oldDeactivate;
  661. }
  662. void textInputRequired (int /*x*/, int /*y*/)
  663. {
  664. if (! hasCreatedCaret)
  665. {
  666. hasCreatedCaret = true;
  667. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  668. }
  669. ShowCaret (hwnd);
  670. SetCaretPos (-1, -1);
  671. }
  672. void repaint (int x, int y, int w, int h)
  673. {
  674. const RECT r = { x, y, x + w, y + h };
  675. InvalidateRect (hwnd, &r, FALSE);
  676. }
  677. void performAnyPendingRepaintsNow()
  678. {
  679. MSG m;
  680. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  681. DispatchMessage (&m);
  682. }
  683. //==============================================================================
  684. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  685. {
  686. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  687. return (Win32ComponentPeer*) GetWindowLongPtr (h, 8);
  688. return 0;
  689. }
  690. //==============================================================================
  691. void setTaskBarIcon (const Image* const image)
  692. {
  693. if (image != 0)
  694. {
  695. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  696. if (taskBarIcon == 0)
  697. {
  698. taskBarIcon = new NOTIFYICONDATA();
  699. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  700. taskBarIcon->hWnd = (HWND) hwnd;
  701. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  702. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  703. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  704. taskBarIcon->hIcon = hicon;
  705. taskBarIcon->szTip[0] = 0;
  706. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  707. }
  708. else
  709. {
  710. HICON oldIcon = taskBarIcon->hIcon;
  711. taskBarIcon->hIcon = hicon;
  712. taskBarIcon->uFlags = NIF_ICON;
  713. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  714. DestroyIcon (oldIcon);
  715. }
  716. DestroyIcon (hicon);
  717. }
  718. else if (taskBarIcon != 0)
  719. {
  720. taskBarIcon->uFlags = 0;
  721. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  722. DestroyIcon (taskBarIcon->hIcon);
  723. deleteAndZero (taskBarIcon);
  724. }
  725. }
  726. void setTaskBarIconToolTip (const String& toolTip) const
  727. {
  728. if (taskBarIcon != 0)
  729. {
  730. taskBarIcon->uFlags = NIF_TIP;
  731. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  732. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  733. }
  734. }
  735. //==============================================================================
  736. juce_UseDebuggingNewOperator
  737. bool dontRepaint;
  738. private:
  739. HWND hwnd;
  740. DropShadower* shadower;
  741. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  742. BorderSize windowBorder;
  743. HICON currentWindowIcon;
  744. NOTIFYICONDATA* taskBarIcon;
  745. IDropTarget* dropTarget;
  746. //==============================================================================
  747. class TemporaryImage : public Timer
  748. {
  749. public:
  750. //==============================================================================
  751. TemporaryImage()
  752. : image (0)
  753. {
  754. }
  755. ~TemporaryImage()
  756. {
  757. delete image;
  758. }
  759. //==============================================================================
  760. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  761. {
  762. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  763. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  764. {
  765. delete image;
  766. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  767. }
  768. startTimer (3000);
  769. return image;
  770. }
  771. //==============================================================================
  772. void timerCallback()
  773. {
  774. stopTimer();
  775. deleteAndZero (image);
  776. }
  777. private:
  778. WindowsBitmapImage* image;
  779. TemporaryImage (const TemporaryImage&);
  780. const TemporaryImage& operator= (const TemporaryImage&);
  781. };
  782. TemporaryImage offscreenImageGenerator;
  783. //==============================================================================
  784. class WindowClassHolder : public DeletedAtShutdown
  785. {
  786. public:
  787. WindowClassHolder()
  788. : windowClassName ("JUCE_")
  789. {
  790. // this name has to be different for each app/dll instance because otherwise
  791. // poor old Win32 can get a bit confused (even despite it not being a process-global
  792. // window class).
  793. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  794. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  795. TCHAR moduleFile [1024];
  796. moduleFile[0] = 0;
  797. GetModuleFileName (moduleHandle, moduleFile, 1024);
  798. WORD iconNum = 0;
  799. WNDCLASSEX wcex;
  800. wcex.cbSize = sizeof (wcex);
  801. wcex.style = CS_OWNDC;
  802. wcex.lpfnWndProc = (WNDPROC) windowProc;
  803. wcex.lpszClassName = windowClassName;
  804. wcex.cbClsExtra = 0;
  805. wcex.cbWndExtra = 32;
  806. wcex.hInstance = moduleHandle;
  807. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  808. iconNum = 1;
  809. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  810. wcex.hCursor = 0;
  811. wcex.hbrBackground = 0;
  812. wcex.lpszMenuName = 0;
  813. RegisterClassEx (&wcex);
  814. }
  815. ~WindowClassHolder()
  816. {
  817. if (ComponentPeer::getNumPeers() == 0)
  818. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  819. clearSingletonInstance();
  820. }
  821. String windowClassName;
  822. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  823. };
  824. //==============================================================================
  825. static void* createWindowCallback (void* userData)
  826. {
  827. ((Win32ComponentPeer*) userData)->createWindow();
  828. return 0;
  829. }
  830. void createWindow()
  831. {
  832. DWORD exstyle = WS_EX_ACCEPTFILES;
  833. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  834. if (hasTitleBar())
  835. {
  836. type |= WS_OVERLAPPED;
  837. exstyle |= WS_EX_APPWINDOW;
  838. if ((styleFlags & windowHasCloseButton) != 0)
  839. {
  840. type |= WS_SYSMENU;
  841. }
  842. else
  843. {
  844. // annoyingly, windows won't let you have a min/max button without a close button
  845. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  846. }
  847. if ((styleFlags & windowIsResizable) != 0)
  848. type |= WS_THICKFRAME;
  849. }
  850. else
  851. {
  852. type |= WS_POPUP | WS_SYSMENU;
  853. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  854. exstyle |= WS_EX_TOOLWINDOW;
  855. else
  856. exstyle |= WS_EX_APPWINDOW;
  857. }
  858. if ((styleFlags & windowHasMinimiseButton) != 0)
  859. type |= WS_MINIMIZEBOX;
  860. if ((styleFlags & windowHasMaximiseButton) != 0)
  861. type |= WS_MAXIMIZEBOX;
  862. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  863. exstyle |= WS_EX_TRANSPARENT;
  864. if ((styleFlags & windowIsSemiTransparent) != 0
  865. && Desktop::canUseSemiTransparentWindows())
  866. exstyle |= WS_EX_LAYERED;
  867. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  868. if (hwnd != 0)
  869. {
  870. SetWindowLongPtr (hwnd, 0, 0);
  871. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  872. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  873. if (dropTarget == 0)
  874. dropTarget = new JuceDropTarget (this);
  875. RegisterDragDrop (hwnd, dropTarget);
  876. updateBorderSize();
  877. // Calling this function here is (for some reason) necessary to make Windows
  878. // correctly enable the menu items that we specify in the wm_initmenu message.
  879. GetSystemMenu (hwnd, false);
  880. }
  881. else
  882. {
  883. jassertfalse
  884. }
  885. }
  886. static void* destroyWindowCallback (void* handle)
  887. {
  888. RevokeDragDrop ((HWND) handle);
  889. DestroyWindow ((HWND) handle);
  890. return 0;
  891. }
  892. static void* toFrontCallback1 (void* h)
  893. {
  894. SetForegroundWindow ((HWND) h);
  895. return 0;
  896. }
  897. static void* toFrontCallback2 (void* h)
  898. {
  899. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  900. return 0;
  901. }
  902. static void* setFocusCallback (void* h)
  903. {
  904. SetFocus ((HWND) h);
  905. return 0;
  906. }
  907. static void* getFocusCallback (void*)
  908. {
  909. return (void*) GetFocus();
  910. }
  911. void offsetWithinParent (int& x, int& y) const
  912. {
  913. if (isTransparent())
  914. {
  915. HWND parentHwnd = GetParent (hwnd);
  916. if (parentHwnd != 0)
  917. {
  918. RECT parentRect;
  919. GetWindowRect (parentHwnd, &parentRect);
  920. x += parentRect.left;
  921. y += parentRect.top;
  922. }
  923. }
  924. }
  925. bool isTransparent() const
  926. {
  927. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  928. }
  929. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  930. void setIcon (const Image& newIcon)
  931. {
  932. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  933. if (hicon != 0)
  934. {
  935. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  936. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  937. if (currentWindowIcon != 0)
  938. DestroyIcon (currentWindowIcon);
  939. currentWindowIcon = hicon;
  940. }
  941. }
  942. //==============================================================================
  943. void handlePaintMessage()
  944. {
  945. #if DEBUG_REPAINT_TIMES
  946. const double paintStart = Time::getMillisecondCounterHiRes();
  947. #endif
  948. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  949. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  950. PAINTSTRUCT paintStruct;
  951. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  952. // message and become re-entrant, but that's OK
  953. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  954. // corrupt the image it's using to paint into, so do a check here.
  955. static bool reentrant = false;
  956. if (reentrant)
  957. {
  958. DeleteObject (rgn);
  959. EndPaint (hwnd, &paintStruct);
  960. return;
  961. }
  962. reentrant = true;
  963. // this is the rectangle to update..
  964. int x = paintStruct.rcPaint.left;
  965. int y = paintStruct.rcPaint.top;
  966. int w = paintStruct.rcPaint.right - x;
  967. int h = paintStruct.rcPaint.bottom - y;
  968. const bool transparent = isTransparent();
  969. if (transparent)
  970. {
  971. // it's not possible to have a transparent window with a title bar at the moment!
  972. jassert (! hasTitleBar());
  973. RECT r;
  974. GetWindowRect (hwnd, &r);
  975. x = y = 0;
  976. w = r.right - r.left;
  977. h = r.bottom - r.top;
  978. }
  979. if (w > 0 && h > 0)
  980. {
  981. clearMaskedRegion();
  982. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  983. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  984. RectangleList* const contextClip = context.getRawClipRegion();
  985. contextClip->clear();
  986. context.setOrigin (-x, -y);
  987. bool needToPaintAll = true;
  988. if (regionType == COMPLEXREGION && ! transparent)
  989. {
  990. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  991. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  992. DeleteObject (clipRgn);
  993. char rgnData [8192];
  994. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  995. if (res > 0 && res <= sizeof (rgnData))
  996. {
  997. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  998. if (hdr->iType == RDH_RECTANGLES
  999. && hdr->rcBound.right - hdr->rcBound.left >= w
  1000. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1001. {
  1002. needToPaintAll = false;
  1003. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1004. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  1005. while (--num >= 0)
  1006. {
  1007. // (need to move this one pixel to the left because of a win32 bug)
  1008. const int cx = jmax (x, rects->left - 1);
  1009. const int cy = rects->top;
  1010. const int cw = rects->right - cx;
  1011. const int ch = rects->bottom - rects->top;
  1012. if (cx + cw - x <= w && cy + ch - y <= h)
  1013. {
  1014. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  1015. }
  1016. else
  1017. {
  1018. needToPaintAll = true;
  1019. break;
  1020. }
  1021. ++rects;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. if (needToPaintAll)
  1027. {
  1028. contextClip->clear();
  1029. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  1030. }
  1031. if (transparent)
  1032. {
  1033. RectangleList::Iterator i (*contextClip);
  1034. while (i.next())
  1035. {
  1036. const Rectangle& r = *i.getRectangle();
  1037. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  1038. }
  1039. }
  1040. // if the component's not opaque, this won't draw properly unless the platform can support this
  1041. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  1042. updateCurrentModifiers();
  1043. handlePaint (context);
  1044. if (! dontRepaint)
  1045. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  1046. }
  1047. DeleteObject (rgn);
  1048. EndPaint (hwnd, &paintStruct);
  1049. reentrant = false;
  1050. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  1051. _fpreset(); // because some graphics cards can unmask FP exceptions
  1052. #endif
  1053. lastPaintTime = Time::getMillisecondCounter();
  1054. #if DEBUG_REPAINT_TIMES
  1055. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  1056. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  1057. #endif
  1058. }
  1059. //==============================================================================
  1060. void doMouseMove (const int x, const int y)
  1061. {
  1062. static uint32 lastMouseTime = 0;
  1063. // this can be set to throttle the mouse-messages to less than a
  1064. // certain number per second, as things can get unresponsive
  1065. // if each drag or move callback has to do a lot of work.
  1066. const int maxMouseMovesPerSecond = 60;
  1067. const int64 mouseEventTime = getMouseEventTime();
  1068. if (! isMouseOver)
  1069. {
  1070. isMouseOver = true;
  1071. TRACKMOUSEEVENT tme;
  1072. tme.cbSize = sizeof (tme);
  1073. tme.dwFlags = TME_LEAVE;
  1074. tme.hwndTrack = hwnd;
  1075. tme.dwHoverTime = 0;
  1076. if (! TrackMouseEvent (&tme))
  1077. {
  1078. jassertfalse;
  1079. }
  1080. updateKeyModifiers();
  1081. handleMouseEnter (x, y, mouseEventTime);
  1082. }
  1083. else if (! isDragging)
  1084. {
  1085. if (((unsigned int) x) < (unsigned int) component->getWidth()
  1086. && ((unsigned int) y) < (unsigned int) component->getHeight())
  1087. {
  1088. RECT r;
  1089. GetWindowRect (hwnd, &r);
  1090. POINT p;
  1091. p.x = x + r.left + windowBorder.getLeft();
  1092. p.y = y + r.top + windowBorder.getTop();
  1093. if (WindowFromPoint (p) == hwnd)
  1094. {
  1095. const uint32 now = Time::getMillisecondCounter();
  1096. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  1097. {
  1098. lastMouseTime = now;
  1099. handleMouseMove (x, y, mouseEventTime);
  1100. }
  1101. }
  1102. }
  1103. }
  1104. else
  1105. {
  1106. const uint32 now = Time::getMillisecondCounter();
  1107. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  1108. {
  1109. lastMouseTime = now;
  1110. handleMouseDrag (x, y, mouseEventTime);
  1111. }
  1112. }
  1113. }
  1114. void doMouseDown (const int x, const int y, const WPARAM wParam)
  1115. {
  1116. if (GetCapture() != hwnd)
  1117. SetCapture (hwnd);
  1118. doMouseMove (x, y);
  1119. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  1120. if ((wParam & MK_LBUTTON) != 0)
  1121. currentModifiers |= ModifierKeys::leftButtonModifier;
  1122. if ((wParam & MK_RBUTTON) != 0)
  1123. currentModifiers |= ModifierKeys::rightButtonModifier;
  1124. if ((wParam & MK_MBUTTON) != 0)
  1125. currentModifiers |= ModifierKeys::middleButtonModifier;
  1126. updateKeyModifiers();
  1127. isDragging = true;
  1128. handleMouseDown (x, y, getMouseEventTime());
  1129. }
  1130. void doMouseUp (const int x, const int y, const WPARAM wParam)
  1131. {
  1132. int numButtons = 0;
  1133. if ((wParam & MK_LBUTTON) != 0)
  1134. ++numButtons;
  1135. if ((wParam & MK_RBUTTON) != 0)
  1136. ++numButtons;
  1137. if ((wParam & MK_MBUTTON) != 0)
  1138. ++numButtons;
  1139. const int oldModifiers = currentModifiers;
  1140. // update the currentmodifiers only after the callback, so the callback
  1141. // knows which button was released.
  1142. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  1143. if ((wParam & MK_LBUTTON) != 0)
  1144. currentModifiers |= ModifierKeys::leftButtonModifier;
  1145. if ((wParam & MK_RBUTTON) != 0)
  1146. currentModifiers |= ModifierKeys::rightButtonModifier;
  1147. if ((wParam & MK_MBUTTON) != 0)
  1148. currentModifiers |= ModifierKeys::middleButtonModifier;
  1149. updateKeyModifiers();
  1150. isDragging = false;
  1151. // release the mouse capture if the user's not still got a button down
  1152. if (numButtons == 0 && hwnd == GetCapture())
  1153. ReleaseCapture();
  1154. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  1155. }
  1156. void doCaptureChanged()
  1157. {
  1158. if (isDragging)
  1159. {
  1160. RECT wr;
  1161. GetWindowRect (hwnd, &wr);
  1162. const DWORD mp = GetMessagePos();
  1163. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  1164. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  1165. getMouseEventTime());
  1166. }
  1167. }
  1168. void doMouseExit()
  1169. {
  1170. if (isMouseOver)
  1171. {
  1172. isMouseOver = false;
  1173. RECT wr;
  1174. GetWindowRect (hwnd, &wr);
  1175. const DWORD mp = GetMessagePos();
  1176. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  1177. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  1178. getMouseEventTime());
  1179. }
  1180. }
  1181. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  1182. {
  1183. updateKeyModifiers();
  1184. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  1185. handleMouseWheel (isVertical ? 0 : amount,
  1186. isVertical ? amount : 0,
  1187. getMouseEventTime());
  1188. }
  1189. //==============================================================================
  1190. void sendModifierKeyChangeIfNeeded()
  1191. {
  1192. if (modifiersAtLastCallback != currentModifiers)
  1193. {
  1194. modifiersAtLastCallback = currentModifiers;
  1195. handleModifierKeysChange();
  1196. }
  1197. }
  1198. bool doKeyUp (const WPARAM key)
  1199. {
  1200. updateKeyModifiers();
  1201. switch (key)
  1202. {
  1203. case VK_SHIFT:
  1204. case VK_CONTROL:
  1205. case VK_MENU:
  1206. case VK_CAPITAL:
  1207. case VK_LWIN:
  1208. case VK_RWIN:
  1209. case VK_APPS:
  1210. case VK_NUMLOCK:
  1211. case VK_SCROLL:
  1212. case VK_LSHIFT:
  1213. case VK_RSHIFT:
  1214. case VK_LCONTROL:
  1215. case VK_LMENU:
  1216. case VK_RCONTROL:
  1217. case VK_RMENU:
  1218. sendModifierKeyChangeIfNeeded();
  1219. }
  1220. return handleKeyUpOrDown();
  1221. }
  1222. bool doKeyDown (const WPARAM key)
  1223. {
  1224. updateKeyModifiers();
  1225. bool used = false;
  1226. switch (key)
  1227. {
  1228. case VK_SHIFT:
  1229. case VK_LSHIFT:
  1230. case VK_RSHIFT:
  1231. case VK_CONTROL:
  1232. case VK_LCONTROL:
  1233. case VK_RCONTROL:
  1234. case VK_MENU:
  1235. case VK_LMENU:
  1236. case VK_RMENU:
  1237. case VK_LWIN:
  1238. case VK_RWIN:
  1239. case VK_CAPITAL:
  1240. case VK_NUMLOCK:
  1241. case VK_SCROLL:
  1242. case VK_APPS:
  1243. sendModifierKeyChangeIfNeeded();
  1244. break;
  1245. case VK_LEFT:
  1246. case VK_RIGHT:
  1247. case VK_UP:
  1248. case VK_DOWN:
  1249. case VK_PRIOR:
  1250. case VK_NEXT:
  1251. case VK_HOME:
  1252. case VK_END:
  1253. case VK_DELETE:
  1254. case VK_INSERT:
  1255. case VK_F1:
  1256. case VK_F2:
  1257. case VK_F3:
  1258. case VK_F4:
  1259. case VK_F5:
  1260. case VK_F6:
  1261. case VK_F7:
  1262. case VK_F8:
  1263. case VK_F9:
  1264. case VK_F10:
  1265. case VK_F11:
  1266. case VK_F12:
  1267. case VK_F13:
  1268. case VK_F14:
  1269. case VK_F15:
  1270. case VK_F16:
  1271. used = handleKeyUpOrDown();
  1272. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  1273. break;
  1274. case VK_ADD:
  1275. case VK_SUBTRACT:
  1276. case VK_MULTIPLY:
  1277. case VK_DIVIDE:
  1278. case VK_SEPARATOR:
  1279. case VK_DECIMAL:
  1280. used = handleKeyUpOrDown();
  1281. break;
  1282. default:
  1283. used = handleKeyUpOrDown();
  1284. {
  1285. MSG msg;
  1286. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  1287. {
  1288. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  1289. // manually generate the key-press event that matches this key-down.
  1290. const UINT keyChar = MapVirtualKey (key, 2);
  1291. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  1292. }
  1293. }
  1294. break;
  1295. }
  1296. return used;
  1297. }
  1298. bool doKeyChar (int key, const LPARAM flags)
  1299. {
  1300. updateKeyModifiers();
  1301. juce_wchar textChar = (juce_wchar) key;
  1302. const int virtualScanCode = (flags >> 16) & 0xff;
  1303. if (key >= '0' && key <= '9')
  1304. {
  1305. switch (virtualScanCode) // check for a numeric keypad scan-code
  1306. {
  1307. case 0x52:
  1308. case 0x4f:
  1309. case 0x50:
  1310. case 0x51:
  1311. case 0x4b:
  1312. case 0x4c:
  1313. case 0x4d:
  1314. case 0x47:
  1315. case 0x48:
  1316. case 0x49:
  1317. key = (key - '0') + KeyPress::numberPad0;
  1318. break;
  1319. default:
  1320. break;
  1321. }
  1322. }
  1323. else
  1324. {
  1325. // convert the scan code to an unmodified character code..
  1326. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  1327. UINT keyChar = MapVirtualKey (virtualKey, 2);
  1328. keyChar = LOWORD (keyChar);
  1329. if (keyChar != 0)
  1330. key = (int) keyChar;
  1331. // avoid sending junk text characters for some control-key combinations
  1332. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  1333. textChar = 0;
  1334. }
  1335. return handleKeyPress (key, textChar);
  1336. }
  1337. bool doAppCommand (const LPARAM lParam)
  1338. {
  1339. int key = 0;
  1340. switch (GET_APPCOMMAND_LPARAM (lParam))
  1341. {
  1342. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  1343. key = KeyPress::playKey;
  1344. break;
  1345. case APPCOMMAND_MEDIA_STOP:
  1346. key = KeyPress::stopKey;
  1347. break;
  1348. case APPCOMMAND_MEDIA_NEXTTRACK:
  1349. key = KeyPress::fastForwardKey;
  1350. break;
  1351. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  1352. key = KeyPress::rewindKey;
  1353. break;
  1354. }
  1355. if (key != 0)
  1356. {
  1357. updateKeyModifiers();
  1358. if (hwnd == GetActiveWindow())
  1359. {
  1360. handleKeyPress (key, 0);
  1361. return true;
  1362. }
  1363. }
  1364. return false;
  1365. }
  1366. //==============================================================================
  1367. class JuceDropTarget : public IDropTarget
  1368. {
  1369. public:
  1370. JuceDropTarget (Win32ComponentPeer* const owner_)
  1371. : owner (owner_),
  1372. refCount (1)
  1373. {
  1374. }
  1375. virtual ~JuceDropTarget()
  1376. {
  1377. jassert (refCount == 0);
  1378. }
  1379. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  1380. {
  1381. if (id == IID_IUnknown || id == IID_IDropTarget)
  1382. {
  1383. AddRef();
  1384. *result = this;
  1385. return S_OK;
  1386. }
  1387. *result = 0;
  1388. return E_NOINTERFACE;
  1389. }
  1390. ULONG __stdcall AddRef() { return ++refCount; }
  1391. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  1392. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1393. {
  1394. updateFileList (pDataObject);
  1395. int x = mousePos.x, y = mousePos.y;
  1396. owner->globalPositionToRelative (x, y);
  1397. owner->handleFileDragMove (files, x, y);
  1398. *pdwEffect = DROPEFFECT_COPY;
  1399. return S_OK;
  1400. }
  1401. HRESULT __stdcall DragLeave()
  1402. {
  1403. owner->handleFileDragExit (files);
  1404. return S_OK;
  1405. }
  1406. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1407. {
  1408. int x = mousePos.x, y = mousePos.y;
  1409. owner->globalPositionToRelative (x, y);
  1410. owner->handleFileDragMove (files, x, y);
  1411. *pdwEffect = DROPEFFECT_COPY;
  1412. return S_OK;
  1413. }
  1414. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1415. {
  1416. updateFileList (pDataObject);
  1417. int x = mousePos.x, y = mousePos.y;
  1418. owner->globalPositionToRelative (x, y);
  1419. owner->handleFileDragDrop (files, x, y);
  1420. *pdwEffect = DROPEFFECT_COPY;
  1421. return S_OK;
  1422. }
  1423. private:
  1424. Win32ComponentPeer* const owner;
  1425. int refCount;
  1426. StringArray files;
  1427. void updateFileList (IDataObject* const pDataObject)
  1428. {
  1429. files.clear();
  1430. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1431. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  1432. if (pDataObject->GetData (&format, &medium) == S_OK)
  1433. {
  1434. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  1435. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  1436. unsigned int i = 0;
  1437. if (pDropFiles->fWide)
  1438. {
  1439. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  1440. for (;;)
  1441. {
  1442. unsigned int len = 0;
  1443. while (i + len < totalLen && fname [i + len] != 0)
  1444. ++len;
  1445. if (len == 0)
  1446. break;
  1447. files.add (String (fname + i, len));
  1448. i += len + 1;
  1449. }
  1450. }
  1451. else
  1452. {
  1453. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  1454. for (;;)
  1455. {
  1456. unsigned int len = 0;
  1457. while (i + len < totalLen && fname [i + len] != 0)
  1458. ++len;
  1459. if (len == 0)
  1460. break;
  1461. files.add (String (fname + i, len));
  1462. i += len + 1;
  1463. }
  1464. }
  1465. GlobalUnlock (medium.hGlobal);
  1466. }
  1467. }
  1468. JuceDropTarget (const JuceDropTarget&);
  1469. const JuceDropTarget& operator= (const JuceDropTarget&);
  1470. };
  1471. void doSettingChange()
  1472. {
  1473. Desktop::getInstance().refreshMonitorSizes();
  1474. if (fullScreen && ! isMinimised())
  1475. {
  1476. const Rectangle r (component->getParentMonitorArea());
  1477. SetWindowPos (hwnd, 0,
  1478. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  1479. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  1480. }
  1481. }
  1482. //==============================================================================
  1483. public:
  1484. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1485. {
  1486. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  1487. if (peer != 0)
  1488. return peer->peerWindowProc (h, message, wParam, lParam);
  1489. return DefWindowProc (h, message, wParam, lParam);
  1490. }
  1491. private:
  1492. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1493. {
  1494. {
  1495. const MessageManagerLock messLock;
  1496. if (isValidPeer (this))
  1497. {
  1498. switch (message)
  1499. {
  1500. case WM_NCHITTEST:
  1501. if (hasTitleBar())
  1502. break;
  1503. return HTCLIENT;
  1504. //==============================================================================
  1505. case WM_PAINT:
  1506. handlePaintMessage();
  1507. return 0;
  1508. case WM_NCPAINT:
  1509. if (wParam != 1)
  1510. handlePaintMessage();
  1511. if (hasTitleBar())
  1512. break;
  1513. return 0;
  1514. case WM_ERASEBKGND:
  1515. case WM_NCCALCSIZE:
  1516. if (hasTitleBar())
  1517. break;
  1518. return 1;
  1519. //==============================================================================
  1520. case WM_MOUSEMOVE:
  1521. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  1522. return 0;
  1523. case WM_MOUSELEAVE:
  1524. doMouseExit();
  1525. return 0;
  1526. case WM_LBUTTONDOWN:
  1527. case WM_MBUTTONDOWN:
  1528. case WM_RBUTTONDOWN:
  1529. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1530. return 0;
  1531. case WM_LBUTTONUP:
  1532. case WM_MBUTTONUP:
  1533. case WM_RBUTTONUP:
  1534. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1535. return 0;
  1536. case WM_CAPTURECHANGED:
  1537. doCaptureChanged();
  1538. return 0;
  1539. case WM_NCMOUSEMOVE:
  1540. if (hasTitleBar())
  1541. break;
  1542. return 0;
  1543. case 0x020A: /* WM_MOUSEWHEEL */
  1544. doMouseWheel (wParam, true);
  1545. return 0;
  1546. case 0x020E: /* WM_MOUSEHWHEEL */
  1547. doMouseWheel (wParam, false);
  1548. return 0;
  1549. //==============================================================================
  1550. case WM_WINDOWPOSCHANGING:
  1551. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  1552. {
  1553. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  1554. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  1555. {
  1556. if (constrainer != 0)
  1557. {
  1558. const Rectangle current (component->getX() - windowBorder.getLeft(),
  1559. component->getY() - windowBorder.getTop(),
  1560. component->getWidth() + windowBorder.getLeftAndRight(),
  1561. component->getHeight() + windowBorder.getTopAndBottom());
  1562. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  1563. current,
  1564. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  1565. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  1566. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  1567. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  1568. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  1569. }
  1570. }
  1571. }
  1572. return 0;
  1573. case WM_WINDOWPOSCHANGED:
  1574. handleMovedOrResized();
  1575. if (dontRepaint)
  1576. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  1577. else
  1578. return 0;
  1579. //==============================================================================
  1580. case WM_KEYDOWN:
  1581. case WM_SYSKEYDOWN:
  1582. if (doKeyDown (wParam))
  1583. return 0;
  1584. break;
  1585. case WM_KEYUP:
  1586. case WM_SYSKEYUP:
  1587. if (doKeyUp (wParam))
  1588. return 0;
  1589. break;
  1590. case WM_CHAR:
  1591. if (doKeyChar ((int) wParam, lParam))
  1592. return 0;
  1593. break;
  1594. case WM_APPCOMMAND:
  1595. if (doAppCommand (lParam))
  1596. return TRUE;
  1597. break;
  1598. //==============================================================================
  1599. case WM_SETFOCUS:
  1600. updateKeyModifiers();
  1601. handleFocusGain();
  1602. break;
  1603. case WM_KILLFOCUS:
  1604. if (hasCreatedCaret)
  1605. {
  1606. hasCreatedCaret = false;
  1607. DestroyCaret();
  1608. }
  1609. handleFocusLoss();
  1610. break;
  1611. case WM_ACTIVATEAPP:
  1612. // Windows does weird things to process priority when you swap apps,
  1613. // so this forces an update when the app is brought to the front
  1614. if (wParam != FALSE)
  1615. juce_repeatLastProcessPriority();
  1616. juce_CheckCurrentlyFocusedTopLevelWindow();
  1617. modifiersAtLastCallback = -1;
  1618. return 0;
  1619. case WM_ACTIVATE:
  1620. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  1621. {
  1622. modifiersAtLastCallback = -1;
  1623. updateKeyModifiers();
  1624. if (isMinimised())
  1625. {
  1626. component->repaint();
  1627. handleMovedOrResized();
  1628. if (! isValidMessageListener())
  1629. return 0;
  1630. }
  1631. if (LOWORD (wParam) == WA_CLICKACTIVE
  1632. && component->isCurrentlyBlockedByAnotherModalComponent())
  1633. {
  1634. int mx, my;
  1635. component->getMouseXYRelative (mx, my);
  1636. Component* const underMouse = component->getComponentAt (mx, my);
  1637. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  1638. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1639. return 0;
  1640. }
  1641. handleBroughtToFront();
  1642. return 0;
  1643. }
  1644. break;
  1645. case WM_NCACTIVATE:
  1646. // while a temporary window is being shown, prevent Windows from deactivating the
  1647. // title bars of our main windows.
  1648. if (wParam == 0 && ! shouldDeactivateTitleBar)
  1649. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  1650. break;
  1651. case WM_MOUSEACTIVATE:
  1652. if (! component->getMouseClickGrabsKeyboardFocus())
  1653. return MA_NOACTIVATE;
  1654. break;
  1655. case WM_SHOWWINDOW:
  1656. if (wParam != 0)
  1657. handleBroughtToFront();
  1658. break;
  1659. case WM_CLOSE:
  1660. handleUserClosingWindow();
  1661. return 0;
  1662. case WM_QUIT:
  1663. JUCEApplication::quit();
  1664. return 0;
  1665. //==============================================================================
  1666. case WM_TRAYNOTIFY:
  1667. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1668. {
  1669. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  1670. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1671. {
  1672. Component* const current = Component::getCurrentlyModalComponent();
  1673. if (current != 0)
  1674. current->inputAttemptWhenModal();
  1675. }
  1676. }
  1677. else
  1678. {
  1679. const int oldModifiers = currentModifiers;
  1680. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  1681. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  1682. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  1683. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  1684. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  1685. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  1686. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  1687. {
  1688. SetFocus (hwnd);
  1689. SetForegroundWindow (hwnd);
  1690. component->mouseDown (e);
  1691. }
  1692. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  1693. {
  1694. e.mods = ModifierKeys (oldModifiers);
  1695. component->mouseUp (e);
  1696. }
  1697. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1698. {
  1699. e.mods = ModifierKeys (oldModifiers);
  1700. component->mouseDoubleClick (e);
  1701. }
  1702. else if (lParam == WM_MOUSEMOVE)
  1703. {
  1704. component->mouseMove (e);
  1705. }
  1706. }
  1707. break;
  1708. //==============================================================================
  1709. case WM_SYNCPAINT:
  1710. return 0;
  1711. case WM_PALETTECHANGED:
  1712. InvalidateRect (h, 0, 0);
  1713. break;
  1714. case WM_DISPLAYCHANGE:
  1715. InvalidateRect (h, 0, 0);
  1716. createPaletteIfNeeded = true;
  1717. // intentional fall-through...
  1718. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  1719. doSettingChange();
  1720. break;
  1721. case WM_INITMENU:
  1722. if (! hasTitleBar())
  1723. {
  1724. if (isFullScreen())
  1725. {
  1726. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  1727. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  1728. }
  1729. else if (! isMinimised())
  1730. {
  1731. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  1732. }
  1733. }
  1734. break;
  1735. case WM_SYSCOMMAND:
  1736. switch (wParam & 0xfff0)
  1737. {
  1738. case SC_CLOSE:
  1739. if (hasTitleBar())
  1740. {
  1741. PostMessage (h, WM_CLOSE, 0, 0);
  1742. return 0;
  1743. }
  1744. break;
  1745. case SC_KEYMENU:
  1746. if (hasTitleBar() && h == GetCapture())
  1747. ReleaseCapture();
  1748. break;
  1749. case SC_MAXIMIZE:
  1750. setFullScreen (true);
  1751. return 0;
  1752. case SC_MINIMIZE:
  1753. if (! hasTitleBar())
  1754. {
  1755. setMinimised (true);
  1756. return 0;
  1757. }
  1758. break;
  1759. case SC_RESTORE:
  1760. if (hasTitleBar())
  1761. {
  1762. if (isFullScreen())
  1763. {
  1764. setFullScreen (false);
  1765. return 0;
  1766. }
  1767. }
  1768. else
  1769. {
  1770. if (isMinimised())
  1771. setMinimised (false);
  1772. else if (isFullScreen())
  1773. setFullScreen (false);
  1774. return 0;
  1775. }
  1776. break;
  1777. case SC_MONITORPOWER:
  1778. case SC_SCREENSAVE:
  1779. if (! screenSaverAllowed)
  1780. return 0;
  1781. break;
  1782. }
  1783. break;
  1784. case WM_NCLBUTTONDOWN:
  1785. case WM_NCRBUTTONDOWN:
  1786. case WM_NCMBUTTONDOWN:
  1787. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1788. {
  1789. Component* const current = Component::getCurrentlyModalComponent();
  1790. if (current != 0)
  1791. current->inputAttemptWhenModal();
  1792. }
  1793. break;
  1794. //case WM_IME_STARTCOMPOSITION;
  1795. // return 0;
  1796. case WM_GETDLGCODE:
  1797. return DLGC_WANTALLKEYS;
  1798. default:
  1799. break;
  1800. }
  1801. }
  1802. }
  1803. // (the message manager lock exits before calling this, to avoid deadlocks if
  1804. // this calls into non-juce windows)
  1805. return DefWindowProc (h, message, wParam, lParam);
  1806. }
  1807. Win32ComponentPeer (const Win32ComponentPeer&);
  1808. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  1809. };
  1810. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  1811. {
  1812. return new Win32ComponentPeer (this, styleFlags);
  1813. }
  1814. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  1815. //==============================================================================
  1816. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  1817. {
  1818. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1819. if (wp != 0)
  1820. wp->setTaskBarIcon (&newImage);
  1821. }
  1822. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  1823. {
  1824. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1825. if (wp != 0)
  1826. wp->setTaskBarIconToolTip (tooltip);
  1827. }
  1828. //==============================================================================
  1829. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  1830. {
  1831. DWORD val = GetWindowLong (h, styleType);
  1832. if (bitIsSet)
  1833. val |= feature;
  1834. else
  1835. val &= ~feature;
  1836. SetWindowLongPtr (h, styleType, val);
  1837. SetWindowPos (h, 0, 0, 0, 0, 0,
  1838. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  1839. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  1840. }
  1841. //==============================================================================
  1842. bool Process::isForegroundProcess() throw()
  1843. {
  1844. HWND fg = GetForegroundWindow();
  1845. if (fg == 0)
  1846. return true;
  1847. DWORD processId = 0;
  1848. GetWindowThreadProcessId (fg, &processId);
  1849. return processId == GetCurrentProcessId();
  1850. }
  1851. //==============================================================================
  1852. void Desktop::getMousePosition (int& x, int& y) throw()
  1853. {
  1854. POINT mousePos;
  1855. GetCursorPos (&mousePos);
  1856. x = mousePos.x;
  1857. y = mousePos.y;
  1858. }
  1859. void Desktop::setMousePosition (int x, int y) throw()
  1860. {
  1861. SetCursorPos (x, y);
  1862. }
  1863. //==============================================================================
  1864. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1865. {
  1866. screenSaverAllowed = isEnabled;
  1867. }
  1868. bool Desktop::isScreenSaverEnabled() throw()
  1869. {
  1870. return screenSaverAllowed;
  1871. }
  1872. //==============================================================================
  1873. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  1874. {
  1875. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  1876. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  1877. return TRUE;
  1878. }
  1879. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1880. {
  1881. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  1882. // make sure the first in the list is the main monitor
  1883. for (int i = 1; i < monitorCoords.size(); ++i)
  1884. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  1885. monitorCoords.swap (i, 0);
  1886. if (monitorCoords.size() == 0)
  1887. {
  1888. RECT r;
  1889. GetWindowRect (GetDesktopWindow(), &r);
  1890. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  1891. }
  1892. if (clipToWorkArea)
  1893. {
  1894. // clip the main monitor to the active non-taskbar area
  1895. RECT r;
  1896. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  1897. Rectangle& screen = monitorCoords.getReference (0);
  1898. screen.setPosition (jmax (screen.getX(), r.left),
  1899. jmax (screen.getY(), r.top));
  1900. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  1901. jmin (screen.getBottom(), r.bottom) - screen.getY());
  1902. }
  1903. }
  1904. //==============================================================================
  1905. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  1906. {
  1907. Image* im = 0;
  1908. if (bitmap != 0)
  1909. {
  1910. BITMAP bm;
  1911. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  1912. && bm.bmWidth > 0 && bm.bmHeight > 0)
  1913. {
  1914. HDC tempDC = GetDC (0);
  1915. HDC dc = CreateCompatibleDC (tempDC);
  1916. ReleaseDC (0, tempDC);
  1917. SelectObject (dc, bitmap);
  1918. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  1919. for (int y = bm.bmHeight; --y >= 0;)
  1920. {
  1921. for (int x = bm.bmWidth; --x >= 0;)
  1922. {
  1923. COLORREF col = GetPixel (dc, x, y);
  1924. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  1925. (uint8) GetGValue (col),
  1926. (uint8) GetBValue (col)));
  1927. }
  1928. }
  1929. DeleteDC (dc);
  1930. }
  1931. }
  1932. return im;
  1933. }
  1934. static Image* createImageFromHICON (HICON icon) throw()
  1935. {
  1936. ICONINFO info;
  1937. if (GetIconInfo (icon, &info))
  1938. {
  1939. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  1940. if (mask == 0)
  1941. return 0;
  1942. Image* const image = createImageFromHBITMAP (info.hbmColor);
  1943. if (image == 0)
  1944. return mask;
  1945. for (int y = image->getHeight(); --y >= 0;)
  1946. {
  1947. for (int x = image->getWidth(); --x >= 0;)
  1948. {
  1949. const float brightness = mask->getPixelAt (x, y).getBrightness();
  1950. if (brightness > 0.0f)
  1951. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  1952. }
  1953. }
  1954. delete mask;
  1955. return image;
  1956. }
  1957. return 0;
  1958. }
  1959. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  1960. {
  1961. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  1962. ICONINFO info;
  1963. info.fIcon = isIcon;
  1964. info.xHotspot = hotspotX;
  1965. info.yHotspot = hotspotY;
  1966. info.hbmMask = mask;
  1967. HICON hi = 0;
  1968. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  1969. {
  1970. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  1971. Graphics g (bitmap);
  1972. g.drawImageAt (&image, 0, 0);
  1973. info.hbmColor = bitmap.hBitmap;
  1974. hi = CreateIconIndirect (&info);
  1975. }
  1976. else
  1977. {
  1978. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  1979. HDC colDC = CreateCompatibleDC (GetDC (0));
  1980. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  1981. SelectObject (colDC, colour);
  1982. SelectObject (alphaDC, mask);
  1983. for (int y = image.getHeight(); --y >= 0;)
  1984. {
  1985. for (int x = image.getWidth(); --x >= 0;)
  1986. {
  1987. const Colour c (image.getPixelAt (x, y));
  1988. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  1989. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  1990. }
  1991. }
  1992. DeleteDC (colDC);
  1993. DeleteDC (alphaDC);
  1994. info.hbmColor = colour;
  1995. hi = CreateIconIndirect (&info);
  1996. DeleteObject (colour);
  1997. }
  1998. DeleteObject (mask);
  1999. return hi;
  2000. }
  2001. Image* juce_createIconForFile (const File& file)
  2002. {
  2003. Image* image = 0;
  2004. TCHAR filename [1024];
  2005. file.getFullPathName().copyToBuffer (filename, 1023);
  2006. WORD iconNum = 0;
  2007. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  2008. filename, &iconNum);
  2009. if (icon != 0)
  2010. {
  2011. image = createImageFromHICON (icon);
  2012. DestroyIcon (icon);
  2013. }
  2014. return image;
  2015. }
  2016. //==============================================================================
  2017. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  2018. {
  2019. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  2020. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  2021. const Image* im = &image;
  2022. Image* newIm = 0;
  2023. if (image.getWidth() > maxW || image.getHeight() > maxH)
  2024. {
  2025. im = newIm = image.createCopy (maxW, maxH);
  2026. hotspotX = (hotspotX * maxW) / image.getWidth();
  2027. hotspotY = (hotspotY * maxH) / image.getHeight();
  2028. }
  2029. void* cursorH = 0;
  2030. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  2031. if (os == SystemStats::WinXP)
  2032. {
  2033. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  2034. }
  2035. else
  2036. {
  2037. const int stride = (maxW + 7) >> 3;
  2038. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  2039. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  2040. int index = 0;
  2041. for (int y = 0; y < maxH; ++y)
  2042. {
  2043. for (int x = 0; x < maxW; ++x)
  2044. {
  2045. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  2046. const Colour pixelColour (im->getPixelAt (x, y));
  2047. if (pixelColour.getAlpha() < 127)
  2048. andPlane [index + (x >> 3)] |= bit;
  2049. else if (pixelColour.getBrightness() >= 0.5f)
  2050. xorPlane [index + (x >> 3)] |= bit;
  2051. }
  2052. index += stride;
  2053. }
  2054. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  2055. juce_free (andPlane);
  2056. juce_free (xorPlane);
  2057. }
  2058. delete newIm;
  2059. return cursorH;
  2060. }
  2061. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2062. {
  2063. if (cursorHandle != 0 && ! isStandard)
  2064. DestroyCursor ((HCURSOR) cursorHandle);
  2065. }
  2066. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  2067. {
  2068. LPCTSTR cursorName = IDC_ARROW;
  2069. switch (type)
  2070. {
  2071. case MouseCursor::NormalCursor:
  2072. cursorName = IDC_ARROW;
  2073. break;
  2074. case MouseCursor::NoCursor:
  2075. return 0;
  2076. case MouseCursor::DraggingHandCursor:
  2077. {
  2078. static void* dragHandCursor = 0;
  2079. if (dragHandCursor == 0)
  2080. {
  2081. static const unsigned char dragHandData[] =
  2082. { 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,
  2083. 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,
  2084. 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 };
  2085. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  2086. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  2087. delete image;
  2088. }
  2089. return dragHandCursor;
  2090. }
  2091. case MouseCursor::WaitCursor:
  2092. cursorName = IDC_WAIT;
  2093. break;
  2094. case MouseCursor::IBeamCursor:
  2095. cursorName = IDC_IBEAM;
  2096. break;
  2097. case MouseCursor::PointingHandCursor:
  2098. cursorName = MAKEINTRESOURCE(32649);
  2099. break;
  2100. case MouseCursor::LeftRightResizeCursor:
  2101. case MouseCursor::LeftEdgeResizeCursor:
  2102. case MouseCursor::RightEdgeResizeCursor:
  2103. cursorName = IDC_SIZEWE;
  2104. break;
  2105. case MouseCursor::UpDownResizeCursor:
  2106. case MouseCursor::TopEdgeResizeCursor:
  2107. case MouseCursor::BottomEdgeResizeCursor:
  2108. cursorName = IDC_SIZENS;
  2109. break;
  2110. case MouseCursor::TopLeftCornerResizeCursor:
  2111. case MouseCursor::BottomRightCornerResizeCursor:
  2112. cursorName = IDC_SIZENWSE;
  2113. break;
  2114. case MouseCursor::TopRightCornerResizeCursor:
  2115. case MouseCursor::BottomLeftCornerResizeCursor:
  2116. cursorName = IDC_SIZENESW;
  2117. break;
  2118. case MouseCursor::UpDownLeftRightResizeCursor:
  2119. cursorName = IDC_SIZEALL;
  2120. break;
  2121. case MouseCursor::CrosshairCursor:
  2122. cursorName = IDC_CROSS;
  2123. break;
  2124. case MouseCursor::CopyingCursor:
  2125. // can't seem to find one of these in the win32 list..
  2126. break;
  2127. }
  2128. HCURSOR cursorH = LoadCursor (0, cursorName);
  2129. if (cursorH == 0)
  2130. cursorH = LoadCursor (0, IDC_ARROW);
  2131. return (void*) cursorH;
  2132. }
  2133. //==============================================================================
  2134. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2135. {
  2136. SetCursor ((HCURSOR) getHandle());
  2137. }
  2138. void MouseCursor::showInAllWindows() const throw()
  2139. {
  2140. showInWindow (0);
  2141. }
  2142. //==============================================================================
  2143. //==============================================================================
  2144. class JuceDropSource : public IDropSource
  2145. {
  2146. int refCount;
  2147. public:
  2148. JuceDropSource()
  2149. : refCount (1)
  2150. {
  2151. }
  2152. virtual ~JuceDropSource()
  2153. {
  2154. jassert (refCount == 0);
  2155. }
  2156. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2157. {
  2158. if (id == IID_IUnknown || id == IID_IDropSource)
  2159. {
  2160. AddRef();
  2161. *result = this;
  2162. return S_OK;
  2163. }
  2164. *result = 0;
  2165. return E_NOINTERFACE;
  2166. }
  2167. ULONG __stdcall AddRef() { return ++refCount; }
  2168. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2169. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  2170. {
  2171. if (escapePressed)
  2172. return DRAGDROP_S_CANCEL;
  2173. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  2174. return DRAGDROP_S_DROP;
  2175. return S_OK;
  2176. }
  2177. HRESULT __stdcall GiveFeedback (DWORD)
  2178. {
  2179. return DRAGDROP_S_USEDEFAULTCURSORS;
  2180. }
  2181. };
  2182. class JuceEnumFormatEtc : public IEnumFORMATETC
  2183. {
  2184. public:
  2185. JuceEnumFormatEtc (const FORMATETC* const format_)
  2186. : refCount (1),
  2187. format (format_),
  2188. index (0)
  2189. {
  2190. }
  2191. virtual ~JuceEnumFormatEtc()
  2192. {
  2193. jassert (refCount == 0);
  2194. }
  2195. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2196. {
  2197. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  2198. {
  2199. AddRef();
  2200. *result = this;
  2201. return S_OK;
  2202. }
  2203. *result = 0;
  2204. return E_NOINTERFACE;
  2205. }
  2206. ULONG __stdcall AddRef() { return ++refCount; }
  2207. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2208. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  2209. {
  2210. if (result == 0)
  2211. return E_POINTER;
  2212. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  2213. newOne->index = index;
  2214. *result = newOne;
  2215. return S_OK;
  2216. }
  2217. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  2218. {
  2219. if (pceltFetched != 0)
  2220. *pceltFetched = 0;
  2221. else if (celt != 1)
  2222. return S_FALSE;
  2223. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  2224. {
  2225. copyFormatEtc (lpFormatEtc [0], *format);
  2226. ++index;
  2227. if (pceltFetched != 0)
  2228. *pceltFetched = 1;
  2229. return S_OK;
  2230. }
  2231. return S_FALSE;
  2232. }
  2233. HRESULT __stdcall Skip (ULONG celt)
  2234. {
  2235. if (index + (int) celt >= 1)
  2236. return S_FALSE;
  2237. index += celt;
  2238. return S_OK;
  2239. }
  2240. HRESULT __stdcall Reset()
  2241. {
  2242. index = 0;
  2243. return S_OK;
  2244. }
  2245. private:
  2246. int refCount;
  2247. const FORMATETC* const format;
  2248. int index;
  2249. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  2250. {
  2251. dest = source;
  2252. if (source.ptd != 0)
  2253. {
  2254. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  2255. *(dest.ptd) = *(source.ptd);
  2256. }
  2257. }
  2258. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  2259. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  2260. };
  2261. class JuceDataObject : public IDataObject
  2262. {
  2263. JuceDropSource* const dropSource;
  2264. const FORMATETC* const format;
  2265. const STGMEDIUM* const medium;
  2266. int refCount;
  2267. JuceDataObject (const JuceDataObject&);
  2268. const JuceDataObject& operator= (const JuceDataObject&);
  2269. public:
  2270. JuceDataObject (JuceDropSource* const dropSource_,
  2271. const FORMATETC* const format_,
  2272. const STGMEDIUM* const medium_)
  2273. : dropSource (dropSource_),
  2274. format (format_),
  2275. medium (medium_),
  2276. refCount (1)
  2277. {
  2278. }
  2279. virtual ~JuceDataObject()
  2280. {
  2281. jassert (refCount == 0);
  2282. }
  2283. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2284. {
  2285. if (id == IID_IUnknown || id == IID_IDataObject)
  2286. {
  2287. AddRef();
  2288. *result = this;
  2289. return S_OK;
  2290. }
  2291. *result = 0;
  2292. return E_NOINTERFACE;
  2293. }
  2294. ULONG __stdcall AddRef() { return ++refCount; }
  2295. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2296. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  2297. {
  2298. if (pFormatEtc->tymed == format->tymed
  2299. && pFormatEtc->cfFormat == format->cfFormat
  2300. && pFormatEtc->dwAspect == format->dwAspect)
  2301. {
  2302. pMedium->tymed = format->tymed;
  2303. pMedium->pUnkForRelease = 0;
  2304. if (format->tymed == TYMED_HGLOBAL)
  2305. {
  2306. const SIZE_T len = GlobalSize (medium->hGlobal);
  2307. void* const src = GlobalLock (medium->hGlobal);
  2308. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  2309. memcpy (dst, src, len);
  2310. GlobalUnlock (medium->hGlobal);
  2311. pMedium->hGlobal = dst;
  2312. return S_OK;
  2313. }
  2314. }
  2315. return DV_E_FORMATETC;
  2316. }
  2317. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  2318. {
  2319. if (f == 0)
  2320. return E_INVALIDARG;
  2321. if (f->tymed == format->tymed
  2322. && f->cfFormat == format->cfFormat
  2323. && f->dwAspect == format->dwAspect)
  2324. return S_OK;
  2325. return DV_E_FORMATETC;
  2326. }
  2327. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  2328. {
  2329. pFormatEtcOut->ptd = 0;
  2330. return E_NOTIMPL;
  2331. }
  2332. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  2333. {
  2334. if (result == 0)
  2335. return E_POINTER;
  2336. if (direction == DATADIR_GET)
  2337. {
  2338. *result = new JuceEnumFormatEtc (format);
  2339. return S_OK;
  2340. }
  2341. *result = 0;
  2342. return E_NOTIMPL;
  2343. }
  2344. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  2345. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  2346. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  2347. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  2348. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  2349. };
  2350. static HDROP createHDrop (const StringArray& fileNames) throw()
  2351. {
  2352. int totalChars = 0;
  2353. for (int i = fileNames.size(); --i >= 0;)
  2354. totalChars += fileNames[i].length() + 1;
  2355. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  2356. sizeof (DROPFILES)
  2357. + sizeof (WCHAR) * (totalChars + 2));
  2358. if (hDrop != 0)
  2359. {
  2360. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  2361. pDropFiles->pFiles = sizeof (DROPFILES);
  2362. pDropFiles->fWide = true;
  2363. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  2364. for (int i = 0; i < fileNames.size(); ++i)
  2365. {
  2366. fileNames[i].copyToBuffer (fname, 2048);
  2367. fname += fileNames[i].length() + 1;
  2368. }
  2369. *fname = 0;
  2370. GlobalUnlock (hDrop);
  2371. }
  2372. return hDrop;
  2373. }
  2374. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  2375. {
  2376. JuceDropSource* const source = new JuceDropSource();
  2377. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  2378. DWORD effect;
  2379. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  2380. data->Release();
  2381. source->Release();
  2382. return res == DRAGDROP_S_DROP;
  2383. }
  2384. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  2385. {
  2386. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2387. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2388. medium.hGlobal = createHDrop (files);
  2389. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  2390. : DROPEFFECT_COPY);
  2391. }
  2392. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2393. {
  2394. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2395. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2396. const int numChars = text.length();
  2397. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  2398. char* d = (char*) GlobalLock (medium.hGlobal);
  2399. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  2400. format.cfFormat = CF_UNICODETEXT;
  2401. GlobalUnlock (medium.hGlobal);
  2402. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  2403. }
  2404. //==============================================================================
  2405. //==============================================================================
  2406. #if JUCE_OPENGL
  2407. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  2408. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  2409. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  2410. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  2411. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  2412. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  2413. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  2414. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  2415. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  2416. #define WGL_ACCELERATION_ARB 0x2003
  2417. #define WGL_SWAP_METHOD_ARB 0x2007
  2418. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  2419. #define WGL_PIXEL_TYPE_ARB 0x2013
  2420. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  2421. #define WGL_COLOR_BITS_ARB 0x2014
  2422. #define WGL_RED_BITS_ARB 0x2015
  2423. #define WGL_GREEN_BITS_ARB 0x2017
  2424. #define WGL_BLUE_BITS_ARB 0x2019
  2425. #define WGL_ALPHA_BITS_ARB 0x201B
  2426. #define WGL_DEPTH_BITS_ARB 0x2022
  2427. #define WGL_STENCIL_BITS_ARB 0x2023
  2428. #define WGL_FULL_ACCELERATION_ARB 0x2027
  2429. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  2430. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  2431. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  2432. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  2433. #define WGL_STEREO_ARB 0x2012
  2434. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  2435. #define WGL_SAMPLES_ARB 0x2042
  2436. #define WGL_TYPE_RGBA_ARB 0x202B
  2437. static void getWglExtensions (HDC dc, StringArray& result) throw()
  2438. {
  2439. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  2440. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  2441. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  2442. else
  2443. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  2444. }
  2445. //==============================================================================
  2446. class WindowedGLContext : public OpenGLContext
  2447. {
  2448. public:
  2449. WindowedGLContext (Component* const component_,
  2450. HGLRC contextToShareWith,
  2451. const OpenGLPixelFormat& pixelFormat)
  2452. : renderContext (0),
  2453. nativeWindow (0),
  2454. dc (0),
  2455. component (component_)
  2456. {
  2457. jassert (component != 0);
  2458. createNativeWindow();
  2459. // Use a default pixel format that should be supported everywhere
  2460. PIXELFORMATDESCRIPTOR pfd;
  2461. zerostruct (pfd);
  2462. pfd.nSize = sizeof (pfd);
  2463. pfd.nVersion = 1;
  2464. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  2465. pfd.iPixelType = PFD_TYPE_RGBA;
  2466. pfd.cColorBits = 24;
  2467. pfd.cDepthBits = 16;
  2468. const int format = ChoosePixelFormat (dc, &pfd);
  2469. if (format != 0)
  2470. SetPixelFormat (dc, format, &pfd);
  2471. renderContext = wglCreateContext (dc);
  2472. makeActive();
  2473. setPixelFormat (pixelFormat);
  2474. if (contextToShareWith != 0 && renderContext != 0)
  2475. wglShareLists (contextToShareWith, renderContext);
  2476. }
  2477. ~WindowedGLContext()
  2478. {
  2479. makeInactive();
  2480. wglDeleteContext (renderContext);
  2481. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  2482. delete nativeWindow;
  2483. }
  2484. bool makeActive() const throw()
  2485. {
  2486. jassert (renderContext != 0);
  2487. return wglMakeCurrent (dc, renderContext) != 0;
  2488. }
  2489. bool makeInactive() const throw()
  2490. {
  2491. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  2492. }
  2493. bool isActive() const throw()
  2494. {
  2495. return wglGetCurrentContext() == renderContext;
  2496. }
  2497. const OpenGLPixelFormat getPixelFormat() const
  2498. {
  2499. OpenGLPixelFormat pf;
  2500. makeActive();
  2501. StringArray availableExtensions;
  2502. getWglExtensions (dc, availableExtensions);
  2503. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  2504. return pf;
  2505. }
  2506. void* getRawContext() const throw()
  2507. {
  2508. return renderContext;
  2509. }
  2510. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  2511. {
  2512. makeActive();
  2513. PIXELFORMATDESCRIPTOR pfd;
  2514. zerostruct (pfd);
  2515. pfd.nSize = sizeof (pfd);
  2516. pfd.nVersion = 1;
  2517. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  2518. pfd.iPixelType = PFD_TYPE_RGBA;
  2519. pfd.iLayerType = PFD_MAIN_PLANE;
  2520. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  2521. pfd.cRedBits = pixelFormat.redBits;
  2522. pfd.cGreenBits = pixelFormat.greenBits;
  2523. pfd.cBlueBits = pixelFormat.blueBits;
  2524. pfd.cAlphaBits = pixelFormat.alphaBits;
  2525. pfd.cDepthBits = pixelFormat.depthBufferBits;
  2526. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  2527. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  2528. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  2529. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  2530. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  2531. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  2532. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  2533. int format = 0;
  2534. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  2535. StringArray availableExtensions;
  2536. getWglExtensions (dc, availableExtensions);
  2537. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  2538. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  2539. {
  2540. int attributes[64];
  2541. int n = 0;
  2542. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  2543. attributes[n++] = GL_TRUE;
  2544. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  2545. attributes[n++] = GL_TRUE;
  2546. attributes[n++] = WGL_ACCELERATION_ARB;
  2547. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  2548. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  2549. attributes[n++] = GL_TRUE;
  2550. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  2551. attributes[n++] = WGL_TYPE_RGBA_ARB;
  2552. attributes[n++] = WGL_COLOR_BITS_ARB;
  2553. attributes[n++] = pfd.cColorBits;
  2554. attributes[n++] = WGL_RED_BITS_ARB;
  2555. attributes[n++] = pixelFormat.redBits;
  2556. attributes[n++] = WGL_GREEN_BITS_ARB;
  2557. attributes[n++] = pixelFormat.greenBits;
  2558. attributes[n++] = WGL_BLUE_BITS_ARB;
  2559. attributes[n++] = pixelFormat.blueBits;
  2560. attributes[n++] = WGL_ALPHA_BITS_ARB;
  2561. attributes[n++] = pixelFormat.alphaBits;
  2562. attributes[n++] = WGL_DEPTH_BITS_ARB;
  2563. attributes[n++] = pixelFormat.depthBufferBits;
  2564. if (pixelFormat.stencilBufferBits > 0)
  2565. {
  2566. attributes[n++] = WGL_STENCIL_BITS_ARB;
  2567. attributes[n++] = pixelFormat.stencilBufferBits;
  2568. }
  2569. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  2570. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  2571. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  2572. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  2573. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  2574. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  2575. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  2576. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  2577. if (availableExtensions.contains ("WGL_ARB_multisample")
  2578. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  2579. {
  2580. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  2581. attributes[n++] = 1;
  2582. attributes[n++] = WGL_SAMPLES_ARB;
  2583. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  2584. }
  2585. attributes[n++] = 0;
  2586. UINT formatsCount;
  2587. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  2588. (void) ok;
  2589. jassert (ok);
  2590. }
  2591. else
  2592. {
  2593. format = ChoosePixelFormat (dc, &pfd);
  2594. }
  2595. if (format != 0)
  2596. {
  2597. makeInactive();
  2598. // win32 can't change the pixel format of a window, so need to delete the
  2599. // old one and create a new one..
  2600. jassert (nativeWindow != 0);
  2601. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  2602. delete nativeWindow;
  2603. createNativeWindow();
  2604. if (SetPixelFormat (dc, format, &pfd))
  2605. {
  2606. wglDeleteContext (renderContext);
  2607. renderContext = wglCreateContext (dc);
  2608. jassert (renderContext != 0);
  2609. return renderContext != 0;
  2610. }
  2611. }
  2612. return false;
  2613. }
  2614. void updateWindowPosition (int x, int y, int w, int h, int)
  2615. {
  2616. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  2617. x, y, w, h,
  2618. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  2619. }
  2620. void repaint()
  2621. {
  2622. int x, y, w, h;
  2623. nativeWindow->getBounds (x, y, w, h);
  2624. nativeWindow->repaint (0, 0, w, h);
  2625. }
  2626. void swapBuffers()
  2627. {
  2628. SwapBuffers (dc);
  2629. }
  2630. bool setSwapInterval (const int numFramesPerSwap)
  2631. {
  2632. makeActive();
  2633. StringArray availableExtensions;
  2634. getWglExtensions (dc, availableExtensions);
  2635. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  2636. return availableExtensions.contains ("WGL_EXT_swap_control")
  2637. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  2638. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  2639. }
  2640. int getSwapInterval() const
  2641. {
  2642. makeActive();
  2643. StringArray availableExtensions;
  2644. getWglExtensions (dc, availableExtensions);
  2645. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  2646. if (availableExtensions.contains ("WGL_EXT_swap_control")
  2647. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  2648. return wglGetSwapIntervalEXT();
  2649. return 0;
  2650. }
  2651. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  2652. {
  2653. jassert (isActive());
  2654. StringArray availableExtensions;
  2655. getWglExtensions (dc, availableExtensions);
  2656. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  2657. int numTypes = 0;
  2658. if (availableExtensions.contains("WGL_ARB_pixel_format")
  2659. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  2660. {
  2661. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  2662. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  2663. jassertfalse
  2664. }
  2665. else
  2666. {
  2667. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  2668. }
  2669. OpenGLPixelFormat pf;
  2670. for (int i = 0; i < numTypes; ++i)
  2671. {
  2672. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  2673. {
  2674. bool alreadyListed = false;
  2675. for (int j = results.size(); --j >= 0;)
  2676. if (pf == *results.getUnchecked(j))
  2677. alreadyListed = true;
  2678. if (! alreadyListed)
  2679. results.add (new OpenGLPixelFormat (pf));
  2680. }
  2681. }
  2682. }
  2683. //==============================================================================
  2684. juce_UseDebuggingNewOperator
  2685. HGLRC renderContext;
  2686. private:
  2687. Win32ComponentPeer* nativeWindow;
  2688. Component* const component;
  2689. HDC dc;
  2690. //==============================================================================
  2691. void createNativeWindow()
  2692. {
  2693. nativeWindow = new Win32ComponentPeer (component, 0);
  2694. nativeWindow->dontRepaint = true;
  2695. nativeWindow->setVisible (true);
  2696. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  2697. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2698. if (peer != 0)
  2699. {
  2700. SetParent (hwnd, (HWND) peer->getNativeHandle());
  2701. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  2702. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  2703. }
  2704. dc = GetDC (hwnd);
  2705. }
  2706. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  2707. OpenGLPixelFormat& result,
  2708. const StringArray& availableExtensions) const throw()
  2709. {
  2710. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  2711. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  2712. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  2713. {
  2714. int attributes[32];
  2715. int numAttributes = 0;
  2716. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  2717. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  2718. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  2719. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  2720. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  2721. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  2722. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  2723. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  2724. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  2725. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  2726. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  2727. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  2728. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  2729. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  2730. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  2731. if (availableExtensions.contains ("WGL_ARB_multisample"))
  2732. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  2733. int values[32];
  2734. zeromem (values, sizeof (values));
  2735. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  2736. {
  2737. int n = 0;
  2738. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  2739. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  2740. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  2741. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  2742. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  2743. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  2744. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  2745. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  2746. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  2747. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  2748. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  2749. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  2750. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  2751. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  2752. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  2753. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  2754. return isValidFormat;
  2755. }
  2756. else
  2757. {
  2758. jassertfalse
  2759. }
  2760. }
  2761. else
  2762. {
  2763. PIXELFORMATDESCRIPTOR pfd;
  2764. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  2765. {
  2766. result.redBits = pfd.cRedBits;
  2767. result.greenBits = pfd.cGreenBits;
  2768. result.blueBits = pfd.cBlueBits;
  2769. result.alphaBits = pfd.cAlphaBits;
  2770. result.depthBufferBits = pfd.cDepthBits;
  2771. result.stencilBufferBits = pfd.cStencilBits;
  2772. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  2773. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  2774. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  2775. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  2776. result.fullSceneAntiAliasingNumSamples = 0;
  2777. return true;
  2778. }
  2779. else
  2780. {
  2781. jassertfalse
  2782. }
  2783. }
  2784. return false;
  2785. }
  2786. WindowedGLContext (const WindowedGLContext&);
  2787. const WindowedGLContext& operator= (const WindowedGLContext&);
  2788. };
  2789. //==============================================================================
  2790. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  2791. const OpenGLPixelFormat& pixelFormat,
  2792. const OpenGLContext* const contextToShareWith)
  2793. {
  2794. WindowedGLContext* c = new WindowedGLContext (component,
  2795. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  2796. pixelFormat);
  2797. if (c->renderContext == 0)
  2798. deleteAndZero (c);
  2799. return c;
  2800. }
  2801. void juce_glViewport (const int w, const int h)
  2802. {
  2803. glViewport (0, 0, w, h);
  2804. }
  2805. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  2806. OwnedArray <OpenGLPixelFormat>& results)
  2807. {
  2808. Component tempComp;
  2809. {
  2810. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  2811. wc.makeActive();
  2812. wc.findAlternativeOpenGLPixelFormats (results);
  2813. }
  2814. }
  2815. #endif
  2816. //==============================================================================
  2817. //==============================================================================
  2818. class JuceIStorage : public IStorage
  2819. {
  2820. int refCount;
  2821. public:
  2822. JuceIStorage() : refCount (1) {}
  2823. virtual ~JuceIStorage()
  2824. {
  2825. jassert (refCount == 0);
  2826. }
  2827. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2828. {
  2829. if (id == IID_IUnknown || id == IID_IStorage)
  2830. {
  2831. AddRef();
  2832. *result = this;
  2833. return S_OK;
  2834. }
  2835. *result = 0;
  2836. return E_NOINTERFACE;
  2837. }
  2838. ULONG __stdcall AddRef() { return ++refCount; }
  2839. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  2840. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  2841. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  2842. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  2843. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  2844. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  2845. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  2846. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  2847. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  2848. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  2849. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  2850. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  2851. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  2852. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  2853. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  2854. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  2855. juce_UseDebuggingNewOperator
  2856. };
  2857. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  2858. {
  2859. int refCount;
  2860. HWND window;
  2861. public:
  2862. JuceOleInPlaceFrame (HWND window_)
  2863. : refCount (1),
  2864. window (window_)
  2865. {
  2866. }
  2867. virtual ~JuceOleInPlaceFrame()
  2868. {
  2869. jassert (refCount == 0);
  2870. }
  2871. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2872. {
  2873. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  2874. {
  2875. AddRef();
  2876. *result = this;
  2877. return S_OK;
  2878. }
  2879. *result = 0;
  2880. return E_NOINTERFACE;
  2881. }
  2882. ULONG __stdcall AddRef() { return ++refCount; }
  2883. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  2884. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  2885. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  2886. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  2887. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  2888. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  2889. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  2890. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  2891. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  2892. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  2893. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  2894. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  2895. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  2896. juce_UseDebuggingNewOperator
  2897. };
  2898. class JuceIOleInPlaceSite : public IOleInPlaceSite
  2899. {
  2900. int refCount;
  2901. HWND window;
  2902. JuceOleInPlaceFrame* frame;
  2903. public:
  2904. JuceIOleInPlaceSite (HWND window_)
  2905. : refCount (1),
  2906. window (window_)
  2907. {
  2908. frame = new JuceOleInPlaceFrame (window);
  2909. }
  2910. virtual ~JuceIOleInPlaceSite()
  2911. {
  2912. jassert (refCount == 0);
  2913. frame->Release();
  2914. }
  2915. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2916. {
  2917. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  2918. {
  2919. AddRef();
  2920. *result = this;
  2921. return S_OK;
  2922. }
  2923. *result = 0;
  2924. return E_NOINTERFACE;
  2925. }
  2926. ULONG __stdcall AddRef() { return ++refCount; }
  2927. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  2928. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  2929. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  2930. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  2931. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  2932. HRESULT __stdcall OnUIActivate() { return S_OK; }
  2933. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  2934. {
  2935. frame->AddRef();
  2936. *lplpFrame = frame;
  2937. *lplpDoc = 0;
  2938. lpFrameInfo->fMDIApp = FALSE;
  2939. lpFrameInfo->hwndFrame = window;
  2940. lpFrameInfo->haccel = 0;
  2941. lpFrameInfo->cAccelEntries = 0;
  2942. return S_OK;
  2943. }
  2944. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  2945. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  2946. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  2947. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  2948. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  2949. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  2950. juce_UseDebuggingNewOperator
  2951. };
  2952. class JuceIOleClientSite : public IOleClientSite
  2953. {
  2954. int refCount;
  2955. JuceIOleInPlaceSite* inplaceSite;
  2956. public:
  2957. JuceIOleClientSite (HWND window)
  2958. : refCount (1)
  2959. {
  2960. inplaceSite = new JuceIOleInPlaceSite (window);
  2961. }
  2962. virtual ~JuceIOleClientSite()
  2963. {
  2964. jassert (refCount == 0);
  2965. inplaceSite->Release();
  2966. }
  2967. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2968. {
  2969. if (id == IID_IUnknown || id == IID_IOleClientSite)
  2970. {
  2971. AddRef();
  2972. *result = this;
  2973. return S_OK;
  2974. }
  2975. else if (id == IID_IOleInPlaceSite)
  2976. {
  2977. inplaceSite->AddRef();
  2978. *result = inplaceSite;
  2979. return S_OK;
  2980. }
  2981. *result = 0;
  2982. return E_NOINTERFACE;
  2983. }
  2984. ULONG __stdcall AddRef() { return ++refCount; }
  2985. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  2986. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  2987. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  2988. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  2989. HRESULT __stdcall ShowObject() { return S_OK; }
  2990. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  2991. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  2992. juce_UseDebuggingNewOperator
  2993. };
  2994. //==============================================================================
  2995. class ActiveXControlData : public ComponentMovementWatcher
  2996. {
  2997. ActiveXControlComponent* const owner;
  2998. bool wasShowing;
  2999. public:
  3000. HWND controlHWND;
  3001. IStorage* storage;
  3002. IOleClientSite* clientSite;
  3003. IOleObject* control;
  3004. //==============================================================================
  3005. ActiveXControlData (HWND hwnd,
  3006. ActiveXControlComponent* const owner_)
  3007. : ComponentMovementWatcher (owner_),
  3008. owner (owner_),
  3009. wasShowing (owner_ != 0 && owner_->isShowing()),
  3010. controlHWND (0),
  3011. storage (new JuceIStorage()),
  3012. clientSite (new JuceIOleClientSite (hwnd)),
  3013. control (0)
  3014. {
  3015. }
  3016. ~ActiveXControlData()
  3017. {
  3018. if (control != 0)
  3019. {
  3020. control->Close (OLECLOSE_NOSAVE);
  3021. control->Release();
  3022. }
  3023. clientSite->Release();
  3024. storage->Release();
  3025. }
  3026. //==============================================================================
  3027. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  3028. {
  3029. Component* const topComp = owner->getTopLevelComponent();
  3030. if (topComp->getPeer() != 0)
  3031. {
  3032. int x = 0, y = 0;
  3033. owner->relativePositionToOtherComponent (topComp, x, y);
  3034. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  3035. }
  3036. }
  3037. void componentPeerChanged()
  3038. {
  3039. const bool isShowingNow = owner->isShowing();
  3040. if (wasShowing != isShowingNow)
  3041. {
  3042. wasShowing = isShowingNow;
  3043. owner->setControlVisible (isShowingNow);
  3044. }
  3045. }
  3046. void componentVisibilityChanged (Component&)
  3047. {
  3048. componentPeerChanged();
  3049. }
  3050. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  3051. {
  3052. return ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  3053. }
  3054. };
  3055. //==============================================================================
  3056. static VoidArray activeXComps;
  3057. static HWND getHWND (const ActiveXControlComponent* const component)
  3058. {
  3059. HWND hwnd = 0;
  3060. const IID iid = IID_IOleWindow;
  3061. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  3062. if (window != 0)
  3063. {
  3064. window->GetWindow (&hwnd);
  3065. window->Release();
  3066. }
  3067. return hwnd;
  3068. }
  3069. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  3070. {
  3071. RECT activeXRect, peerRect;
  3072. GetWindowRect (hwnd, &activeXRect);
  3073. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  3074. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  3075. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  3076. const int64 mouseEventTime = getMouseEventTime();
  3077. const int oldModifiers = currentModifiers;
  3078. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  3079. switch (message)
  3080. {
  3081. case WM_MOUSEMOVE:
  3082. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  3083. peer->handleMouseDrag (mx, my, mouseEventTime);
  3084. else
  3085. peer->handleMouseMove (mx, my, mouseEventTime);
  3086. break;
  3087. case WM_LBUTTONDOWN:
  3088. case WM_MBUTTONDOWN:
  3089. case WM_RBUTTONDOWN:
  3090. peer->handleMouseDown (mx, my, mouseEventTime);
  3091. break;
  3092. case WM_LBUTTONUP:
  3093. case WM_MBUTTONUP:
  3094. case WM_RBUTTONUP:
  3095. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  3096. break;
  3097. default:
  3098. break;
  3099. }
  3100. }
  3101. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  3102. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  3103. {
  3104. for (int i = activeXComps.size(); --i >= 0;)
  3105. {
  3106. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  3107. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  3108. {
  3109. switch (message)
  3110. {
  3111. case WM_MOUSEMOVE:
  3112. case WM_LBUTTONDOWN:
  3113. case WM_MBUTTONDOWN:
  3114. case WM_RBUTTONDOWN:
  3115. case WM_LBUTTONUP:
  3116. case WM_MBUTTONUP:
  3117. case WM_RBUTTONUP:
  3118. case WM_LBUTTONDBLCLK:
  3119. case WM_MBUTTONDBLCLK:
  3120. case WM_RBUTTONDBLCLK:
  3121. if (ax->isShowing())
  3122. {
  3123. ComponentPeer* const peer = ax->getPeer();
  3124. if (peer != 0)
  3125. {
  3126. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  3127. if (! ax->areMouseEventsAllowed())
  3128. return 0;
  3129. }
  3130. }
  3131. break;
  3132. default:
  3133. break;
  3134. }
  3135. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  3136. }
  3137. }
  3138. return DefWindowProc (hwnd, message, wParam, lParam);
  3139. }
  3140. ActiveXControlComponent::ActiveXControlComponent()
  3141. : originalWndProc (0),
  3142. control (0),
  3143. mouseEventsAllowed (true)
  3144. {
  3145. activeXComps.add (this);
  3146. }
  3147. ActiveXControlComponent::~ActiveXControlComponent()
  3148. {
  3149. deleteControl();
  3150. activeXComps.removeValue (this);
  3151. }
  3152. void ActiveXControlComponent::paint (Graphics& g)
  3153. {
  3154. if (control == 0)
  3155. g.fillAll (Colours::lightgrey);
  3156. }
  3157. bool ActiveXControlComponent::createControl (const void* controlIID)
  3158. {
  3159. deleteControl();
  3160. ComponentPeer* const peer = getPeer();
  3161. // the component must have already been added to a real window when you call this!
  3162. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  3163. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  3164. {
  3165. int x = 0, y = 0;
  3166. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  3167. HWND hwnd = (HWND) peer->getNativeHandle();
  3168. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  3169. HRESULT hr;
  3170. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  3171. info->clientSite, info->storage,
  3172. (void**) &(info->control))) == S_OK)
  3173. {
  3174. info->control->SetHostNames (L"Juce", 0);
  3175. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  3176. {
  3177. RECT rect;
  3178. rect.left = x;
  3179. rect.top = y;
  3180. rect.right = x + getWidth();
  3181. rect.bottom = y + getHeight();
  3182. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  3183. {
  3184. control = info;
  3185. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  3186. info->controlHWND = getHWND (this);
  3187. if (info->controlHWND != 0)
  3188. {
  3189. originalWndProc = (void*) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  3190. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  3191. }
  3192. return true;
  3193. }
  3194. }
  3195. }
  3196. delete info;
  3197. }
  3198. return false;
  3199. }
  3200. void ActiveXControlComponent::deleteControl()
  3201. {
  3202. ActiveXControlData* const info = (ActiveXControlData*) control;
  3203. if (info != 0)
  3204. {
  3205. delete info;
  3206. control = 0;
  3207. originalWndProc = 0;
  3208. }
  3209. }
  3210. void* ActiveXControlComponent::queryInterface (const void* iid) const
  3211. {
  3212. ActiveXControlData* const info = (ActiveXControlData*) control;
  3213. void* result = 0;
  3214. if (info != 0 && info->control != 0
  3215. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  3216. return result;
  3217. return 0;
  3218. }
  3219. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  3220. {
  3221. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  3222. if (hwnd != 0)
  3223. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  3224. }
  3225. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  3226. {
  3227. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  3228. if (hwnd != 0)
  3229. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  3230. }
  3231. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  3232. {
  3233. mouseEventsAllowed = eventsCanReachControl;
  3234. }
  3235. END_JUCE_NAMESPACE