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.

3635 lines
117KB

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