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.

1383 lines
40KB

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