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.

1203 lines
40KB

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