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.

3549 lines
114KB

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