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.

3647 lines
118KB

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