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.

1346 lines
39KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. *** DON't EDIT THIS FILE!! ***
  25. The idea is that everyone's plugins should share this same wrapper
  26. code, so if you start hacking around in here you're missing the point!
  27. If there's a bug or a function you need that can't be done without changing
  28. some of the code in here, give me a shout so we can add it to the library,
  29. rather than branching off and going it alone!
  30. */
  31. //==============================================================================
  32. #ifdef _MSC_VER
  33. #pragma warning (disable : 4996)
  34. #endif
  35. #ifdef _WIN32
  36. #include <windows.h>
  37. #elif defined (LINUX)
  38. #include <X11/Xlib.h>
  39. #include <X11/Xutil.h>
  40. #include <X11/Xatom.h>
  41. #undef KeyPress
  42. #else
  43. #include <Carbon/Carbon.h>
  44. #endif
  45. #ifdef PRAGMA_ALIGN_SUPPORTED
  46. #undef PRAGMA_ALIGN_SUPPORTED
  47. #define PRAGMA_ALIGN_SUPPORTED 1
  48. #endif
  49. #include "../../juce_IncludeCharacteristics.h"
  50. //==============================================================================
  51. /* These files come with the Steinberg VST SDK - to get them, you'll need to
  52. visit the Steinberg website and jump through some hoops to sign up as a
  53. VST developer.
  54. Then, you'll need to make sure your include path contains your "vstsdk2.3" or
  55. "vstsdk2.4" directory.
  56. Note that the JUCE_USE_VSTSDK_2_4 macro should be defined in JucePluginCharacteristics.h
  57. */
  58. #if JUCE_USE_VSTSDK_2_4
  59. // VSTSDK V2.4 includes..
  60. #include "public.sdk/source/vst2.x/audioeffectx.h"
  61. #include "public.sdk/source/vst2.x/aeffeditor.h"
  62. #include "public.sdk/source/vst2.x/audioeffectx.cpp"
  63. #include "public.sdk/source/vst2.x/audioeffect.cpp"
  64. #else
  65. // VSTSDK V2.3 includes..
  66. #include "source/common/audioeffectx.h"
  67. #include "source/common/AEffEditor.hpp"
  68. #include "source/common/audioeffectx.cpp"
  69. #include "source/common/AudioEffect.cpp"
  70. typedef long VstInt32;
  71. typedef long VstIntPtr;
  72. #endif
  73. //==============================================================================
  74. #include "../../juce_AudioFilterBase.h"
  75. #undef MemoryBlock
  76. class JuceVSTWrapper;
  77. static bool recursionCheck = false;
  78. static uint32 lastMasterIdleCall = 0;
  79. BEGIN_JUCE_NAMESPACE
  80. extern void juce_callAnyTimersSynchronously();
  81. #if JUCE_LINUX
  82. extern Display* display;
  83. extern bool juce_postMessageToSystemQueue (void* message);
  84. #endif
  85. END_JUCE_NAMESPACE
  86. //==============================================================================
  87. #if JUCE_WIN32
  88. static HWND findMDIParentOf (HWND w)
  89. {
  90. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  91. while (w != 0)
  92. {
  93. HWND parent = GetParent (w);
  94. if (parent == 0)
  95. break;
  96. TCHAR windowType [32];
  97. zeromem (windowType, sizeof (windowType));
  98. GetClassName (parent, windowType, 31);
  99. if (String (windowType).equalsIgnoreCase (T("MDIClient")))
  100. {
  101. w = parent;
  102. break;
  103. }
  104. RECT windowPos;
  105. GetWindowRect (w, &windowPos);
  106. RECT parentPos;
  107. GetWindowRect (parent, &parentPos);
  108. int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  109. int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  110. if (dw > 100 || dh > 100)
  111. break;
  112. w = parent;
  113. if (dw == 2 * frameThickness)
  114. break;
  115. }
  116. return w;
  117. }
  118. //==============================================================================
  119. #elif JUCE_LINUX
  120. class SharedMessageThread : public Thread
  121. {
  122. public:
  123. SharedMessageThread()
  124. : Thread (T("VstMessageThread"))
  125. {
  126. startThread (7);
  127. }
  128. ~SharedMessageThread()
  129. {
  130. signalThreadShouldExit();
  131. const int quitMessageId = 0xfffff321;
  132. Message* const m = new Message (quitMessageId, 1, 0, 0);
  133. if (! juce_postMessageToSystemQueue (m))
  134. delete m;
  135. clearSingletonInstance();
  136. }
  137. void run()
  138. {
  139. MessageManager* const messageManager = MessageManager::getInstance();
  140. const int originalThreadId = messageManager->getCurrentMessageThread();
  141. messageManager->setCurrentMessageThread (getThreadId());
  142. while (! threadShouldExit()
  143. && messageManager->dispatchNextMessage())
  144. {
  145. }
  146. messageManager->setCurrentMessageThread (originalThreadId);
  147. }
  148. juce_DeclareSingleton (SharedMessageThread, false)
  149. };
  150. juce_ImplementSingleton (SharedMessageThread);
  151. #endif
  152. //==============================================================================
  153. // A component to hold the AudioFilterEditor, and cope with some housekeeping
  154. // chores when it changes or repaints.
  155. class EditorCompWrapper : public Component,
  156. public AsyncUpdater
  157. {
  158. JuceVSTWrapper* wrapper;
  159. public:
  160. EditorCompWrapper (JuceVSTWrapper* const wrapper_,
  161. AudioFilterEditor* const editor)
  162. : wrapper (wrapper_)
  163. {
  164. setOpaque (true);
  165. editor->setOpaque (true);
  166. setBounds (editor->getBounds());
  167. editor->setTopLeftPosition (0, 0);
  168. addAndMakeVisible (editor);
  169. #if JUCE_WIN32
  170. addMouseListener (this, true);
  171. #endif
  172. }
  173. ~EditorCompWrapper()
  174. {
  175. deleteAllChildren();
  176. }
  177. void paint (Graphics& g)
  178. {
  179. }
  180. void paintOverChildren (Graphics& g)
  181. {
  182. // this causes an async call to masterIdle() to help
  183. // creaky old DAWs like Nuendo repaint themselves while we're
  184. // repainting. Otherwise they just seem to give up and sit there
  185. // waiting.
  186. triggerAsyncUpdate();
  187. }
  188. AudioFilterEditor* getEditorComp() const
  189. {
  190. return dynamic_cast <AudioFilterEditor*> (getChildComponent (0));
  191. }
  192. void resized()
  193. {
  194. Component* const c = getChildComponent (0);
  195. if (c != 0)
  196. {
  197. #if JUCE_LINUX
  198. const MessageManagerLock mml;
  199. #endif
  200. c->setBounds (0, 0, getWidth(), getHeight());
  201. }
  202. }
  203. void childBoundsChanged (Component* child);
  204. void handleAsyncUpdate();
  205. #if JUCE_WIN32
  206. void mouseDown (const MouseEvent&)
  207. {
  208. broughtToFront();
  209. }
  210. void broughtToFront()
  211. {
  212. // for hosts like nuendo, need to also pop the MDI container to the
  213. // front when our comp is clicked on.
  214. HWND parent = findMDIParentOf ((HWND) getWindowHandle());
  215. if (parent != 0)
  216. {
  217. SetWindowPos (parent,
  218. HWND_TOP,
  219. 0, 0, 0, 0,
  220. SWP_NOMOVE | SWP_NOSIZE);
  221. }
  222. }
  223. #endif
  224. //==============================================================================
  225. juce_UseDebuggingNewOperator
  226. };
  227. static VoidArray activePlugins;
  228. //==============================================================================
  229. /**
  230. This wraps an AudioFilterBase as an AudioEffectX...
  231. */
  232. class JuceVSTWrapper : public AudioEffectX,
  233. private Timer,
  234. public AudioFilterBase::FilterNativeCallbacks
  235. {
  236. public:
  237. //==============================================================================
  238. JuceVSTWrapper (audioMasterCallback audioMaster,
  239. AudioFilterBase* const filter_)
  240. : AudioEffectX (audioMaster,
  241. filter_->getNumPrograms(),
  242. filter_->getNumParameters()),
  243. filter (filter_)
  244. {
  245. filter->numInputChannels = JucePlugin_MaxNumInputChannels;
  246. filter->numOutputChannels = JucePlugin_MaxNumOutputChannels;
  247. filter_->initialiseInternal (this);
  248. editorComp = 0;
  249. outgoingEvents = 0;
  250. outgoingEventSize = 0;
  251. chunkMemoryTime = 0;
  252. isProcessing = false;
  253. firstResize = true;
  254. channels = 0;
  255. #if JUCE_MAC || JUCE_LINUX
  256. hostWindow = 0;
  257. #endif
  258. cEffect.flags |= effFlagsHasEditor;
  259. setUniqueID ((int) (JucePlugin_VSTUniqueID));
  260. getAeffect()->version = (long) (JucePlugin_VersionCode);
  261. #if JucePlugin_WantsMidiInput && ! JUCE_USE_VSTSDK_2_4
  262. wantEvents();
  263. #endif
  264. setNumInputs (filter->numInputChannels);
  265. setNumOutputs (filter->numOutputChannels);
  266. canProcessReplacing (true);
  267. #if ! JUCE_USE_VSTSDK_2_4
  268. hasVu (false);
  269. hasClip (false);
  270. #endif
  271. isSynth ((JucePlugin_IsSynth) != 0);
  272. noTail ((JucePlugin_SilenceInProducesSilenceOut) != 0);
  273. setInitialDelay (JucePlugin_Latency);
  274. programsAreChunks (true);
  275. activePlugins.add (this);
  276. }
  277. ~JuceVSTWrapper()
  278. {
  279. stopTimer();
  280. deleteEditor();
  281. delete filter;
  282. filter = 0;
  283. if (outgoingEvents != 0)
  284. {
  285. for (int i = outgoingEventSize; --i >= 0;)
  286. juce_free (outgoingEvents->events[i]);
  287. juce_free (outgoingEvents);
  288. outgoingEvents = 0;
  289. }
  290. jassert (editorComp == 0);
  291. jassert (activePlugins.contains (this));
  292. activePlugins.removeValue (this);
  293. juce_free (channels);
  294. #if JUCE_MAC || JUCE_LINUX
  295. if (activePlugins.size() == 0)
  296. {
  297. #if JUCE_LINUX
  298. SharedMessageThread::deleteInstance();
  299. #endif
  300. shutdownJuce_GUI();
  301. }
  302. #endif
  303. }
  304. void open()
  305. {
  306. startTimer (1000 / 4);
  307. }
  308. void close()
  309. {
  310. jassert (! recursionCheck);
  311. stopTimer();
  312. deleteEditor();
  313. }
  314. //==============================================================================
  315. bool getEffectName (char* name)
  316. {
  317. String (JucePlugin_Name).copyToBuffer (name, 64);
  318. return true;
  319. }
  320. bool getVendorString (char* text)
  321. {
  322. String (JucePlugin_Manufacturer).copyToBuffer (text, 64);
  323. return true;
  324. }
  325. bool getProductString (char* text)
  326. {
  327. return getEffectName (text);
  328. }
  329. VstInt32 getVendorVersion()
  330. {
  331. return JucePlugin_VersionCode;
  332. }
  333. VstPlugCategory getPlugCategory()
  334. {
  335. return JucePlugin_VSTCategory;
  336. }
  337. VstInt32 canDo (char* text)
  338. {
  339. VstInt32 result = 0;
  340. if (strcmp (text, "receiveVstEvents") == 0
  341. || strcmp (text, "receiveVstMidiEvent") == 0
  342. || strcmp (text, "receiveVstMidiEvents") == 0)
  343. {
  344. #if JucePlugin_WantsMidiInput
  345. result = 1;
  346. #else
  347. result = -1;
  348. #endif
  349. }
  350. else if (strcmp (text, "sendVstEvents") == 0
  351. || strcmp (text, "sendVstMidiEvent") == 0
  352. || strcmp (text, "sendVstMidiEvents") == 0)
  353. {
  354. #if JucePlugin_ProducesMidiOutput
  355. result = 1;
  356. #else
  357. result = -1;
  358. #endif
  359. }
  360. else if (strcmp (text, "receiveVstTimeInfo") == 0)
  361. {
  362. result = 1;
  363. }
  364. else if (strcmp (text, "conformsToWindowRules") == 0)
  365. {
  366. result = 1;
  367. }
  368. return result;
  369. }
  370. bool keysRequired()
  371. {
  372. return (JucePlugin_EditorRequiresKeyboardFocus) != 0;
  373. }
  374. bool getInputProperties (VstInt32 index, VstPinProperties* properties)
  375. {
  376. const String name (filter->getInputChannelName ((int) index));
  377. name.copyToBuffer (properties->label, kVstMaxLabelLen - 1);
  378. name.copyToBuffer (properties->shortLabel, kVstMaxShortLabelLen - 1);
  379. properties->flags = kVstPinIsActive;
  380. if (filter->isInputChannelStereoPair ((int) index))
  381. properties->flags |= kVstPinIsStereo;
  382. properties->arrangementType = 0;
  383. return true;
  384. }
  385. bool getOutputProperties (VstInt32 index, VstPinProperties* properties)
  386. {
  387. const String name (filter->getOutputChannelName ((int) index));
  388. name.copyToBuffer (properties->label, kVstMaxLabelLen - 1);
  389. name.copyToBuffer (properties->shortLabel, kVstMaxShortLabelLen - 1);
  390. properties->flags = kVstPinIsActive;
  391. if (filter->isOutputChannelStereoPair ((int) index))
  392. properties->flags |= kVstPinIsStereo;
  393. properties->arrangementType = 0;
  394. return true;
  395. }
  396. //==============================================================================
  397. VstInt32 processEvents (VstEvents* events)
  398. {
  399. #if JucePlugin_WantsMidiInput
  400. for (int i = 0; i < events->numEvents; ++i)
  401. {
  402. const VstEvent* const e = events->events[i];
  403. if (e != 0 && e->type == kVstMidiType)
  404. {
  405. const VstMidiEvent* const vme = (const VstMidiEvent*) e;
  406. midiEvents.addEvent ((const uint8*) vme->midiData,
  407. 4,
  408. vme->deltaFrames);
  409. }
  410. }
  411. return 1;
  412. #else
  413. return 0;
  414. #endif
  415. }
  416. void process (float** inputs, float** outputs, VstInt32 numSamples)
  417. {
  418. AudioSampleBuffer temp (filter->numInputChannels, numSamples);
  419. int i;
  420. for (i = filter->numInputChannels; --i >= 0;)
  421. memcpy (temp.getSampleData (i), outputs[i], sizeof (float) * numSamples);
  422. processReplacing (inputs, outputs, numSamples);
  423. AudioSampleBuffer dest (outputs, filter->numOutputChannels, numSamples);
  424. for (i = jmin (filter->numOutputChannels, filter->numInputChannels); --i >= 0;)
  425. dest.addFrom (i, 0, temp, i, 0, numSamples);
  426. }
  427. void processReplacing (float** inputs, float** outputs, VstInt32 numSamples)
  428. {
  429. //process (inputs, outputs, numSamples, false);
  430. // if this fails, the host hasn't called resume() before processing
  431. jassert (isProcessing);
  432. // (tragically, some hosts actually need this, although it's stupid to have
  433. // to do it here..)
  434. if (! isProcessing)
  435. resume();
  436. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  437. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  438. #endif
  439. jassert (activePlugins.contains (this));
  440. {
  441. const ScopedLock sl (filter->getCallbackLock());
  442. const int numIn = filter->numInputChannels;
  443. const int numOut = filter->numOutputChannels;
  444. const int totalChans = jmax (numIn, numOut);
  445. if (filter->suspended)
  446. {
  447. for (int i = 0; i < numOut; ++i)
  448. zeromem (outputs [i], sizeof (float) * numSamples);
  449. }
  450. else
  451. {
  452. {
  453. int i;
  454. for (i = 0; i < numOut; ++i)
  455. {
  456. channels[i] = outputs [i];
  457. if (i < numIn && inputs != outputs)
  458. memcpy (outputs [i], inputs[i], sizeof (float) * numSamples);
  459. }
  460. for (; i < numIn; ++i)
  461. channels [i] = inputs [i];
  462. }
  463. AudioSampleBuffer chans (channels, totalChans, numSamples);
  464. filter->processBlock (chans, midiEvents);
  465. }
  466. }
  467. if (! midiEvents.isEmpty())
  468. {
  469. #if JucePlugin_ProducesMidiOutput
  470. const int numEvents = midiEvents.getNumEvents();
  471. ensureOutgoingEventSize (numEvents);
  472. outgoingEvents->numEvents = 0;
  473. const uint8* midiEventData;
  474. int midiEventSize, midiEventPosition;
  475. MidiBuffer::Iterator i (midiEvents);
  476. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  477. {
  478. if (midiEventSize <= 4)
  479. {
  480. VstMidiEvent* const vme = (VstMidiEvent*) outgoingEvents->events [outgoingEvents->numEvents++];
  481. memcpy (vme->midiData, midiEventData, midiEventSize);
  482. vme->deltaFrames = midiEventPosition;
  483. jassert (vme->deltaFrames >= 0 && vme->deltaFrames < numSamples);
  484. }
  485. }
  486. sendVstEventsToHost (outgoingEvents);
  487. #else
  488. /* This assertion is caused when you've added some events to the
  489. midiMessages array in your processBlock() method, which usually means
  490. that you're trying to send them somewhere. But in this case they're
  491. getting thrown away.
  492. If your plugin does want to send midi messages, you'll need to set
  493. the JucePlugin_ProducesMidiOutput macro to 1 in your
  494. JucePluginCharacteristics.h file.
  495. If you don't want to produce any midi output, then you should clear the
  496. midiMessages array at the end of your processBlock() method, to
  497. indicate that you don't want any of the events to be passed through
  498. to the output.
  499. */
  500. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  501. #endif
  502. midiEvents.clear();
  503. }
  504. }
  505. //==============================================================================
  506. void resume()
  507. {
  508. isProcessing = true;
  509. juce_free (channels);
  510. channels = (float**) juce_calloc (sizeof (float*) * jmax (filter->getNumInputChannels(), filter->getNumOutputChannels()));
  511. filter->sampleRate = getSampleRate();
  512. jassert (filter->sampleRate > 0);
  513. if (filter->sampleRate <= 0)
  514. filter->sampleRate = 44100.0;
  515. filter->blockSize = getBlockSize();
  516. jassert (filter->blockSize > 0);
  517. filter->prepareToPlay (filter->sampleRate, filter->blockSize);
  518. midiEvents.clear();
  519. AudioEffectX::resume();
  520. #if JucePlugin_ProducesMidiOutput
  521. ensureOutgoingEventSize (64);
  522. #endif
  523. #if JucePlugin_WantsMidiInput && ! JUCE_USE_VSTSDK_2_4
  524. wantEvents();
  525. #endif
  526. }
  527. void suspend()
  528. {
  529. AudioEffectX::suspend();
  530. filter->releaseResources();
  531. midiEvents.clear();
  532. isProcessing = false;
  533. juce_free (channels);
  534. channels = 0;
  535. }
  536. bool JUCE_CALLTYPE getCurrentPositionInfo (AudioFilterBase::CurrentPositionInfo& info)
  537. {
  538. const VstTimeInfo* const ti = getTimeInfo (kVstPpqPosValid
  539. | kVstTempoValid
  540. | kVstBarsValid
  541. //| kVstCyclePosValid
  542. | kVstTimeSigValid
  543. | kVstSmpteValid
  544. | kVstClockValid);
  545. if (ti == 0 || ti->sampleRate <= 0)
  546. return false;
  547. if ((ti->flags & kVstTempoValid) != 0)
  548. info.bpm = ti->tempo;
  549. else
  550. info.bpm = 0.0;
  551. if ((ti->flags & kVstTimeSigValid) != 0)
  552. {
  553. info.timeSigNumerator = ti->timeSigNumerator;
  554. info.timeSigDenominator = ti->timeSigDenominator;
  555. }
  556. else
  557. {
  558. info.timeSigNumerator = 4;
  559. info.timeSigDenominator = 4;
  560. }
  561. info.timeInSeconds = ti->samplePos / ti->sampleRate;
  562. if ((ti->flags & kVstPpqPosValid) != 0)
  563. info.ppqPosition = ti->ppqPos;
  564. else
  565. info.ppqPosition = 0.0;
  566. if ((ti->flags & kVstBarsValid) != 0)
  567. info.ppqPositionOfLastBarStart = ti->barStartPos;
  568. else
  569. info.ppqPositionOfLastBarStart = 0.0;
  570. if ((ti->flags & kVstSmpteValid) != 0)
  571. {
  572. info.frameRate = (AudioFilterBase::CurrentPositionInfo::FrameRateType) (int) ti->smpteFrameRate;
  573. const double fpsDivisors[] = { 24.0, 25.0, 30.0, 30.0, 30.0, 30.0, 1.0 };
  574. info.editOriginTime = (ti->smpteOffset / (80.0 * fpsDivisors [(int) info.frameRate]));
  575. }
  576. else
  577. {
  578. info.frameRate = AudioFilterBase::CurrentPositionInfo::fpsUnknown;
  579. info.editOriginTime = 0;
  580. }
  581. info.isRecording = (ti->flags & kVstTransportRecording) != 0;
  582. info.isPlaying = (ti->flags & kVstTransportPlaying) != 0 || info.isRecording;
  583. return true;
  584. }
  585. //==============================================================================
  586. VstInt32 getProgram()
  587. {
  588. return filter->getCurrentProgram();
  589. }
  590. void setProgram (VstInt32 program)
  591. {
  592. filter->setCurrentProgram (program);
  593. }
  594. void setProgramName (char* name)
  595. {
  596. filter->changeProgramName (filter->getCurrentProgram(), name);
  597. }
  598. void getProgramName (char* name)
  599. {
  600. filter->getProgramName (filter->getCurrentProgram()).copyToBuffer (name, 24);
  601. }
  602. bool getProgramNameIndexed (VstInt32 category, VstInt32 index, char* text)
  603. {
  604. if (index >= 0 && index < filter->getNumPrograms())
  605. {
  606. filter->getProgramName (index).copyToBuffer (text, 24);
  607. return true;
  608. }
  609. return false;
  610. }
  611. //==============================================================================
  612. float getParameter (VstInt32 index)
  613. {
  614. jassert (index >= 0 && index < filter->getNumParameters());
  615. return filter->getParameter (index);
  616. }
  617. void setParameter (VstInt32 index, float value)
  618. {
  619. jassert (index >= 0 && index < filter->getNumParameters());
  620. filter->setParameter (index, value);
  621. }
  622. void getParameterDisplay (VstInt32 index, char* text)
  623. {
  624. jassert (index >= 0 && index < filter->getNumParameters());
  625. filter->getParameterText (index).copyToBuffer (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  626. }
  627. void getParameterName (VstInt32 index, char* text)
  628. {
  629. jassert (index >= 0 && index < filter->getNumParameters());
  630. filter->getParameterName (index).copyToBuffer (text, 16); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  631. }
  632. void JUCE_CALLTYPE informHostOfParameterChange (int index, float newValue)
  633. {
  634. setParameterAutomated (index, newValue);
  635. }
  636. void JUCE_CALLTYPE updateHostDisplay()
  637. {
  638. updateDisplay();
  639. }
  640. bool canParameterBeAutomated (VstInt32 index)
  641. {
  642. return filter->isParameterAutomatable ((int) index);
  643. }
  644. //==============================================================================
  645. VstInt32 getChunk (void** data, bool onlyStoreCurrentProgramData)
  646. {
  647. chunkMemory.setSize (0);
  648. if (onlyStoreCurrentProgramData)
  649. filter->getCurrentProgramStateInformation (chunkMemory);
  650. else
  651. filter->getStateInformation (chunkMemory);
  652. *data = (void*) chunkMemory;
  653. // because the chunk is only needed temporarily by the host (or at least you'd
  654. // hope so) we'll give it a while and then free it in the timer callback.
  655. chunkMemoryTime = JUCE_NAMESPACE::Time::getApproximateMillisecondCounter();
  656. return chunkMemory.getSize();
  657. }
  658. VstInt32 setChunk (void* data, VstInt32 byteSize, bool onlyRestoreCurrentProgramData)
  659. {
  660. chunkMemory.setSize (0);
  661. chunkMemoryTime = 0;
  662. if (byteSize > 0 && data != 0)
  663. {
  664. if (onlyRestoreCurrentProgramData)
  665. filter->setCurrentProgramStateInformation (data, byteSize);
  666. else
  667. filter->setStateInformation (data, byteSize);
  668. }
  669. return 0;
  670. }
  671. void timerCallback()
  672. {
  673. if (chunkMemoryTime > 0
  674. && chunkMemoryTime < JUCE_NAMESPACE::Time::getApproximateMillisecondCounter() - 2000
  675. && ! recursionCheck)
  676. {
  677. chunkMemoryTime = 0;
  678. chunkMemory.setSize (0);
  679. }
  680. tryMasterIdle();
  681. }
  682. void tryMasterIdle()
  683. {
  684. if (Component::isMouseButtonDownAnywhere()
  685. && ! recursionCheck)
  686. {
  687. const uint32 now = JUCE_NAMESPACE::Time::getMillisecondCounter();
  688. if (now > lastMasterIdleCall + 20 && editorComp != 0)
  689. {
  690. lastMasterIdleCall = now;
  691. recursionCheck = true;
  692. masterIdle();
  693. recursionCheck = false;
  694. }
  695. }
  696. }
  697. void doIdleCallback()
  698. {
  699. // (wavelab calls this on a separate thread and causes a deadlock)..
  700. if (MessageManager::getInstance()->isThisTheMessageThread())
  701. {
  702. if (! recursionCheck)
  703. {
  704. const MessageManagerLock mml;
  705. recursionCheck = true;
  706. juce_callAnyTimersSynchronously();
  707. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  708. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  709. recursionCheck = false;
  710. }
  711. }
  712. }
  713. void createEditorComp()
  714. {
  715. if (editorComp == 0)
  716. {
  717. #if JUCE_LINUX
  718. const MessageManagerLock mml;
  719. #endif
  720. AudioFilterEditor* const ed = filter->createEditorIfNeeded();
  721. if (ed != 0)
  722. {
  723. ed->setOpaque (true);
  724. ed->setVisible (true);
  725. editorComp = new EditorCompWrapper (this, ed);
  726. }
  727. }
  728. }
  729. void deleteEditor()
  730. {
  731. PopupMenu::dismissAllActiveMenus();
  732. jassert (! recursionCheck);
  733. recursionCheck = true;
  734. #if JUCE_LINUX
  735. const MessageManagerLock mml;
  736. #endif
  737. if (editorComp != 0)
  738. {
  739. Component* const modalComponent = Component::getCurrentlyModalComponent();
  740. if (modalComponent != 0)
  741. modalComponent->exitModalState (0);
  742. filter->editorBeingDeleted (editorComp->getEditorComp());
  743. deleteAndZero (editorComp);
  744. // there's some kind of component currently modal, but the host
  745. // is trying to delete our plugin. You should try to avoid this happening..
  746. jassert (Component::getCurrentlyModalComponent() == 0);
  747. }
  748. #if JUCE_MAC || JUCE_LINUX
  749. hostWindow = 0;
  750. #endif
  751. recursionCheck = false;
  752. }
  753. VstIntPtr dispatcher (VstInt32 opCode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  754. {
  755. if (opCode == effEditIdle)
  756. {
  757. doIdleCallback();
  758. return 0;
  759. }
  760. else if (opCode == effEditOpen)
  761. {
  762. jassert (! recursionCheck);
  763. deleteEditor();
  764. createEditorComp();
  765. if (editorComp != 0)
  766. {
  767. #if JUCE_LINUX
  768. const MessageManagerLock mml;
  769. #endif
  770. editorComp->setOpaque (true);
  771. editorComp->setVisible (false);
  772. #if JUCE_WIN32
  773. editorComp->addToDesktop (0);
  774. hostWindow = (HWND) ptr;
  775. HWND editorWnd = (HWND) editorComp->getWindowHandle();
  776. SetParent (editorWnd, hostWindow);
  777. DWORD val = GetWindowLong (editorWnd, GWL_STYLE);
  778. val = (val & ~WS_POPUP) | WS_CHILD;
  779. SetWindowLong (editorWnd, GWL_STYLE, val);
  780. editorComp->setVisible (true);
  781. #elif JUCE_LINUX
  782. editorComp->addToDesktop (0);
  783. hostWindow = (Window) ptr;
  784. Window editorWnd = (Window) editorComp->getWindowHandle();
  785. XReparentWindow (display, editorWnd, hostWindow, 0, 0);
  786. editorComp->setVisible (true);
  787. #else
  788. hostWindow = (WindowRef) ptr;
  789. firstResize = true;
  790. SetAutomaticControlDragTrackingEnabledForWindow (hostWindow, true);
  791. WindowAttributes attributes;
  792. GetWindowAttributes (hostWindow, &attributes);
  793. HIViewRef parentView = 0;
  794. if ((attributes & kWindowCompositingAttribute) != 0)
  795. {
  796. HIViewRef root = HIViewGetRoot (hostWindow);
  797. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  798. if (parentView == 0)
  799. parentView = root;
  800. }
  801. else
  802. {
  803. GetRootControl (hostWindow, (ControlRef*) &parentView);
  804. if (parentView == 0)
  805. CreateRootControl (hostWindow, (ControlRef*) &parentView);
  806. }
  807. jassert (parentView != 0); // agh - the host has to provide a compositing window..
  808. editorComp->setVisible (true);
  809. editorComp->addToDesktop (0, (void*) parentView);
  810. #endif
  811. return 1;
  812. }
  813. }
  814. else if (opCode == effEditClose)
  815. {
  816. deleteEditor();
  817. return 0;
  818. }
  819. else if (opCode == effEditGetRect)
  820. {
  821. createEditorComp();
  822. if (editorComp != 0)
  823. {
  824. editorSize.left = 0;
  825. editorSize.top = 0;
  826. editorSize.right = editorComp->getWidth();
  827. editorSize.bottom = editorComp->getHeight();
  828. *((ERect**) ptr) = &editorSize;
  829. return (VstIntPtr) &editorSize;
  830. }
  831. else
  832. {
  833. return 0;
  834. }
  835. }
  836. return AudioEffectX::dispatcher (opCode, index, value, ptr, opt);
  837. }
  838. void resizeHostWindow (int newWidth, int newHeight)
  839. {
  840. if (editorComp != 0)
  841. {
  842. #if ! JUCE_LINUX // linux hosts shouldn't be trusted!
  843. if (! (canHostDo ("sizeWindow") && sizeWindow (newWidth, newHeight)))
  844. #endif
  845. {
  846. // some hosts don't support the sizeWindow call, so do it manually..
  847. #if JUCE_MAC
  848. Rect r;
  849. GetWindowBounds (hostWindow, kWindowContentRgn, &r);
  850. if (firstResize)
  851. {
  852. diffW = (r.right - r.left) - editorComp->getWidth();
  853. diffH = (r.bottom - r.top) - editorComp->getHeight();
  854. firstResize = false;
  855. }
  856. r.right = r.left + newWidth + diffW;
  857. r.bottom = r.top + newHeight + diffH;
  858. SetWindowBounds (hostWindow, kWindowContentRgn, &r);
  859. r.bottom -= r.top;
  860. r.right -= r.left;
  861. r.left = r.top = 0;
  862. InvalWindowRect (hostWindow, &r);
  863. #elif JUCE_LINUX
  864. Window root;
  865. int x, y;
  866. unsigned int width, height, border, depth;
  867. XGetGeometry (display, hostWindow, &root,
  868. &x, &y, &width, &height, &border, &depth);
  869. newWidth += (width + border) - editorComp->getWidth();
  870. newHeight += (height + border) - editorComp->getHeight();
  871. XResizeWindow (display, hostWindow, newWidth, newHeight);
  872. #else
  873. int dw = 0;
  874. int dh = 0;
  875. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  876. HWND w = (HWND) editorComp->getWindowHandle();
  877. while (w != 0)
  878. {
  879. HWND parent = GetParent (w);
  880. if (parent == 0)
  881. break;
  882. TCHAR windowType [32];
  883. zeromem (windowType, sizeof (windowType));
  884. GetClassName (parent, windowType, 31);
  885. if (String (windowType).equalsIgnoreCase (T("MDIClient")))
  886. break;
  887. RECT windowPos;
  888. GetWindowRect (w, &windowPos);
  889. RECT parentPos;
  890. GetWindowRect (parent, &parentPos);
  891. SetWindowPos (w, 0, 0, 0,
  892. newWidth + dw,
  893. newHeight + dh,
  894. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  895. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  896. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  897. w = parent;
  898. if (dw == 2 * frameThickness)
  899. break;
  900. if (dw > 100 || dh > 100)
  901. w = 0;
  902. }
  903. if (w != 0)
  904. SetWindowPos (w, 0, 0, 0,
  905. newWidth + dw,
  906. newHeight + dh,
  907. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  908. #endif
  909. }
  910. if (editorComp->getPeer() != 0)
  911. editorComp->getPeer()->handleMovedOrResized();
  912. }
  913. }
  914. //==============================================================================
  915. juce_UseDebuggingNewOperator
  916. private:
  917. AudioFilterBase* filter;
  918. juce::MemoryBlock chunkMemory;
  919. uint32 chunkMemoryTime;
  920. EditorCompWrapper* editorComp;
  921. ERect editorSize;
  922. MidiBuffer midiEvents;
  923. VstEvents* outgoingEvents;
  924. int outgoingEventSize;
  925. bool isProcessing;
  926. bool firstResize;
  927. int diffW, diffH;
  928. float** channels;
  929. void ensureOutgoingEventSize (int numEvents)
  930. {
  931. if (outgoingEventSize < numEvents)
  932. {
  933. numEvents += 32;
  934. const int size = 16 + sizeof (VstEvent*) * numEvents;
  935. if (outgoingEvents == 0)
  936. outgoingEvents = (VstEvents*) juce_calloc (size);
  937. else
  938. outgoingEvents = (VstEvents*) juce_realloc (outgoingEvents, size);
  939. for (int i = outgoingEventSize; i < numEvents; ++i)
  940. {
  941. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  942. e->type = kVstMidiType;
  943. e->byteSize = 24;
  944. outgoingEvents->events[i] = (VstEvent*) e;
  945. }
  946. outgoingEventSize = numEvents;
  947. }
  948. }
  949. const String getHostName()
  950. {
  951. char host[256];
  952. zeromem (host, sizeof (host));
  953. getHostProductString (host);
  954. return host;
  955. }
  956. #if JUCE_MAC
  957. WindowRef hostWindow;
  958. #elif JUCE_LINUX
  959. Window hostWindow;
  960. #else
  961. HWND hostWindow;
  962. #endif
  963. };
  964. //==============================================================================
  965. void EditorCompWrapper::childBoundsChanged (Component* child)
  966. {
  967. child->setTopLeftPosition (0, 0);
  968. const int cw = child->getWidth();
  969. const int ch = child->getHeight();
  970. wrapper->resizeHostWindow (cw, ch);
  971. setSize (cw, ch);
  972. #if JUCE_MAC
  973. wrapper->resizeHostWindow (cw, ch); // (doing this a second time seems to be necessary in tracktion)
  974. #endif
  975. }
  976. void EditorCompWrapper::handleAsyncUpdate()
  977. {
  978. wrapper->tryMasterIdle();
  979. }
  980. //==============================================================================
  981. static AEffect* pluginEntryPoint (audioMasterCallback audioMaster)
  982. {
  983. #if JUCE_MAC || JUCE_LINUX
  984. initialiseJuce_GUI();
  985. #endif
  986. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  987. try
  988. {
  989. if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0)
  990. {
  991. AudioFilterBase* const filter = createPluginFilter();
  992. if (filter != 0)
  993. {
  994. JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter);
  995. return wrapper->getAeffect();
  996. }
  997. }
  998. }
  999. catch (...)
  1000. {}
  1001. return 0;
  1002. }
  1003. //==============================================================================
  1004. // Mac startup code..
  1005. #if JUCE_MAC
  1006. extern "C" __attribute__ ((visibility("default"))) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1007. {
  1008. return pluginEntryPoint (audioMaster);
  1009. }
  1010. extern "C" __attribute__ ((visibility("default"))) AEffect* main_macho (audioMasterCallback audioMaster)
  1011. {
  1012. return pluginEntryPoint (audioMaster);
  1013. }
  1014. //==============================================================================
  1015. // Linux startup code..
  1016. #elif JUCE_LINUX
  1017. extern "C" AEffect* main_plugin (audioMasterCallback audioMaster) asm ("main");
  1018. extern "C" AEffect* main_plugin (audioMasterCallback audioMaster)
  1019. {
  1020. initialiseJuce_GUI();
  1021. SharedMessageThread::getInstance();
  1022. return pluginEntryPoint (audioMaster);
  1023. }
  1024. __attribute__((constructor)) void myPluginInit()
  1025. {
  1026. // don't put initialiseJuce_GUI here... it will crash !
  1027. }
  1028. __attribute__((destructor)) void myPluginFini()
  1029. {
  1030. // don't put shutdownJuce_GUI here... it will crash !
  1031. }
  1032. //==============================================================================
  1033. // Win32 startup code..
  1034. #else
  1035. extern "C" __declspec (dllexport) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1036. {
  1037. return pluginEntryPoint (audioMaster);
  1038. }
  1039. extern "C" __declspec (dllexport) void* main (audioMasterCallback audioMaster)
  1040. {
  1041. return (void*) pluginEntryPoint (audioMaster);
  1042. }
  1043. BOOL WINAPI DllMain (HINSTANCE instance, DWORD dwReason, LPVOID)
  1044. {
  1045. if (dwReason == DLL_PROCESS_ATTACH)
  1046. {
  1047. PlatformUtilities::setCurrentModuleInstanceHandle (instance);
  1048. initialiseJuce_GUI();
  1049. }
  1050. else if (dwReason == DLL_PROCESS_DETACH)
  1051. {
  1052. shutdownJuce_GUI();
  1053. }
  1054. return TRUE;
  1055. }
  1056. #endif