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.

4174 lines
140KB

  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. {
  1364. MSG msg;
  1365. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  1366. {
  1367. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  1368. // manually generate the key-press event that matches this key-down.
  1369. #if JUCE_ENABLE_WIN98_COMPATIBILITY
  1370. const UINT keyChar = wMapVirtualKeyW != 0 ? wMapVirtualKeyW (key, 2)
  1371. : MapVirtualKey (key, 2);
  1372. #else
  1373. const UINT keyChar = MapVirtualKeyW (key, 2);
  1374. #endif
  1375. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  1376. }
  1377. }
  1378. break;
  1379. }
  1380. return used;
  1381. }
  1382. bool doKeyChar (int key, const LPARAM flags)
  1383. {
  1384. updateKeyModifiers();
  1385. juce_wchar textChar = (juce_wchar) key;
  1386. const int virtualScanCode = (flags >> 16) & 0xff;
  1387. if (key >= '0' && key <= '9')
  1388. {
  1389. switch (virtualScanCode) // check for a numeric keypad scan-code
  1390. {
  1391. case 0x52:
  1392. case 0x4f:
  1393. case 0x50:
  1394. case 0x51:
  1395. case 0x4b:
  1396. case 0x4c:
  1397. case 0x4d:
  1398. case 0x47:
  1399. case 0x48:
  1400. case 0x49:
  1401. key = (key - '0') + KeyPress::numberPad0;
  1402. break;
  1403. default:
  1404. break;
  1405. }
  1406. }
  1407. else
  1408. {
  1409. // convert the scan code to an unmodified character code..
  1410. #if JUCE_ENABLE_WIN98_COMPATIBILITY
  1411. const UINT virtualKey = wMapVirtualKeyW != 0 ? wMapVirtualKeyW (virtualScanCode, 1)
  1412. : MapVirtualKey (virtualScanCode, 1);
  1413. UINT keyChar = wMapVirtualKeyW != 0 ? wMapVirtualKeyW (virtualKey, 2)
  1414. : MapVirtualKey (virtualKey, 2);
  1415. if (wToUnicode != 0)
  1416. {
  1417. BYTE keyState[256];
  1418. GetKeyboardState (keyState);
  1419. WCHAR unicodeChar[32];
  1420. const DWORD converted = wToUnicode (virtualKey, virtualScanCode, keyState,
  1421. unicodeChar, 32, 0);
  1422. if (converted > 0)
  1423. {
  1424. // ahem.. can't actually remember why this section of code was originall here,
  1425. // so if you see this assertion, please let me know what you were doing at
  1426. // the time!
  1427. jassert (textChar == unicodeChar[0]);
  1428. // textChar = unicodeChar[0];
  1429. }
  1430. }
  1431. #else
  1432. const UINT virtualKey = MapVirtualKeyW (virtualScanCode, 1);
  1433. UINT keyChar = MapVirtualKeyW (virtualKey, 2);
  1434. {
  1435. BYTE keyState[256];
  1436. GetKeyboardState (keyState);
  1437. WCHAR unicodeChar[32];
  1438. const DWORD converted = ToUnicode (virtualKey, virtualScanCode, keyState,
  1439. unicodeChar, 32, 0);
  1440. if (converted > 0)
  1441. {
  1442. // ahem.. can't actually remember why this section of code was originall here,
  1443. // so if you see this assertion, please let me know what you were doing at
  1444. // the time!
  1445. jassert (textChar == unicodeChar[0]);
  1446. // textChar = unicodeChar[0];
  1447. }
  1448. }
  1449. #endif
  1450. keyChar = LOWORD (keyChar);
  1451. if (keyChar != 0)
  1452. key = (int) keyChar;
  1453. // avoid sending junk text characters for some control-key combinations
  1454. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  1455. textChar = 0;
  1456. }
  1457. return handleKeyPress (key, textChar);
  1458. }
  1459. bool doAppCommand (const LPARAM lParam)
  1460. {
  1461. int key = 0;
  1462. switch (GET_APPCOMMAND_LPARAM (lParam))
  1463. {
  1464. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  1465. key = KeyPress::playKey;
  1466. break;
  1467. case APPCOMMAND_MEDIA_STOP:
  1468. key = KeyPress::stopKey;
  1469. break;
  1470. case APPCOMMAND_MEDIA_NEXTTRACK:
  1471. key = KeyPress::fastForwardKey;
  1472. break;
  1473. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  1474. key = KeyPress::rewindKey;
  1475. break;
  1476. }
  1477. if (key != 0)
  1478. {
  1479. updateKeyModifiers();
  1480. if (hwnd == GetActiveWindow())
  1481. {
  1482. handleKeyPress (key, 0);
  1483. return true;
  1484. }
  1485. }
  1486. return false;
  1487. }
  1488. //==============================================================================
  1489. class JuceDropTarget : public IDropTarget
  1490. {
  1491. public:
  1492. JuceDropTarget (Win32ComponentPeer* const owner_)
  1493. : owner (owner_),
  1494. refCount (1)
  1495. {
  1496. }
  1497. virtual ~JuceDropTarget()
  1498. {
  1499. jassert (refCount == 0);
  1500. }
  1501. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  1502. {
  1503. if (id == IID_IUnknown || id == IID_IDropTarget)
  1504. {
  1505. AddRef();
  1506. *result = this;
  1507. return S_OK;
  1508. }
  1509. *result = 0;
  1510. return E_NOINTERFACE;
  1511. }
  1512. ULONG __stdcall AddRef() { return ++refCount; }
  1513. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  1514. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1515. {
  1516. updateFileList (pDataObject);
  1517. int x = mousePos.x, y = mousePos.y;
  1518. owner->globalPositionToRelative (x, y);
  1519. owner->handleFileDragMove (files, x, y);
  1520. *pdwEffect = DROPEFFECT_COPY;
  1521. return S_OK;
  1522. }
  1523. HRESULT __stdcall DragLeave()
  1524. {
  1525. owner->handleFileDragExit (files);
  1526. return S_OK;
  1527. }
  1528. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1529. {
  1530. int x = mousePos.x, y = mousePos.y;
  1531. owner->globalPositionToRelative (x, y);
  1532. owner->handleFileDragMove (files, x, y);
  1533. *pdwEffect = DROPEFFECT_COPY;
  1534. return S_OK;
  1535. }
  1536. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  1537. {
  1538. updateFileList (pDataObject);
  1539. int x = mousePos.x, y = mousePos.y;
  1540. owner->globalPositionToRelative (x, y);
  1541. owner->handleFileDragDrop (files, x, y);
  1542. *pdwEffect = DROPEFFECT_COPY;
  1543. return S_OK;
  1544. }
  1545. private:
  1546. Win32ComponentPeer* const owner;
  1547. int refCount;
  1548. StringArray files;
  1549. void updateFileList (IDataObject* const pDataObject)
  1550. {
  1551. files.clear();
  1552. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1553. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  1554. if (pDataObject->GetData (&format, &medium) == S_OK)
  1555. {
  1556. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  1557. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  1558. unsigned int i = 0;
  1559. if (pDropFiles->fWide)
  1560. {
  1561. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  1562. for (;;)
  1563. {
  1564. unsigned int len = 0;
  1565. while (i + len < totalLen && fname [i + len] != 0)
  1566. ++len;
  1567. if (len == 0)
  1568. break;
  1569. files.add (String (fname + i, len));
  1570. i += len + 1;
  1571. }
  1572. }
  1573. else
  1574. {
  1575. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  1576. for (;;)
  1577. {
  1578. unsigned int len = 0;
  1579. while (i + len < totalLen && fname [i + len] != 0)
  1580. ++len;
  1581. if (len == 0)
  1582. break;
  1583. files.add (String (fname + i, len));
  1584. i += len + 1;
  1585. }
  1586. }
  1587. GlobalUnlock (medium.hGlobal);
  1588. }
  1589. }
  1590. JuceDropTarget (const JuceDropTarget&);
  1591. const JuceDropTarget& operator= (const JuceDropTarget&);
  1592. };
  1593. void doSettingChange()
  1594. {
  1595. Desktop::getInstance().refreshMonitorSizes();
  1596. if (fullScreen && ! isMinimised())
  1597. {
  1598. const Rectangle r (component->getParentMonitorArea());
  1599. SetWindowPos (hwnd, 0,
  1600. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  1601. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  1602. }
  1603. }
  1604. //==============================================================================
  1605. public:
  1606. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1607. {
  1608. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  1609. if (peer != 0)
  1610. return peer->peerWindowProc (h, message, wParam, lParam);
  1611. return DefWindowProc (h, message, wParam, lParam);
  1612. }
  1613. private:
  1614. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1615. {
  1616. {
  1617. const MessageManagerLock messLock;
  1618. if (isValidPeer (this))
  1619. {
  1620. switch (message)
  1621. {
  1622. case WM_NCHITTEST:
  1623. if (hasTitleBar())
  1624. break;
  1625. return HTCLIENT;
  1626. //==============================================================================
  1627. case WM_PAINT:
  1628. handlePaintMessage();
  1629. return 0;
  1630. case WM_NCPAINT:
  1631. if (wParam != 1)
  1632. handlePaintMessage();
  1633. if (hasTitleBar())
  1634. break;
  1635. return 0;
  1636. case WM_ERASEBKGND:
  1637. case WM_NCCALCSIZE:
  1638. if (hasTitleBar())
  1639. break;
  1640. return 1;
  1641. //==============================================================================
  1642. case WM_MOUSEMOVE:
  1643. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  1644. return 0;
  1645. case WM_MOUSELEAVE:
  1646. doMouseExit();
  1647. return 0;
  1648. case WM_LBUTTONDOWN:
  1649. case WM_MBUTTONDOWN:
  1650. case WM_RBUTTONDOWN:
  1651. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1652. return 0;
  1653. case WM_LBUTTONUP:
  1654. case WM_MBUTTONUP:
  1655. case WM_RBUTTONUP:
  1656. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  1657. return 0;
  1658. case WM_CAPTURECHANGED:
  1659. doCaptureChanged();
  1660. return 0;
  1661. case WM_NCMOUSEMOVE:
  1662. if (hasTitleBar())
  1663. break;
  1664. return 0;
  1665. case 0x020A: /* WM_MOUSEWHEEL */
  1666. doMouseWheel (wParam, true);
  1667. return 0;
  1668. case 0x020E: /* WM_MOUSEHWHEEL */
  1669. doMouseWheel (wParam, false);
  1670. return 0;
  1671. //==============================================================================
  1672. case WM_WINDOWPOSCHANGING:
  1673. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  1674. {
  1675. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  1676. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  1677. {
  1678. if (constrainer != 0)
  1679. {
  1680. const Rectangle current (component->getX() - windowBorder.getLeft(),
  1681. component->getY() - windowBorder.getTop(),
  1682. component->getWidth() + windowBorder.getLeftAndRight(),
  1683. component->getHeight() + windowBorder.getTopAndBottom());
  1684. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  1685. current,
  1686. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  1687. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  1688. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  1689. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  1690. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  1691. }
  1692. }
  1693. }
  1694. return 0;
  1695. case WM_WINDOWPOSCHANGED:
  1696. handleMovedOrResized();
  1697. if (dontRepaint)
  1698. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  1699. else
  1700. return 0;
  1701. //==============================================================================
  1702. case WM_KEYDOWN:
  1703. case WM_SYSKEYDOWN:
  1704. if (doKeyDown (wParam))
  1705. return 0;
  1706. break;
  1707. case WM_KEYUP:
  1708. case WM_SYSKEYUP:
  1709. if (doKeyUp (wParam))
  1710. return 0;
  1711. break;
  1712. case WM_CHAR:
  1713. if (doKeyChar ((int) wParam, lParam))
  1714. return 0;
  1715. break;
  1716. case WM_APPCOMMAND:
  1717. if (doAppCommand (lParam))
  1718. return TRUE;
  1719. break;
  1720. //==============================================================================
  1721. case WM_SETFOCUS:
  1722. updateKeyModifiers();
  1723. handleFocusGain();
  1724. break;
  1725. case WM_KILLFOCUS:
  1726. handleFocusLoss();
  1727. break;
  1728. case WM_ACTIVATEAPP:
  1729. // Windows does weird things to process priority when you swap apps,
  1730. // so this forces an update when the app is brought to the front
  1731. if (wParam != FALSE)
  1732. juce_repeatLastProcessPriority();
  1733. juce_CheckCurrentlyFocusedTopLevelWindow();
  1734. modifiersAtLastCallback = -1;
  1735. return 0;
  1736. case WM_ACTIVATE:
  1737. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  1738. {
  1739. modifiersAtLastCallback = -1;
  1740. updateKeyModifiers();
  1741. if (isMinimised())
  1742. {
  1743. component->repaint();
  1744. handleMovedOrResized();
  1745. if (! isValidMessageListener())
  1746. return 0;
  1747. }
  1748. if (LOWORD (wParam) == WA_CLICKACTIVE
  1749. && component->isCurrentlyBlockedByAnotherModalComponent())
  1750. {
  1751. int mx, my;
  1752. component->getMouseXYRelative (mx, my);
  1753. Component* const underMouse = component->getComponentAt (mx, my);
  1754. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  1755. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1756. return 0;
  1757. }
  1758. handleBroughtToFront();
  1759. return 0;
  1760. }
  1761. break;
  1762. case WM_NCACTIVATE:
  1763. // while a temporary window is being shown, prevent Windows from deactivating the
  1764. // title bars of our main windows.
  1765. if (wParam == 0 && ! shouldDeactivateTitleBar)
  1766. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  1767. break;
  1768. case WM_MOUSEACTIVATE:
  1769. if (! component->getMouseClickGrabsKeyboardFocus())
  1770. return MA_NOACTIVATE;
  1771. break;
  1772. case WM_SHOWWINDOW:
  1773. if (wParam != 0)
  1774. handleBroughtToFront();
  1775. break;
  1776. case WM_CLOSE:
  1777. handleUserClosingWindow();
  1778. return 0;
  1779. //==============================================================================
  1780. case WM_TRAYNOTIFY:
  1781. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1782. {
  1783. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  1784. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1785. {
  1786. Component* const current = Component::getCurrentlyModalComponent();
  1787. if (current != 0)
  1788. current->inputAttemptWhenModal();
  1789. }
  1790. }
  1791. else
  1792. {
  1793. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  1794. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  1795. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  1796. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  1797. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  1798. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  1799. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  1800. {
  1801. SetFocus (hwnd);
  1802. SetForegroundWindow (hwnd);
  1803. component->mouseDown (e);
  1804. }
  1805. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  1806. component->mouseUp (e);
  1807. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  1808. component->mouseDoubleClick (e);
  1809. else if (lParam == WM_MOUSEMOVE)
  1810. component->mouseMove (e);
  1811. }
  1812. break;
  1813. //==============================================================================
  1814. case WM_SYNCPAINT:
  1815. return 0;
  1816. case WM_PALETTECHANGED:
  1817. InvalidateRect (h, 0, 0);
  1818. break;
  1819. case WM_DISPLAYCHANGE:
  1820. InvalidateRect (h, 0, 0);
  1821. createPaletteIfNeeded = true;
  1822. // intentional fall-through...
  1823. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  1824. doSettingChange();
  1825. break;
  1826. case WM_INITMENU:
  1827. if (! hasTitleBar())
  1828. {
  1829. if (isFullScreen())
  1830. {
  1831. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  1832. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  1833. }
  1834. else if (! isMinimised())
  1835. {
  1836. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  1837. }
  1838. }
  1839. break;
  1840. case WM_SYSCOMMAND:
  1841. switch (wParam & 0xfff0)
  1842. {
  1843. case SC_CLOSE:
  1844. if (hasTitleBar())
  1845. {
  1846. PostMessage (h, WM_CLOSE, 0, 0);
  1847. return 0;
  1848. }
  1849. break;
  1850. case SC_KEYMENU:
  1851. if (hasTitleBar() && h == GetCapture())
  1852. ReleaseCapture();
  1853. break;
  1854. case SC_MAXIMIZE:
  1855. setFullScreen (true);
  1856. return 0;
  1857. case SC_MINIMIZE:
  1858. if (! hasTitleBar())
  1859. {
  1860. setMinimised (true);
  1861. return 0;
  1862. }
  1863. break;
  1864. case SC_RESTORE:
  1865. if (hasTitleBar())
  1866. {
  1867. if (isFullScreen())
  1868. {
  1869. setFullScreen (false);
  1870. return 0;
  1871. }
  1872. }
  1873. else
  1874. {
  1875. if (isMinimised())
  1876. setMinimised (false);
  1877. else if (isFullScreen())
  1878. setFullScreen (false);
  1879. return 0;
  1880. }
  1881. break;
  1882. case SC_MONITORPOWER:
  1883. case SC_SCREENSAVE:
  1884. if (! screenSaverAllowed)
  1885. return 0;
  1886. break;
  1887. }
  1888. break;
  1889. case WM_NCLBUTTONDOWN:
  1890. case WM_NCRBUTTONDOWN:
  1891. case WM_NCMBUTTONDOWN:
  1892. if (component->isCurrentlyBlockedByAnotherModalComponent())
  1893. {
  1894. Component* const current = Component::getCurrentlyModalComponent();
  1895. if (current != 0)
  1896. current->inputAttemptWhenModal();
  1897. }
  1898. break;
  1899. //case WM_IME_STARTCOMPOSITION;
  1900. // return 0;
  1901. case WM_GETDLGCODE:
  1902. return DLGC_WANTALLKEYS;
  1903. default:
  1904. break;
  1905. }
  1906. }
  1907. }
  1908. // (the message manager lock exits before calling this, to avoid deadlocks if
  1909. // this calls into non-juce windows)
  1910. return DefWindowProc (h, message, wParam, lParam);
  1911. }
  1912. Win32ComponentPeer (const Win32ComponentPeer&);
  1913. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  1914. };
  1915. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  1916. {
  1917. return new Win32ComponentPeer (this, styleFlags);
  1918. }
  1919. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  1920. //==============================================================================
  1921. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  1922. {
  1923. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1924. if (wp != 0)
  1925. wp->setTaskBarIcon (&newImage);
  1926. }
  1927. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  1928. {
  1929. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  1930. if (wp != 0)
  1931. wp->setTaskBarIconToolTip (tooltip);
  1932. }
  1933. //==============================================================================
  1934. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  1935. {
  1936. DWORD val = GetWindowLong (h, styleType);
  1937. if (bitIsSet)
  1938. val |= feature;
  1939. else
  1940. val &= ~feature;
  1941. SetWindowLongPtr (h, styleType, val);
  1942. SetWindowPos (h, 0, 0, 0, 0, 0,
  1943. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  1944. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  1945. }
  1946. //==============================================================================
  1947. bool Process::isForegroundProcess() throw()
  1948. {
  1949. HWND fg = GetForegroundWindow();
  1950. if (fg == 0)
  1951. return true;
  1952. DWORD processId = 0;
  1953. GetWindowThreadProcessId (fg, &processId);
  1954. return processId == GetCurrentProcessId();
  1955. }
  1956. //==============================================================================
  1957. void Desktop::getMousePosition (int& x, int& y) throw()
  1958. {
  1959. POINT mousePos;
  1960. GetCursorPos (&mousePos);
  1961. x = mousePos.x;
  1962. y = mousePos.y;
  1963. }
  1964. void Desktop::setMousePosition (int x, int y) throw()
  1965. {
  1966. SetCursorPos (x, y);
  1967. }
  1968. //==============================================================================
  1969. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1970. {
  1971. screenSaverAllowed = isEnabled;
  1972. }
  1973. bool Desktop::isScreenSaverEnabled() throw()
  1974. {
  1975. return screenSaverAllowed;
  1976. }
  1977. //==============================================================================
  1978. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  1979. {
  1980. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  1981. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  1982. return TRUE;
  1983. }
  1984. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1985. {
  1986. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  1987. // make sure the first in the list is the main monitor
  1988. for (int i = 1; i < monitorCoords.size(); ++i)
  1989. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  1990. monitorCoords.swap (i, 0);
  1991. if (monitorCoords.size() == 0)
  1992. {
  1993. RECT r;
  1994. GetWindowRect (GetDesktopWindow(), &r);
  1995. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  1996. }
  1997. if (clipToWorkArea)
  1998. {
  1999. // clip the main monitor to the active non-taskbar area
  2000. RECT r;
  2001. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  2002. Rectangle& screen = monitorCoords.getReference (0);
  2003. screen.setPosition (jmax (screen.getX(), r.left),
  2004. jmax (screen.getY(), r.top));
  2005. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  2006. jmin (screen.getBottom(), r.bottom) - screen.getY());
  2007. }
  2008. }
  2009. //==============================================================================
  2010. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  2011. {
  2012. Image* im = 0;
  2013. if (bitmap != 0)
  2014. {
  2015. BITMAP bm;
  2016. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  2017. && bm.bmWidth > 0 && bm.bmHeight > 0)
  2018. {
  2019. HDC tempDC = GetDC (0);
  2020. HDC dc = CreateCompatibleDC (tempDC);
  2021. ReleaseDC (0, tempDC);
  2022. SelectObject (dc, bitmap);
  2023. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  2024. for (int y = bm.bmHeight; --y >= 0;)
  2025. {
  2026. for (int x = bm.bmWidth; --x >= 0;)
  2027. {
  2028. COLORREF col = GetPixel (dc, x, y);
  2029. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  2030. (uint8) GetGValue (col),
  2031. (uint8) GetBValue (col)));
  2032. }
  2033. }
  2034. DeleteDC (dc);
  2035. }
  2036. }
  2037. return im;
  2038. }
  2039. static Image* createImageFromHICON (HICON icon) throw()
  2040. {
  2041. ICONINFO info;
  2042. if (GetIconInfo (icon, &info))
  2043. {
  2044. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  2045. if (mask == 0)
  2046. return 0;
  2047. Image* const image = createImageFromHBITMAP (info.hbmColor);
  2048. if (image == 0)
  2049. return mask;
  2050. for (int y = image->getHeight(); --y >= 0;)
  2051. {
  2052. for (int x = image->getWidth(); --x >= 0;)
  2053. {
  2054. const float brightness = mask->getPixelAt (x, y).getBrightness();
  2055. if (brightness > 0.0f)
  2056. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  2057. }
  2058. }
  2059. delete mask;
  2060. return image;
  2061. }
  2062. return 0;
  2063. }
  2064. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  2065. {
  2066. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  2067. ICONINFO info;
  2068. info.fIcon = isIcon;
  2069. info.xHotspot = hotspotX;
  2070. info.yHotspot = hotspotY;
  2071. info.hbmMask = mask;
  2072. HICON hi = 0;
  2073. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  2074. {
  2075. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  2076. Graphics g (bitmap);
  2077. g.drawImageAt (&image, 0, 0);
  2078. info.hbmColor = bitmap.hBitmap;
  2079. hi = CreateIconIndirect (&info);
  2080. }
  2081. else
  2082. {
  2083. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  2084. HDC colDC = CreateCompatibleDC (GetDC (0));
  2085. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  2086. SelectObject (colDC, colour);
  2087. SelectObject (alphaDC, mask);
  2088. for (int y = image.getHeight(); --y >= 0;)
  2089. {
  2090. for (int x = image.getWidth(); --x >= 0;)
  2091. {
  2092. const Colour c (image.getPixelAt (x, y));
  2093. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  2094. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  2095. }
  2096. }
  2097. DeleteDC (colDC);
  2098. DeleteDC (alphaDC);
  2099. info.hbmColor = colour;
  2100. hi = CreateIconIndirect (&info);
  2101. DeleteObject (colour);
  2102. }
  2103. DeleteObject (mask);
  2104. return hi;
  2105. }
  2106. Image* juce_createIconForFile (const File& file)
  2107. {
  2108. Image* image = 0;
  2109. TCHAR filename [1024];
  2110. file.getFullPathName().copyToBuffer (filename, 1023);
  2111. WORD iconNum = 0;
  2112. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  2113. filename, &iconNum);
  2114. if (icon != 0)
  2115. {
  2116. image = createImageFromHICON (icon);
  2117. DestroyIcon (icon);
  2118. }
  2119. return image;
  2120. }
  2121. //==============================================================================
  2122. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  2123. {
  2124. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  2125. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  2126. const Image* im = &image;
  2127. Image* newIm = 0;
  2128. if (image.getWidth() > maxW || image.getHeight() > maxH)
  2129. {
  2130. im = newIm = image.createCopy (maxW, maxH);
  2131. hotspotX = (hotspotX * maxW) / image.getWidth();
  2132. hotspotY = (hotspotY * maxH) / image.getHeight();
  2133. }
  2134. void* cursorH = 0;
  2135. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  2136. if (os == SystemStats::WinXP)
  2137. {
  2138. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  2139. }
  2140. else
  2141. {
  2142. const int stride = (maxW + 7) >> 3;
  2143. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  2144. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  2145. int index = 0;
  2146. for (int y = 0; y < maxH; ++y)
  2147. {
  2148. for (int x = 0; x < maxW; ++x)
  2149. {
  2150. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  2151. const Colour pixelColour (im->getPixelAt (x, y));
  2152. if (pixelColour.getAlpha() < 127)
  2153. andPlane [index + (x >> 3)] |= bit;
  2154. else if (pixelColour.getBrightness() >= 0.5f)
  2155. xorPlane [index + (x >> 3)] |= bit;
  2156. }
  2157. index += stride;
  2158. }
  2159. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  2160. juce_free (andPlane);
  2161. juce_free (xorPlane);
  2162. }
  2163. delete newIm;
  2164. return cursorH;
  2165. }
  2166. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2167. {
  2168. if (cursorHandle != 0 && ! isStandard)
  2169. DestroyCursor ((HCURSOR) cursorHandle);
  2170. }
  2171. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  2172. {
  2173. LPCTSTR cursorName = IDC_ARROW;
  2174. switch (type)
  2175. {
  2176. case MouseCursor::NormalCursor:
  2177. cursorName = IDC_ARROW;
  2178. break;
  2179. case MouseCursor::NoCursor:
  2180. return 0;
  2181. case MouseCursor::DraggingHandCursor:
  2182. {
  2183. static void* dragHandCursor = 0;
  2184. if (dragHandCursor == 0)
  2185. {
  2186. static const unsigned char dragHandData[] =
  2187. { 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,
  2188. 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,
  2189. 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 };
  2190. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  2191. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  2192. delete image;
  2193. }
  2194. return dragHandCursor;
  2195. }
  2196. case MouseCursor::WaitCursor:
  2197. cursorName = IDC_WAIT;
  2198. break;
  2199. case MouseCursor::IBeamCursor:
  2200. cursorName = IDC_IBEAM;
  2201. break;
  2202. case MouseCursor::PointingHandCursor:
  2203. cursorName = MAKEINTRESOURCE(32649);
  2204. break;
  2205. case MouseCursor::LeftRightResizeCursor:
  2206. case MouseCursor::LeftEdgeResizeCursor:
  2207. case MouseCursor::RightEdgeResizeCursor:
  2208. cursorName = IDC_SIZEWE;
  2209. break;
  2210. case MouseCursor::UpDownResizeCursor:
  2211. case MouseCursor::TopEdgeResizeCursor:
  2212. case MouseCursor::BottomEdgeResizeCursor:
  2213. cursorName = IDC_SIZENS;
  2214. break;
  2215. case MouseCursor::TopLeftCornerResizeCursor:
  2216. case MouseCursor::BottomRightCornerResizeCursor:
  2217. cursorName = IDC_SIZENWSE;
  2218. break;
  2219. case MouseCursor::TopRightCornerResizeCursor:
  2220. case MouseCursor::BottomLeftCornerResizeCursor:
  2221. cursorName = IDC_SIZENESW;
  2222. break;
  2223. case MouseCursor::UpDownLeftRightResizeCursor:
  2224. cursorName = IDC_SIZEALL;
  2225. break;
  2226. case MouseCursor::CrosshairCursor:
  2227. cursorName = IDC_CROSS;
  2228. break;
  2229. case MouseCursor::CopyingCursor:
  2230. // can't seem to find one of these in the win32 list..
  2231. break;
  2232. }
  2233. HCURSOR cursorH = LoadCursor (0, cursorName);
  2234. if (cursorH == 0)
  2235. cursorH = LoadCursor (0, IDC_ARROW);
  2236. return (void*) cursorH;
  2237. }
  2238. //==============================================================================
  2239. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2240. {
  2241. SetCursor ((HCURSOR) getHandle());
  2242. }
  2243. void MouseCursor::showInAllWindows() const throw()
  2244. {
  2245. showInWindow (0);
  2246. }
  2247. //==============================================================================
  2248. //==============================================================================
  2249. class JuceDropSource : public IDropSource
  2250. {
  2251. int refCount;
  2252. public:
  2253. JuceDropSource()
  2254. : refCount (1)
  2255. {
  2256. }
  2257. virtual ~JuceDropSource()
  2258. {
  2259. jassert (refCount == 0);
  2260. }
  2261. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2262. {
  2263. if (id == IID_IUnknown || id == IID_IDropSource)
  2264. {
  2265. AddRef();
  2266. *result = this;
  2267. return S_OK;
  2268. }
  2269. *result = 0;
  2270. return E_NOINTERFACE;
  2271. }
  2272. ULONG __stdcall AddRef() { return ++refCount; }
  2273. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2274. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  2275. {
  2276. if (escapePressed)
  2277. return DRAGDROP_S_CANCEL;
  2278. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  2279. return DRAGDROP_S_DROP;
  2280. return S_OK;
  2281. }
  2282. HRESULT __stdcall GiveFeedback (DWORD)
  2283. {
  2284. return DRAGDROP_S_USEDEFAULTCURSORS;
  2285. }
  2286. };
  2287. class JuceEnumFormatEtc : public IEnumFORMATETC
  2288. {
  2289. public:
  2290. JuceEnumFormatEtc (const FORMATETC* const format_)
  2291. : refCount (1),
  2292. format (format_),
  2293. index (0)
  2294. {
  2295. }
  2296. virtual ~JuceEnumFormatEtc()
  2297. {
  2298. jassert (refCount == 0);
  2299. }
  2300. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2301. {
  2302. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  2303. {
  2304. AddRef();
  2305. *result = this;
  2306. return S_OK;
  2307. }
  2308. *result = 0;
  2309. return E_NOINTERFACE;
  2310. }
  2311. ULONG __stdcall AddRef() { return ++refCount; }
  2312. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2313. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  2314. {
  2315. if (result == 0)
  2316. return E_POINTER;
  2317. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  2318. newOne->index = index;
  2319. *result = newOne;
  2320. return S_OK;
  2321. }
  2322. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  2323. {
  2324. if (pceltFetched != 0)
  2325. *pceltFetched = 0;
  2326. else if (celt != 1)
  2327. return S_FALSE;
  2328. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  2329. {
  2330. copyFormatEtc (lpFormatEtc [0], *format);
  2331. ++index;
  2332. if (pceltFetched != 0)
  2333. *pceltFetched = 1;
  2334. return S_OK;
  2335. }
  2336. return S_FALSE;
  2337. }
  2338. HRESULT __stdcall Skip (ULONG celt)
  2339. {
  2340. if (index + (int) celt >= 1)
  2341. return S_FALSE;
  2342. index += celt;
  2343. return S_OK;
  2344. }
  2345. HRESULT __stdcall Reset()
  2346. {
  2347. index = 0;
  2348. return S_OK;
  2349. }
  2350. private:
  2351. int refCount;
  2352. const FORMATETC* const format;
  2353. int index;
  2354. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  2355. {
  2356. dest = source;
  2357. if (source.ptd != 0)
  2358. {
  2359. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  2360. *(dest.ptd) = *(source.ptd);
  2361. }
  2362. }
  2363. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  2364. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  2365. };
  2366. class JuceDataObject : public IDataObject
  2367. {
  2368. JuceDropSource* const dropSource;
  2369. const FORMATETC* const format;
  2370. const STGMEDIUM* const medium;
  2371. int refCount;
  2372. JuceDataObject (const JuceDataObject&);
  2373. const JuceDataObject& operator= (const JuceDataObject&);
  2374. public:
  2375. JuceDataObject (JuceDropSource* const dropSource_,
  2376. const FORMATETC* const format_,
  2377. const STGMEDIUM* const medium_)
  2378. : dropSource (dropSource_),
  2379. format (format_),
  2380. medium (medium_),
  2381. refCount (1)
  2382. {
  2383. }
  2384. virtual ~JuceDataObject()
  2385. {
  2386. jassert (refCount == 0);
  2387. }
  2388. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2389. {
  2390. if (id == IID_IUnknown || id == IID_IDataObject)
  2391. {
  2392. AddRef();
  2393. *result = this;
  2394. return S_OK;
  2395. }
  2396. *result = 0;
  2397. return E_NOINTERFACE;
  2398. }
  2399. ULONG __stdcall AddRef() { return ++refCount; }
  2400. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  2401. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  2402. {
  2403. if (pFormatEtc->tymed == format->tymed
  2404. && pFormatEtc->cfFormat == format->cfFormat
  2405. && pFormatEtc->dwAspect == format->dwAspect)
  2406. {
  2407. pMedium->tymed = format->tymed;
  2408. pMedium->pUnkForRelease = 0;
  2409. if (format->tymed == TYMED_HGLOBAL)
  2410. {
  2411. const SIZE_T len = GlobalSize (medium->hGlobal);
  2412. void* const src = GlobalLock (medium->hGlobal);
  2413. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  2414. memcpy (dst, src, len);
  2415. GlobalUnlock (medium->hGlobal);
  2416. pMedium->hGlobal = dst;
  2417. return S_OK;
  2418. }
  2419. }
  2420. return DV_E_FORMATETC;
  2421. }
  2422. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  2423. {
  2424. if (f == 0)
  2425. return E_INVALIDARG;
  2426. if (f->tymed == format->tymed
  2427. && f->cfFormat == format->cfFormat
  2428. && f->dwAspect == format->dwAspect)
  2429. return S_OK;
  2430. return DV_E_FORMATETC;
  2431. }
  2432. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  2433. {
  2434. pFormatEtcOut->ptd = 0;
  2435. return E_NOTIMPL;
  2436. }
  2437. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  2438. {
  2439. if (result == 0)
  2440. return E_POINTER;
  2441. if (direction == DATADIR_GET)
  2442. {
  2443. *result = new JuceEnumFormatEtc (format);
  2444. return S_OK;
  2445. }
  2446. *result = 0;
  2447. return E_NOTIMPL;
  2448. }
  2449. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  2450. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  2451. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  2452. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  2453. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  2454. };
  2455. static HDROP createHDrop (const StringArray& fileNames) throw()
  2456. {
  2457. int totalChars = 0;
  2458. for (int i = fileNames.size(); --i >= 0;)
  2459. totalChars += fileNames[i].length() + 1;
  2460. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  2461. sizeof (DROPFILES)
  2462. + sizeof (WCHAR) * (totalChars + 2));
  2463. if (hDrop != 0)
  2464. {
  2465. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  2466. pDropFiles->pFiles = sizeof (DROPFILES);
  2467. #if JUCE_ENABLE_WIN98_COMPATIBILITY
  2468. pDropFiles->fWide = (SystemStats::getOperatingSystemType() & SystemStats::WindowsNT) != 0;
  2469. if (pDropFiles->fWide)
  2470. {
  2471. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  2472. for (int i = 0; i < fileNames.size(); ++i)
  2473. {
  2474. fileNames[i].copyToBuffer (fname, 2048);
  2475. fname += fileNames[i].length() + 1;
  2476. }
  2477. *fname = 0;
  2478. }
  2479. else
  2480. {
  2481. char* fname = ((char*) pDropFiles) + sizeof (DROPFILES);
  2482. for (int i = 0; i < fileNames.size(); ++i)
  2483. {
  2484. fileNames[i].copyToBuffer (fname, 2048);
  2485. fname += fileNames[i].length() + 1;
  2486. }
  2487. *fname = 0;
  2488. }
  2489. #else
  2490. pDropFiles->fWide = true;
  2491. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  2492. for (int i = 0; i < fileNames.size(); ++i)
  2493. {
  2494. fileNames[i].copyToBuffer (fname, 2048);
  2495. fname += fileNames[i].length() + 1;
  2496. }
  2497. *fname = 0;
  2498. #endif
  2499. GlobalUnlock (hDrop);
  2500. }
  2501. return hDrop;
  2502. }
  2503. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  2504. {
  2505. JuceDropSource* const source = new JuceDropSource();
  2506. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  2507. DWORD effect;
  2508. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  2509. data->Release();
  2510. source->Release();
  2511. return res == DRAGDROP_S_DROP;
  2512. }
  2513. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  2514. {
  2515. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2516. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2517. medium.hGlobal = createHDrop (files);
  2518. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  2519. : DROPEFFECT_COPY);
  2520. }
  2521. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2522. {
  2523. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  2524. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  2525. const int numChars = text.length();
  2526. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  2527. char* d = (char*) GlobalLock (medium.hGlobal);
  2528. #if JUCE_ENABLE_WIN98_COMPATIBILITY
  2529. if ((SystemStats::getOperatingSystemType() & SystemStats::WindowsNT) != 0)
  2530. {
  2531. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  2532. format.cfFormat = CF_UNICODETEXT;
  2533. }
  2534. else
  2535. {
  2536. text.copyToBuffer (d, numChars + 1);
  2537. }
  2538. #else
  2539. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  2540. format.cfFormat = CF_UNICODETEXT;
  2541. #endif
  2542. GlobalUnlock (medium.hGlobal);
  2543. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  2544. }
  2545. //==============================================================================
  2546. //==============================================================================
  2547. #if JUCE_OPENGL
  2548. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  2549. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  2550. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  2551. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  2552. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  2553. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  2554. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  2555. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  2556. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  2557. #define WGL_ACCELERATION_ARB 0x2003
  2558. #define WGL_SWAP_METHOD_ARB 0x2007
  2559. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  2560. #define WGL_PIXEL_TYPE_ARB 0x2013
  2561. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  2562. #define WGL_COLOR_BITS_ARB 0x2014
  2563. #define WGL_RED_BITS_ARB 0x2015
  2564. #define WGL_GREEN_BITS_ARB 0x2017
  2565. #define WGL_BLUE_BITS_ARB 0x2019
  2566. #define WGL_ALPHA_BITS_ARB 0x201B
  2567. #define WGL_DEPTH_BITS_ARB 0x2022
  2568. #define WGL_STENCIL_BITS_ARB 0x2023
  2569. #define WGL_FULL_ACCELERATION_ARB 0x2027
  2570. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  2571. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  2572. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  2573. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  2574. #define WGL_STEREO_ARB 0x2012
  2575. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  2576. #define WGL_SAMPLES_ARB 0x2042
  2577. #define WGL_TYPE_RGBA_ARB 0x202B
  2578. static void getWglExtensions (HDC dc, StringArray& result) throw()
  2579. {
  2580. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  2581. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  2582. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  2583. else
  2584. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  2585. }
  2586. //==============================================================================
  2587. class WindowedGLContext : public OpenGLContext
  2588. {
  2589. public:
  2590. WindowedGLContext (Component* const component_,
  2591. HGLRC contextToShareWith,
  2592. const OpenGLPixelFormat& pixelFormat)
  2593. : renderContext (0),
  2594. nativeWindow (0),
  2595. dc (0),
  2596. component (component_)
  2597. {
  2598. jassert (component != 0);
  2599. createNativeWindow();
  2600. // Use a default pixel format that should be supported everywhere
  2601. PIXELFORMATDESCRIPTOR pfd;
  2602. zerostruct (pfd);
  2603. pfd.nSize = sizeof (pfd);
  2604. pfd.nVersion = 1;
  2605. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  2606. pfd.iPixelType = PFD_TYPE_RGBA;
  2607. pfd.cColorBits = 24;
  2608. pfd.cDepthBits = 16;
  2609. const int format = ChoosePixelFormat (dc, &pfd);
  2610. if (format != 0)
  2611. SetPixelFormat (dc, format, &pfd);
  2612. renderContext = wglCreateContext (dc);
  2613. makeActive();
  2614. setPixelFormat (pixelFormat);
  2615. if (contextToShareWith != 0 && renderContext != 0)
  2616. wglShareLists (contextToShareWith, renderContext);
  2617. }
  2618. ~WindowedGLContext()
  2619. {
  2620. makeInactive();
  2621. wglDeleteContext (renderContext);
  2622. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  2623. delete nativeWindow;
  2624. }
  2625. bool makeActive() const throw()
  2626. {
  2627. jassert (renderContext != 0);
  2628. return wglMakeCurrent (dc, renderContext) != 0;
  2629. }
  2630. bool makeInactive() const throw()
  2631. {
  2632. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  2633. }
  2634. bool isActive() const throw()
  2635. {
  2636. return wglGetCurrentContext() == renderContext;
  2637. }
  2638. const OpenGLPixelFormat getPixelFormat() const
  2639. {
  2640. OpenGLPixelFormat pf;
  2641. makeActive();
  2642. StringArray availableExtensions;
  2643. getWglExtensions (dc, availableExtensions);
  2644. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  2645. return pf;
  2646. }
  2647. void* getRawContext() const throw()
  2648. {
  2649. return renderContext;
  2650. }
  2651. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  2652. {
  2653. makeActive();
  2654. PIXELFORMATDESCRIPTOR pfd;
  2655. zerostruct (pfd);
  2656. pfd.nSize = sizeof (pfd);
  2657. pfd.nVersion = 1;
  2658. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  2659. pfd.iPixelType = PFD_TYPE_RGBA;
  2660. pfd.iLayerType = PFD_MAIN_PLANE;
  2661. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  2662. pfd.cRedBits = pixelFormat.redBits;
  2663. pfd.cGreenBits = pixelFormat.greenBits;
  2664. pfd.cBlueBits = pixelFormat.blueBits;
  2665. pfd.cAlphaBits = pixelFormat.alphaBits;
  2666. pfd.cDepthBits = pixelFormat.depthBufferBits;
  2667. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  2668. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  2669. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  2670. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  2671. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  2672. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  2673. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  2674. int format = 0;
  2675. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  2676. StringArray availableExtensions;
  2677. getWglExtensions (dc, availableExtensions);
  2678. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  2679. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  2680. {
  2681. int attributes[64];
  2682. int n = 0;
  2683. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  2684. attributes[n++] = GL_TRUE;
  2685. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  2686. attributes[n++] = GL_TRUE;
  2687. attributes[n++] = WGL_ACCELERATION_ARB;
  2688. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  2689. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  2690. attributes[n++] = GL_TRUE;
  2691. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  2692. attributes[n++] = WGL_TYPE_RGBA_ARB;
  2693. attributes[n++] = WGL_COLOR_BITS_ARB;
  2694. attributes[n++] = pfd.cColorBits;
  2695. attributes[n++] = WGL_RED_BITS_ARB;
  2696. attributes[n++] = pixelFormat.redBits;
  2697. attributes[n++] = WGL_GREEN_BITS_ARB;
  2698. attributes[n++] = pixelFormat.greenBits;
  2699. attributes[n++] = WGL_BLUE_BITS_ARB;
  2700. attributes[n++] = pixelFormat.blueBits;
  2701. attributes[n++] = WGL_ALPHA_BITS_ARB;
  2702. attributes[n++] = pixelFormat.alphaBits;
  2703. attributes[n++] = WGL_DEPTH_BITS_ARB;
  2704. attributes[n++] = pixelFormat.depthBufferBits;
  2705. if (pixelFormat.stencilBufferBits > 0)
  2706. {
  2707. attributes[n++] = WGL_STENCIL_BITS_ARB;
  2708. attributes[n++] = pixelFormat.stencilBufferBits;
  2709. }
  2710. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  2711. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  2712. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  2713. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  2714. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  2715. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  2716. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  2717. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  2718. if (availableExtensions.contains ("WGL_ARB_multisample")
  2719. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  2720. {
  2721. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  2722. attributes[n++] = 1;
  2723. attributes[n++] = WGL_SAMPLES_ARB;
  2724. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  2725. }
  2726. attributes[n++] = 0;
  2727. UINT formatsCount;
  2728. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  2729. (void) ok;
  2730. jassert (ok);
  2731. }
  2732. else
  2733. {
  2734. format = ChoosePixelFormat (dc, &pfd);
  2735. }
  2736. if (format != 0)
  2737. {
  2738. makeInactive();
  2739. // win32 can't change the pixel format of a window, so need to delete the
  2740. // old one and create a new one..
  2741. jassert (nativeWindow != 0);
  2742. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  2743. delete nativeWindow;
  2744. createNativeWindow();
  2745. if (SetPixelFormat (dc, format, &pfd))
  2746. {
  2747. wglDeleteContext (renderContext);
  2748. renderContext = wglCreateContext (dc);
  2749. jassert (renderContext != 0);
  2750. return renderContext != 0;
  2751. }
  2752. }
  2753. return false;
  2754. }
  2755. void updateWindowPosition (int x, int y, int w, int h, int)
  2756. {
  2757. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  2758. x, y, w, h,
  2759. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  2760. }
  2761. void repaint()
  2762. {
  2763. int x, y, w, h;
  2764. nativeWindow->getBounds (x, y, w, h);
  2765. nativeWindow->repaint (0, 0, w, h);
  2766. }
  2767. void swapBuffers()
  2768. {
  2769. SwapBuffers (dc);
  2770. }
  2771. bool setSwapInterval (const int numFramesPerSwap)
  2772. {
  2773. makeActive();
  2774. StringArray availableExtensions;
  2775. getWglExtensions (dc, availableExtensions);
  2776. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  2777. return availableExtensions.contains ("WGL_EXT_swap_control")
  2778. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  2779. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  2780. }
  2781. int getSwapInterval() const
  2782. {
  2783. makeActive();
  2784. StringArray availableExtensions;
  2785. getWglExtensions (dc, availableExtensions);
  2786. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  2787. if (availableExtensions.contains ("WGL_EXT_swap_control")
  2788. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  2789. return wglGetSwapIntervalEXT();
  2790. return 0;
  2791. }
  2792. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  2793. {
  2794. jassert (isActive());
  2795. StringArray availableExtensions;
  2796. getWglExtensions (dc, availableExtensions);
  2797. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  2798. int numTypes = 0;
  2799. if (availableExtensions.contains("WGL_ARB_pixel_format")
  2800. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  2801. {
  2802. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  2803. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  2804. jassertfalse
  2805. }
  2806. else
  2807. {
  2808. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  2809. }
  2810. OpenGLPixelFormat pf;
  2811. for (int i = 0; i < numTypes; ++i)
  2812. {
  2813. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  2814. {
  2815. bool alreadyListed = false;
  2816. for (int j = results.size(); --j >= 0;)
  2817. if (pf == *results.getUnchecked(j))
  2818. alreadyListed = true;
  2819. if (! alreadyListed)
  2820. results.add (new OpenGLPixelFormat (pf));
  2821. }
  2822. }
  2823. }
  2824. //==============================================================================
  2825. juce_UseDebuggingNewOperator
  2826. HGLRC renderContext;
  2827. private:
  2828. Win32ComponentPeer* nativeWindow;
  2829. Component* const component;
  2830. HDC dc;
  2831. //==============================================================================
  2832. void createNativeWindow()
  2833. {
  2834. nativeWindow = new Win32ComponentPeer (component, 0);
  2835. nativeWindow->dontRepaint = true;
  2836. nativeWindow->setVisible (true);
  2837. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  2838. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2839. if (peer != 0)
  2840. {
  2841. SetParent (hwnd, (HWND) peer->getNativeHandle());
  2842. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  2843. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  2844. }
  2845. dc = GetDC (hwnd);
  2846. }
  2847. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  2848. OpenGLPixelFormat& result,
  2849. const StringArray& availableExtensions) const throw()
  2850. {
  2851. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  2852. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  2853. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  2854. {
  2855. int attributes[32];
  2856. int numAttributes = 0;
  2857. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  2858. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  2859. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  2860. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  2861. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  2862. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  2863. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  2864. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  2865. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  2866. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  2867. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  2868. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  2869. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  2870. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  2871. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  2872. if (availableExtensions.contains ("WGL_ARB_multisample"))
  2873. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  2874. int values[32];
  2875. zeromem (values, sizeof (values));
  2876. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  2877. {
  2878. int n = 0;
  2879. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  2880. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  2881. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  2882. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  2883. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  2884. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  2885. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  2886. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  2887. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  2888. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  2889. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  2890. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  2891. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  2892. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  2893. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  2894. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  2895. return isValidFormat;
  2896. }
  2897. else
  2898. {
  2899. jassertfalse
  2900. }
  2901. }
  2902. else
  2903. {
  2904. PIXELFORMATDESCRIPTOR pfd;
  2905. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  2906. {
  2907. result.redBits = pfd.cRedBits;
  2908. result.greenBits = pfd.cGreenBits;
  2909. result.blueBits = pfd.cBlueBits;
  2910. result.alphaBits = pfd.cAlphaBits;
  2911. result.depthBufferBits = pfd.cDepthBits;
  2912. result.stencilBufferBits = pfd.cStencilBits;
  2913. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  2914. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  2915. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  2916. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  2917. result.fullSceneAntiAliasingNumSamples = 0;
  2918. return true;
  2919. }
  2920. else
  2921. {
  2922. jassertfalse
  2923. }
  2924. }
  2925. return false;
  2926. }
  2927. WindowedGLContext (const WindowedGLContext&);
  2928. const WindowedGLContext& operator= (const WindowedGLContext&);
  2929. };
  2930. //==============================================================================
  2931. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  2932. const OpenGLPixelFormat& pixelFormat,
  2933. const OpenGLContext* const contextToShareWith)
  2934. {
  2935. WindowedGLContext* c = new WindowedGLContext (component,
  2936. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  2937. pixelFormat);
  2938. if (c->renderContext == 0)
  2939. deleteAndZero (c);
  2940. return c;
  2941. }
  2942. void juce_glViewport (const int w, const int h)
  2943. {
  2944. glViewport (0, 0, w, h);
  2945. }
  2946. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  2947. OwnedArray <OpenGLPixelFormat>& results)
  2948. {
  2949. Component tempComp;
  2950. {
  2951. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  2952. wc.makeActive();
  2953. wc.findAlternativeOpenGLPixelFormats (results);
  2954. }
  2955. }
  2956. #endif
  2957. //==============================================================================
  2958. //==============================================================================
  2959. class JuceIStorage : public IStorage
  2960. {
  2961. int refCount;
  2962. public:
  2963. JuceIStorage() : refCount (1) {}
  2964. virtual ~JuceIStorage()
  2965. {
  2966. jassert (refCount == 0);
  2967. }
  2968. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  2969. {
  2970. if (id == IID_IUnknown || id == IID_IStorage)
  2971. {
  2972. AddRef();
  2973. *result = this;
  2974. return S_OK;
  2975. }
  2976. *result = 0;
  2977. return E_NOINTERFACE;
  2978. }
  2979. ULONG __stdcall AddRef() { return ++refCount; }
  2980. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  2981. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  2982. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  2983. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  2984. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  2985. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  2986. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  2987. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  2988. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  2989. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  2990. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  2991. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  2992. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  2993. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  2994. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  2995. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  2996. juce_UseDebuggingNewOperator
  2997. };
  2998. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  2999. {
  3000. int refCount;
  3001. HWND window;
  3002. public:
  3003. JuceOleInPlaceFrame (HWND window_)
  3004. : refCount (1),
  3005. window (window_)
  3006. {
  3007. }
  3008. virtual ~JuceOleInPlaceFrame()
  3009. {
  3010. jassert (refCount == 0);
  3011. }
  3012. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  3013. {
  3014. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  3015. {
  3016. AddRef();
  3017. *result = this;
  3018. return S_OK;
  3019. }
  3020. *result = 0;
  3021. return E_NOINTERFACE;
  3022. }
  3023. ULONG __stdcall AddRef() { return ++refCount; }
  3024. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  3025. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  3026. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  3027. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  3028. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  3029. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  3030. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  3031. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  3032. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  3033. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  3034. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  3035. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  3036. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  3037. juce_UseDebuggingNewOperator
  3038. };
  3039. class JuceIOleInPlaceSite : public IOleInPlaceSite
  3040. {
  3041. int refCount;
  3042. HWND window;
  3043. JuceOleInPlaceFrame* frame;
  3044. public:
  3045. JuceIOleInPlaceSite (HWND window_)
  3046. : refCount (1),
  3047. window (window_)
  3048. {
  3049. frame = new JuceOleInPlaceFrame (window);
  3050. }
  3051. virtual ~JuceIOleInPlaceSite()
  3052. {
  3053. jassert (refCount == 0);
  3054. frame->Release();
  3055. }
  3056. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  3057. {
  3058. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  3059. {
  3060. AddRef();
  3061. *result = this;
  3062. return S_OK;
  3063. }
  3064. *result = 0;
  3065. return E_NOINTERFACE;
  3066. }
  3067. ULONG __stdcall AddRef() { return ++refCount; }
  3068. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  3069. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  3070. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  3071. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  3072. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  3073. HRESULT __stdcall OnUIActivate() { return S_OK; }
  3074. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  3075. {
  3076. frame->AddRef();
  3077. *lplpFrame = frame;
  3078. *lplpDoc = 0;
  3079. lpFrameInfo->fMDIApp = FALSE;
  3080. lpFrameInfo->hwndFrame = window;
  3081. lpFrameInfo->haccel = 0;
  3082. lpFrameInfo->cAccelEntries = 0;
  3083. return S_OK;
  3084. }
  3085. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  3086. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  3087. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  3088. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  3089. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  3090. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  3091. juce_UseDebuggingNewOperator
  3092. };
  3093. class JuceIOleClientSite : public IOleClientSite
  3094. {
  3095. int refCount;
  3096. JuceIOleInPlaceSite* inplaceSite;
  3097. public:
  3098. JuceIOleClientSite (HWND window)
  3099. : refCount (1)
  3100. {
  3101. inplaceSite = new JuceIOleInPlaceSite (window);
  3102. }
  3103. virtual ~JuceIOleClientSite()
  3104. {
  3105. jassert (refCount == 0);
  3106. inplaceSite->Release();
  3107. }
  3108. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  3109. {
  3110. if (id == IID_IUnknown || id == IID_IOleClientSite)
  3111. {
  3112. AddRef();
  3113. *result = this;
  3114. return S_OK;
  3115. }
  3116. else if (id == IID_IOleInPlaceSite)
  3117. {
  3118. inplaceSite->AddRef();
  3119. *result = inplaceSite;
  3120. return S_OK;
  3121. }
  3122. *result = 0;
  3123. return E_NOINTERFACE;
  3124. }
  3125. ULONG __stdcall AddRef() { return ++refCount; }
  3126. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  3127. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  3128. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  3129. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  3130. HRESULT __stdcall ShowObject() { return S_OK; }
  3131. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  3132. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  3133. juce_UseDebuggingNewOperator
  3134. };
  3135. //==============================================================================
  3136. class ActiveXControlData : public ComponentMovementWatcher
  3137. {
  3138. ActiveXControlComponent* const owner;
  3139. bool wasShowing;
  3140. public:
  3141. IStorage* storage;
  3142. IOleClientSite* clientSite;
  3143. IOleObject* control;
  3144. //==============================================================================
  3145. ActiveXControlData (HWND hwnd,
  3146. ActiveXControlComponent* const owner_)
  3147. : ComponentMovementWatcher (owner_),
  3148. owner (owner_),
  3149. wasShowing (owner_ != 0 && owner_->isShowing()),
  3150. storage (new JuceIStorage()),
  3151. clientSite (new JuceIOleClientSite (hwnd)),
  3152. control (0)
  3153. {
  3154. }
  3155. ~ActiveXControlData()
  3156. {
  3157. if (control != 0)
  3158. {
  3159. control->Close (OLECLOSE_NOSAVE);
  3160. control->Release();
  3161. }
  3162. clientSite->Release();
  3163. storage->Release();
  3164. }
  3165. //==============================================================================
  3166. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  3167. {
  3168. Component* const topComp = owner->getTopLevelComponent();
  3169. if (topComp->getPeer() != 0)
  3170. {
  3171. int x = 0, y = 0;
  3172. owner->relativePositionToOtherComponent (topComp, x, y);
  3173. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  3174. }
  3175. }
  3176. void componentPeerChanged()
  3177. {
  3178. const bool isShowingNow = owner->isShowing();
  3179. if (wasShowing != isShowingNow)
  3180. {
  3181. wasShowing = isShowingNow;
  3182. owner->setControlVisible (isShowingNow);
  3183. }
  3184. }
  3185. void componentVisibilityChanged (Component&)
  3186. {
  3187. componentPeerChanged();
  3188. }
  3189. };
  3190. //==============================================================================
  3191. static VoidArray activeXComps;
  3192. static HWND getHWND (const ActiveXControlComponent* const component)
  3193. {
  3194. HWND hwnd = 0;
  3195. const IID iid = IID_IOleWindow;
  3196. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  3197. if (window != 0)
  3198. {
  3199. window->GetWindow (&hwnd);
  3200. window->Release();
  3201. }
  3202. return hwnd;
  3203. }
  3204. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  3205. {
  3206. RECT activeXRect, peerRect;
  3207. GetWindowRect (hwnd, &activeXRect);
  3208. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  3209. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  3210. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  3211. const int64 mouseEventTime = getMouseEventTime();
  3212. const int oldModifiers = currentModifiers;
  3213. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  3214. switch (message)
  3215. {
  3216. case WM_MOUSEMOVE:
  3217. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  3218. peer->handleMouseDrag (mx, my, mouseEventTime);
  3219. else
  3220. peer->handleMouseMove (mx, my, mouseEventTime);
  3221. break;
  3222. case WM_LBUTTONDOWN:
  3223. case WM_MBUTTONDOWN:
  3224. case WM_RBUTTONDOWN:
  3225. peer->handleMouseDown (mx, my, mouseEventTime);
  3226. break;
  3227. case WM_LBUTTONUP:
  3228. case WM_MBUTTONUP:
  3229. case WM_RBUTTONUP:
  3230. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  3231. break;
  3232. default:
  3233. break;
  3234. }
  3235. }
  3236. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  3237. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  3238. {
  3239. for (int i = activeXComps.size(); --i >= 0;)
  3240. {
  3241. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  3242. HWND controlHWND = getHWND (ax);
  3243. if (controlHWND == hwnd)
  3244. {
  3245. switch (message)
  3246. {
  3247. case WM_MOUSEMOVE:
  3248. case WM_LBUTTONDOWN:
  3249. case WM_MBUTTONDOWN:
  3250. case WM_RBUTTONDOWN:
  3251. case WM_LBUTTONUP:
  3252. case WM_MBUTTONUP:
  3253. case WM_RBUTTONUP:
  3254. if (ax->isShowing())
  3255. {
  3256. ComponentPeer* const peer = ax->getPeer();
  3257. if (peer != 0)
  3258. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  3259. }
  3260. break;
  3261. default:
  3262. break;
  3263. }
  3264. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  3265. }
  3266. }
  3267. return DefWindowProc (hwnd, message, wParam, lParam);
  3268. }
  3269. ActiveXControlComponent::ActiveXControlComponent()
  3270. : originalWndProc (0),
  3271. control (0)
  3272. {
  3273. activeXComps.add (this);
  3274. }
  3275. ActiveXControlComponent::~ActiveXControlComponent()
  3276. {
  3277. deleteControl();
  3278. activeXComps.removeValue (this);
  3279. }
  3280. void ActiveXControlComponent::paint (Graphics& g)
  3281. {
  3282. if (control == 0)
  3283. g.fillAll (Colours::lightgrey);
  3284. }
  3285. bool ActiveXControlComponent::createControl (const void* controlIID)
  3286. {
  3287. deleteControl();
  3288. ComponentPeer* const peer = getPeer();
  3289. // the component must have already been added to a real window when you call this!
  3290. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  3291. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  3292. {
  3293. int x = 0, y = 0;
  3294. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  3295. HWND hwnd = (HWND) peer->getNativeHandle();
  3296. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  3297. HRESULT hr;
  3298. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  3299. info->clientSite, info->storage,
  3300. (void**) &(info->control))) == S_OK)
  3301. {
  3302. info->control->SetHostNames (L"Juce", 0);
  3303. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  3304. {
  3305. RECT rect;
  3306. rect.left = x;
  3307. rect.top = y;
  3308. rect.right = x + getWidth();
  3309. rect.bottom = y + getHeight();
  3310. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  3311. {
  3312. control = info;
  3313. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  3314. HWND controlHWND = getHWND (this);
  3315. if (controlHWND != 0)
  3316. {
  3317. originalWndProc = (void*) GetWindowLongPtr (controlHWND, GWLP_WNDPROC);
  3318. SetWindowLongPtr (controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  3319. }
  3320. return true;
  3321. }
  3322. }
  3323. }
  3324. delete info;
  3325. }
  3326. return false;
  3327. }
  3328. void ActiveXControlComponent::deleteControl()
  3329. {
  3330. ActiveXControlData* const info = (ActiveXControlData*) control;
  3331. if (info != 0)
  3332. {
  3333. delete info;
  3334. control = 0;
  3335. originalWndProc = 0;
  3336. }
  3337. }
  3338. void* ActiveXControlComponent::queryInterface (const void* iid) const
  3339. {
  3340. ActiveXControlData* const info = (ActiveXControlData*) control;
  3341. void* result = 0;
  3342. if (info != 0 && info->control != 0
  3343. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  3344. return result;
  3345. return 0;
  3346. }
  3347. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  3348. {
  3349. HWND hwnd = getHWND (this);
  3350. if (hwnd != 0)
  3351. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  3352. }
  3353. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  3354. {
  3355. HWND hwnd = getHWND (this);
  3356. if (hwnd != 0)
  3357. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  3358. }
  3359. END_JUCE_NAMESPACE