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.

3672 lines
119KB

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