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.

4153 lines
139KB

  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 (hasTitleBar())
  608. ShowWindow (hwnd, SW_SHOWNORMAL);
  609. if (! boundsCopy.isEmpty())
  610. {
  611. setBounds (boundsCopy.getX(),
  612. boundsCopy.getY(),
  613. boundsCopy.getWidth(),
  614. boundsCopy.getHeight(),
  615. false);
  616. }
  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. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  1776. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  1777. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  1778. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  1779. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  1780. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  1781. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  1782. {
  1783. SetFocus (hwnd);
  1784. SetForegroundWindow (hwnd);
  1785. component->mouseDown (e);
  1786. }
  1787. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  1788. component->mouseUp (e);
  1789. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1790. component->mouseDoubleClick (e);
  1791. else if (lParam == WM_MOUSEMOVE)
  1792. component->mouseMove (e);
  1793. }
  1794. break;
  1795. //==============================================================================
  1796. case WM_SYNCPAINT:
  1797. return 0;
  1798. case WM_PALETTECHANGED:
  1799. InvalidateRect (h, 0, 0);
  1800. break;
  1801. case WM_DISPLAYCHANGE:
  1802. InvalidateRect (h, 0, 0);
  1803. createPaletteIfNeeded = true;
  1804. // intentional fall-through...
  1805. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  1806. doSettingChange();
  1807. break;
  1808. case WM_INITMENU:
  1809. if (! hasTitleBar())
  1810. {
  1811. if (isFullScreen())
  1812. {
  1813. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  1814. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  1815. }
  1816. else if (! isMinimised())
  1817. {
  1818. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  1819. }
  1820. }
  1821. break;
  1822. case WM_SYSCOMMAND:
  1823. switch (wParam & 0xfff0)
  1824. {
  1825. case SC_CLOSE:
  1826. if (hasTitleBar())
  1827. {
  1828. PostMessage (h, WM_CLOSE, 0, 0);
  1829. return 0;
  1830. }
  1831. break;
  1832. case SC_KEYMENU:
  1833. if (hasTitleBar() && h == GetCapture())
  1834. ReleaseCapture();
  1835. break;
  1836. case SC_MAXIMIZE:
  1837. setFullScreen (true);
  1838. return 0;
  1839. case SC_MINIMIZE:
  1840. if (! hasTitleBar())
  1841. {
  1842. setMinimised (true);
  1843. return 0;
  1844. }
  1845. break;
  1846. case SC_RESTORE:
  1847. if (hasTitleBar())
  1848. {
  1849. if (isFullScreen())
  1850. {
  1851. setFullScreen (false);
  1852. return 0;
  1853. }
  1854. }
  1855. else
  1856. {
  1857. if (isMinimised())
  1858. setMinimised (false);
  1859. else if (isFullScreen())
  1860. setFullScreen (false);
  1861. return 0;
  1862. }
  1863. break;
  1864. case SC_MONITORPOWER:
  1865. case SC_SCREENSAVE:
  1866. if (! screenSaverAllowed)
  1867. return 0;
  1868. break;
  1869. }
  1870. break;
  1871. case WM_NCLBUTTONDOWN:
  1872. case WM_NCRBUTTONDOWN:
  1873. case WM_NCMBUTTONDOWN:
  1874. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1875. {
  1876. Component* const current = Component::getCurrentlyModalComponent();
  1877. if (current != 0)
  1878. current->inputAttemptWhenModal();
  1879. }
  1880. break;
  1881. //case WM_IME_STARTCOMPOSITION;
  1882. // return 0;
  1883. case WM_GETDLGCODE:
  1884. return DLGC_WANTALLKEYS;
  1885. default:
  1886. break;
  1887. }
  1888. }
  1889. }
  1890. // (the message manager lock exits before calling this, to avoid deadlocks if
  1891. // this calls into non-juce windows)
  1892. return DefWindowProc (h, message, wParam, lParam);
  1893. }
  1894. Win32ComponentPeer (const Win32ComponentPeer&);
  1895. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  1896. };
  1897. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  1898. {
  1899. return new Win32ComponentPeer (this, styleFlags);
  1900. }
  1901. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  1902. //==============================================================================
  1903. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  1904. {
  1905. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1906. if (wp != 0)
  1907. wp->setTaskBarIcon (&newImage);
  1908. }
  1909. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  1910. {
  1911. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1912. if (wp != 0)
  1913. wp->setTaskBarIconToolTip (tooltip);
  1914. }
  1915. //==============================================================================
  1916. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  1917. {
  1918. DWORD val = GetWindowLong (h, styleType);
  1919. if (bitIsSet)
  1920. val |= feature;
  1921. else
  1922. val &= ~feature;
  1923. SetWindowLongPtr (h, styleType, val);
  1924. SetWindowPos (h, 0, 0, 0, 0, 0,
  1925. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  1926. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  1927. }
  1928. //==============================================================================
  1929. bool Process::isForegroundProcess() throw()
  1930. {
  1931. HWND fg = GetForegroundWindow();
  1932. if (fg == 0)
  1933. return true;
  1934. DWORD processId = 0;
  1935. GetWindowThreadProcessId (fg, &processId);
  1936. return processId == GetCurrentProcessId();
  1937. }
  1938. //==============================================================================
  1939. void Desktop::getMousePosition (int& x, int& y) throw()
  1940. {
  1941. POINT mousePos;
  1942. GetCursorPos (&mousePos);
  1943. x = mousePos.x;
  1944. y = mousePos.y;
  1945. }
  1946. void Desktop::setMousePosition (int x, int y) throw()
  1947. {
  1948. SetCursorPos (x, y);
  1949. }
  1950. //==============================================================================
  1951. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1952. {
  1953. screenSaverAllowed = isEnabled;
  1954. }
  1955. bool Desktop::isScreenSaverEnabled() throw()
  1956. {
  1957. return screenSaverAllowed;
  1958. }
  1959. //==============================================================================
  1960. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  1961. {
  1962. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  1963. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  1964. return TRUE;
  1965. }
  1966. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1967. {
  1968. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  1969. // make sure the first in the list is the main monitor
  1970. for (int i = 1; i < monitorCoords.size(); ++i)
  1971. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  1972. monitorCoords.swap (i, 0);
  1973. if (monitorCoords.size() == 0)
  1974. {
  1975. RECT r;
  1976. GetWindowRect (GetDesktopWindow(), &r);
  1977. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  1978. }
  1979. if (clipToWorkArea)
  1980. {
  1981. // clip the main monitor to the active non-taskbar area
  1982. RECT r;
  1983. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  1984. Rectangle& screen = monitorCoords.getReference (0);
  1985. screen.setPosition (jmax (screen.getX(), r.left),
  1986. jmax (screen.getY(), r.top));
  1987. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  1988. jmin (screen.getBottom(), r.bottom) - screen.getY());
  1989. }
  1990. }
  1991. //==============================================================================
  1992. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  1993. {
  1994. Image* im = 0;
  1995. if (bitmap != 0)
  1996. {
  1997. BITMAP bm;
  1998. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  1999. && bm.bmWidth > 0 && bm.bmHeight > 0)
  2000. {
  2001. HDC tempDC = GetDC (0);
  2002. HDC dc = CreateCompatibleDC (tempDC);
  2003. ReleaseDC (0, tempDC);
  2004. SelectObject (dc, bitmap);
  2005. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  2006. for (int y = bm.bmHeight; --y >= 0;)
  2007. {
  2008. for (int x = bm.bmWidth; --x >= 0;)
  2009. {
  2010. COLORREF col = GetPixel (dc, x, y);
  2011. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  2012. (uint8) GetGValue (col),
  2013. (uint8) GetBValue (col)));
  2014. }
  2015. }
  2016. DeleteDC (dc);
  2017. }
  2018. }
  2019. return im;
  2020. }
  2021. static Image* createImageFromHICON (HICON icon) throw()
  2022. {
  2023. ICONINFO info;
  2024. if (GetIconInfo (icon, &info))
  2025. {
  2026. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  2027. if (mask == 0)
  2028. return 0;
  2029. Image* const image = createImageFromHBITMAP (info.hbmColor);
  2030. if (image == 0)
  2031. return mask;
  2032. for (int y = image->getHeight(); --y >= 0;)
  2033. {
  2034. for (int x = image->getWidth(); --x >= 0;)
  2035. {
  2036. const float brightness = mask->getPixelAt (x, y).getBrightness();
  2037. if (brightness > 0.0f)
  2038. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  2039. }
  2040. }
  2041. delete mask;
  2042. return image;
  2043. }
  2044. return 0;
  2045. }
  2046. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  2047. {
  2048. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  2049. ICONINFO info;
  2050. info.fIcon = isIcon;
  2051. info.xHotspot = hotspotX;
  2052. info.yHotspot = hotspotY;
  2053. info.hbmMask = mask;
  2054. HICON hi = 0;
  2055. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  2056. {
  2057. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  2058. Graphics g (bitmap);
  2059. g.drawImageAt (&image, 0, 0);
  2060. info.hbmColor = bitmap.hBitmap;
  2061. hi = CreateIconIndirect (&info);
  2062. }
  2063. else
  2064. {
  2065. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  2066. HDC colDC = CreateCompatibleDC (GetDC (0));
  2067. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  2068. SelectObject (colDC, colour);
  2069. SelectObject (alphaDC, mask);
  2070. for (int y = image.getHeight(); --y >= 0;)
  2071. {
  2072. for (int x = image.getWidth(); --x >= 0;)
  2073. {
  2074. const Colour c (image.getPixelAt (x, y));
  2075. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  2076. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  2077. }
  2078. }
  2079. DeleteDC (colDC);
  2080. DeleteDC (alphaDC);
  2081. info.hbmColor = colour;
  2082. hi = CreateIconIndirect (&info);
  2083. DeleteObject (colour);
  2084. }
  2085. DeleteObject (mask);
  2086. return hi;
  2087. }
  2088. Image* juce_createIconForFile (const File& file)
  2089. {
  2090. Image* image = 0;
  2091. TCHAR filename [1024];
  2092. file.getFullPathName().copyToBuffer (filename, 1023);
  2093. WORD iconNum = 0;
  2094. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  2095. filename, &iconNum);
  2096. if (icon != 0)
  2097. {
  2098. image = createImageFromHICON (icon);
  2099. DestroyIcon (icon);
  2100. }
  2101. return image;
  2102. }
  2103. //==============================================================================
  2104. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  2105. {
  2106. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  2107. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  2108. const Image* im = &image;
  2109. Image* newIm = 0;
  2110. if (image.getWidth() > maxW || image.getHeight() > maxH)
  2111. {
  2112. im = newIm = image.createCopy (maxW, maxH);
  2113. hotspotX = (hotspotX * maxW) / image.getWidth();
  2114. hotspotY = (hotspotY * maxH) / image.getHeight();
  2115. }
  2116. void* cursorH = 0;
  2117. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  2118. if (os == SystemStats::WinXP)
  2119. {
  2120. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  2121. }
  2122. else
  2123. {
  2124. const int stride = (maxW + 7) >> 3;
  2125. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  2126. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  2127. int index = 0;
  2128. for (int y = 0; y < maxH; ++y)
  2129. {
  2130. for (int x = 0; x < maxW; ++x)
  2131. {
  2132. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  2133. const Colour pixelColour (im->getPixelAt (x, y));
  2134. if (pixelColour.getAlpha() < 127)
  2135. andPlane [index + (x >> 3)] |= bit;
  2136. else if (pixelColour.getBrightness() >= 0.5f)
  2137. xorPlane [index + (x >> 3)] |= bit;
  2138. }
  2139. index += stride;
  2140. }
  2141. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  2142. juce_free (andPlane);
  2143. juce_free (xorPlane);
  2144. }
  2145. delete newIm;
  2146. return cursorH;
  2147. }
  2148. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2149. {
  2150. if (cursorHandle != 0 && ! isStandard)
  2151. DestroyCursor ((HCURSOR) cursorHandle);
  2152. }
  2153. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  2154. {
  2155. LPCTSTR cursorName = IDC_ARROW;
  2156. switch (type)
  2157. {
  2158. case MouseCursor::NormalCursor:
  2159. cursorName = IDC_ARROW;
  2160. break;
  2161. case MouseCursor::NoCursor:
  2162. return 0;
  2163. case MouseCursor::DraggingHandCursor:
  2164. {
  2165. static void* dragHandCursor = 0;
  2166. if (dragHandCursor == 0)
  2167. {
  2168. static const unsigned char dragHandData[] =
  2169. { 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,
  2170. 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,
  2171. 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 };
  2172. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  2173. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  2174. delete image;
  2175. }
  2176. return dragHandCursor;
  2177. }
  2178. case MouseCursor::WaitCursor:
  2179. cursorName = IDC_WAIT;
  2180. break;
  2181. case MouseCursor::IBeamCursor:
  2182. cursorName = IDC_IBEAM;
  2183. break;
  2184. case MouseCursor::PointingHandCursor:
  2185. cursorName = MAKEINTRESOURCE(32649);
  2186. break;
  2187. case MouseCursor::LeftRightResizeCursor:
  2188. case MouseCursor::LeftEdgeResizeCursor:
  2189. case MouseCursor::RightEdgeResizeCursor:
  2190. cursorName = IDC_SIZEWE;
  2191. break;
  2192. case MouseCursor::UpDownResizeCursor:
  2193. case MouseCursor::TopEdgeResizeCursor:
  2194. case MouseCursor::BottomEdgeResizeCursor:
  2195. cursorName = IDC_SIZENS;
  2196. break;
  2197. case MouseCursor::TopLeftCornerResizeCursor:
  2198. case MouseCursor::BottomRightCornerResizeCursor:
  2199. cursorName = IDC_SIZENWSE;
  2200. break;
  2201. case MouseCursor::TopRightCornerResizeCursor:
  2202. case MouseCursor::BottomLeftCornerResizeCursor:
  2203. cursorName = IDC_SIZENESW;
  2204. break;
  2205. case MouseCursor::UpDownLeftRightResizeCursor:
  2206. cursorName = IDC_SIZEALL;
  2207. break;
  2208. case MouseCursor::CrosshairCursor:
  2209. cursorName = IDC_CROSS;
  2210. break;
  2211. case MouseCursor::CopyingCursor:
  2212. // can't seem to find one of these in the win32 list..
  2213. break;
  2214. }
  2215. HCURSOR cursorH = LoadCursor (0, cursorName);
  2216. if (cursorH == 0)
  2217. cursorH = LoadCursor (0, IDC_ARROW);
  2218. return (void*) cursorH;
  2219. }
  2220. //==============================================================================
  2221. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2222. {
  2223. SetCursor ((HCURSOR) getHandle());
  2224. }
  2225. void MouseCursor::showInAllWindows() const throw()
  2226. {
  2227. showInWindow (0);
  2228. }
  2229. //==============================================================================
  2230. //==============================================================================
  2231. class JuceDropSource : public IDropSource
  2232. {
  2233. int refCount;
  2234. public:
  2235. JuceDropSource()
  2236. : refCount (1)
  2237. {
  2238. }
  2239. virtual ~JuceDropSource()
  2240. {
  2241. jassert (refCount == 0);
  2242. }
  2243. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2244. {
  2245. if (id == IID_IUnknown || id == IID_IDropSource)
  2246. {
  2247. AddRef();
  2248. *result = this;
  2249. return S_OK;
  2250. }
  2251. *result = 0;
  2252. return E_NOINTERFACE;
  2253. }
  2254. ULONG __stdcall AddRef() { return ++refCount; }
  2255. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2256. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  2257. {
  2258. if (escapePressed)
  2259. return DRAGDROP_S_CANCEL;
  2260. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  2261. return DRAGDROP_S_DROP;
  2262. return S_OK;
  2263. }
  2264. HRESULT __stdcall GiveFeedback (DWORD)
  2265. {
  2266. return DRAGDROP_S_USEDEFAULTCURSORS;
  2267. }
  2268. };
  2269. class JuceEnumFormatEtc : public IEnumFORMATETC
  2270. {
  2271. public:
  2272. JuceEnumFormatEtc (const FORMATETC* const format_)
  2273. : refCount (1),
  2274. format (format_),
  2275. index (0)
  2276. {
  2277. }
  2278. virtual ~JuceEnumFormatEtc()
  2279. {
  2280. jassert (refCount == 0);
  2281. }
  2282. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2283. {
  2284. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  2285. {
  2286. AddRef();
  2287. *result = this;
  2288. return S_OK;
  2289. }
  2290. *result = 0;
  2291. return E_NOINTERFACE;
  2292. }
  2293. ULONG __stdcall AddRef() { return ++refCount; }
  2294. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2295. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  2296. {
  2297. if (result == 0)
  2298. return E_POINTER;
  2299. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  2300. newOne->index = index;
  2301. *result = newOne;
  2302. return S_OK;
  2303. }
  2304. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  2305. {
  2306. if (pceltFetched != 0)
  2307. *pceltFetched = 0;
  2308. else if (celt != 1)
  2309. return S_FALSE;
  2310. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  2311. {
  2312. copyFormatEtc (lpFormatEtc [0], *format);
  2313. ++index;
  2314. if (pceltFetched != 0)
  2315. *pceltFetched = 1;
  2316. return S_OK;
  2317. }
  2318. return S_FALSE;
  2319. }
  2320. HRESULT __stdcall Skip (ULONG celt)
  2321. {
  2322. if (index + (int) celt >= 1)
  2323. return S_FALSE;
  2324. index += celt;
  2325. return S_OK;
  2326. }
  2327. HRESULT __stdcall Reset()
  2328. {
  2329. index = 0;
  2330. return S_OK;
  2331. }
  2332. private:
  2333. int refCount;
  2334. const FORMATETC* const format;
  2335. int index;
  2336. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  2337. {
  2338. dest = source;
  2339. if (source.ptd != 0)
  2340. {
  2341. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  2342. *(dest.ptd) = *(source.ptd);
  2343. }
  2344. }
  2345. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  2346. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  2347. };
  2348. class JuceDataObject : public IDataObject
  2349. {
  2350. JuceDropSource* const dropSource;
  2351. const FORMATETC* const format;
  2352. const STGMEDIUM* const medium;
  2353. int refCount;
  2354. JuceDataObject (const JuceDataObject&);
  2355. const JuceDataObject& operator= (const JuceDataObject&);
  2356. public:
  2357. JuceDataObject (JuceDropSource* const dropSource_,
  2358. const FORMATETC* const format_,
  2359. const STGMEDIUM* const medium_)
  2360. : dropSource (dropSource_),
  2361. format (format_),
  2362. medium (medium_),
  2363. refCount (1)
  2364. {
  2365. }
  2366. virtual ~JuceDataObject()
  2367. {
  2368. jassert (refCount == 0);
  2369. }
  2370. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2371. {
  2372. if (id == IID_IUnknown || id == IID_IDataObject)
  2373. {
  2374. AddRef();
  2375. *result = this;
  2376. return S_OK;
  2377. }
  2378. *result = 0;
  2379. return E_NOINTERFACE;
  2380. }
  2381. ULONG __stdcall AddRef() { return ++refCount; }
  2382. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2383. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  2384. {
  2385. if (pFormatEtc->tymed == format->tymed
  2386. && pFormatEtc->cfFormat == format->cfFormat
  2387. && pFormatEtc->dwAspect == format->dwAspect)
  2388. {
  2389. pMedium->tymed = format->tymed;
  2390. pMedium->pUnkForRelease = 0;
  2391. if (format->tymed == TYMED_HGLOBAL)
  2392. {
  2393. const SIZE_T len = GlobalSize (medium->hGlobal);
  2394. void* const src = GlobalLock (medium->hGlobal);
  2395. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  2396. memcpy (dst, src, len);
  2397. GlobalUnlock (medium->hGlobal);
  2398. pMedium->hGlobal = dst;
  2399. return S_OK;
  2400. }
  2401. }
  2402. return DV_E_FORMATETC;
  2403. }
  2404. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  2405. {
  2406. if (f == 0)
  2407. return E_INVALIDARG;
  2408. if (f->tymed == format->tymed
  2409. && f->cfFormat == format->cfFormat
  2410. && f->dwAspect == format->dwAspect)
  2411. return S_OK;
  2412. return DV_E_FORMATETC;
  2413. }
  2414. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  2415. {
  2416. pFormatEtcOut->ptd = 0;
  2417. return E_NOTIMPL;
  2418. }
  2419. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  2420. {
  2421. if (result == 0)
  2422. return E_POINTER;
  2423. if (direction == DATADIR_GET)
  2424. {
  2425. *result = new JuceEnumFormatEtc (format);
  2426. return S_OK;
  2427. }
  2428. *result = 0;
  2429. return E_NOTIMPL;
  2430. }
  2431. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  2432. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  2433. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  2434. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  2435. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  2436. };
  2437. static HDROP createHDrop (const StringArray& fileNames) throw()
  2438. {
  2439. int totalChars = 0;
  2440. for (int i = fileNames.size(); --i >= 0;)
  2441. totalChars += fileNames[i].length() + 1;
  2442. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  2443. sizeof (DROPFILES)
  2444. + sizeof (WCHAR) * (totalChars + 2));
  2445. if (hDrop != 0)
  2446. {
  2447. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  2448. pDropFiles->pFiles = sizeof (DROPFILES);
  2449. #if JUCE_ENABLE_WIN98_COMPATIBILITY
  2450. pDropFiles->fWide = (SystemStats::getOperatingSystemType() & SystemStats::WindowsNT) != 0;
  2451. if (pDropFiles->fWide)
  2452. {
  2453. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  2454. for (int i = 0; i < fileNames.size(); ++i)
  2455. {
  2456. fileNames[i].copyToBuffer (fname, 2048);
  2457. fname += fileNames[i].length() + 1;
  2458. }
  2459. *fname = 0;
  2460. }
  2461. else
  2462. {
  2463. char* fname = ((char*) pDropFiles) + sizeof (DROPFILES);
  2464. for (int i = 0; i < fileNames.size(); ++i)
  2465. {
  2466. fileNames[i].copyToBuffer (fname, 2048);
  2467. fname += fileNames[i].length() + 1;
  2468. }
  2469. *fname = 0;
  2470. }
  2471. #else
  2472. pDropFiles->fWide = true;
  2473. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  2474. for (int i = 0; i < fileNames.size(); ++i)
  2475. {
  2476. fileNames[i].copyToBuffer (fname, 2048);
  2477. fname += fileNames[i].length() + 1;
  2478. }
  2479. *fname = 0;
  2480. #endif
  2481. GlobalUnlock (hDrop);
  2482. }
  2483. return hDrop;
  2484. }
  2485. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  2486. {
  2487. JuceDropSource* const source = new JuceDropSource();
  2488. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  2489. DWORD effect;
  2490. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  2491. data->Release();
  2492. source->Release();
  2493. return res == DRAGDROP_S_DROP;
  2494. }
  2495. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  2496. {
  2497. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2498. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2499. medium.hGlobal = createHDrop (files);
  2500. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  2501. : DROPEFFECT_COPY);
  2502. }
  2503. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2504. {
  2505. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2506. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2507. const int numChars = text.length();
  2508. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  2509. char* d = (char*) GlobalLock (medium.hGlobal);
  2510. #if JUCE_ENABLE_WIN98_COMPATIBILITY
  2511. if ((SystemStats::getOperatingSystemType() & SystemStats::WindowsNT) != 0)
  2512. {
  2513. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  2514. format.cfFormat = CF_UNICODETEXT;
  2515. }
  2516. else
  2517. {
  2518. text.copyToBuffer (d, numChars + 1);
  2519. }
  2520. #else
  2521. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  2522. format.cfFormat = CF_UNICODETEXT;
  2523. #endif
  2524. GlobalUnlock (medium.hGlobal);
  2525. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  2526. }
  2527. //==============================================================================
  2528. //==============================================================================
  2529. #if JUCE_OPENGL
  2530. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  2531. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  2532. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  2533. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  2534. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  2535. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  2536. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  2537. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  2538. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  2539. #define WGL_ACCELERATION_ARB 0x2003
  2540. #define WGL_SWAP_METHOD_ARB 0x2007
  2541. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  2542. #define WGL_PIXEL_TYPE_ARB 0x2013
  2543. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  2544. #define WGL_COLOR_BITS_ARB 0x2014
  2545. #define WGL_RED_BITS_ARB 0x2015
  2546. #define WGL_GREEN_BITS_ARB 0x2017
  2547. #define WGL_BLUE_BITS_ARB 0x2019
  2548. #define WGL_ALPHA_BITS_ARB 0x201B
  2549. #define WGL_DEPTH_BITS_ARB 0x2022
  2550. #define WGL_STENCIL_BITS_ARB 0x2023
  2551. #define WGL_FULL_ACCELERATION_ARB 0x2027
  2552. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  2553. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  2554. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  2555. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  2556. #define WGL_STEREO_ARB 0x2012
  2557. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  2558. #define WGL_SAMPLES_ARB 0x2042
  2559. #define WGL_TYPE_RGBA_ARB 0x202B
  2560. static void getWglExtensions (HDC dc, StringArray& result) throw()
  2561. {
  2562. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  2563. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  2564. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  2565. else
  2566. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  2567. }
  2568. //==============================================================================
  2569. class WindowedGLContext : public OpenGLContext
  2570. {
  2571. public:
  2572. WindowedGLContext (Component* const component_,
  2573. HGLRC contextToShareWith,
  2574. const OpenGLPixelFormat& pixelFormat)
  2575. : renderContext (0),
  2576. nativeWindow (0),
  2577. dc (0),
  2578. component (component_)
  2579. {
  2580. jassert (component != 0);
  2581. createNativeWindow();
  2582. // Use a default pixel format that should be supported everywhere
  2583. PIXELFORMATDESCRIPTOR pfd;
  2584. zerostruct (pfd);
  2585. pfd.nSize = sizeof (pfd);
  2586. pfd.nVersion = 1;
  2587. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  2588. pfd.iPixelType = PFD_TYPE_RGBA;
  2589. pfd.cColorBits = 24;
  2590. pfd.cDepthBits = 16;
  2591. const int format = ChoosePixelFormat (dc, &pfd);
  2592. if (format != 0)
  2593. SetPixelFormat (dc, format, &pfd);
  2594. renderContext = wglCreateContext (dc);
  2595. makeActive();
  2596. setPixelFormat (pixelFormat);
  2597. if (contextToShareWith != 0 && renderContext != 0)
  2598. wglShareLists (contextToShareWith, renderContext);
  2599. }
  2600. ~WindowedGLContext()
  2601. {
  2602. makeInactive();
  2603. wglDeleteContext (renderContext);
  2604. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  2605. delete nativeWindow;
  2606. }
  2607. bool makeActive() const throw()
  2608. {
  2609. jassert (renderContext != 0);
  2610. return wglMakeCurrent (dc, renderContext) != 0;
  2611. }
  2612. bool makeInactive() const throw()
  2613. {
  2614. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  2615. }
  2616. bool isActive() const throw()
  2617. {
  2618. return wglGetCurrentContext() == renderContext;
  2619. }
  2620. const OpenGLPixelFormat getPixelFormat() const
  2621. {
  2622. OpenGLPixelFormat pf;
  2623. makeActive();
  2624. StringArray availableExtensions;
  2625. getWglExtensions (dc, availableExtensions);
  2626. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  2627. return pf;
  2628. }
  2629. void* getRawContext() const throw()
  2630. {
  2631. return renderContext;
  2632. }
  2633. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  2634. {
  2635. makeActive();
  2636. PIXELFORMATDESCRIPTOR pfd;
  2637. zerostruct (pfd);
  2638. pfd.nSize = sizeof (pfd);
  2639. pfd.nVersion = 1;
  2640. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  2641. pfd.iPixelType = PFD_TYPE_RGBA;
  2642. pfd.iLayerType = PFD_MAIN_PLANE;
  2643. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  2644. pfd.cRedBits = pixelFormat.redBits;
  2645. pfd.cGreenBits = pixelFormat.greenBits;
  2646. pfd.cBlueBits = pixelFormat.blueBits;
  2647. pfd.cAlphaBits = pixelFormat.alphaBits;
  2648. pfd.cDepthBits = pixelFormat.depthBufferBits;
  2649. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  2650. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  2651. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  2652. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  2653. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  2654. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  2655. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  2656. int format = 0;
  2657. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  2658. StringArray availableExtensions;
  2659. getWglExtensions (dc, availableExtensions);
  2660. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  2661. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  2662. {
  2663. int attributes[64];
  2664. int n = 0;
  2665. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  2666. attributes[n++] = GL_TRUE;
  2667. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  2668. attributes[n++] = GL_TRUE;
  2669. attributes[n++] = WGL_ACCELERATION_ARB;
  2670. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  2671. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  2672. attributes[n++] = GL_TRUE;
  2673. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  2674. attributes[n++] = WGL_TYPE_RGBA_ARB;
  2675. attributes[n++] = WGL_COLOR_BITS_ARB;
  2676. attributes[n++] = pfd.cColorBits;
  2677. attributes[n++] = WGL_RED_BITS_ARB;
  2678. attributes[n++] = pixelFormat.redBits;
  2679. attributes[n++] = WGL_GREEN_BITS_ARB;
  2680. attributes[n++] = pixelFormat.greenBits;
  2681. attributes[n++] = WGL_BLUE_BITS_ARB;
  2682. attributes[n++] = pixelFormat.blueBits;
  2683. attributes[n++] = WGL_ALPHA_BITS_ARB;
  2684. attributes[n++] = pixelFormat.alphaBits;
  2685. attributes[n++] = WGL_DEPTH_BITS_ARB;
  2686. attributes[n++] = pixelFormat.depthBufferBits;
  2687. if (pixelFormat.stencilBufferBits > 0)
  2688. {
  2689. attributes[n++] = WGL_STENCIL_BITS_ARB;
  2690. attributes[n++] = pixelFormat.stencilBufferBits;
  2691. }
  2692. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  2693. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  2694. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  2695. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  2696. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  2697. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  2698. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  2699. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  2700. if (availableExtensions.contains ("WGL_ARB_multisample")
  2701. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  2702. {
  2703. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  2704. attributes[n++] = 1;
  2705. attributes[n++] = WGL_SAMPLES_ARB;
  2706. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  2707. }
  2708. attributes[n++] = 0;
  2709. UINT formatsCount;
  2710. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  2711. (void) ok;
  2712. jassert (ok);
  2713. }
  2714. else
  2715. {
  2716. format = ChoosePixelFormat (dc, &pfd);
  2717. }
  2718. if (format != 0)
  2719. {
  2720. makeInactive();
  2721. // win32 can't change the pixel format of a window, so need to delete the
  2722. // old one and create a new one..
  2723. jassert (nativeWindow != 0);
  2724. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  2725. delete nativeWindow;
  2726. createNativeWindow();
  2727. if (SetPixelFormat (dc, format, &pfd))
  2728. {
  2729. wglDeleteContext (renderContext);
  2730. renderContext = wglCreateContext (dc);
  2731. jassert (renderContext != 0);
  2732. return renderContext != 0;
  2733. }
  2734. }
  2735. return false;
  2736. }
  2737. void updateWindowPosition (int x, int y, int w, int h, int)
  2738. {
  2739. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  2740. x, y, w, h,
  2741. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  2742. }
  2743. void repaint()
  2744. {
  2745. int x, y, w, h;
  2746. nativeWindow->getBounds (x, y, w, h);
  2747. nativeWindow->repaint (0, 0, w, h);
  2748. }
  2749. void swapBuffers()
  2750. {
  2751. SwapBuffers (dc);
  2752. }
  2753. bool setSwapInterval (const int numFramesPerSwap)
  2754. {
  2755. makeActive();
  2756. StringArray availableExtensions;
  2757. getWglExtensions (dc, availableExtensions);
  2758. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  2759. return availableExtensions.contains ("WGL_EXT_swap_control")
  2760. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  2761. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  2762. }
  2763. int getSwapInterval() const
  2764. {
  2765. makeActive();
  2766. StringArray availableExtensions;
  2767. getWglExtensions (dc, availableExtensions);
  2768. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  2769. if (availableExtensions.contains ("WGL_EXT_swap_control")
  2770. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  2771. return wglGetSwapIntervalEXT();
  2772. return 0;
  2773. }
  2774. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  2775. {
  2776. jassert (isActive());
  2777. StringArray availableExtensions;
  2778. getWglExtensions (dc, availableExtensions);
  2779. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  2780. int numTypes = 0;
  2781. if (availableExtensions.contains("WGL_ARB_pixel_format")
  2782. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  2783. {
  2784. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  2785. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  2786. jassertfalse
  2787. }
  2788. else
  2789. {
  2790. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  2791. }
  2792. OpenGLPixelFormat pf;
  2793. for (int i = 0; i < numTypes; ++i)
  2794. {
  2795. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  2796. {
  2797. bool alreadyListed = false;
  2798. for (int j = results.size(); --j >= 0;)
  2799. if (pf == *results.getUnchecked(j))
  2800. alreadyListed = true;
  2801. if (! alreadyListed)
  2802. results.add (new OpenGLPixelFormat (pf));
  2803. }
  2804. }
  2805. }
  2806. //==============================================================================
  2807. juce_UseDebuggingNewOperator
  2808. HGLRC renderContext;
  2809. private:
  2810. Win32ComponentPeer* nativeWindow;
  2811. Component* const component;
  2812. HDC dc;
  2813. //==============================================================================
  2814. void createNativeWindow()
  2815. {
  2816. nativeWindow = new Win32ComponentPeer (component, 0);
  2817. nativeWindow->dontRepaint = true;
  2818. nativeWindow->setVisible (true);
  2819. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  2820. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2821. if (peer != 0)
  2822. {
  2823. SetParent (hwnd, (HWND) peer->getNativeHandle());
  2824. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  2825. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  2826. }
  2827. dc = GetDC (hwnd);
  2828. }
  2829. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  2830. OpenGLPixelFormat& result,
  2831. const StringArray& availableExtensions) const throw()
  2832. {
  2833. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  2834. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  2835. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  2836. {
  2837. int attributes[32];
  2838. int numAttributes = 0;
  2839. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  2840. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  2841. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  2842. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  2843. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  2844. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  2845. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  2846. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  2847. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  2848. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  2849. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  2850. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  2851. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  2852. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  2853. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  2854. if (availableExtensions.contains ("WGL_ARB_multisample"))
  2855. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  2856. int values[32];
  2857. zeromem (values, sizeof (values));
  2858. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  2859. {
  2860. int n = 0;
  2861. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  2862. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  2863. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  2864. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  2865. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  2866. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  2867. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  2868. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  2869. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  2870. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  2871. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  2872. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  2873. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  2874. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  2875. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  2876. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  2877. return isValidFormat;
  2878. }
  2879. else
  2880. {
  2881. jassertfalse
  2882. }
  2883. }
  2884. else
  2885. {
  2886. PIXELFORMATDESCRIPTOR pfd;
  2887. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  2888. {
  2889. result.redBits = pfd.cRedBits;
  2890. result.greenBits = pfd.cGreenBits;
  2891. result.blueBits = pfd.cBlueBits;
  2892. result.alphaBits = pfd.cAlphaBits;
  2893. result.depthBufferBits = pfd.cDepthBits;
  2894. result.stencilBufferBits = pfd.cStencilBits;
  2895. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  2896. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  2897. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  2898. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  2899. result.fullSceneAntiAliasingNumSamples = 0;
  2900. return true;
  2901. }
  2902. else
  2903. {
  2904. jassertfalse
  2905. }
  2906. }
  2907. return false;
  2908. }
  2909. WindowedGLContext (const WindowedGLContext&);
  2910. const WindowedGLContext& operator= (const WindowedGLContext&);
  2911. };
  2912. //==============================================================================
  2913. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  2914. const OpenGLPixelFormat& pixelFormat,
  2915. const OpenGLContext* const contextToShareWith)
  2916. {
  2917. WindowedGLContext* c = new WindowedGLContext (component,
  2918. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  2919. pixelFormat);
  2920. if (c->renderContext == 0)
  2921. deleteAndZero (c);
  2922. return c;
  2923. }
  2924. void juce_glViewport (const int w, const int h)
  2925. {
  2926. glViewport (0, 0, w, h);
  2927. }
  2928. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  2929. OwnedArray <OpenGLPixelFormat>& results)
  2930. {
  2931. Component tempComp;
  2932. {
  2933. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  2934. wc.makeActive();
  2935. wc.findAlternativeOpenGLPixelFormats (results);
  2936. }
  2937. }
  2938. #endif
  2939. //==============================================================================
  2940. //==============================================================================
  2941. class JuceIStorage : public IStorage
  2942. {
  2943. int refCount;
  2944. public:
  2945. JuceIStorage() : refCount (1) {}
  2946. virtual ~JuceIStorage()
  2947. {
  2948. jassert (refCount == 0);
  2949. }
  2950. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2951. {
  2952. if (id == IID_IUnknown || id == IID_IStorage)
  2953. {
  2954. AddRef();
  2955. *result = this;
  2956. return S_OK;
  2957. }
  2958. *result = 0;
  2959. return E_NOINTERFACE;
  2960. }
  2961. ULONG __stdcall AddRef() { return ++refCount; }
  2962. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  2963. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  2964. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  2965. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  2966. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  2967. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  2968. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  2969. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  2970. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  2971. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  2972. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  2973. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  2974. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  2975. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  2976. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  2977. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  2978. juce_UseDebuggingNewOperator
  2979. };
  2980. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  2981. {
  2982. int refCount;
  2983. HWND window;
  2984. public:
  2985. JuceOleInPlaceFrame (HWND window_)
  2986. : refCount (1),
  2987. window (window_)
  2988. {
  2989. }
  2990. virtual ~JuceOleInPlaceFrame()
  2991. {
  2992. jassert (refCount == 0);
  2993. }
  2994. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2995. {
  2996. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  2997. {
  2998. AddRef();
  2999. *result = this;
  3000. return S_OK;
  3001. }
  3002. *result = 0;
  3003. return E_NOINTERFACE;
  3004. }
  3005. ULONG __stdcall AddRef() { return ++refCount; }
  3006. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  3007. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  3008. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  3009. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  3010. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  3011. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  3012. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  3013. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  3014. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  3015. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  3016. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  3017. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  3018. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  3019. juce_UseDebuggingNewOperator
  3020. };
  3021. class JuceIOleInPlaceSite : public IOleInPlaceSite
  3022. {
  3023. int refCount;
  3024. HWND window;
  3025. JuceOleInPlaceFrame* frame;
  3026. public:
  3027. JuceIOleInPlaceSite (HWND window_)
  3028. : refCount (1),
  3029. window (window_)
  3030. {
  3031. frame = new JuceOleInPlaceFrame (window);
  3032. }
  3033. virtual ~JuceIOleInPlaceSite()
  3034. {
  3035. jassert (refCount == 0);
  3036. frame->Release();
  3037. }
  3038. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  3039. {
  3040. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  3041. {
  3042. AddRef();
  3043. *result = this;
  3044. return S_OK;
  3045. }
  3046. *result = 0;
  3047. return E_NOINTERFACE;
  3048. }
  3049. ULONG __stdcall AddRef() { return ++refCount; }
  3050. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  3051. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  3052. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  3053. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  3054. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  3055. HRESULT __stdcall OnUIActivate() { return S_OK; }
  3056. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  3057. {
  3058. frame->AddRef();
  3059. *lplpFrame = frame;
  3060. *lplpDoc = 0;
  3061. lpFrameInfo->fMDIApp = FALSE;
  3062. lpFrameInfo->hwndFrame = window;
  3063. lpFrameInfo->haccel = 0;
  3064. lpFrameInfo->cAccelEntries = 0;
  3065. return S_OK;
  3066. }
  3067. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  3068. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  3069. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  3070. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  3071. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  3072. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  3073. juce_UseDebuggingNewOperator
  3074. };
  3075. class JuceIOleClientSite : public IOleClientSite
  3076. {
  3077. int refCount;
  3078. JuceIOleInPlaceSite* inplaceSite;
  3079. public:
  3080. JuceIOleClientSite (HWND window)
  3081. : refCount (1)
  3082. {
  3083. inplaceSite = new JuceIOleInPlaceSite (window);
  3084. }
  3085. virtual ~JuceIOleClientSite()
  3086. {
  3087. jassert (refCount == 0);
  3088. inplaceSite->Release();
  3089. }
  3090. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  3091. {
  3092. if (id == IID_IUnknown || id == IID_IOleClientSite)
  3093. {
  3094. AddRef();
  3095. *result = this;
  3096. return S_OK;
  3097. }
  3098. else if (id == IID_IOleInPlaceSite)
  3099. {
  3100. inplaceSite->AddRef();
  3101. *result = inplaceSite;
  3102. return S_OK;
  3103. }
  3104. *result = 0;
  3105. return E_NOINTERFACE;
  3106. }
  3107. ULONG __stdcall AddRef() { return ++refCount; }
  3108. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  3109. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  3110. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  3111. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  3112. HRESULT __stdcall ShowObject() { return S_OK; }
  3113. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  3114. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  3115. juce_UseDebuggingNewOperator
  3116. };
  3117. //==============================================================================
  3118. class ActiveXControlData : public ComponentMovementWatcher
  3119. {
  3120. ActiveXControlComponent* const owner;
  3121. bool wasShowing;
  3122. public:
  3123. IStorage* storage;
  3124. IOleClientSite* clientSite;
  3125. IOleObject* control;
  3126. //==============================================================================
  3127. ActiveXControlData (HWND hwnd,
  3128. ActiveXControlComponent* const owner_)
  3129. : ComponentMovementWatcher (owner_),
  3130. owner (owner_),
  3131. wasShowing (owner_ != 0 && owner_->isShowing()),
  3132. storage (new JuceIStorage()),
  3133. clientSite (new JuceIOleClientSite (hwnd)),
  3134. control (0)
  3135. {
  3136. }
  3137. ~ActiveXControlData()
  3138. {
  3139. if (control != 0)
  3140. {
  3141. control->Close (OLECLOSE_NOSAVE);
  3142. control->Release();
  3143. }
  3144. clientSite->Release();
  3145. storage->Release();
  3146. }
  3147. //==============================================================================
  3148. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  3149. {
  3150. Component* const topComp = owner->getTopLevelComponent();
  3151. if (topComp->getPeer() != 0)
  3152. {
  3153. int x = 0, y = 0;
  3154. owner->relativePositionToOtherComponent (topComp, x, y);
  3155. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  3156. }
  3157. }
  3158. void componentPeerChanged()
  3159. {
  3160. const bool isShowingNow = owner->isShowing();
  3161. if (wasShowing != isShowingNow)
  3162. {
  3163. wasShowing = isShowingNow;
  3164. owner->setControlVisible (isShowingNow);
  3165. }
  3166. }
  3167. void componentVisibilityChanged (Component&)
  3168. {
  3169. componentPeerChanged();
  3170. }
  3171. };
  3172. //==============================================================================
  3173. static VoidArray activeXComps;
  3174. static HWND getHWND (const ActiveXControlComponent* const component)
  3175. {
  3176. HWND hwnd = 0;
  3177. const IID iid = IID_IOleWindow;
  3178. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  3179. if (window != 0)
  3180. {
  3181. window->GetWindow (&hwnd);
  3182. window->Release();
  3183. }
  3184. return hwnd;
  3185. }
  3186. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  3187. {
  3188. RECT activeXRect, peerRect;
  3189. GetWindowRect (hwnd, &activeXRect);
  3190. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  3191. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  3192. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  3193. const int64 mouseEventTime = getMouseEventTime();
  3194. const int oldModifiers = currentModifiers;
  3195. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  3196. switch (message)
  3197. {
  3198. case WM_MOUSEMOVE:
  3199. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  3200. peer->handleMouseDrag (mx, my, mouseEventTime);
  3201. else
  3202. peer->handleMouseMove (mx, my, mouseEventTime);
  3203. break;
  3204. case WM_LBUTTONDOWN:
  3205. case WM_MBUTTONDOWN:
  3206. case WM_RBUTTONDOWN:
  3207. peer->handleMouseDown (mx, my, mouseEventTime);
  3208. break;
  3209. case WM_LBUTTONUP:
  3210. case WM_MBUTTONUP:
  3211. case WM_RBUTTONUP:
  3212. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  3213. break;
  3214. default:
  3215. break;
  3216. }
  3217. }
  3218. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  3219. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  3220. {
  3221. for (int i = activeXComps.size(); --i >= 0;)
  3222. {
  3223. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  3224. HWND controlHWND = getHWND (ax);
  3225. if (controlHWND == hwnd)
  3226. {
  3227. switch (message)
  3228. {
  3229. case WM_MOUSEMOVE:
  3230. case WM_LBUTTONDOWN:
  3231. case WM_MBUTTONDOWN:
  3232. case WM_RBUTTONDOWN:
  3233. case WM_LBUTTONUP:
  3234. case WM_MBUTTONUP:
  3235. case WM_RBUTTONUP:
  3236. if (ax->isShowing())
  3237. {
  3238. ComponentPeer* const peer = ax->getPeer();
  3239. if (peer != 0)
  3240. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  3241. }
  3242. break;
  3243. default:
  3244. break;
  3245. }
  3246. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  3247. }
  3248. }
  3249. return DefWindowProc (hwnd, message, wParam, lParam);
  3250. }
  3251. ActiveXControlComponent::ActiveXControlComponent()
  3252. : originalWndProc (0),
  3253. control (0)
  3254. {
  3255. activeXComps.add (this);
  3256. }
  3257. ActiveXControlComponent::~ActiveXControlComponent()
  3258. {
  3259. deleteControl();
  3260. activeXComps.removeValue (this);
  3261. }
  3262. void ActiveXControlComponent::paint (Graphics& g)
  3263. {
  3264. if (control == 0)
  3265. g.fillAll (Colours::lightgrey);
  3266. }
  3267. bool ActiveXControlComponent::createControl (const void* controlIID)
  3268. {
  3269. deleteControl();
  3270. ComponentPeer* const peer = getPeer();
  3271. // the component must have already been added to a real window when you call this!
  3272. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  3273. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  3274. {
  3275. int x = 0, y = 0;
  3276. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  3277. HWND hwnd = (HWND) peer->getNativeHandle();
  3278. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  3279. HRESULT hr;
  3280. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  3281. info->clientSite, info->storage,
  3282. (void**) &(info->control))) == S_OK)
  3283. {
  3284. info->control->SetHostNames (L"Juce", 0);
  3285. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  3286. {
  3287. RECT rect;
  3288. rect.left = x;
  3289. rect.top = y;
  3290. rect.right = x + getWidth();
  3291. rect.bottom = y + getHeight();
  3292. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  3293. {
  3294. control = info;
  3295. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  3296. HWND controlHWND = getHWND (this);
  3297. if (controlHWND != 0)
  3298. {
  3299. originalWndProc = (void*) GetWindowLongPtr (controlHWND, GWLP_WNDPROC);
  3300. SetWindowLongPtr (controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  3301. }
  3302. return true;
  3303. }
  3304. }
  3305. }
  3306. delete info;
  3307. }
  3308. return false;
  3309. }
  3310. void ActiveXControlComponent::deleteControl()
  3311. {
  3312. ActiveXControlData* const info = (ActiveXControlData*) control;
  3313. if (info != 0)
  3314. {
  3315. delete info;
  3316. control = 0;
  3317. originalWndProc = 0;
  3318. }
  3319. }
  3320. void* ActiveXControlComponent::queryInterface (const void* iid) const
  3321. {
  3322. ActiveXControlData* const info = (ActiveXControlData*) control;
  3323. void* result = 0;
  3324. if (info != 0 && info->control != 0
  3325. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  3326. return result;
  3327. return 0;
  3328. }
  3329. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  3330. {
  3331. HWND hwnd = getHWND (this);
  3332. if (hwnd != 0)
  3333. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  3334. }
  3335. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  3336. {
  3337. HWND hwnd = getHWND (this);
  3338. if (hwnd != 0)
  3339. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  3340. }
  3341. END_JUCE_NAMESPACE