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.

3674 lines
119KB

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