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.

1312 lines
37KB

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