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.

4119 lines
137KB

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