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.

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