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.

3571 lines
115KB

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