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.

3629 lines
118KB

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