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.

4145 lines
138KB

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