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.

4148 lines
138KB

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