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.

3651 lines
118KB

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