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.

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