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.

3664 lines
119KB

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