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.

1194 lines
39KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. //==============================================================================
  19. /*
  20. This file contains all the mess that creates an NPAPI interface, and connects
  21. that interface to your BrowserPluginComponent object.
  22. */
  23. //==============================================================================
  24. #if defined (__APPLE__) && ! JUCE_NPAPI_WRAPPED_IN_MM
  25. #error "On the Mac, you can't compile this .cpp file directly - use juce_NPAPI_GlueCode.mm instead"
  26. #endif
  27. #define XPCOM_GLUE
  28. //==============================================================================
  29. #if _MSC_VER
  30. #define XP_WIN
  31. #define _X86_
  32. #include <windows.h>
  33. #include <windowsx.h>
  34. #include "npapi/npupp.h"
  35. // Cunning trick used to add functions to export list and avoid messing about with .def files.
  36. // (can't add a declspec because the functions have already been pre-declared in the npapi headers).
  37. #define EXPORTED_FUNCTION comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  38. //==============================================================================
  39. #elif defined (__APPLE__)
  40. #define XP_MACOSX
  41. #define OSCALL
  42. #include <WebKit/npapi.h>
  43. #include <WebKit/npfunctions.h>
  44. #include <WebKit/npruntime.h>
  45. //==============================================================================
  46. #else
  47. #define XP_UNIX
  48. #include "npapi.h"
  49. #include "npupp.h"
  50. #include "npruntime.h"
  51. #endif
  52. //==============================================================================
  53. #include "../../../juce_amalgamated.h"
  54. #include "juce_BrowserPluginComponent.h"
  55. #include "juce_IncludeBrowserPluginInfo.h"
  56. #if JUCE_MAC && JUCE_DEBUG && 0
  57. static void log (const String& s)
  58. {
  59. FILE* f = fopen ("/Users/jules/Desktop/log.txt", "a+");
  60. fprintf (f, (const char*) s);
  61. fprintf (f, "\n");
  62. fflush (f);
  63. fclose (f);
  64. }
  65. #else
  66. #define log(a)
  67. #endif
  68. //==============================================================================
  69. #if JUCE_MAC
  70. static const String nsStringToJuce (NSString* s) { return String::fromUTF8 ((juce::uint8*) [s UTF8String]); }
  71. static NSString* juceStringToNS (const String& s) { return [NSString stringWithUTF8String: (const char*) s.toUTF8()]; }
  72. #pragma export on
  73. extern "C"
  74. {
  75. NPError NP_Initialize (NPNetscapeFuncs*);
  76. NPError NP_GetEntryPoints (NPPluginFuncs*);
  77. NPError NP_Shutdown();
  78. }
  79. #pragma export off
  80. #ifndef NP_CLASS_STRUCT_VERSION_ENUM // fill in some symbols that are missing from the OSX 10.4 SDK
  81. #define NPNVpluginDrawingModel 1000
  82. #define NPDrawingModelCoreGraphics 1
  83. typedef struct NP_CGContext
  84. {
  85. CGContextRef context;
  86. WindowRef window;
  87. } NP_CGContext;
  88. #endif
  89. #endif
  90. //==============================================================================
  91. static NPNetscapeFuncs browser;
  92. String browserVersionDesc;
  93. //==============================================================================
  94. NPError NP_GetValue (void* future, NPPVariable variable, void* value)
  95. {
  96. return NPP_GetValue ((NPP_t*) future, variable, value);
  97. }
  98. #if JUCE_WIN32 || JUCE_MAC
  99. NPError OSCALL NP_GetEntryPoints (NPPluginFuncs* funcs)
  100. {
  101. #if JUCE_WIN32
  102. #pragma EXPORTED_FUNCTION
  103. #endif
  104. log ("NP_GetEntryPoints");
  105. if (funcs == 0 || (funcs->size > 0 && funcs->size < sizeof (NPPluginFuncs)))
  106. return NPERR_INVALID_FUNCTABLE_ERROR;
  107. funcs->size = sizeof (NPPluginFuncs);
  108. funcs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
  109. funcs->newp = NPP_New;
  110. funcs->destroy = NPP_Destroy;
  111. funcs->setwindow = NPP_SetWindow;
  112. funcs->newstream = NPP_NewStream;
  113. funcs->destroystream = NPP_DestroyStream;
  114. funcs->asfile = NPP_StreamAsFile;
  115. funcs->writeready = NPP_WriteReady;
  116. #if JUCE_MAC
  117. funcs->write = (NPP_WriteProcPtr) NPP_Write;
  118. #else
  119. funcs->write = NPP_Write;
  120. #endif
  121. funcs->print = NPP_Print;
  122. funcs->event = NPP_HandleEvent;
  123. funcs->urlnotify = NPP_URLNotify;
  124. funcs->getvalue = NPP_GetValue;
  125. funcs->setvalue = NPP_SetValue;
  126. funcs->javaClass = 0;
  127. return NPERR_NO_ERROR;
  128. }
  129. #endif
  130. NPError OSCALL NP_Initialize (NPNetscapeFuncs* funcs
  131. #ifdef XP_UNIX
  132. , NPPluginFuncs* pluginFuncs
  133. #endif
  134. )
  135. {
  136. #if JUCE_WIN32
  137. #pragma EXPORTED_FUNCTION
  138. #endif
  139. log ("NP_Initialize");
  140. if (funcs == 0)
  141. return NPERR_INVALID_FUNCTABLE_ERROR;
  142. if (((funcs->version >> 8) & 0xff) > NP_VERSION_MAJOR)
  143. return NPERR_INCOMPATIBLE_VERSION_ERROR;
  144. zerostruct (browser);
  145. memcpy (&browser, funcs, jmin (funcs->size, sizeof (browser)));
  146. #ifdef XP_UNIX
  147. pluginFuncs->version = (NP_VERSION_MAJOR << 8) + NP_VERSION_MINOR;
  148. pluginFuncs->size = sizeof (NPPluginFuncs);
  149. pluginFuncs->newp = NewNPP_NewProc (NPP_New);
  150. pluginFuncs->destroy = NewNPP_DestroyProc (NPP_Destroy);
  151. pluginFuncs->setwindow = NewNPP_SetWindowProc (NPP_SetWindow);
  152. pluginFuncs->newstream = NewNPP_NewStreamProc (NPP_NewStream);
  153. pluginFuncs->destroystream = NewNPP_DestroyStreamProc (NPP_DestroyStream);
  154. pluginFuncs->asfile = NewNPP_StreamAsFileProc (NPP_StreamAsFile);
  155. pluginFuncs->writeready = NewNPP_WriteReadyProc (NPP_WriteReady);
  156. pluginFuncs->write = NewNPP_WriteProc (NPP_Write);
  157. pluginFuncs->print = NewNPP_PrintProc (NPP_Print);
  158. pluginFuncs->urlnotify = NewNPP_URLNotifyProc (NPP_URLNotify);
  159. pluginFuncs->event = 0;
  160. pluginFuncs->getvalue = NewNPP_GetValueProc (NPP_GetValue);
  161. #ifdef OJI
  162. pluginFuncs->javaClass = NPP_GetJavaClass();
  163. #endif
  164. #endif
  165. return NPERR_NO_ERROR;
  166. }
  167. NPError OSCALL NP_Shutdown()
  168. {
  169. #if JUCE_WIN32
  170. #pragma EXPORTED_FUNCTION
  171. #endif
  172. log ("NP_Shutdown");
  173. return NPERR_NO_ERROR;
  174. }
  175. char* NP_GetMIMEDescription()
  176. {
  177. log ("NP_GetMIMEDescription");
  178. static String mimeDesc;
  179. mimeDesc = String (T(JuceBrowserPlugin_MimeType))
  180. + T(":") + String (T(JuceBrowserPlugin_FileSuffix))
  181. + T(":") + String (T(JuceBrowserPlugin_Name));
  182. return (char*) (const char*) mimeDesc.toUTF8();
  183. }
  184. //==============================================================================
  185. /*
  186. NPError NPN_GetURLNotify (NPP instance, const char *url, const char *target, void* notifyData)
  187. {
  188. return (browser.version & 0xFF) >= NPVERS_HAS_NOTIFICATION
  189. ? browser.geturlnotify (instance, url, target, notifyData);
  190. : NPERR_INCOMPATIBLE_VERSION_ERROR;
  191. }
  192. NPError NPN_PostURLNotify (NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file, void* notifyData)
  193. {
  194. return (browser.version & 0xFF) >= NPVERS_HAS_NOTIFICATION
  195. ? browser.posturlnotify (instance, url, window, len, buf, file, notifyData)
  196. : NPERR_INCOMPATIBLE_VERSION_ERROR;
  197. }
  198. NPError NPN_NewStream (NPP instance, NPMIMEType type, const char* target, NPStream** stream)
  199. {
  200. return (browser.version & 0xFF) >= NPVERS_HAS_STREAMOUTPUT
  201. ? browser.newstream (instance, type, target, stream)
  202. : NPERR_INCOMPATIBLE_VERSION_ERROR;
  203. }
  204. int32 NPN_Write (NPP instance, NPStream *stream, int32 len, void *buffer)
  205. {
  206. return (browser.version & 0xFF) >= NPVERS_HAS_STREAMOUTPUT
  207. ? browser.write (instance, stream, len, buffer)
  208. : -1;
  209. }
  210. NPError NPN_DestroyStream (NPP instance, NPStream* stream, NPError reason)
  211. {
  212. return (browser.version & 0xFF) >= NPVERS_HAS_STREAMOUTPUT
  213. ? browser.destroystream (instance, stream, reason)
  214. : NPERR_INCOMPATIBLE_VERSION_ERROR;
  215. }
  216. */
  217. //==============================================================================
  218. class BrowserPluginHolderComponent : public Component
  219. {
  220. public:
  221. //==============================================================================
  222. BrowserPluginHolderComponent (NPP npp_)
  223. : npp (npp_),
  224. child (0)
  225. {
  226. log ("BrowserPluginHolderComponent created");
  227. #if JUCE_WIN32
  228. parentHWND = 0;
  229. oldWinProc = 0;
  230. #else
  231. currentParentView = 0;
  232. #endif
  233. setOpaque (true);
  234. setWantsKeyboardFocus (false);
  235. addAndMakeVisible (child = createBrowserPlugin());
  236. jassert (child != 0); // You have to create one of these!
  237. }
  238. ~BrowserPluginHolderComponent()
  239. {
  240. log ("BrowserPluginHolderComponent deleted");
  241. setWindow (0);
  242. deleteAndZero (child);
  243. }
  244. //==============================================================================
  245. void paint (Graphics& g)
  246. {
  247. if (child == 0 || ! child->isOpaque())
  248. g.fillAll (Colours::white);
  249. }
  250. void resized()
  251. {
  252. if (child != 0)
  253. child->setBounds (0, 0, getWidth(), getHeight());
  254. }
  255. const var getObject()
  256. {
  257. return child->getJavascriptObject();
  258. }
  259. //==============================================================================
  260. NPP npp;
  261. BrowserPluginComponent* child;
  262. private:
  263. //==============================================================================
  264. #if JUCE_WIN32
  265. HWND parentHWND;
  266. WNDPROC oldWinProc;
  267. void resizeToParentWindow (const int requestedWidth = 0, const int requestedHeight = 0)
  268. {
  269. if (IsWindow (parentHWND))
  270. {
  271. RECT r;
  272. GetWindowRect (parentHWND, &r);
  273. int w = r.right - r.left;
  274. int h = r.bottom - r.top;
  275. if (w == 0 || h == 0)
  276. {
  277. w = requestedWidth; // On Safari, the HWND can have a zero-size, so we might need to
  278. h = requestedHeight; // force it to the size that the NPAPI call asked for..
  279. MoveWindow (parentHWND, r.left, r.top, w, h, TRUE);
  280. }
  281. setBounds (0, 0, w, h);
  282. }
  283. }
  284. static LRESULT CALLBACK interceptingWinProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  285. {
  286. switch (msg)
  287. {
  288. case WM_PAINT:
  289. {
  290. PAINTSTRUCT ps;
  291. HDC hdc = BeginPaint (hWnd, &ps);
  292. EndPaint (hWnd, &ps);
  293. }
  294. return 0;
  295. case WM_ERASEBKGND:
  296. return 1;
  297. case WM_WINDOWPOSCHANGING:
  298. if ((((WINDOWPOS*) lParam)->flags & SWP_NOSIZE) == 0)
  299. {
  300. BrowserPluginHolderComponent* const comp = (BrowserPluginHolderComponent*) GetWindowLongPtr (hWnd, GWL_USERDATA);
  301. comp->resizeToParentWindow();
  302. }
  303. break;
  304. default:
  305. break;
  306. }
  307. return DefWindowProc (hWnd, msg, wParam, lParam);
  308. }
  309. public:
  310. void setWindow (NPWindow* window)
  311. {
  312. HWND newHWND = (window != 0 ? ((HWND) window->window) : 0);
  313. if (parentHWND != newHWND)
  314. {
  315. removeFromDesktop();
  316. setVisible (false);
  317. if (IsWindow (parentHWND))
  318. {
  319. SubclassWindow (parentHWND, oldWinProc); // restore the old winproc..
  320. oldWinProc = 0;
  321. }
  322. parentHWND = newHWND;
  323. if (parentHWND != 0)
  324. {
  325. addToDesktop (0);
  326. HWND ourHWND = (HWND) getWindowHandle();
  327. SetParent (ourHWND, parentHWND);
  328. DWORD val = GetWindowLongPtr (ourHWND, GWL_STYLE);
  329. val = (val & ~WS_POPUP) | WS_CHILD;
  330. SetWindowLongPtr (ourHWND, GWL_STYLE, val);
  331. setVisible (true);
  332. oldWinProc = SubclassWindow (parentHWND, (WNDPROC) interceptingWinProc);
  333. SetWindowLongPtr (parentHWND, GWL_USERDATA, (LONG_PTR) this);
  334. resizeToParentWindow (window->width, window->height);
  335. }
  336. }
  337. }
  338. //==============================================================================
  339. #else
  340. NSView* currentParentView;
  341. NSView* findViewAt (NSView* parent, float x, float y) const
  342. {
  343. NSRect frame = [parent frame];
  344. NSRect bounds = [parent bounds];
  345. x -= frame.origin.x;
  346. y -= frame.origin.y;
  347. Rectangle rr (frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
  348. Rectangle rr2 (bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
  349. //log (String ((int) x) + ", " + String ((int) y) + " - " + nsStringToJuce([parent description]) + " " + rr.toString() + " " + rr2.toString());
  350. if (x >= 0 && x < frame.size.width && y >= 0 && y < frame.size.height)
  351. {
  352. x += bounds.origin.x; // adjust for scrolling panels
  353. y += bounds.origin.y;
  354. for (int i = [[parent subviews] count]; --i >= 0;)
  355. {
  356. NSView* v = (NSView*) [[parent subviews] objectAtIndex: i];
  357. if (v != (NSView*) getWindowHandle())
  358. {
  359. NSView* found = findViewAt (v, x, y);
  360. if (found != 0)
  361. return found;
  362. }
  363. }
  364. return parent;
  365. }
  366. return 0;
  367. }
  368. public:
  369. static bool isBrowserContentView (NSView* v)
  370. {
  371. return [[v className] isEqualToString: @"WebNetscapePluginDocumentView"]
  372. || [[v className] isEqualToString: @"WebPluginDocumentView"]
  373. || ([[v className] isEqualToString: @"ChildView"] && ([v frame].origin.x != 0 && [v frame].origin.y != 0));
  374. }
  375. void setWindow (NPWindow* window)
  376. {
  377. const ScopedAutoReleasePool pool;
  378. NSView* parentView = 0;
  379. WindowRef windowRef = window != 0 ? ((NP_CGContext*) window->window)->window : 0;
  380. if (windowRef != 0)
  381. {
  382. NSWindow* win = [[[NSWindow alloc] initWithWindowRef: windowRef] autorelease];
  383. const Rectangle clip (window->clipRect.left, window->clipRect.top,
  384. window->clipRect.right - window->clipRect.left,
  385. window->clipRect.bottom - window->clipRect.top);
  386. const Rectangle target ((int) window->x, (int) window->y, (int) window->width, (int) window->height);
  387. const Rectangle intersection (clip.getIntersection (target));
  388. // in firefox the clip rect is usually out of step with the target rect, but in safari it matches
  389. log ("plugin window clip: " + clip.toString());
  390. log ("plugin window target: " + target.toString());
  391. log ("plugin window intersection: " + intersection.toString());
  392. if (! intersection.isEmpty())
  393. {
  394. NSView* content = [win contentView];
  395. float wx = (float) intersection.getCentreX();
  396. float wy = (float) intersection.getCentreY();
  397. NSRect v = [content convertRect: [content frame] toView: nil];
  398. NSRect w = [win frame];
  399. log ("wx: " + Rectangle (v.origin.x, v.origin.y, v.size.width, v.size.height).toString()
  400. + " " + Rectangle (w.origin.x, w.origin.y, w.size.width, w.size.height).toString());
  401. // adjust the requested window pos to deal with the content view's origin within the window
  402. wy -= w.size.height - (v.origin.y + v.size.height);
  403. parentView = findViewAt (content, wx, wy);
  404. if (! isBrowserContentView (parentView))
  405. parentView = currentParentView;
  406. }
  407. log ("parent: " + nsStringToJuce ([parentView description]));
  408. }
  409. if (parentView != currentParentView)
  410. {
  411. log ("new view: " + nsStringToJuce ([parentView description]));
  412. removeFromDesktop();
  413. setVisible (false);
  414. currentParentView = parentView;
  415. if (parentView != 0)
  416. {
  417. setSize (window->width, window->height);
  418. addToDesktop (0, parentView);
  419. setVisible (true);
  420. }
  421. }
  422. if (window != 0)
  423. setSize (window->width, window->height);
  424. }
  425. #endif
  426. };
  427. //==============================================================================
  428. static NPIdentifier getIdentifierFromString (const var::identifier& s) throw()
  429. {
  430. return browser.getstringidentifier (s.name.toUTF8());
  431. }
  432. static const var createValueFromNPVariant (NPP npp, const NPVariant& v);
  433. static void createNPVariantFromValue (NPP npp, NPVariant& out, const var& v);
  434. #if JUCE_DEBUG
  435. static int numDOWNP = 0, numJuceSO = 0;
  436. #endif
  437. //==============================================================================
  438. class DynamicObjectWrappingNPObject : public DynamicObject
  439. {
  440. NPP npp;
  441. NPObject* const source;
  442. public:
  443. DynamicObjectWrappingNPObject (NPP npp_, NPObject* const source_)
  444. : npp (npp_),
  445. source (browser.retainobject (source_))
  446. {
  447. DBG ("num NP wrapper objs: " + String (++numDOWNP));
  448. }
  449. ~DynamicObjectWrappingNPObject()
  450. {
  451. browser.releaseobject (source);
  452. DBG ("num NP wrapper objs: " + String (--numDOWNP));
  453. }
  454. const var getProperty (const var::identifier& propertyName) const
  455. {
  456. NPVariant result;
  457. VOID_TO_NPVARIANT (result);
  458. browser.getproperty (npp, source, getIdentifierFromString (propertyName), &result);
  459. const var v (createValueFromNPVariant (npp, result));
  460. browser.releasevariantvalue (&result);
  461. return v;
  462. }
  463. bool hasProperty (const var::identifier& propertyName) const
  464. {
  465. NPVariant result;
  466. VOID_TO_NPVARIANT (result);
  467. const bool hasProp = browser.getproperty (npp, source, getIdentifierFromString (propertyName), &result);
  468. browser.releasevariantvalue (&result);
  469. return hasProp;
  470. }
  471. void setProperty (const var::identifier& propertyName, const var& newValue)
  472. {
  473. NPVariant value;
  474. createNPVariantFromValue (npp, value, newValue);
  475. browser.setproperty (npp, source, getIdentifierFromString (propertyName), &value);
  476. browser.releasevariantvalue (&value);
  477. }
  478. void removeProperty (const var::identifier& propertyName)
  479. {
  480. browser.removeproperty (npp, source, getIdentifierFromString (propertyName));
  481. }
  482. bool hasMethod (const var::identifier& methodName) const
  483. {
  484. return browser.hasmethod (npp, source, getIdentifierFromString (methodName));
  485. }
  486. const var invokeMethod (const var::identifier& methodName,
  487. const var* parameters,
  488. int numParameters)
  489. {
  490. var returnVal;
  491. NPVariant result;
  492. VOID_TO_NPVARIANT (result);
  493. if (numParameters > 0)
  494. {
  495. NPVariant* const params = (NPVariant*) juce_malloc (sizeof (NPVariant) * numParameters);
  496. int i;
  497. for (i = 0; i < numParameters; ++i)
  498. createNPVariantFromValue (npp, params[i], parameters[i]);
  499. if (browser.invoke (npp, source, getIdentifierFromString (methodName),
  500. params, numParameters, &result))
  501. {
  502. returnVal = createValueFromNPVariant (npp, result);
  503. browser.releasevariantvalue (&result);
  504. }
  505. for (i = 0; i < numParameters; ++i)
  506. browser.releasevariantvalue (&params[i]);
  507. juce_free (params);
  508. }
  509. else
  510. {
  511. if (browser.invoke (npp, source, getIdentifierFromString (methodName), 0, 0, &result))
  512. {
  513. returnVal = createValueFromNPVariant (npp, result);
  514. browser.releasevariantvalue (&result);
  515. }
  516. }
  517. return returnVal;
  518. }
  519. };
  520. //==============================================================================
  521. class NPObjectWrappingDynamicObject : public NPObject
  522. {
  523. public:
  524. static NPObject* create (NPP npp, const var& objectToWrap);
  525. virtual ~NPObjectWrappingDynamicObject()
  526. {
  527. DBG ("num Juce wrapper objs: " + String (--numJuceSO));
  528. }
  529. private:
  530. NPObjectWrappingDynamicObject (NPP npp_)
  531. : npp (npp_)
  532. {
  533. DBG ("num Juce wrapper objs: " + String (++numJuceSO));
  534. }
  535. //==============================================================================
  536. bool construct (const NPVariant *args, uint32_t argCount, NPVariant *result);
  537. void invalidate() {}
  538. bool hasMethod (NPIdentifier name)
  539. {
  540. DynamicObject* const o = object.getObject();
  541. return o != 0 && o->hasMethod (identifierToString (name));
  542. }
  543. bool invoke (NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* out)
  544. {
  545. DynamicObject* const o = object.getObject();
  546. const var::identifier methodName (identifierToString (name));
  547. if (o == 0 || ! o->hasMethod (methodName))
  548. return false;
  549. var* params = (var*) juce_calloc (sizeof (var) * argCount);
  550. for (uint32_t i = 0; i < argCount; ++i)
  551. params[i] = createValueFromNPVariant (npp, args[i]);
  552. const var result (o->invokeMethod (methodName, params, argCount));
  553. for (int i = argCount; --i >= 0;)
  554. params[i] = var();
  555. juce_free (params);
  556. if (out != 0)
  557. createNPVariantFromValue (npp, *out, result);
  558. return true;
  559. }
  560. bool invokeDefault (const NPVariant* args, uint32_t argCount, NPVariant* result)
  561. {
  562. return false;
  563. }
  564. bool hasProperty (NPIdentifier name)
  565. {
  566. DynamicObject* const o = object.getObject();
  567. return o != 0 && o->hasProperty (identifierToString (name));
  568. }
  569. bool getProperty (NPIdentifier name, NPVariant* out)
  570. {
  571. DynamicObject* const o = object.getObject();
  572. const var::identifier propName (identifierToString (name));
  573. if (o == 0 || ! o->hasProperty (propName))
  574. return false;
  575. const var result (o->getProperty (propName));
  576. if (out != 0)
  577. createNPVariantFromValue (npp, *out, result);
  578. return true;
  579. }
  580. bool setProperty (NPIdentifier name, const NPVariant* value)
  581. {
  582. DynamicObject* const o = object.getObject();
  583. if (value == 0 || o == 0)
  584. return false;
  585. o->setProperty (identifierToString (name), createValueFromNPVariant (npp, *value));
  586. return true;
  587. }
  588. bool removeProperty (NPIdentifier name)
  589. {
  590. DynamicObject* const o = object.getObject();
  591. const var::identifier propName (identifierToString (name));
  592. if (o == 0 || ! o->hasProperty (propName))
  593. return false;
  594. o->removeProperty (propName);
  595. return true;
  596. }
  597. bool enumerate (NPIdentifier** identifier, uint32_t* count)
  598. {
  599. return false;
  600. }
  601. //==============================================================================
  602. NPP npp;
  603. var object;
  604. static const var::identifier identifierToString (NPIdentifier id)
  605. {
  606. NPUTF8* const name = browser.utf8fromidentifier (id);
  607. const var::identifier result ((const char*) name);
  608. browser.memfree (name);
  609. return result;
  610. }
  611. public:
  612. //==============================================================================
  613. static NPObject* createInstance (NPP npp, NPClass* aClass) { return new NPObjectWrappingDynamicObject (npp); }
  614. static void class_deallocate (NPObject* npobj) { delete (NPObjectWrappingDynamicObject*) npobj; }
  615. static void class_invalidate (NPObject* npobj) { ((NPObjectWrappingDynamicObject*) npobj)->invalidate(); }
  616. static bool class_hasMethod (NPObject* npobj, NPIdentifier name) { return ((NPObjectWrappingDynamicObject*) npobj)->hasMethod (name); }
  617. static bool class_invoke (NPObject* npobj, NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->invoke (name, args, argCount, result); }
  618. static bool class_invokeDefault (NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->invokeDefault (args, argCount, result); }
  619. static bool class_hasProperty (NPObject* npobj, NPIdentifier name) { return ((NPObjectWrappingDynamicObject*) npobj)->hasProperty (name); }
  620. static bool class_getProperty (NPObject* npobj, NPIdentifier name, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->getProperty (name, result); }
  621. static bool class_setProperty (NPObject* npobj, NPIdentifier name, const NPVariant* value) { return ((NPObjectWrappingDynamicObject*) npobj)->setProperty (name, value); }
  622. static bool class_removeProperty (NPObject* npobj, NPIdentifier name) { return ((NPObjectWrappingDynamicObject*) npobj)->removeProperty (name); }
  623. static bool class_enumerate (NPObject* npobj, NPIdentifier** identifier, uint32_t* count) { return ((NPObjectWrappingDynamicObject*) npobj)->enumerate (identifier, count); }
  624. static bool class_construct (NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->construct (args, argCount, result); }
  625. };
  626. #ifndef NP_CLASS_STRUCT_VERSION_ENUM
  627. static NPClass sNPObjectWrappingDynamicObject_NPClass =
  628. {
  629. NP_CLASS_STRUCT_VERSION, NPObjectWrappingDynamicObject::createInstance,
  630. NPObjectWrappingDynamicObject::class_deallocate, NPObjectWrappingDynamicObject::class_invalidate,
  631. NPObjectWrappingDynamicObject::class_hasMethod, NPObjectWrappingDynamicObject::class_invoke,
  632. NPObjectWrappingDynamicObject::class_invokeDefault, NPObjectWrappingDynamicObject::class_hasProperty,
  633. NPObjectWrappingDynamicObject::class_getProperty, NPObjectWrappingDynamicObject::class_setProperty,
  634. NPObjectWrappingDynamicObject::class_removeProperty
  635. };
  636. #else
  637. static NPClass sNPObjectWrappingDynamicObject_NPClass =
  638. {
  639. NP_CLASS_STRUCT_VERSION_ENUM, NPObjectWrappingDynamicObject::createInstance,
  640. NPObjectWrappingDynamicObject::class_deallocate, NPObjectWrappingDynamicObject::class_invalidate,
  641. NPObjectWrappingDynamicObject::class_hasMethod, NPObjectWrappingDynamicObject::class_invoke,
  642. NPObjectWrappingDynamicObject::class_invokeDefault, NPObjectWrappingDynamicObject::class_hasProperty,
  643. NPObjectWrappingDynamicObject::class_getProperty, NPObjectWrappingDynamicObject::class_setProperty,
  644. NPObjectWrappingDynamicObject::class_removeProperty, NPObjectWrappingDynamicObject::class_enumerate
  645. };
  646. #endif
  647. bool NPObjectWrappingDynamicObject::construct (const NPVariant* args, uint32_t argCount, NPVariant* result)
  648. {
  649. NPObject* const newObj = browser.createobject (npp, &sNPObjectWrappingDynamicObject_NPClass);
  650. if (newObj == 0)
  651. return false;
  652. OBJECT_TO_NPVARIANT (newObj, *result);
  653. return true;
  654. }
  655. NPObject* NPObjectWrappingDynamicObject::create (NPP npp, const var& objectToWrap)
  656. {
  657. jassert (objectToWrap.getObject() != 0);
  658. NPObject* const nppObject = browser.createobject (npp, &sNPObjectWrappingDynamicObject_NPClass);
  659. if (nppObject != 0)
  660. ((NPObjectWrappingDynamicObject*) nppObject)->object = objectToWrap;
  661. return nppObject;
  662. }
  663. //==============================================================================
  664. static const var createValueFromNPVariant (NPP npp, const NPVariant& v)
  665. {
  666. if (NPVARIANT_IS_BOOLEAN (v))
  667. return var (NPVARIANT_TO_BOOLEAN (v));
  668. else if (NPVARIANT_IS_INT32 (v))
  669. return var (NPVARIANT_TO_INT32 (v));
  670. else if (NPVARIANT_IS_DOUBLE (v))
  671. return var (NPVARIANT_TO_DOUBLE (v));
  672. else if (NPVARIANT_IS_STRING (v))
  673. #if JUCE_MAC
  674. return var (String::fromUTF8 ((const juce::uint8*) (NPVARIANT_TO_STRING (v).UTF8Characters),
  675. (int) NPVARIANT_TO_STRING (v).UTF8Length));
  676. #else
  677. return var (String::fromUTF8 ((const juce::uint8*) (NPVARIANT_TO_STRING (v).utf8characters),
  678. (int) NPVARIANT_TO_STRING (v).utf8length));
  679. #endif
  680. else if (NPVARIANT_IS_OBJECT (v))
  681. return var (new DynamicObjectWrappingNPObject (npp, NPVARIANT_TO_OBJECT (v)));
  682. return var();
  683. }
  684. static void createNPVariantFromValue (NPP npp, NPVariant& out, const var& v)
  685. {
  686. if (v.isInt())
  687. INT32_TO_NPVARIANT ((int) v, out);
  688. else if (v.isBool())
  689. BOOLEAN_TO_NPVARIANT ((bool) v, out);
  690. else if (v.isDouble())
  691. DOUBLE_TO_NPVARIANT ((double) v, out);
  692. else if (v.isString())
  693. {
  694. const String s (v.toString());
  695. const char* const utf8 = s.toUTF8();
  696. const int utf8Len = strlen (utf8) + 1;
  697. char* const stringCopy = (char*) browser.memalloc (utf8Len);
  698. memcpy (stringCopy, utf8, utf8Len);
  699. STRINGZ_TO_NPVARIANT (stringCopy, out);
  700. }
  701. else if (v.isObject())
  702. OBJECT_TO_NPVARIANT (NPObjectWrappingDynamicObject::create (npp, v), out);
  703. else
  704. VOID_TO_NPVARIANT (out);
  705. }
  706. //==============================================================================
  707. class JucePluginInstance
  708. {
  709. public:
  710. //==============================================================================
  711. JucePluginInstance (NPP npp_)
  712. : npp (npp_),
  713. holderComp (0),
  714. scriptObject (0)
  715. {
  716. }
  717. ~JucePluginInstance()
  718. {
  719. setWindow (0);
  720. }
  721. bool setWindow (NPWindow* window)
  722. {
  723. if (window != 0)
  724. {
  725. if (holderComp == 0)
  726. holderComp = new BrowserPluginHolderComponent (npp);
  727. holderComp->setWindow (window);
  728. }
  729. else
  730. {
  731. deleteAndZero (holderComp);
  732. scriptObject = 0;
  733. }
  734. return true;
  735. }
  736. NPObject* getScriptableObject()
  737. {
  738. if (scriptObject == 0)
  739. scriptObject = NPObjectWrappingDynamicObject::create (npp, holderComp->getObject());
  740. if (scriptObject != 0 && shouldRetainBrowserObject())
  741. browser.retainobject (scriptObject);
  742. return scriptObject;
  743. }
  744. //==============================================================================
  745. NPP npp;
  746. BrowserPluginHolderComponent* holderComp;
  747. NPObject* scriptObject;
  748. private:
  749. bool shouldRetainBrowserObject() const
  750. {
  751. const String version (browser.uagent (npp));
  752. if (! version.containsIgnoreCase (T(" AppleWebKit/")))
  753. return true;
  754. int versionNum = version.fromFirstOccurrenceOf (T(" AppleWebKit/"), false, true).getIntValue();
  755. return versionNum == 0 || versionNum >= 420;
  756. }
  757. };
  758. //==============================================================================
  759. static NPP currentlyInitialisingNPP = 0;
  760. static int numPluginInstances = 0;
  761. NPError NPP_New (NPMIMEType pluginType, NPP npp, ::uint16 mode, ::int16 argc, char* argn[], char* argv[], NPSavedData* saved)
  762. {
  763. log ("NPP_New");
  764. if (npp == 0)
  765. return NPERR_INVALID_INSTANCE_ERROR;
  766. #if JUCE_MAC
  767. browser.setvalue (npp, (NPPVariable) NPNVpluginDrawingModel, (void*) NPDrawingModelCoreGraphics);
  768. #endif
  769. if (numPluginInstances++ == 0)
  770. {
  771. log ("initialiseJuce_GUI()");
  772. initialiseJuce_GUI();
  773. }
  774. currentlyInitialisingNPP = npp;
  775. JucePluginInstance* p = new JucePluginInstance (npp);
  776. currentlyInitialisingNPP = 0;
  777. npp->pdata = (void*) p;
  778. return NPERR_NO_ERROR;
  779. }
  780. NPError NPP_Destroy (NPP npp, NPSavedData** save)
  781. {
  782. log ("NPP_Destroy");
  783. if (npp == 0)
  784. return NPERR_INVALID_INSTANCE_ERROR;
  785. JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  786. if (p != 0)
  787. {
  788. delete p;
  789. if (--numPluginInstances == 0)
  790. {
  791. log ("shutdownJuce_GUI()");
  792. shutdownJuce_GUI();
  793. browserVersionDesc = String::empty;
  794. }
  795. }
  796. return NPERR_NO_ERROR;
  797. }
  798. NPError NPP_SetWindow (NPP npp, NPWindow* pNPWindow)
  799. {
  800. if (npp == 0)
  801. return NPERR_INVALID_INSTANCE_ERROR;
  802. if (pNPWindow == 0)
  803. return NPERR_GENERIC_ERROR;
  804. JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  805. if (p == 0)
  806. return NPERR_GENERIC_ERROR;
  807. currentlyInitialisingNPP = npp;
  808. NPError result = p->setWindow (pNPWindow) ? NPERR_NO_ERROR
  809. : NPERR_MODULE_LOAD_FAILED_ERROR;
  810. currentlyInitialisingNPP = 0;
  811. return result;
  812. }
  813. //==============================================================================
  814. NPError NPP_GetValue (NPP npp, NPPVariable variable, void* value)
  815. {
  816. if (npp == 0)
  817. return NPERR_INVALID_INSTANCE_ERROR;
  818. JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  819. if (p == 0)
  820. return NPERR_GENERIC_ERROR;
  821. switch (variable)
  822. {
  823. case NPPVpluginNameString:
  824. *((char**) value) = JuceBrowserPlugin_Name;
  825. break;
  826. case NPPVpluginDescriptionString:
  827. *((char**) value) = JuceBrowserPlugin_Desc;
  828. break;
  829. case NPPVpluginScriptableNPObject:
  830. *((NPObject**) value) = p->getScriptableObject();
  831. break;
  832. default:
  833. return NPERR_GENERIC_ERROR;
  834. }
  835. return NPERR_NO_ERROR;
  836. }
  837. NPError NPP_NewStream (NPP npp,
  838. NPMIMEType type,
  839. NPStream* stream,
  840. NPBool seekable,
  841. ::uint16* stype)
  842. {
  843. if (npp == 0)
  844. return NPERR_INVALID_INSTANCE_ERROR;
  845. return NPERR_NO_ERROR;
  846. }
  847. ::int32 NPP_WriteReady (NPP npp, NPStream *stream)
  848. {
  849. if (npp == 0)
  850. return NPERR_INVALID_INSTANCE_ERROR;
  851. return 0x0fffffff;
  852. }
  853. ::int32 NPP_Write (NPP npp, NPStream *stream, ::int32 offset, ::int32 len, void *buffer)
  854. {
  855. if (npp == 0)
  856. return NPERR_INVALID_INSTANCE_ERROR;
  857. return len;
  858. }
  859. NPError NPP_DestroyStream (NPP npp, NPStream *stream, NPError reason)
  860. {
  861. if (npp == 0)
  862. return NPERR_INVALID_INSTANCE_ERROR;
  863. return NPERR_NO_ERROR;
  864. }
  865. void NPP_StreamAsFile (NPP npp, NPStream* stream, const char* fname)
  866. {
  867. if (npp == 0)
  868. return;
  869. }
  870. void NPP_Print (NPP npp, NPPrint* printInfo)
  871. {
  872. if (npp == 0)
  873. return;
  874. }
  875. void NPP_URLNotify (NPP npp, const char* url, NPReason reason, void* notifyData)
  876. {
  877. if (npp == 0)
  878. return;
  879. }
  880. NPError NPP_SetValue (NPP npp, NPNVariable variable, void* value)
  881. {
  882. if (npp == 0)
  883. return NPERR_INVALID_INSTANCE_ERROR;
  884. return NPERR_NO_ERROR;
  885. }
  886. ::int16 NPP_HandleEvent (NPP npp, void* ev)
  887. {
  888. if (npp != 0)
  889. {
  890. //JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  891. }
  892. return 0;
  893. }
  894. //==============================================================================
  895. static NPP getInstance (const BrowserPluginComponent* bpc)
  896. {
  897. BrowserPluginHolderComponent* holder = dynamic_cast <BrowserPluginHolderComponent*> (bpc->getParentComponent());
  898. if (holder != 0)
  899. return holder->npp;
  900. return currentlyInitialisingNPP;
  901. }
  902. //==============================================================================
  903. BrowserPluginComponent::BrowserPluginComponent()
  904. {
  905. }
  906. BrowserPluginComponent::~BrowserPluginComponent()
  907. {
  908. }
  909. const String BrowserPluginComponent::getBrowserVersion() const
  910. {
  911. if (browserVersionDesc.isEmpty())
  912. {
  913. if (getInstance (this) != 0)
  914. browserVersionDesc << browser.uagent (getInstance (this));
  915. else
  916. browserVersionDesc << "Netscape Plugin V" << (int) ((browser.version >> 8) & 0xff)
  917. << "." << (int) (browser.version & 0xff);
  918. }
  919. return browserVersionDesc;
  920. }
  921. //==============================================================================
  922. #if JUCE_WIN32
  923. extern const String getActiveXBrowserURL (const BrowserPluginComponent* comp);
  924. #endif
  925. const String BrowserPluginComponent::getBrowserURL() const
  926. {
  927. String result;
  928. #if JUCE_WIN32
  929. result = getActiveXBrowserURL (this);
  930. if (result.isNotEmpty())
  931. return result;
  932. #endif
  933. // (FireFox doesn't seem happy if you call this from a background thread..)
  934. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  935. NPP npp = getInstance (this);
  936. if (npp != 0)
  937. {
  938. NPObject* windowObj = 0;
  939. browser.getvalue (npp, NPNVWindowNPObject, &windowObj);
  940. if (windowObj != 0)
  941. {
  942. NPVariant location;
  943. bool ok = browser.getproperty (npp, windowObj,
  944. browser.getstringidentifier ("location"), &location);
  945. browser.releaseobject (windowObj);
  946. jassert (ok);
  947. if (ok)
  948. {
  949. NPVariant href;
  950. ok = browser.getproperty (npp, location.value.objectValue,
  951. browser.getstringidentifier ("href"), &href);
  952. browser.releasevariantvalue (&location);
  953. jassert (ok);
  954. if (ok)
  955. {
  956. result = URL::removeEscapeChars (createValueFromNPVariant (npp, href).toString());
  957. browser.releasevariantvalue (&href);
  958. }
  959. }
  960. }
  961. }
  962. return result;
  963. }