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.

3621 lines
117KB

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