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.

1317 lines
36KB

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