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.

1183 lines
38KB

  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()
  268. {
  269. if (IsWindow (parentHWND))
  270. {
  271. RECT r;
  272. GetWindowRect (parentHWND, &r);
  273. setBounds (0, 0, r.right - r.left, r.bottom - r.top);
  274. }
  275. }
  276. static LRESULT CALLBACK interceptingWinProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
  277. {
  278. switch (msg)
  279. {
  280. case WM_PAINT:
  281. {
  282. PAINTSTRUCT ps;
  283. HDC hdc = BeginPaint (hWnd, &ps);
  284. EndPaint (hWnd, &ps);
  285. }
  286. return 0;
  287. case WM_ERASEBKGND:
  288. return 1;
  289. case WM_WINDOWPOSCHANGING:
  290. if ((((WINDOWPOS*) lParam)->flags & SWP_NOSIZE) == 0)
  291. {
  292. BrowserPluginHolderComponent* const comp = (BrowserPluginHolderComponent*) GetWindowLongPtr (hWnd, GWL_USERDATA);
  293. comp->resizeToParentWindow();
  294. }
  295. break;
  296. default:
  297. break;
  298. }
  299. return DefWindowProc (hWnd, msg, wParam, lParam);
  300. }
  301. public:
  302. void setWindow (NPWindow* window)
  303. {
  304. HWND newHWND = (window != 0 ? ((HWND) window->window) : 0);
  305. if (parentHWND != newHWND)
  306. {
  307. removeFromDesktop();
  308. setVisible (false);
  309. if (IsWindow (parentHWND))
  310. {
  311. SubclassWindow (parentHWND, oldWinProc); // restore the old winproc..
  312. oldWinProc = 0;
  313. }
  314. parentHWND = newHWND;
  315. if (parentHWND != 0)
  316. {
  317. addToDesktop (0);
  318. HWND ourHWND = (HWND) getWindowHandle();
  319. SetParent (ourHWND, parentHWND);
  320. DWORD val = GetWindowLongPtr (ourHWND, GWL_STYLE);
  321. val = (val & ~WS_POPUP) | WS_CHILD;
  322. SetWindowLongPtr (ourHWND, GWL_STYLE, val);
  323. setVisible (true);
  324. oldWinProc = SubclassWindow (parentHWND, (WNDPROC) interceptingWinProc);
  325. SetWindowLongPtr (parentHWND, GWL_USERDATA, (LONG_PTR) this);
  326. resizeToParentWindow();
  327. }
  328. }
  329. }
  330. //==============================================================================
  331. #else
  332. NSView* currentParentView;
  333. NSView* findViewAt (NSView* parent, float x, float y) const
  334. {
  335. NSRect frame = [parent frame];
  336. NSRect bounds = [parent bounds];
  337. x -= frame.origin.x;
  338. y -= frame.origin.y;
  339. Rectangle rr (frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
  340. Rectangle rr2 (bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
  341. //log (String ((int) x) + ", " + String ((int) y) + " - " + nsStringToJuce([parent description]) + " " + rr.toString() + " " + rr2.toString());
  342. if (x >= 0 && x < frame.size.width && y >= 0 && y < frame.size.height)
  343. {
  344. x += bounds.origin.x; // adjust for scrolling panels
  345. y += bounds.origin.y;
  346. for (int i = [[parent subviews] count]; --i >= 0;)
  347. {
  348. NSView* v = (NSView*) [[parent subviews] objectAtIndex: i];
  349. if (v != (NSView*) getWindowHandle())
  350. {
  351. NSView* found = findViewAt (v, x, y);
  352. if (found != 0)
  353. return found;
  354. }
  355. }
  356. return parent;
  357. }
  358. return 0;
  359. }
  360. public:
  361. static bool isBrowserContentView (NSView* v)
  362. {
  363. return [[v className] isEqualToString: @"WebNetscapePluginDocumentView"]
  364. || [[v className] isEqualToString: @"WebPluginDocumentView"]
  365. || ([[v className] isEqualToString: @"ChildView"] && ([v frame].origin.x != 0 && [v frame].origin.y != 0));
  366. }
  367. void setWindow (NPWindow* window)
  368. {
  369. const ScopedAutoReleasePool pool;
  370. NSView* parentView = 0;
  371. WindowRef windowRef = window != 0 ? ((NP_CGContext*) window->window)->window : 0;
  372. if (windowRef != 0)
  373. {
  374. NSWindow* win = [[[NSWindow alloc] initWithWindowRef: windowRef] autorelease];
  375. const Rectangle clip (window->clipRect.left, window->clipRect.top,
  376. window->clipRect.right - window->clipRect.left,
  377. window->clipRect.bottom - window->clipRect.top);
  378. const Rectangle target ((int) window->x, (int) window->y, (int) window->width, (int) window->height);
  379. const Rectangle intersection (clip.getIntersection (target));
  380. // in firefox the clip rect is usually out of step with the target rect, but in safari it matches
  381. log ("plugin window clip: " + clip.toString());
  382. log ("plugin window target: " + target.toString());
  383. log ("plugin window intersection: " + intersection.toString());
  384. if (! intersection.isEmpty())
  385. {
  386. NSView* content = [win contentView];
  387. float wx = (float) intersection.getCentreX();
  388. float wy = (float) intersection.getCentreY();
  389. NSRect v = [content convertRect: [content frame] toView: nil];
  390. NSRect w = [win frame];
  391. log ("wx: " + Rectangle (v.origin.x, v.origin.y, v.size.width, v.size.height).toString()
  392. + " " + Rectangle (w.origin.x, w.origin.y, w.size.width, w.size.height).toString());
  393. // adjust the requested window pos to deal with the content view's origin within the window
  394. wy -= w.size.height - (v.origin.y + v.size.height);
  395. parentView = findViewAt (content, wx, wy);
  396. if (! isBrowserContentView (parentView))
  397. parentView = currentParentView;
  398. }
  399. log ("parent: " + nsStringToJuce ([parentView description]));
  400. }
  401. if (parentView != currentParentView)
  402. {
  403. log ("new view: " + nsStringToJuce ([parentView description]));
  404. removeFromDesktop();
  405. setVisible (false);
  406. currentParentView = parentView;
  407. if (parentView != 0)
  408. {
  409. setSize (window->width, window->height);
  410. addToDesktop (0, parentView);
  411. setVisible (true);
  412. }
  413. }
  414. if (window != 0)
  415. setSize (window->width, window->height);
  416. }
  417. #endif
  418. };
  419. //==============================================================================
  420. static NPIdentifier getIdentifierFromString (const var::identifier& s) throw()
  421. {
  422. return browser.getstringidentifier (s.name.toUTF8());
  423. }
  424. static const var createValueFromNPVariant (NPP npp, const NPVariant& v);
  425. static void createNPVariantFromValue (NPP npp, NPVariant& out, const var& v);
  426. #if JUCE_DEBUG
  427. static int numDOWNP = 0, numJuceSO = 0;
  428. #endif
  429. //==============================================================================
  430. class DynamicObjectWrappingNPObject : public DynamicObject
  431. {
  432. NPP npp;
  433. NPObject* const source;
  434. public:
  435. DynamicObjectWrappingNPObject (NPP npp_, NPObject* const source_)
  436. : npp (npp_),
  437. source (browser.retainobject (source_))
  438. {
  439. DBG ("num NP wrapper objs: " + String (++numDOWNP));
  440. }
  441. ~DynamicObjectWrappingNPObject()
  442. {
  443. browser.releaseobject (source);
  444. DBG ("num NP wrapper objs: " + String (--numDOWNP));
  445. }
  446. const var getProperty (const var::identifier& propertyName) const
  447. {
  448. NPVariant result;
  449. VOID_TO_NPVARIANT (result);
  450. browser.getproperty (npp, source, getIdentifierFromString (propertyName), &result);
  451. const var v (createValueFromNPVariant (npp, result));
  452. browser.releasevariantvalue (&result);
  453. return v;
  454. }
  455. bool hasProperty (const var::identifier& propertyName) const
  456. {
  457. NPVariant result;
  458. VOID_TO_NPVARIANT (result);
  459. const bool hasProp = browser.getproperty (npp, source, getIdentifierFromString (propertyName), &result);
  460. browser.releasevariantvalue (&result);
  461. return hasProp;
  462. }
  463. void setProperty (const var::identifier& propertyName, const var& newValue)
  464. {
  465. NPVariant value;
  466. createNPVariantFromValue (npp, value, newValue);
  467. browser.setproperty (npp, source, getIdentifierFromString (propertyName), &value);
  468. browser.releasevariantvalue (&value);
  469. }
  470. void removeProperty (const var::identifier& propertyName)
  471. {
  472. browser.removeproperty (npp, source, getIdentifierFromString (propertyName));
  473. }
  474. bool hasMethod (const var::identifier& methodName) const
  475. {
  476. return browser.hasmethod (npp, source, getIdentifierFromString (methodName));
  477. }
  478. const var invokeMethod (const var::identifier& methodName,
  479. const var* parameters,
  480. int numParameters)
  481. {
  482. var returnVal;
  483. NPVariant result;
  484. VOID_TO_NPVARIANT (result);
  485. if (numParameters > 0)
  486. {
  487. NPVariant* const params = (NPVariant*) juce_malloc (sizeof (NPVariant) * numParameters);
  488. int i;
  489. for (i = 0; i < numParameters; ++i)
  490. createNPVariantFromValue (npp, params[i], parameters[i]);
  491. if (browser.invoke (npp, source, getIdentifierFromString (methodName),
  492. params, numParameters, &result))
  493. {
  494. returnVal = createValueFromNPVariant (npp, result);
  495. browser.releasevariantvalue (&result);
  496. }
  497. for (i = 0; i < numParameters; ++i)
  498. browser.releasevariantvalue (&params[i]);
  499. juce_free (params);
  500. }
  501. else
  502. {
  503. if (browser.invoke (npp, source, getIdentifierFromString (methodName), 0, 0, &result))
  504. {
  505. returnVal = createValueFromNPVariant (npp, result);
  506. browser.releasevariantvalue (&result);
  507. }
  508. }
  509. return returnVal;
  510. }
  511. };
  512. //==============================================================================
  513. class NPObjectWrappingDynamicObject : public NPObject
  514. {
  515. public:
  516. static NPObject* create (NPP npp, const var& objectToWrap);
  517. virtual ~NPObjectWrappingDynamicObject()
  518. {
  519. DBG ("num Juce wrapper objs: " + String (--numJuceSO));
  520. }
  521. private:
  522. NPObjectWrappingDynamicObject (NPP npp_)
  523. : npp (npp_)
  524. {
  525. DBG ("num Juce wrapper objs: " + String (++numJuceSO));
  526. }
  527. //==============================================================================
  528. bool construct (const NPVariant *args, uint32_t argCount, NPVariant *result);
  529. void invalidate() {}
  530. bool hasMethod (NPIdentifier name)
  531. {
  532. DynamicObject* const o = object.getObject();
  533. return o != 0 && o->hasMethod (identifierToString (name));
  534. }
  535. bool invoke (NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* out)
  536. {
  537. DynamicObject* const o = object.getObject();
  538. const var::identifier methodName (identifierToString (name));
  539. if (o == 0 || ! o->hasMethod (methodName))
  540. return false;
  541. var* params = (var*) juce_calloc (sizeof (var) * argCount);
  542. for (uint32_t i = 0; i < argCount; ++i)
  543. params[i] = createValueFromNPVariant (npp, args[i]);
  544. const var result (o->invokeMethod (methodName, params, argCount));
  545. for (int i = argCount; --i >= 0;)
  546. params[i] = var();
  547. juce_free (params);
  548. if (out != 0)
  549. createNPVariantFromValue (npp, *out, result);
  550. return true;
  551. }
  552. bool invokeDefault (const NPVariant* args, uint32_t argCount, NPVariant* result)
  553. {
  554. return false;
  555. }
  556. bool hasProperty (NPIdentifier name)
  557. {
  558. DynamicObject* const o = object.getObject();
  559. return o != 0 && o->hasProperty (identifierToString (name));
  560. }
  561. bool getProperty (NPIdentifier name, NPVariant* out)
  562. {
  563. DynamicObject* const o = object.getObject();
  564. const var::identifier propName (identifierToString (name));
  565. if (o == 0 || ! o->hasProperty (propName))
  566. return false;
  567. const var result (o->getProperty (propName));
  568. if (out != 0)
  569. createNPVariantFromValue (npp, *out, result);
  570. return true;
  571. }
  572. bool setProperty (NPIdentifier name, const NPVariant* value)
  573. {
  574. DynamicObject* const o = object.getObject();
  575. if (value == 0 || o == 0)
  576. return false;
  577. o->setProperty (identifierToString (name), createValueFromNPVariant (npp, *value));
  578. return true;
  579. }
  580. bool removeProperty (NPIdentifier name)
  581. {
  582. DynamicObject* const o = object.getObject();
  583. const var::identifier propName (identifierToString (name));
  584. if (o == 0 || ! o->hasProperty (propName))
  585. return false;
  586. o->removeProperty (propName);
  587. return true;
  588. }
  589. bool enumerate (NPIdentifier** identifier, uint32_t* count)
  590. {
  591. return false;
  592. }
  593. //==============================================================================
  594. NPP npp;
  595. var object;
  596. static const var::identifier identifierToString (NPIdentifier id)
  597. {
  598. NPUTF8* const name = browser.utf8fromidentifier (id);
  599. const var::identifier result ((const char*) name);
  600. browser.memfree (name);
  601. return result;
  602. }
  603. public:
  604. //==============================================================================
  605. static NPObject* createInstance (NPP npp, NPClass* aClass) { return new NPObjectWrappingDynamicObject (npp); }
  606. static void class_deallocate (NPObject* npobj) { delete (NPObjectWrappingDynamicObject*) npobj; }
  607. static void class_invalidate (NPObject* npobj) { ((NPObjectWrappingDynamicObject*) npobj)->invalidate(); }
  608. static bool class_hasMethod (NPObject* npobj, NPIdentifier name) { return ((NPObjectWrappingDynamicObject*) npobj)->hasMethod (name); }
  609. static bool class_invoke (NPObject* npobj, NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->invoke (name, args, argCount, result); }
  610. static bool class_invokeDefault (NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->invokeDefault (args, argCount, result); }
  611. static bool class_hasProperty (NPObject* npobj, NPIdentifier name) { return ((NPObjectWrappingDynamicObject*) npobj)->hasProperty (name); }
  612. static bool class_getProperty (NPObject* npobj, NPIdentifier name, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->getProperty (name, result); }
  613. static bool class_setProperty (NPObject* npobj, NPIdentifier name, const NPVariant* value) { return ((NPObjectWrappingDynamicObject*) npobj)->setProperty (name, value); }
  614. static bool class_removeProperty (NPObject* npobj, NPIdentifier name) { return ((NPObjectWrappingDynamicObject*) npobj)->removeProperty (name); }
  615. static bool class_enumerate (NPObject* npobj, NPIdentifier** identifier, uint32_t* count) { return ((NPObjectWrappingDynamicObject*) npobj)->enumerate (identifier, count); }
  616. static bool class_construct (NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { return ((NPObjectWrappingDynamicObject*) npobj)->construct (args, argCount, result); }
  617. };
  618. #ifndef NP_CLASS_STRUCT_VERSION_ENUM
  619. static NPClass sNPObjectWrappingDynamicObject_NPClass =
  620. {
  621. NP_CLASS_STRUCT_VERSION, NPObjectWrappingDynamicObject::createInstance,
  622. NPObjectWrappingDynamicObject::class_deallocate, NPObjectWrappingDynamicObject::class_invalidate,
  623. NPObjectWrappingDynamicObject::class_hasMethod, NPObjectWrappingDynamicObject::class_invoke,
  624. NPObjectWrappingDynamicObject::class_invokeDefault, NPObjectWrappingDynamicObject::class_hasProperty,
  625. NPObjectWrappingDynamicObject::class_getProperty, NPObjectWrappingDynamicObject::class_setProperty,
  626. NPObjectWrappingDynamicObject::class_removeProperty
  627. };
  628. #else
  629. static NPClass sNPObjectWrappingDynamicObject_NPClass =
  630. {
  631. NP_CLASS_STRUCT_VERSION_ENUM, NPObjectWrappingDynamicObject::createInstance,
  632. NPObjectWrappingDynamicObject::class_deallocate, NPObjectWrappingDynamicObject::class_invalidate,
  633. NPObjectWrappingDynamicObject::class_hasMethod, NPObjectWrappingDynamicObject::class_invoke,
  634. NPObjectWrappingDynamicObject::class_invokeDefault, NPObjectWrappingDynamicObject::class_hasProperty,
  635. NPObjectWrappingDynamicObject::class_getProperty, NPObjectWrappingDynamicObject::class_setProperty,
  636. NPObjectWrappingDynamicObject::class_removeProperty, NPObjectWrappingDynamicObject::class_enumerate
  637. };
  638. #endif
  639. bool NPObjectWrappingDynamicObject::construct (const NPVariant* args, uint32_t argCount, NPVariant* result)
  640. {
  641. NPObject* const newObj = browser.createobject (npp, &sNPObjectWrappingDynamicObject_NPClass);
  642. if (newObj == 0)
  643. return false;
  644. OBJECT_TO_NPVARIANT (newObj, *result);
  645. return true;
  646. }
  647. NPObject* NPObjectWrappingDynamicObject::create (NPP npp, const var& objectToWrap)
  648. {
  649. jassert (objectToWrap.getObject() != 0);
  650. NPObject* const nppObject = browser.createobject (npp, &sNPObjectWrappingDynamicObject_NPClass);
  651. if (nppObject != 0)
  652. ((NPObjectWrappingDynamicObject*) nppObject)->object = objectToWrap;
  653. return nppObject;
  654. }
  655. //==============================================================================
  656. static const var createValueFromNPVariant (NPP npp, const NPVariant& v)
  657. {
  658. if (NPVARIANT_IS_BOOLEAN (v))
  659. return var (NPVARIANT_TO_BOOLEAN (v));
  660. else if (NPVARIANT_IS_INT32 (v))
  661. return var (NPVARIANT_TO_INT32 (v));
  662. else if (NPVARIANT_IS_DOUBLE (v))
  663. return var (NPVARIANT_TO_DOUBLE (v));
  664. else if (NPVARIANT_IS_STRING (v))
  665. #if JUCE_MAC
  666. return var (String::fromUTF8 ((const juce::uint8*) (NPVARIANT_TO_STRING (v).UTF8Characters),
  667. (int) NPVARIANT_TO_STRING (v).UTF8Length));
  668. #else
  669. return var (String::fromUTF8 ((const juce::uint8*) (NPVARIANT_TO_STRING (v).utf8characters),
  670. (int) NPVARIANT_TO_STRING (v).utf8length));
  671. #endif
  672. else if (NPVARIANT_IS_OBJECT (v))
  673. return var (new DynamicObjectWrappingNPObject (npp, NPVARIANT_TO_OBJECT (v)));
  674. return var();
  675. }
  676. static void createNPVariantFromValue (NPP npp, NPVariant& out, const var& v)
  677. {
  678. if (v.isInt())
  679. INT32_TO_NPVARIANT ((int) v, out);
  680. else if (v.isBool())
  681. BOOLEAN_TO_NPVARIANT ((bool) v, out);
  682. else if (v.isDouble())
  683. DOUBLE_TO_NPVARIANT ((double) v, out);
  684. else if (v.isString())
  685. {
  686. const String s (v.toString());
  687. const char* const utf8 = s.toUTF8();
  688. const int utf8Len = strlen (utf8) + 1;
  689. char* const stringCopy = (char*) browser.memalloc (utf8Len);
  690. memcpy (stringCopy, utf8, utf8Len);
  691. STRINGZ_TO_NPVARIANT (stringCopy, out);
  692. }
  693. else if (v.isObject())
  694. OBJECT_TO_NPVARIANT (NPObjectWrappingDynamicObject::create (npp, v), out);
  695. else
  696. VOID_TO_NPVARIANT (out);
  697. }
  698. //==============================================================================
  699. class JucePluginInstance
  700. {
  701. public:
  702. //==============================================================================
  703. JucePluginInstance (NPP npp_)
  704. : npp (npp_),
  705. holderComp (0),
  706. scriptObject (0)
  707. {
  708. }
  709. ~JucePluginInstance()
  710. {
  711. setWindow (0);
  712. }
  713. bool setWindow (NPWindow* window)
  714. {
  715. if (window != 0)
  716. {
  717. if (holderComp == 0)
  718. holderComp = new BrowserPluginHolderComponent (npp);
  719. holderComp->setWindow (window);
  720. }
  721. else
  722. {
  723. deleteAndZero (holderComp);
  724. scriptObject = 0;
  725. }
  726. return true;
  727. }
  728. NPObject* getScriptableObject()
  729. {
  730. if (scriptObject == 0)
  731. scriptObject = NPObjectWrappingDynamicObject::create (npp, holderComp->getObject());
  732. if (scriptObject != 0 && shouldRetainBrowserObject())
  733. browser.retainobject (scriptObject);
  734. return scriptObject;
  735. }
  736. //==============================================================================
  737. NPP npp;
  738. BrowserPluginHolderComponent* holderComp;
  739. NPObject* scriptObject;
  740. private:
  741. bool shouldRetainBrowserObject() const
  742. {
  743. const String version (browser.uagent (npp));
  744. if (! version.containsIgnoreCase (T(" AppleWebKit/")))
  745. return true;
  746. int versionNum = version.fromFirstOccurrenceOf (T(" AppleWebKit/"), false, true).getIntValue();
  747. return versionNum == 0 || versionNum >= 420;
  748. }
  749. };
  750. //==============================================================================
  751. static NPP currentlyInitialisingNPP = 0;
  752. static int numPluginInstances = 0;
  753. NPError NPP_New (NPMIMEType pluginType, NPP npp, ::uint16 mode, ::int16 argc, char* argn[], char* argv[], NPSavedData* saved)
  754. {
  755. log ("NPP_New");
  756. if (npp == 0)
  757. return NPERR_INVALID_INSTANCE_ERROR;
  758. #if JUCE_MAC
  759. browser.setvalue (npp, (NPPVariable) NPNVpluginDrawingModel, (void*) NPDrawingModelCoreGraphics);
  760. #endif
  761. if (numPluginInstances++ == 0)
  762. {
  763. log ("initialiseJuce_GUI()");
  764. initialiseJuce_GUI();
  765. }
  766. currentlyInitialisingNPP = npp;
  767. JucePluginInstance* p = new JucePluginInstance (npp);
  768. currentlyInitialisingNPP = 0;
  769. npp->pdata = (void*) p;
  770. return NPERR_NO_ERROR;
  771. }
  772. NPError NPP_Destroy (NPP npp, NPSavedData** save)
  773. {
  774. log ("NPP_Destroy");
  775. if (npp == 0)
  776. return NPERR_INVALID_INSTANCE_ERROR;
  777. JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  778. if (p != 0)
  779. {
  780. delete p;
  781. if (--numPluginInstances == 0)
  782. {
  783. log ("shutdownJuce_GUI()");
  784. shutdownJuce_GUI();
  785. browserVersionDesc = String::empty;
  786. }
  787. }
  788. return NPERR_NO_ERROR;
  789. }
  790. NPError NPP_SetWindow (NPP npp, NPWindow* pNPWindow)
  791. {
  792. if (npp == 0)
  793. return NPERR_INVALID_INSTANCE_ERROR;
  794. if (pNPWindow == 0)
  795. return NPERR_GENERIC_ERROR;
  796. JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  797. if (p == 0)
  798. return NPERR_GENERIC_ERROR;
  799. currentlyInitialisingNPP = npp;
  800. NPError result = p->setWindow (pNPWindow) ? NPERR_NO_ERROR
  801. : NPERR_MODULE_LOAD_FAILED_ERROR;
  802. currentlyInitialisingNPP = 0;
  803. return result;
  804. }
  805. //==============================================================================
  806. NPError NPP_GetValue (NPP npp, NPPVariable variable, void* value)
  807. {
  808. if (npp == 0)
  809. return NPERR_INVALID_INSTANCE_ERROR;
  810. JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  811. if (p == 0)
  812. return NPERR_GENERIC_ERROR;
  813. switch (variable)
  814. {
  815. case NPPVpluginNameString:
  816. *((char**) value) = JuceBrowserPlugin_Name;
  817. break;
  818. case NPPVpluginDescriptionString:
  819. *((char**) value) = JuceBrowserPlugin_Desc;
  820. break;
  821. case NPPVpluginScriptableNPObject:
  822. *((NPObject**) value) = p->getScriptableObject();
  823. break;
  824. default:
  825. return NPERR_GENERIC_ERROR;
  826. }
  827. return NPERR_NO_ERROR;
  828. }
  829. NPError NPP_NewStream (NPP npp,
  830. NPMIMEType type,
  831. NPStream* stream,
  832. NPBool seekable,
  833. ::uint16* stype)
  834. {
  835. if (npp == 0)
  836. return NPERR_INVALID_INSTANCE_ERROR;
  837. return NPERR_NO_ERROR;
  838. }
  839. ::int32 NPP_WriteReady (NPP npp, NPStream *stream)
  840. {
  841. if (npp == 0)
  842. return NPERR_INVALID_INSTANCE_ERROR;
  843. return 0x0fffffff;
  844. }
  845. ::int32 NPP_Write (NPP npp, NPStream *stream, ::int32 offset, ::int32 len, void *buffer)
  846. {
  847. if (npp == 0)
  848. return NPERR_INVALID_INSTANCE_ERROR;
  849. return len;
  850. }
  851. NPError NPP_DestroyStream (NPP npp, NPStream *stream, NPError reason)
  852. {
  853. if (npp == 0)
  854. return NPERR_INVALID_INSTANCE_ERROR;
  855. return NPERR_NO_ERROR;
  856. }
  857. void NPP_StreamAsFile (NPP npp, NPStream* stream, const char* fname)
  858. {
  859. if (npp == 0)
  860. return;
  861. }
  862. void NPP_Print (NPP npp, NPPrint* printInfo)
  863. {
  864. if (npp == 0)
  865. return;
  866. }
  867. void NPP_URLNotify (NPP npp, const char* url, NPReason reason, void* notifyData)
  868. {
  869. if (npp == 0)
  870. return;
  871. }
  872. NPError NPP_SetValue (NPP npp, NPNVariable variable, void* value)
  873. {
  874. if (npp == 0)
  875. return NPERR_INVALID_INSTANCE_ERROR;
  876. return NPERR_NO_ERROR;
  877. }
  878. ::int16 NPP_HandleEvent (NPP npp, void* ev)
  879. {
  880. if (npp != 0)
  881. {
  882. //JucePluginInstance* const p = (JucePluginInstance*) npp->pdata;
  883. }
  884. return 0;
  885. }
  886. //==============================================================================
  887. static NPP getInstance (const BrowserPluginComponent* bpc)
  888. {
  889. BrowserPluginHolderComponent* holder = dynamic_cast <BrowserPluginHolderComponent*> (bpc->getParentComponent());
  890. if (holder != 0)
  891. return holder->npp;
  892. return currentlyInitialisingNPP;
  893. }
  894. //==============================================================================
  895. BrowserPluginComponent::BrowserPluginComponent()
  896. {
  897. }
  898. BrowserPluginComponent::~BrowserPluginComponent()
  899. {
  900. }
  901. const String BrowserPluginComponent::getBrowserVersion() const
  902. {
  903. if (browserVersionDesc.isEmpty())
  904. {
  905. if (getInstance (this) != 0)
  906. browserVersionDesc << browser.uagent (getInstance (this));
  907. else
  908. browserVersionDesc << "Netscape Plugin V" << (int) ((browser.version >> 8) & 0xff)
  909. << "." << (int) (browser.version & 0xff);
  910. }
  911. return browserVersionDesc;
  912. }
  913. //==============================================================================
  914. #if JUCE_WIN32
  915. extern const String getActiveXBrowserURL (const BrowserPluginComponent* comp);
  916. #endif
  917. const String BrowserPluginComponent::getBrowserURL() const
  918. {
  919. String result;
  920. #if JUCE_WIN32
  921. result = getActiveXBrowserURL (this);
  922. if (result.isNotEmpty())
  923. return result;
  924. #endif
  925. // (FireFox doesn't seem happy if you call this from a background thread..)
  926. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  927. NPP npp = getInstance (this);
  928. if (npp != 0)
  929. {
  930. NPObject* windowObj = 0;
  931. browser.getvalue (npp, NPNVWindowNPObject, &windowObj);
  932. if (windowObj != 0)
  933. {
  934. NPVariant location;
  935. bool ok = browser.getproperty (npp, windowObj,
  936. browser.getstringidentifier ("location"), &location);
  937. browser.releaseobject (windowObj);
  938. jassert (ok);
  939. if (ok)
  940. {
  941. NPVariant href;
  942. ok = browser.getproperty (npp, location.value.objectValue,
  943. browser.getstringidentifier ("href"), &href);
  944. browser.releasevariantvalue (&location);
  945. jassert (ok);
  946. if (ok)
  947. {
  948. result = URL::removeEscapeChars (createValueFromNPVariant (npp, href).toString());
  949. browser.releasevariantvalue (&href);
  950. }
  951. }
  952. }
  953. }
  954. return result;
  955. }