code:
/*
 * vestige.cpp - instrument-plugin for hosting VST-instruments
 *
 * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */

#include <QtCore/QtGlobal>

#include "VstPlugin.h"

#include "vestige.h"

#include <memory>

#include <QDropEvent>
#include <QMessageBox>
#include <QPainter>
#include <QPushButton>
#include <QMdiArea>
#include <QMenu>
#include <QDomElement>

#include <string>

#include "BufferManager.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "FileDialog.h"
#include "GuiApplication.h"
#include "gui_templates.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include "LocaleHelper.h"
#include "MainWindow.h"
#include "Mixer.h"
#include "PathUtil.h"
#include "PixmapButton.h"
#include "SampleBuffer.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "TextFloat.h"
#include "ToolTip.h"
#include "Clipboard.h"

#include "embed.h"

extern "C"
{

Plugin::Descriptor Q_DECL_EXPORT  vestige_plugin_descriptor =
{
	STRINGIFY( PLUGIN_NAME ),
	"VeSTige",
	QT_TRANSLATE_NOOP( "PluginBrowser",
			"VST-host for using VST(i)-plugins within LMMS" ),
	"Tobias Doerffel <tobydox/at/users.sf.net>",
	0x0100,
	Plugin::Instrument,
	new PluginPixmapLoader( "logo" ),
	"dll",
	NULL
} ;

}

class vstSubWin : public SubWindow
{
public:
	vstSubWin( QWidget * _parent ) :
		SubWindow( _parent )
	{
		setAttribute( Qt::WA_DeleteOnClose, false );
		setWindowFlags( Qt::WindowCloseButtonHint );
	}

	virtual ~vstSubWin()
	{
	}

	virtual void closeEvent( QCloseEvent * e )
	{
		// ignore close-events - for some reason otherwise the VST GUI
		// remains hidden when re-opening
		hide();
		e->ignore();
	}
};

class VstInstrumentPlugin : public VstPlugin
{
public:
	using VstPlugin::VstPlugin;

	void createUI( QWidget *parent ) override
	{
		Q_UNUSED(parent);
		if ( !hasEditor() ) {
			return;
		}
		if ( embedMethod() != "none" ) {
			m_pluginSubWindow.reset(new vstSubWin( gui->mainWindow()->workspace() ));
			VstPlugin::createUI( m_pluginSubWindow.get() );
			m_pluginSubWindow->setWidget(pluginWidget());
		} else {
			VstPlugin::createUI( nullptr );
		}
	}

	/// Overwrite editor() to return the sub window instead of the embed widget
	/// itself. This makes toggleUI() and related functions toggle the
	/// sub window's visibility.
	QWidget* editor() override
	{
		return m_pluginSubWindow.get();
	}
private:
	unique_ptr<QMdiSubWindow> m_pluginSubWindow;
};

QPixmap * VestigeInstrumentView::s_artwork = NULL;
QPixmap * manageVestigeInstrumentView::s_artwork = NULL;

vestigeInstrument::vestigeInstrument( InstrumentTrack * _instrument_track ) :
	Instrument( _instrument_track, &vestige_plugin_descriptor ),
	m_plugin( NULL ),
	m_pluginMutex(),
	m_subWindow( NULL ),
	m_scrollArea( NULL ),
	knobFModel( NULL ),
	p_subWindow( NULL )
{
	// now we need a play-handle which cares for calling play()
	InstrumentPlayHandle * iph = new InstrumentPlayHandle( this, _instrument_track );
	Engine::mixer()->addPlayHandle( iph );

	connect( ConfigManager::inst(), SIGNAL( valueChanged(QString,QString,QString) ),
			 this, SLOT( handleConfigChange(QString, QString, QString) ),
			 Qt::QueuedConnection );
}

vestigeInstrument::~vestigeInstrument()
{
	if (p_subWindow != NULL) {
		delete p_subWindow;
		p_subWindow = NULL;
	}

	if (knobFModel != NULL) {
		delete []knobFModel;
		knobFModel = NULL;
	}

	Engine::mixer()->removePlayHandlesOfTypes( instrumentTrack(),
				PlayHandle::TypeNotePlayHandle
				| PlayHandle::TypeInstrumentPlayHandle );
	closePlugin();
}

void vestigeInstrument::loadSettings( const QDomElement & _this )
{
	QString plugin = _this.attribute( "plugin" );
	if( plugin.isEmpty() )
	{
		return;
	}

	loadFile( plugin );
	m_pluginMutex.lock();
	if( m_plugin != NULL )
	{
		m_plugin->loadSettings( _this );

		if (instrumentTrack() != NULL && instrumentTrack()->isPreviewMode())
		{
			m_plugin->hideUI();
		}
		else if (_this.attribute( "guivisible" ).toInt())
		{
			m_plugin->showUI();
		} else
		{
			m_plugin->hideUI();
		}

		const QMap<QString, QString> & dump = m_plugin->parameterDump();
		paramCount = dump.size();
		char paramStr[35];
		knobFModel = new FloatModel *[ paramCount ];
		QStringList s_dumpValues;
		for( int i = 0; i < paramCount; i++ )
		{
			sprintf( paramStr, "param%d", i );
			s_dumpValues = dump[ paramStr ].split( ":" );

			knobFModel[i] = new FloatModel( 0.0f, 0.0f, 1.0f, 0.01f, this, QString::number(i) );
			knobFModel[i]->loadSettings( _this, paramStr );

			if( !( knobFModel[ i ]->isAutomated() || knobFModel[ i ]->controllerConnection() ) )
			{
				knobFModel[ i ]->setValue(LocaleHelper::toFloat(s_dumpValues.at(2)));
				knobFModel[ i ]->setInitValue(LocaleHelper::toFloat(s_dumpValues.at(2)));
			}

			connect( knobFModel[i], &FloatModel::dataChanged, this,
				[this, i]() { setParameter( knobFModel[i] ); }, Qt::DirectConnection);
		}
	}
	m_pluginMutex.unlock();
}

void vestigeInstrument::setParameter( Model * action )
{
	int knobUNID = action->displayName().toInt();

	if ( m_plugin != NULL ) {
		m_plugin->setParam( knobUNID, knobFModel[knobUNID]->value() );
	}
}

void vestigeInstrument::handleConfigChange(QString cls, QString attr, QString value)
{
    Q_UNUSED(cls); Q_UNUSED(attr); Q_UNUSED(value);
    // Disabled for consistency with VST effects that don't implement this. (#3786)
    // if ( cls == "ui" && attr == "vstembedmethod" )
    // {
    // 	reloadPlugin();
    // }
}

void vestigeInstrument::reloadPlugin()
{
	closePlugin();
	loadFile( m_pluginDLL );
}

void vestigeInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
	_this.setAttribute( "plugin", PathUtil::toShortestRelative(m_pluginDLL) );
	m_pluginMutex.lock();
	if( m_plugin != NULL )
	{
		m_plugin->saveSettings( _doc, _this );
		if (knobFModel != NULL) {
			const QMap<QString, QString> & dump = m_plugin->parameterDump();
			paramCount = dump.size();
			char paramStr[35];
			for( int i = 0; i < paramCount; i++ )
			{
				if (knobFModel[i]->isAutomated() || knobFModel[i]->controllerConnection()) {
					sprintf( paramStr, "param%d", i);
					knobFModel[i]->saveSettings( _doc, _this, paramStr );
				}

/*				QDomElement me = _doc.createElement( paramStr );
				me.setAttribute( "id", knobFModel[i]->id() );
				me.setAttribute( "value", knobFModel[i]->value() );
				_this.appendChild( me );

				ControllerConnection * m_controllerConnection = knobFModel[i]->controllerConnection();
				if (m_controllerConnection) {
					QDomElement controller_element;
					QDomNode node = _this.namedItem( "connection" );
					if( node.isElement() )
					{
						controller_element = node.toElement();
					}
					else
					{
						controller_element = _doc.createElement( "connection" );
						_this.appendChild( controller_element );
					}
					QDomElement element = _doc.createElement( paramStr );
					m_controllerConnection->saveSettings( _doc, element );
					controller_element.appendChild( element );
				}*/
			}
		}
	}
	m_pluginMutex.unlock();
}

QString vestigeInstrument::nodeName( void ) const
{
	return( vestige_plugin_descriptor.name );
}

void vestigeInstrument::loadFile( const QString & _file )
{
	m_pluginMutex.lock();
	const bool set_ch_name = ( m_plugin != NULL &&
			instrumentTrack()->name() == m_plugin->name() ) ||
			instrumentTrack()->name() == InstrumentTrack::tr( "Default preset" ) ||
			instrumentTrack()->name() == displayName();

	m_pluginMutex.unlock();

	// if the same is loaded don't load again (for preview)
	if (instrumentTrack() != NULL && instrumentTrack()->isPreviewMode() &&
			m_pluginDLL == PathUtil::toShortestRelative( _file ))
		return;

	if ( m_plugin != NULL )
	{
		closePlugin();
	}
	m_pluginDLL = PathUtil::toShortestRelative( _file );
	TextFloat * tf = NULL;
	if( gui )
	{
		tf = TextFloat::displayMessage(
				tr( "Loading plugin" ),
				tr( "Please wait while loading the VST plugin..." ),
				PLUGIN_NAME::getIconPixmap( "logo", 24, 24 ), 0 );
	}

	m_pluginMutex.lock();
	m_plugin = new VstInstrumentPlugin( m_pluginDLL );
	if( m_plugin->failed() )
	{
		m_pluginMutex.unlock();
		closePlugin();
		delete tf;
		collectErrorForUI( VstPlugin::tr( "The VST plugin %1 could not be loaded." ).arg( m_pluginDLL ) );
		m_pluginDLL = "";
		return;
	}

	if ( !(instrumentTrack() != NULL && instrumentTrack()->isPreviewMode()))
	{
		m_plugin->createUI(nullptr);
		m_plugin->showUI();
	}

	if( set_ch_name )
	{
		instrumentTrack()->setName( m_plugin->name() );
	}

	m_pluginMutex.unlock();

	emit dataChanged();

	delete tf;
}

void vestigeInstrument::play( sampleFrame * _buf )
{
	if (!m_pluginMutex.tryLock(Engine::getSong()->isExporting() ? -1 : 0)) {return;}

	const fpp_t frames = Engine::mixer()->framesPerPeriod();

	if( m_plugin == NULL )
	{
		m_pluginMutex.unlock();
		return;
	}

	m_plugin->process( NULL, _buf );

	instrumentTrack()->processAudioBuffer( _buf, frames, NULL );

	m_pluginMutex.unlock();
}

bool vestigeInstrument::handleMidiEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset )
{
	m_pluginMutex.lock();
	if( m_plugin != NULL )
	{
		m_plugin->processMidiEvent( event, offset );
	}
	m_pluginMutex.unlock();

	return true;
}

void vestigeInstrument::closePlugin( void )
{
	// disconnect all signals
	if( knobFModel != NULL )
	{
		for( int i = 0; i < paramCount; i++ )
		{
			delete knobFModel[ i ];
		}
	}

	if( knobFModel != NULL )
	{
		delete [] knobFModel;
		knobFModel = NULL;
	}

	if( m_scrollArea != NULL )
	{
//		delete m_scrollArea;
		m_scrollArea = NULL;
	}

	if( m_subWindow != NULL )
	{
		m_subWindow->setAttribute( Qt::WA_DeleteOnClose );
		m_subWindow->close();

		if( m_subWindow != NULL )
		{
			delete m_subWindow;
		}
		m_subWindow = NULL;
	}

	if( p_subWindow != NULL )
	{
		p_subWindow = NULL;
	}

	m_pluginMutex.lock();
	delete m_plugin;
	m_plugin = NULL;
	m_pluginMutex.unlock();
}

PluginView * vestigeInstrument::instantiateView( QWidget * _parent )
{
	return new VestigeInstrumentView( this, _parent );
}

VestigeInstrumentView::VestigeInstrumentView( Instrument * _instrument,
							QWidget * _parent ) :
	InstrumentViewFixedSize( _instrument, _parent ),
	lastPosInMenu (0)
{
	if( s_artwork == NULL )
	{
		s_artwork = new QPixmap( PLUGIN_NAME::getIconPixmap(
								"artwork" ) );
	}

	m_openPluginButton = new PixmapButton( this, "" );
	m_openPluginButton->setCheckable( false );
	m_openPluginButton->setCursor( Qt::PointingHandCursor );
	m_openPluginButton->move( 216, 81 );
	m_openPluginButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
							"select_file_active" ) );
	m_openPluginButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
							"select_file" ) );
	connect( m_openPluginButton, SIGNAL( clicked() ), this,
						SLOT( openPlugin() ) );
	ToolTip::add( m_openPluginButton, tr( "Open VST plugin" ) );

	m_managePluginButton = new PixmapButton( this, "" );
	m_managePluginButton->setCheckable( false );
	m_managePluginButton->setCursor( Qt::PointingHandCursor );
	m_managePluginButton->move( 216, 101 );
	m_managePluginButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
							"controls_active" ) );
	m_managePluginButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
							"controls" ) );
	connect( m_managePluginButton, SIGNAL( clicked() ), this,
						SLOT( managePlugin() ) );
	ToolTip::add( m_managePluginButton, tr( "Control VST plugin from LMMS host" ) );

	m_openPresetButton = new PixmapButton( this, "" );
	m_openPresetButton->setCheckable( false );
	m_openPresetButton->setCursor( Qt::PointingHandCursor );
	m_openPresetButton->move( 200, 224 );
	m_openPresetButton->setActiveGraphic( embed::getIconPixmap(
							"project_open", 20, 20 ) );
	m_openPresetButton->setInactiveGraphic( embed::getIconPixmap(
							"project_open", 20, 20 ) );
	connect( m_openPresetButton, SIGNAL( clicked() ), this,
						SLOT( openPreset() ) );
	ToolTip::add( m_openPresetButton, tr( "Open VST plugin preset" ) );

	m_rolLPresetButton = new PixmapButton( this, "" );
	m_rolLPresetButton->setCheckable( false );
	m_rolLPresetButton->setCursor( Qt::PointingHandCursor );
	m_rolLPresetButton->move( 190, 201 );
	m_rolLPresetButton->setActiveGraphic( embed::getIconPixmap(
							"stepper-left-press" ) );
	m_rolLPresetButton->setInactiveGraphic( embed::getIconPixmap(
							"stepper-left" ) );
	connect( m_rolLPresetButton, SIGNAL( clicked() ), this,
						SLOT( previousProgram() ) );
	ToolTip::add( m_rolLPresetButton, tr( "Previous (-)" ) );

	m_rolLPresetButton->setShortcut( Qt::Key_Minus );

	m_savePresetButton = new PixmapButton( this, "" );
	m_savePresetButton->setCheckable( false );
	m_savePresetButton->setCursor( Qt::PointingHandCursor );
	m_savePresetButton->move( 224, 224 );
	m_savePresetButton->setActiveGraphic( embed::getIconPixmap(
							"project_save", 20, 20  ) );
	m_savePresetButton->setInactiveGraphic( embed::getIconPixmap(
							"project_save", 20, 20  ) );
	connect( m_savePresetButton, SIGNAL( clicked() ), this,
						SLOT( savePreset() ) );
	ToolTip::add( m_savePresetButton, tr( "Save preset" ) );

	m_rolRPresetButton = new PixmapButton( this, "" );
	m_rolRPresetButton->setCheckable( false );
	m_rolRPresetButton->setCursor( Qt::PointingHandCursor );
	m_rolRPresetButton->move( 209, 201 );
	m_rolRPresetButton->setActiveGraphic( embed::getIconPixmap(
							"stepper-right-press" ) );
	m_rolRPresetButton->setInactiveGraphic( embed::getIconPixmap(
							"stepper-right" ) );
	connect( m_rolRPresetButton, SIGNAL( clicked() ), this,
						SLOT( nextProgram() ) );
	ToolTip::add( m_rolRPresetButton, tr( "Next (+)" ) );

	m_rolRPresetButton->setShortcut( Qt::Key_Plus );

	m_selPresetButton = new QPushButton( tr( "" ), this );
	m_selPresetButton->setGeometry( 228, 201, 16, 16 );

	QMenu *menu = new QMenu;

	connect( menu, SIGNAL( aboutToShow() ), this, SLOT( updateMenu() ) );

	m_selPresetButton->setIcon( embed::getIconPixmap( "stepper-down" ) );

	m_selPresetButton->setMenu(menu);

	m_toggleGUIButton = new QPushButton( tr( "Show/hide GUI" ), this );
	m_toggleGUIButton->setGeometry( 20, 130, 200, 24 );
	m_toggleGUIButton->setIcon( embed::getIconPixmap( "zoom" ) );
	m_toggleGUIButton->setFont( pointSize<8>( m_toggleGUIButton->font() ) );
	connect( m_toggleGUIButton, SIGNAL( clicked() ), this,
							SLOT( toggleGUI() ) );

	QPushButton * note_off_all_btn = new QPushButton( tr( "Turn off all "
							"notes" ), this );
	note_off_all_btn->setGeometry( 20, 160, 200, 24 );
	note_off_all_btn->setIcon( embed::getIconPixmap( "stop" ) );
	note_off_all_btn->setFont( pointSize<8>( note_off_all_btn->font() ) );
	connect( note_off_all_btn, SIGNAL( clicked() ), this,
							SLOT( noteOffAll() ) );

	setAcceptDrops( true );
	_instrument2 = _instrument;
	_parent2 = _parent;
}

void VestigeInstrumentView::managePlugin( void )
{
	if ( m_vi->m_plugin != NULL && m_vi->m_subWindow == NULL ) {
		m_vi->p_subWindow = new manageVestigeInstrumentView( _instrument2, _parent2, m_vi);
	} else if (m_vi->m_subWindow != NULL) {
		if (m_vi->m_subWindow->widget()->isVisible() == false ) {
			m_vi->m_scrollArea->show();
			m_vi->m_subWindow->show();
		} else {
			m_vi->m_scrollArea->hide();
			m_vi->m_subWindow->hide();
		}
	}
}

void VestigeInstrumentView::updateMenu( void )
{

	// get all presets -
	if ( m_vi->m_plugin != NULL )
	{
		m_vi->m_plugin->loadProgramNames();
		QWidget::update();

     		QString str = m_vi->m_plugin->allProgramNames();

    		QStringList list1 = str.split("|");

     		QMenu * to_menu = m_selPresetButton->menu();
    		to_menu->clear();

			QVector<QAction*> presetActions(list1.size());

     		for (int i = 0; i < list1.size(); i++) {
			presetActions[i] = new QAction(this);
			connect(presetActions[i], SIGNAL(triggered()), this, SLOT(selPreset()));

        		presetActions[i]->setText(QString("%1. %2").arg(QString::number(i+1), list1.at(i)));
        		presetActions[i]->setData(i);
			if (i == lastPosInMenu) {
        			presetActions[i]->setIcon(embed::getIconPixmap( "sample_file", 16, 16 ));
			} else  presetActions[i]->setIcon(embed::getIconPixmap( "edit_copy", 16, 16 ));
			to_menu->addAction( presetActions[i] );
     		}

	}
}

VestigeInstrumentView::~VestigeInstrumentView()
{
}

void VestigeInstrumentView::modelChanged()
{
	m_vi = castModel<vestigeInstrument>();
}

void VestigeInstrumentView::openPlugin()
{
	FileDialog ofd( NULL, tr( "Open VST plugin" ) );

	// set filters
	QStringList types;
	types << tr( "DLL-files (*.dll)" )
		<< tr( "EXE-files (*.exe)" )
		;
	ofd.setNameFilters( types );

	if( m_vi->m_pluginDLL != "" )
	{
		QString f = PathUtil::toAbsolute( m_vi->m_pluginDLL );
		ofd.setDirectory( QFileInfo( f ).absolutePath() );
		ofd.selectFile( QFileInfo( f ).fileName() );
	}
	else
	{
		ofd.setDirectory( ConfigManager::inst()->vstDir() );
	}

	if ( ofd.exec () == QDialog::Accepted )
	{
		if( ofd.selectedFiles().isEmpty() )
		{
			return;
		}
		Engine::mixer()->requestChangeInModel();

		if (m_vi->p_subWindow != NULL) {
			delete m_vi->p_subWindow;
			m_vi->p_subWindow = NULL;
		}

		m_vi->loadFile( ofd.selectedFiles()[0] );
		Engine::mixer()->doneChangeInModel();
		if( m_vi->m_plugin && m_vi->m_plugin->pluginWidget() )
		{
			m_vi->m_plugin->pluginWidget()->setWindowIcon(
									PLUGIN_NAME::getIconPixmap( "logo" ) );
		}
	}
}

void VestigeInstrumentView::openPreset()
{

	if ( m_vi->m_plugin != NULL ) {
		m_vi->m_plugin->openPreset( );
    		bool converted;
    		QString str = m_vi->m_plugin->currentProgramName().section("/", 0, 0);
     		if (str != "")
   			lastPosInMenu = str.toInt(&converted, 10) - 1;
		QWidget::update();
	}

}

void VestigeInstrumentView::savePreset()
{

	if ( m_vi->m_plugin != NULL )
	{
		m_vi->m_plugin->savePreset( );
/*    		bool converted;
    		QString str = m_vi->m_plugin->presetString().section("/", 0, 0);
     		if (str != "")
   			lastPosInMenu = str.toInt(&converted, 10) - 1;
		QWidget::update();*/
	}

}

void VestigeInstrumentView::nextProgram()
{

	if ( m_vi->m_plugin != NULL ) {
		m_vi->m_plugin->rotateProgram( 1 );
    		bool converted;
    		QString str = m_vi->m_plugin->currentProgramName().section("/", 0, 0);
     		if (str != "")
   			lastPosInMenu = str.toInt(&converted, 10) - 1;
		QWidget::update();
	}
}

void VestigeInstrumentView::previousProgram()
{

	if ( m_vi->m_plugin != NULL ) {
		m_vi->m_plugin->rotateProgram( -1 );
    		bool converted;
    		QString str = m_vi->m_plugin->currentProgramName().section("/", 0, 0);
     		if (str != "")
   			lastPosInMenu = str.toInt(&converted, 10) - 1;
		QWidget::update();
	}
}

void VestigeInstrumentView::selPreset( void )
{

     QAction *action = qobject_cast<QAction *>(sender());
     if (action)
         if ( m_vi->m_plugin != NULL ) {
		lastPosInMenu = action->data().toInt();
		m_vi->m_plugin->setProgram( action->data().toInt() );
		QWidget::update();
	 }
}

void VestigeInstrumentView::toggleGUI( void )
{
	if( m_vi == NULL || m_vi->m_plugin == NULL )
	{
		return;
	}
	m_vi->m_plugin->toggleUI();
}

void VestigeInstrumentView::noteOffAll( void )
{
	m_vi->m_pluginMutex.lock();
	if( m_vi->m_plugin != NULL )
	{
		for( int key = 0; key <= MidiMaxKey; ++key )
		{
			m_vi->m_plugin->processMidiEvent( MidiEvent( MidiNoteOff, 0, key, 0 ), 0 );
		}
	}
	m_vi->m_pluginMutex.unlock();
}

void VestigeInstrumentView::dragEnterEvent( QDragEnterEvent * _dee )
{
	// For mimeType() and MimeType enum class
	using namespace Clipboard;

	if( _dee->mimeData()->hasFormat( mimeType( MimeType::StringPair ) ) )
	{
		QString txt = _dee->mimeData()->data(
						mimeType( MimeType::StringPair ) );
		if( txt.section( ':', 0, 0 ) == "vstplugin" )
		{
			_dee->acceptProposedAction();
		}
		else
		{
			_dee->ignore();
		}
	}
	else
	{
		_dee->ignore();
	}
}

void VestigeInstrumentView::dropEvent( QDropEvent * _de )
{
	QString type = StringPairDrag::decodeKey( _de );
	QString value = StringPairDrag::decodeValue( _de );
	if( type == "vstplugin" )
	{
		m_vi->loadFile( value );
		_de->accept();
		return;
	}
	_de->ignore();
}

void VestigeInstrumentView::paintEvent( QPaintEvent * )
{
	QPainter p( this );

	p.drawPixmap( 0, 0, *s_artwork );

	QString plugin_name = ( m_vi->m_plugin != NULL ) ?
				m_vi->m_plugin->name()/* + QString::number(
						m_plugin->version() )*/
					:
				tr( "No VST plugin loaded" );
	QFont f = p.font();
	f.setBold( true );
	p.setFont( pointSize<10>( f ) );
	p.setPen( QColor( 255, 255, 255 ) );
	p.drawText( 10, 100, plugin_name );

	p.setPen( QColor( 50, 50, 50 ) );
	p.drawText( 10, 211, tr( "Preset" ) );

//	m_pluginMutex.lock();
	if( m_vi->m_plugin != NULL )
	{
		p.setPen( QColor( 0, 0, 0 ) );
		f.setBold( false );
		p.setFont( pointSize<8>( f ) );
		p.drawText( 10, 114, tr( "by " ) +
					m_vi->m_plugin->vendorString() );
		p.setPen( QColor( 255, 255, 255 ) );
		p.drawText( 10, 225, m_vi->m_plugin->currentProgramName() );
	}

	if( m_vi->m_subWindow != NULL )
	{
		m_vi->m_subWindow->setWindowTitle( m_vi->instrumentTrack()->name()
								+ tr( " - VST plugin control" ) );
	}
//	m_pluginMutex.unlock();
}

manageVestigeInstrumentView::manageVestigeInstrumentView( Instrument * _instrument,
							QWidget * _parent, vestigeInstrument * m_vi2 ) :
	InstrumentViewFixedSize( _instrument, _parent )
{
	m_vi = m_vi2;
	m_vi->m_scrollArea = new QScrollArea( this );
	widget = new QWidget(this);
	l = new QGridLayout( this );

	m_vi->m_subWindow = gui->mainWindow()->addWindowedWidget(NULL, Qt::SubWindow |
			Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
	m_vi->m_subWindow->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::MinimumExpanding );
	m_vi->m_subWindow->setFixedWidth( 960 );
	m_vi->m_subWindow->setMinimumHeight( 300 );
	m_vi->m_subWindow->setWidget(m_vi->m_scrollArea);
	m_vi->m_subWindow->setWindowTitle( m_vi->instrumentTrack()->name()
								+ tr( " - VST plugin control" ) );
	m_vi->m_subWindow->setWindowIcon( PLUGIN_NAME::getIconPixmap( "logo" ) );
	m_vi->m_subWindow->setAttribute( Qt::WA_DeleteOnClose, false );

	l->setContentsMargins( 20, 10, 10, 10 );
	l->setVerticalSpacing( 10 );
	l->setHorizontalSpacing( 23 );

	m_syncButton = new QPushButton( tr( "VST Sync" ), this );
	connect( m_syncButton, SIGNAL( clicked() ), this,
							SLOT( syncPlugin() ) );

	l->addWidget( m_syncButton, 0, 0, 1, 2, Qt::AlignLeft );

	m_displayAutomatedOnly = new QPushButton( tr( "Automated" ), this );
	connect( m_displayAutomatedOnly, SIGNAL( clicked() ), this,
							SLOT( displayAutomatedOnly() ) );

	l->addWidget( m_displayAutomatedOnly, 0, 1, 1, 2, Qt::AlignLeft );

	m_closeButton = new QPushButton( tr( "    Close    " ), widget );
	connect( m_closeButton, SIGNAL( clicked() ), this,
							SLOT( closeWindow() ) );

	l->addWidget( m_closeButton, 0, 2, 1, 7, Qt::AlignLeft );

	for( int i = 0; i < 10; i++ )
	{
		l->addItem( new QSpacerItem( 68, 45, QSizePolicy::Fixed, QSizePolicy::Fixed ), 0, i );
	}

	const QMap<QString, QString> & dump = m_vi->m_plugin->parameterDump();
	m_vi->paramCount = dump.size();

	vstKnobs = new CustomTextKnob *[ m_vi->paramCount ];

	bool hasKnobModel = true;
	if (m_vi->knobFModel == NULL) {
		m_vi->knobFModel = new FloatModel *[ m_vi->paramCount ];
		hasKnobModel = false;
	}

	char paramStr[35];
	QStringList s_dumpValues;

	for( int i = 0; i < m_vi->paramCount; i++ )
	{
		sprintf( paramStr, "param%d", i);
		s_dumpValues = dump[ paramStr ].split( ":" );

		vstKnobs[ i ] = new CustomTextKnob( knobBright_26, this, s_dumpValues.at( 1 ) );
		vstKnobs[ i ]->setDescription( s_dumpValues.at( 1 ) + ":" );
		vstKnobs[ i ]->setLabel( s_dumpValues.at( 1 ).left( 15 ) );

		if( !hasKnobModel )
		{
			sprintf( paramStr, "%d", i);
			m_vi->knobFModel[ i ] = new FloatModel( LocaleHelper::toFloat(s_dumpValues.at(2)),
				0.0f, 1.0f, 0.01f, castModel<vestigeInstrument>(), paramStr );
		}

		FloatModel * model = m_vi->knobFModel[i];
		connect( model, &FloatModel::dataChanged, this,
			[this, model]() { setParameter( model ); }, Qt::DirectConnection);
		vstKnobs[i] ->setModel( model );
	}
	syncParameterText();

	int i = 0;
	for( int lrow = 1; lrow < ( int( m_vi->paramCount / 10 ) + 1 ) + 1; lrow++ )
	{
		for( int lcolumn = 0; lcolumn < 10; lcolumn++ )
		{
			if( i < m_vi->paramCount )
			{
				l->addWidget( vstKnobs[i], lrow, lcolumn, Qt::AlignCenter );
			}
			i++;
		}
	}

	l->setRowStretch( ( int( m_vi->paramCount / 10) + 1), 1 );
	l->setColumnStretch( 10, 1 );

	widget->setLayout(l);
	widget->setAutoFillBackground(true);

	m_vi->m_scrollArea->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
	m_vi->m_scrollArea->setPalette( QApplication::palette( m_vi->m_scrollArea ) );
	m_vi->m_scrollArea->setMinimumHeight( 64 );

	m_vi->m_scrollArea->setWidget( widget );

	m_vi->m_subWindow->show();
}

void manageVestigeInstrumentView::closeWindow()
{
	m_vi->m_subWindow->hide();
}

void manageVestigeInstrumentView::syncPlugin( void )
{
	char paramStr[35];
	QStringList s_dumpValues;
	const QMap<QString, QString> & dump = m_vi->m_plugin->parameterDump();
	float f_value;

	for( int i = 0; i < m_vi->paramCount; i++ )
	{
		// only not automated knobs are synced from VST
		// those auto-setted values are not jurnaled, tracked for undo / redo
		if( !( m_vi->knobFModel[ i ]->isAutomated() || m_vi->knobFModel[ i ]->controllerConnection() ) )
		{
			sprintf( paramStr, "param%d", i );
    			s_dumpValues = dump[ paramStr ].split( ":" );
			f_value = LocaleHelper::toFloat(s_dumpValues.at(2));
			m_vi->knobFModel[ i ]->setAutomatedValue( f_value );
			m_vi->knobFModel[ i ]->setInitValue( f_value );
		}
	}
	syncParameterText();
}

void manageVestigeInstrumentView::displayAutomatedOnly( void )
{
	bool isAuto = QString::compare( m_displayAutomatedOnly->text(), tr( "Automated" ) ) == 0;

	for( int i = 0; i< m_vi->paramCount; i++ )
	{

		if( !( m_vi->knobFModel[ i ]->isAutomated() || m_vi->knobFModel[ i ]->controllerConnection() ) )
		{
			if( vstKnobs[ i ]->isVisible() == true  && isAuto )
			{
				vstKnobs[ i ]->hide();
				m_displayAutomatedOnly->setText( "All" );
			} else {
				vstKnobs[ i ]->show();
				m_displayAutomatedOnly->setText( "Automated" );
			}
		}
	}
}

manageVestigeInstrumentView::~manageVestigeInstrumentView()
{
	if( m_vi->knobFModel != NULL )
	{
		for( int i = 0; i < m_vi->paramCount; i++ )
		{
			delete m_vi->knobFModel[ i ];
			delete vstKnobs[ i ];
		}
	}

	if (vstKnobs != NULL) {
		delete []vstKnobs;
		vstKnobs = NULL;
	}

	if( m_vi->knobFModel != NULL )
	{
		delete [] m_vi->knobFModel;
		m_vi->knobFModel = NULL;
	}

	if (m_vi->m_scrollArea != NULL) {
		delete m_vi->m_scrollArea;
		m_vi->m_scrollArea = NULL;
	}

	if ( m_vi->m_subWindow != NULL ) {
		m_vi->m_subWindow->setAttribute(Qt::WA_DeleteOnClose);
		m_vi->m_subWindow->close();

		if ( m_vi->m_subWindow != NULL )
			delete m_vi->m_subWindow;
		m_vi->m_subWindow = NULL;
	}

	m_vi->p_subWindow = NULL;
}

void manageVestigeInstrumentView::setParameter( Model * action )
{
	int knobUNID = action->displayName().toInt();

	if ( m_vi->m_plugin != NULL ) {
		m_vi->m_plugin->setParam( knobUNID, m_vi->knobFModel[knobUNID]->value() );
		syncParameterText();
	}
}

void manageVestigeInstrumentView::syncParameterText()
{
	m_vi->m_plugin->loadParameterLabels();
	m_vi->m_plugin->loadParameterDisplays();

	QString paramLabelStr   = m_vi->m_plugin->allParameterLabels();
	QString paramDisplayStr = m_vi->m_plugin->allParameterDisplays();

	QStringList paramLabelList;
	QStringList paramDisplayList;

	for( int i = 0; i < paramLabelStr.size(); )
	{
		const int length = paramLabelStr[i].digitValue();
		paramLabelList.append(paramLabelStr.mid(i + 1, length));
		i += length + 1;
	}

	for( int i = 0; i < paramDisplayStr.size(); )
	{
		const int length = paramDisplayStr[i].digitValue();
		paramDisplayList.append(paramDisplayStr.mid(i + 1, length));
		i += length + 1;
	}

	for( int i = 0; i < paramLabelList.size(); ++i )
	{
		vstKnobs[i]->setValueText(paramDisplayList[i] + ' ' + paramLabelList[i]);
	}
}

void manageVestigeInstrumentView::dragEnterEvent( QDragEnterEvent * _dee )
{
	// For mimeType() and MimeType enum class
	using namespace Clipboard;

	if( _dee->mimeData()->hasFormat( mimeType( MimeType::StringPair ) ) )
	{
		QString txt = _dee->mimeData()->data(
						mimeType( MimeType::StringPair ) );
		if( txt.section( ':', 0, 0 ) == "vstplugin" )
		{
			_dee->acceptProposedAction();
		}
		else
		{
			_dee->ignore();
		}
	}
	else
	{
		_dee->ignore();
	}
}

void manageVestigeInstrumentView::dropEvent( QDropEvent * _de )
{
	QString type = StringPairDrag::decodeKey( _de );
	QString value = StringPairDrag::decodeValue( _de );
	if( type == "vstplugin" )
	{
		m_vi->loadFile( value );
		_de->accept();
		return;
	}
	_de->ignore();
}

void manageVestigeInstrumentView::paintEvent( QPaintEvent * )
{
	m_vi->m_subWindow->setWindowTitle( m_vi->instrumentTrack()->name()
					+ tr( " - VST plugin control" ) );
}

extern "C"
{

// necessary for getting instance out of shared lib
Q_DECL_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
	return new vestigeInstrument( static_cast<InstrumentTrack *>( m ) );
}

}


code:
/*
 * vestige.h - instrument VeSTige for hosting VST-plugins
 *
 * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */

#ifndef _VESTIGE_H
#define _VESTIGE_H

#include <QMutex>
#include <QLayout>
#include <QScrollArea>

#include "Instrument.h"
#include "InstrumentView.h"
#include "Note.h"
#include "CustomTextKnob.h"
#include "SubWindow.h"
#include "AutomatableModel.h"

class QPixmap;
class QPushButton;

class PixmapButton;
class VstPlugin;

class vestigeInstrument : public Instrument
{
	Q_OBJECT
public:
	vestigeInstrument( InstrumentTrack * _instrument_track );
	virtual ~vestigeInstrument();

	virtual void play( sampleFrame * _working_buffer );

	virtual void saveSettings( QDomDocument & _doc, QDomElement & _parent );
	virtual void loadSettings( const QDomElement & _this );

	virtual QString nodeName( void ) const;

	virtual void loadFile( const QString & _file );

	virtual Flags flags() const
	{
		return IsSingleStreamed | IsMidiBased;
	}

	virtual bool handleMidiEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset = 0 );

	virtual PluginView * instantiateView( QWidget * _parent );

protected slots:
	void setParameter( Model * action );
	void handleConfigChange( QString cls, QString attr, QString value );
	void reloadPlugin();

private:
	void closePlugin( void );

	VstPlugin * m_plugin;
	QMutex m_pluginMutex;

	QString m_pluginDLL;
	QMdiSubWindow * m_subWindow;
	QScrollArea * m_scrollArea;
	FloatModel ** knobFModel;
	QObject * p_subWindow;
	int paramCount;

	friend class VestigeInstrumentView;
	friend class manageVestigeInstrumentView;

} ;

class manageVestigeInstrumentView : public InstrumentViewFixedSize
{
	Q_OBJECT
public:
	manageVestigeInstrumentView( Instrument * _instrument, QWidget * _parent, vestigeInstrument * m_vi2 );
	virtual ~manageVestigeInstrumentView();

protected slots:
	void syncPlugin( void );
	void displayAutomatedOnly( void );
	void setParameter( Model * action );
	void syncParameterText();
	void closeWindow();

protected:
	virtual void dragEnterEvent( QDragEnterEvent * _dee );
	virtual void dropEvent( QDropEvent * _de );
	virtual void paintEvent( QPaintEvent * _pe );

private:
	static QPixmap * s_artwork;

	vestigeInstrument * m_vi;

	QWidget *widget;
	QGridLayout * l;
	QPushButton * m_syncButton;
	QPushButton * m_displayAutomatedOnly;
	QPushButton * m_closeButton;
	CustomTextKnob ** vstKnobs;

} ;

class VestigeInstrumentView : public InstrumentViewFixedSize
{
	Q_OBJECT
public:
	VestigeInstrumentView( Instrument * _instrument, QWidget * _parent );
	virtual ~VestigeInstrumentView();

protected slots:
	void updateMenu( void );
	void openPlugin( void );
	void managePlugin( void );
	void openPreset( void );
	void savePreset( void );
	void nextProgram();
	void previousProgram();
	void selPreset( void );
	void toggleGUI( void );
	void noteOffAll( void );

protected:
	virtual void dragEnterEvent( QDragEnterEvent * _dee );
	virtual void dropEvent( QDropEvent * _de );
	virtual void paintEvent( QPaintEvent * _pe );

private:
	virtual void modelChanged( void );

	static QPixmap * s_artwork;

	vestigeInstrument * m_vi;

	int lastPosInMenu;

	PixmapButton * m_openPluginButton;
	PixmapButton * m_openPresetButton;
	PixmapButton * m_rolLPresetButton;
	PixmapButton * m_rolRPresetButton;
	QPushButton * m_selPresetButton;
	QPushButton * m_toggleGUIButton;
	PixmapButton * m_managePluginButton;
	PixmapButton * m_savePresetButton;

	Instrument * _instrument2;
	QWidget * _parent2;

} ;

#endif

repo_name: CYBERDEViL/LMMS

license: mit


code:
INCLUDE(BuildPlugin)

BUILD_PLUGIN(vibedstrings vibed.cpp nine_button_selector.cpp string_container.cpp vibrating_string.cpp vibed.h nine_button_selector.h string_container.h vibrating_string.h MOCFILES vibed.h nine_button_selector.h EMBEDDED_RESOURCES *.png)


code:
/*
 * nine_button_selector.cpp
 *
 * Copyright (c) 2006-2007 Danny McRae <khjklujn/at/yahoo/com>
 * Copyright (c) 2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */

#include "nine_button_selector.h"

#include "CaptionMenu.h"
#include "embed.h"

nineButtonSelector::nineButtonSelector(	QPixmap _button0_on,
					QPixmap _button0_off,
					QPixmap _button1_on,
					QPixmap _button1_off,
					QPixmap _button2_on,
					QPixmap _button2_off,
					QPixmap _button3_on,
					QPixmap _button3_off,
					QPixmap _button4_on,
					QPixmap _button4_off,
					QPixmap _button5_on,
					QPixmap _button5_off,
					QPixmap _button6_on,
					QPixmap _button6_off,
					QPixmap _button7_on,
					QPixmap _button7_off,
					QPixmap _button8_on,
					QPixmap _button8_off,
					int _default,
					int _x, int _y,
					QWidget * _parent ):
	QWidget( _parent ),
	IntModelView( new nineButtonSelectorModel(0, 8, _default, NULL,
				QString(), true ), this )
{
	setFixedSize( 50, 50 );
	move( _x, _y );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 1, 1 );
	m_button->setActiveGraphic( _button0_on );
	m_button->setInactiveGraphic( _button0_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button0Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 18, 1 );
	m_button->setActiveGraphic( _button1_on );
	m_button->setInactiveGraphic( _button1_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button1Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 35, 1 );
	m_button->setActiveGraphic( _button2_on );
	m_button->setInactiveGraphic( _button2_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button2Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 1, 18 );
	m_button->setActiveGraphic( _button3_on );
	m_button->setInactiveGraphic( _button3_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button3Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 18, 18 );
	m_button->setActiveGraphic( _button4_on );
	m_button->setInactiveGraphic( _button4_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button4Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 35, 18 );
	m_button->setActiveGraphic( _button5_on );
	m_button->setInactiveGraphic( _button5_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button5Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 1, 35 );
	m_button->setActiveGraphic( _button6_on );
	m_button->setInactiveGraphic( _button6_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button6Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 18, 35 );
	m_button->setActiveGraphic( _button7_on );
	m_button->setInactiveGraphic( _button7_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button7Clicked() ) );
	m_buttons.append( m_button );

	m_button = new PixmapButton( this, NULL );
	m_button->move( 35, 35 );
	m_button->setActiveGraphic( _button8_on );
	m_button->setInactiveGraphic( _button8_off );
	m_button->setChecked( false );
	connect( m_button, SIGNAL ( clicked () ),
		 this, SLOT ( button8Clicked() ) );
	m_buttons.append( m_button );

	m_lastBtn = m_buttons[_default];
	m_lastBtn->setChecked( true );
}

nineButtonSelector::~ nineButtonSelector()
{
	for( int i = 0; i < 9; i++ )
	{
		delete m_buttons[i];
	}
}

void nineButtonSelector::button0Clicked()
{
	setSelected( 0 );
}

void nineButtonSelector::button1Clicked()
{
	setSelected( 1 );
}

void nineButtonSelector::button2Clicked()
{
	setSelected( 2 );
}

void nineButtonSelector::button3Clicked()
{
	setSelected( 3 );
}

void nineButtonSelector::button4Clicked()
{
	setSelected( 4 );
}

void nineButtonSelector::button5Clicked()
{
	setSelected( 5 );
}

void nineButtonSelector::button6Clicked()
{
	setSelected( 6 );
}

void nineButtonSelector::button7Clicked()
{
	setSelected( 7 );
}

void nineButtonSelector::button8Clicked()
{
	setSelected( 8 );
}

void nineButtonSelector::modelChanged()
{
	updateButton( model()->value() );
}

void nineButtonSelector::setSelected( int _new_button )
{
	model()->setValue(_new_button);
	updateButton( _new_button );
}

void nineButtonSelector::updateButton( int _new_button )
{
	m_lastBtn->setChecked( false );
	m_lastBtn->update();

	m_lastBtn = m_buttons[_new_button];
	m_lastBtn->setChecked( true );
	m_lastBtn->update();

	emit nineButtonSelection( _new_button );
}

void nineButtonSelector::contextMenuEvent( QContextMenuEvent * )
{
	CaptionMenu contextMenu( windowTitle(), this );
	contextMenu.exec( QCursor::pos() );
}


code:
/*
 * nine_button_selector.h
 *
 * Copyright (c) 2006-2007 Danny McRae <khjklujn/at/yahoo/com>
 * Copyright (c) 2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */
#ifndef _NINE_BUTTON_SELECTOR_H
#define _NINE_BUTTON_SELECTOR_H

#include "PixmapButton.h"

class nineButtonSelector: public QWidget , public IntModelView
{
	Q_OBJECT

public:
	nineButtonSelector( 	QPixmap _button0_on,
				QPixmap _button0_off,
				QPixmap _button1_on,
				QPixmap _button1_off,
				QPixmap _button2_on,
				QPixmap _button2_off,
				QPixmap _button3_on,
				QPixmap _button3_off,
				QPixmap _button4_on,
				QPixmap _button4_off,
				QPixmap _button5_on,
				QPixmap _button5_off,
				QPixmap _button6_on,
				QPixmap _button6_off,
				QPixmap _button7_on,
				QPixmap _button7_off,
				QPixmap _button8_on,
				QPixmap _button8_off,
				int _default,
				int _x, int _y,
				QWidget * _parent);
	virtual ~nineButtonSelector();

//	inline int getSelected() {
//		return( castModel<nineButtonSelectorModel>()->value() );
//	};

protected:
	void setSelected( int _new_button );

public slots:
	void button0Clicked();
	void button1Clicked();
	void button2Clicked();
	void button3Clicked();
	void button4Clicked();
	void button5Clicked();
	void button6Clicked();
	void button7Clicked();
	void button8Clicked();
	void contextMenuEvent( QContextMenuEvent * );

signals:
	void nineButtonSelection( int );

private:
	virtual void modelChanged();
	void updateButton( int );

	QList<PixmapButton *> m_buttons;
	PixmapButton * m_button;
	PixmapButton * m_lastBtn;

} ;

typedef IntModel nineButtonSelectorModel;

#endif


code:
/*
 * string_container.cpp - contains a collection of strings
 *
 * Copyright (c) 2006 Danny McRae <khjklujn/at/yahoo/com>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */

#include "string_container.h"

stringContainer::stringContainer(const float _pitch,
				const sample_rate_t _sample_rate,
				const int _buffer_length,
				const int _strings ) :
	m_pitch( _pitch ),
	m_sampleRate( _sample_rate ),
	m_bufferLength( _buffer_length )
{
	for( int i = 0; i < _strings; i++ )
	{
		m_exists.append( false );
	}
}

void stringContainer::addString(int _harm,
				const float _pick,
				const float _pickup,
				const float * _impulse,
				const float _randomize,
				const float _string_loss,
				const float _detune,
				const int _oversample,
				const bool _state,
				const int _id )
{
	float harm;
	switch( _harm )
	{
		case 0:
			harm = 0.25f;
			break;
		case 1:
			harm = 0.5f;
			break;
		case 2:
			harm = 1.0f;
			break;
		case 3:
			harm = 2.0f;
			break;
		case 4:
			harm = 3.0f;
			break;
		case 5:
			harm = 4.0f;
			break;
		case 6:
			harm = 5.0f;
			break;
		case 7:
			harm = 6.0f;
			break;
		case 8:
			harm = 7.0f;
			break;
		default:
			harm = 1.0f;
	}

	m_strings.append( new vibratingString(	m_pitch * harm,
						_pick,
						_pickup,
						const_cast<float*>(_impulse),
						m_bufferLength,
						m_sampleRate,
						_oversample,
						_randomize,
						_string_loss,
						_detune,
						_state ) );
	m_exists[_id] = true;
}


code:
/* string_container.h - contains a collection of strings
 *
 * Copyright (c) 2006 Danny McRae <khjklujn/at/yahoo/com>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */

#ifndef _STRING_CONTAINER_H
#define _STRING_CONTAINER_H

#include <QVector>

#include "vibrating_string.h"
#include "MemoryManager.h"

class stringContainer
{
	MM_OPERATORS
public:
	stringContainer(const float _pitch,
			const sample_rate_t _sample_rate,
			const int _buffer_length,
			const int _strings = 9 );

	void addString(	int _harm,
			const float _pick,
			const float _pickup,
			const float * _impluse,
			const float _randomize,
			const float _string_loss,
			const float _detune,
			const int _oversample,
			const bool _state,
			const int _id );

	bool exists( int _id ) const
	{
		return m_exists[_id];
	}

	~stringContainer()
	{
		int strings = m_strings.count();
		for( int i = 0; i < strings; i++ )
		{
			delete m_strings[i];
		}
	}

	float getStringSample( int _string )
	{
		return m_strings[_string]->nextSample();
	}

private:
	QVector<vibratingString *> m_strings;
	const float m_pitch;
	const sample_rate_t m_sampleRate;
	const int m_bufferLength;
	QVector<bool> m_exists;
} ;

#endif


code:
/*
 * vibed.cpp - combination of PluckedStringSynth and BitInvader
 *
 * Copyright (c) 2006-2008 Danny McRae <khjklujn/at/yahoo/com>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */

#include <QDomDocument>
#include <QMap>

#include "vibed.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "Mixer.h"
#include "NotePlayHandle.h"
#include "ToolTip.h"
#include "base64.h"
#include "CaptionMenu.h"
#include "Oscillator.h"
#include "string_container.h"
#include "volume.h"
#include "Song.h"

#include "embed.h"
#include "plugin_export.h"

extern "C"
{

Plugin::Descriptor PLUGIN_EXPORT vibedstrings_plugin_descriptor =
{
	STRINGIFY( PLUGIN_NAME ),
	"Vibed",
	QT_TRANSLATE_NOOP( "PluginBrowser",
					"Vibrating string modeler" ),
	"Danny McRae <khjklujn/at/yahoo/com>",
	0x0100,
	Plugin::Instrument,
	new PluginPixmapLoader( "logo" ),
	NULL,
	NULL
};

}

vibed::vibed( InstrumentTrack * _instrumentTrack ) :
	Instrument( _instrumentTrack, &vibedstrings_plugin_descriptor )
{

	FloatModel * knob;
	BoolModel * led;
	nineButtonSelectorModel * harmonic;
	graphModel * graphTmp;

	for( int harm = 0; harm < 9; harm++ )
	{
		knob = new FloatModel( DefaultVolume, MinVolume, MaxVolume,
				1.0f, this, tr( "String %1 volume" ).arg( harm+1 ) );
		m_volumeKnobs.append( knob );

		knob = new FloatModel( 0.0f, 0.0f, 0.05f, 0.001f, this,
				tr( "String %1 stiffness" ).arg( harm+1 ) );
		m_stiffnessKnobs.append( knob );

		knob = new FloatModel( 0.0f, 0.0f, 0.05f, 0.005f, this,
				tr( "Pick %1 position" ).arg( harm+1 )  );
		m_pickKnobs.append( knob );

		knob = new FloatModel( 0.05f, 0.0f, 0.05f, 0.005f, this,
				tr( "Pickup %1 position" ).arg( harm+1 ) );
		m_pickupKnobs.append( knob );

		knob = new FloatModel( 0.0f, -1.0f, 1.0f, 0.01f, this,
				tr( "String %1 panning" ).arg( harm+1 )  );
		m_panKnobs.append( knob );

		knob = new FloatModel( 0.0f, -0.1f, 0.1f, 0.001f, this,
				tr( "String %1 detune" ).arg( harm+1 ) );
		m_detuneKnobs.append( knob );

		knob = new FloatModel( 0.0f, 0.0f, 0.75f, 0.01f, this,
				tr( "String %1 fuzziness" ).arg( harm+1 ) );
		m_randomKnobs.append( knob );

		knob = new FloatModel( 1, 1, 16, 1, this,
				tr( "String %1 length" ).arg( harm+1 ) );
		m_lengthKnobs.append( knob );

		led = new BoolModel( false, this,
				tr( "Impulse %1" ).arg( harm+1 ) );
		m_impulses.append( led );

		led = new BoolModel( harm==0, this,
				tr( "String %1" ).arg( harm+1 )  );
		m_powerButtons.append( led );

		harmonic = new nineButtonSelectorModel( 2, 0, 8, this );
		m_harmonics.append( harmonic );

		graphTmp = new graphModel( -1.0, 1.0, __sampleLength, this );
		graphTmp->setWaveToSine();

		m_graphs.append( graphTmp );

	}
}

vibed::~vibed()
{
}

void vibed::saveSettings( QDomDocument & _doc, QDomElement & _this )
{

	QString name;

	// Save plugin version
	_this.setAttribute( "version", "0.1" );

	for( int i = 0; i < 9; i++ )
	{
		name = "active" + QString::number( i );
		_this.setAttribute( name, QString::number(
				m_powerButtons[i]->value() ) );

		if( m_powerButtons[i]->value() )
		{
			name = "volume" + QString::number( i );
			m_volumeKnobs[i]->saveSettings( _doc, _this, name );

			name = "stiffness" + QString::number( i );
			m_stiffnessKnobs[i]->saveSettings( _doc, _this, name );

			name = "pick" + QString::number( i );
			m_pickKnobs[i]->saveSettings( _doc, _this, name );

			name = "pickup" + QString::number( i );
			m_pickupKnobs[i]->saveSettings( _doc, _this, name );

			name = "octave" + QString::number( i );
			m_harmonics[i]->saveSettings( _doc, _this, name );

			name = "length" + QString::number( i );
			m_lengthKnobs[i]->saveSettings( _doc, _this, name );

			name = "pan" + QString::number( i );
			m_panKnobs[i]->saveSettings( _doc, _this, name );

			name = "detune" + QString::number( i );
			m_detuneKnobs[i]->saveSettings( _doc, _this, name );

			name = "slap" + QString::number( i );
			m_randomKnobs[i]->saveSettings( _doc, _this, name );

			name = "impulse" + QString::number( i );
			m_impulses[i]->saveSettings( _doc, _this, name );

			QString sampleString;
			base64::encode(
				(const char *)m_graphs[i]->samples(),
				__sampleLength * sizeof(float),
				sampleString );
			name = "graph" + QString::number( i );
			_this.setAttribute( name, sampleString );
		}
	}

}

void vibed::loadSettings( const QDomElement & _this )
{

	QString name;

	for( int i = 0; i < 9; i++ )
	{
		name = "active" + QString::number( i );
		m_powerButtons[i]->setValue( _this.attribute( name ).toInt() );

		if( m_powerButtons[i]->value() &&
			_this.hasAttribute( "volume" + QString::number( i ) ) )
		{
			name = "volume" + QString::number( i );
			m_volumeKnobs[i]->loadSettings( _this, name );

			name = "stiffness" + QString::number( i );
			m_stiffnessKnobs[i]->loadSettings( _this, name );

			name = "pick" + QString::number( i );
			m_pickKnobs[i]->loadSettings( _this, name );

			name = "pickup" + QString::number( i );
			m_pickupKnobs[i]->loadSettings( _this, name );

			name = "octave" + QString::number( i );
			m_harmonics[i]->loadSettings( _this, name );

			name = "length" + QString::number( i );
			m_lengthKnobs[i]->loadSettings( _this, name );

			name = "pan" + QString::number( i );
			m_panKnobs[i]->loadSettings( _this, name );

			name = "detune" + QString::number( i );
			m_detuneKnobs[i]->loadSettings( _this, name );

			name = "slap" + QString::number( i );
			m_randomKnobs[i]->loadSettings( _this, name );

			name = "impulse" + QString::number( i );
			m_impulses[i]->loadSettings( _this, name );

			int size = 0;
			float * shp = 0;
			base64::decode( _this.attribute( "graph" +
						QString::number( i ) ),
						&shp,
						&size );
			// TODO: check whether size == 128 * sizeof( float ),
			// otherwise me might and up in a segfault
			m_graphs[i]->setSamples( shp );
			delete[] shp;

			// TODO: do one of the following to avoid
			// "uninitialized" wave-shape-buttongroup
			// - activate random-wave-shape-button here
			// - make wave-shape-buttons simple toggle-buttons
			//   instead of checkable buttons
			// - save and restore selected wave-shape-button
		}
	}

//	update();
}

QString vibed::nodeName() const
{
	return( vibedstrings_plugin_descriptor.name );
}

void vibed::playNote( NotePlayHandle * _n, sampleFrame * _working_buffer )
{
	if ( _n->totalFramesPlayed() == 0 || _n->m_pluginData == NULL )
	{
		_n->m_pluginData = new stringContainer( _n->frequency(),
				Engine::mixer()->processingSampleRate(),
						__sampleLength );

		for( int i = 0; i < 9; ++i )
		{
			if( m_powerButtons[i]->value() )
			{
				static_cast<stringContainer*>(
					_n->m_pluginData )->addString(
				m_harmonics[i]->value(),
				m_pickKnobs[i]->value(),
				m_pickupKnobs[i]->value(),
				m_graphs[i]->samples(),
				m_randomKnobs[i]->value(),
				m_stiffnessKnobs[i]->value(),
				m_detuneKnobs[i]->value(),
				static_cast<int>(
					m_lengthKnobs[i]->value() ),
				m_impulses[i]->value(),
				i );
			}
		}
	}

	const fpp_t frames = _n->framesLeftForCurrentPeriod();
	const f_cnt_t offset = _n->noteOffset();
	stringContainer * ps = static_cast<stringContainer *>(
							_n->m_pluginData );

	for( fpp_t i = offset; i < frames + offset; ++i )
	{
		_working_buffer[i][0] = 0.0f;
		_working_buffer[i][1] = 0.0f;
		int s = 0;
		for( int string = 0; string < 9; ++string )
		{
			if( ps->exists( string ) )
			{
				// pan: 0 -> left, 1 -> right
				const float pan = ( m_panKnobs[string]->value() + 1 ) / 2.0f;
				const sample_t sample = ps->getStringSample( s ) * m_volumeKnobs[string]->value() / 100.0f;
				_working_buffer[i][0] += ( 1.0f - pan ) * sample;
				_working_buffer[i][1] += pan * sample;
				s++;
			}
		}
	}

	instrumentTrack()->processAudioBuffer( _working_buffer, frames + offset, _n );
}

void vibed::deleteNotePluginData( NotePlayHandle * _n )
{
	delete static_cast<stringContainer *>( _n->m_pluginData );
}

PluginView * vibed::instantiateView( QWidget * _parent )
{
	return( new vibedView( this, _parent ) );
}

vibedView::vibedView( Instrument * _instrument,
				QWidget * _parent ) :
	InstrumentViewFixedSize( _instrument, _parent )
{
	setAutoFillBackground( true );
	QPalette pal;
	pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap(
								"artwork" ) );
	setPalette( pal );

	m_volumeKnob = new Knob( knobBright_26, this );
	m_volumeKnob->setVolumeKnob( true );
	m_volumeKnob->move( 103, 142 );
	m_volumeKnob->setHintText( tr( "String volume:" ), "" );

	m_stiffnessKnob = new Knob( knobBright_26, this );
	m_stiffnessKnob->move( 129, 142 );
	m_stiffnessKnob->setHintText( tr( "String stiffness:" )
							, "" );

	m_pickKnob = new Knob( knobBright_26, this );
	m_pickKnob->move( 153, 142 );
	m_pickKnob->setHintText( tr( "Pick position:" ), "" );

	m_pickupKnob = new Knob( knobBright_26, this );
	m_pickupKnob->move( 177, 142 );
	m_pickupKnob->setHintText( tr( "Pickup position:" )
						, "" );

	m_panKnob = new Knob( knobBright_26, this );
	m_panKnob->move( 105, 187 );
    m_panKnob->setHintText( tr( "String panning:" ), "" );

	m_detuneKnob = new Knob( knobBright_26, this );
	m_detuneKnob->move( 150, 187 );
	m_detuneKnob->setHintText( tr( "String detune:" ), "" );

	m_randomKnob = new Knob( knobBright_26, this );
	m_randomKnob->move( 194, 187 );
	m_randomKnob->setHintText( tr( "String fuzziness:" )
						, "" );

	m_lengthKnob = new Knob( knobBright_26, this );
	m_lengthKnob->move( 23, 193 );
	m_lengthKnob->setHintText( tr( "String length:" )
						, "" );

	m_impulse = new LedCheckBox( "", this );
	m_impulse->move( 23, 94 );
	ToolTip::add( m_impulse,
			tr( "Impulse" ) );

	m_harmonic = new nineButtonSelector(
		PLUGIN_NAME::getIconPixmap( "button_-2_on" ),
		PLUGIN_NAME::getIconPixmap( "button_-2_off" ),
		PLUGIN_NAME::getIconPixmap( "button_-1_on" ),
		PLUGIN_NAME::getIconPixmap( "button_-1_off" ),
		PLUGIN_NAME::getIconPixmap( "button_f_on" ),
		PLUGIN_NAME::getIconPixmap( "button_f_off" ),
		PLUGIN_NAME::getIconPixmap( "button_2_on" ),
		PLUGIN_NAME::getIconPixmap( "button_2_off" ),
		PLUGIN_NAME::getIconPixmap( "button_3_on" ),
		PLUGIN_NAME::getIconPixmap( "button_3_off" ),
		PLUGIN_NAME::getIconPixmap( "button_4_on" ),
		PLUGIN_NAME::getIconPixmap( "button_4_off" ),
		PLUGIN_NAME::getIconPixmap( "button_5_on" ),
		PLUGIN_NAME::getIconPixmap( "button_5_off" ),
		PLUGIN_NAME::getIconPixmap( "button_6_on" ),
		PLUGIN_NAME::getIconPixmap( "button_6_off" ),
		PLUGIN_NAME::getIconPixmap( "button_7_on" ),
		PLUGIN_NAME::getIconPixmap( "button_7_off" ),
		2,
		21, 127,
		this );

	m_harmonic->setWindowTitle( tr( "Octave" ) );

	m_stringSelector = new nineButtonSelector(
			PLUGIN_NAME::getIconPixmap( "button_1_on" ),
			PLUGIN_NAME::getIconPixmap( "button_1_off" ),
			PLUGIN_NAME::getIconPixmap( "button_2_on" ),
			PLUGIN_NAME::getIconPixmap( "button_2_off" ),
			PLUGIN_NAME::getIconPixmap( "button_3_on" ),
			PLUGIN_NAME::getIconPixmap( "button_3_off" ),
			PLUGIN_NAME::getIconPixmap( "button_4_on" ),
			PLUGIN_NAME::getIconPixmap( "button_4_off" ),
			PLUGIN_NAME::getIconPixmap( "button_5_on" ),
			PLUGIN_NAME::getIconPixmap( "button_5_off" ),
			PLUGIN_NAME::getIconPixmap( "button_6_on" ),
			PLUGIN_NAME::getIconPixmap( "button_6_off" ),
			PLUGIN_NAME::getIconPixmap( "button_7_on" ),
			PLUGIN_NAME::getIconPixmap( "button_7_off" ),
			PLUGIN_NAME::getIconPixmap( "button_8_on" ),
			PLUGIN_NAME::getIconPixmap( "button_8_off" ),
			PLUGIN_NAME::getIconPixmap( "button_9_on" ),
			PLUGIN_NAME::getIconPixmap( "button_9_off" ),
			0,
			21, 39,
			this);

	m_graph = new Graph( this );
	m_graph->setWindowTitle( tr( "Impulse Editor" ) );
	m_graph->setForeground( PLUGIN_NAME::getIconPixmap( "wavegraph4" ) );
	m_graph->move( 76, 21 );
	m_graph->resize(132, 104);

	m_power = new LedCheckBox( "", this, tr( "Enable waveform" ) );
	m_power->move( 212, 130 );
	ToolTip::add( m_power,
			tr( "Enable/disable string" ) );

	// String selector is not a part of the model
	m_stringSelector->setWindowTitle( tr( "String" ) );

	connect( m_stringSelector, SIGNAL( nineButtonSelection( int ) ),
			this, SLOT( showString( int ) ) );

	showString( 0 );

	m_sinWaveBtn = new PixmapButton( this, tr( "Sine wave" ) );
	m_sinWaveBtn->move( 212, 24 );
	m_sinWaveBtn->setActiveGraphic( embed::getIconPixmap(
				"sin_wave_active" ) );
	m_sinWaveBtn->setInactiveGraphic( embed::getIconPixmap(
				"sin_wave_inactive" ) );
	ToolTip::add( m_sinWaveBtn,
				tr( "Sine wave" ) );
	connect( m_sinWaveBtn, SIGNAL (clicked () ),
			this, SLOT ( sinWaveClicked() ) );

	m_triangleWaveBtn = new PixmapButton( this, tr( "Triangle wave" ) );
	m_triangleWaveBtn->move( 212, 41 );
	m_triangleWaveBtn->setActiveGraphic(
			embed::getIconPixmap( "triangle_wave_active" ) );
	m_triangleWaveBtn->setInactiveGraphic(
			embed::getIconPixmap( "triangle_wave_inactive" ) );
	ToolTip::add( m_triangleWaveBtn,
			tr( "Triangle wave" ) );
	connect( m_triangleWaveBtn, SIGNAL ( clicked () ),
			this, SLOT ( triangleWaveClicked( ) ) );

	m_sawWaveBtn = new PixmapButton( this, tr( "Saw wave" ) );
	m_sawWaveBtn->move( 212, 58 );
	m_sawWaveBtn->setActiveGraphic( embed::getIconPixmap(
				"saw_wave_active" ) );
	m_sawWaveBtn->setInactiveGraphic( embed::getIconPixmap(
				"saw_wave_inactive" ) );
	ToolTip::add( m_sawWaveBtn,
				tr( "Saw wave" ) );
	connect( m_sawWaveBtn, SIGNAL (clicked () ),
			this, SLOT ( sawWaveClicked() ) );

	m_sqrWaveBtn = new PixmapButton( this, tr( "Square wave" ) );
	m_sqrWaveBtn->move( 212, 75 );
	m_sqrWaveBtn->setActiveGraphic( embed::getIconPixmap(
				"square_wave_active" ) );
	m_sqrWaveBtn->setInactiveGraphic( embed::getIconPixmap(
				"square_wave_inactive" ) );
	ToolTip::add( m_sqrWaveBtn,
			tr( "Square wave" ) );
	connect( m_sqrWaveBtn, SIGNAL ( clicked () ),
			this, SLOT ( sqrWaveClicked() ) );

	m_whiteNoiseWaveBtn = new PixmapButton( this, tr( "White noise" ) );
	m_whiteNoiseWaveBtn->move( 212, 92 );
	m_whiteNoiseWaveBtn->setActiveGraphic(
			embed::getIconPixmap( "white_noise_wave_active" ) );
	m_whiteNoiseWaveBtn->setInactiveGraphic(
			embed::getIconPixmap( "white_noise_wave_inactive" ) );
	ToolTip::add( m_whiteNoiseWaveBtn,
			tr( "White noise" ) );
	connect( m_whiteNoiseWaveBtn, SIGNAL ( clicked () ),
			this, SLOT ( noiseWaveClicked() ) );

	m_usrWaveBtn = new PixmapButton( this, tr( "User-defined wave" ) );
	m_usrWaveBtn->move( 212, 109 );
	m_usrWaveBtn->setActiveGraphic( embed::getIconPixmap(
				"usr_wave_active" ) );
	m_usrWaveBtn->setInactiveGraphic( embed::getIconPixmap(
				"usr_wave_inactive" ) );
	ToolTip::add( m_usrWaveBtn,
			tr( "User-defined wave" ) );
	connect( m_usrWaveBtn, SIGNAL ( clicked () ),
			this, SLOT ( usrWaveClicked() ) );

	m_smoothBtn = new PixmapButton( this, tr( "Smooth waveform" ) );
	m_smoothBtn->move( 79, 129 );
	m_smoothBtn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
			"smooth_active" ) );
	m_smoothBtn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
			"smooth_inactive" ) );
	m_smoothBtn->setChecked( false );
	ToolTip::add( m_smoothBtn,
			tr( "Smooth waveform" ) );
	connect( m_smoothBtn, SIGNAL ( clicked () ),
			this, SLOT ( smoothClicked() ) );

	m_normalizeBtn = new PixmapButton( this, tr( "Normalize waveform" ) );
	m_normalizeBtn->move( 96, 129 );
	m_normalizeBtn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
			"normalize_active" ) );
	m_normalizeBtn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
			"normalize_inactive" ) );
	m_normalizeBtn->setChecked( false );
	ToolTip::add( m_normalizeBtn,
			tr( "Normalize waveform" ) );

	connect( m_normalizeBtn, SIGNAL ( clicked () ),
			this, SLOT ( normalizeClicked() ) );

}

void vibedView::modelChanged()
{
	showString( 0 );
}

void vibedView::showString( int _string )
{
	vibed * v = castModel<vibed>();

	m_pickKnob->setModel( v->m_pickKnobs[_string] );
	m_pickupKnob->setModel( v->m_pickupKnobs[_string] );
	m_stiffnessKnob->setModel( v->m_stiffnessKnobs[_string] );
	m_volumeKnob->setModel( v->m_volumeKnobs[_string] );
	m_panKnob->setModel( v->m_panKnobs[_string] );
	m_detuneKnob->setModel( v->m_detuneKnobs[_string] );
	m_randomKnob->setModel( v->m_randomKnobs[_string] );
	m_lengthKnob->setModel( v->m_lengthKnobs[_string] );
	m_graph->setModel( v->m_graphs[_string] );
	m_impulse->setModel( v->m_impulses[_string] );
	m_harmonic->setModel( v->m_harmonics[_string] );
	m_power->setModel( v->m_powerButtons[_string] );

}

void vibedView::sinWaveClicked()
{
	m_graph->model()->setWaveToSine();
	Engine::getSong()->setModified();
}

void vibedView::triangleWaveClicked()
{
	m_graph->model()->setWaveToTriangle();
	Engine::getSong()->setModified();
}

void vibedView::sawWaveClicked()
{
	m_graph->model()->setWaveToSaw();
	Engine::getSong()->setModified();
}

void vibedView::sqrWaveClicked()
{
	m_graph->model()->setWaveToSquare();
	Engine::getSong()->setModified();
}

void vibedView::noiseWaveClicked()
{
	m_graph->model()->setWaveToNoise();
	Engine::getSong()->setModified();
}

void vibedView::usrWaveClicked()
{
	QString fileName = m_graph->model()->setWaveToUser();
	ToolTip::add( m_usrWaveBtn, fileName );
	Engine::getSong()->setModified();
}

void vibedView::smoothClicked()
{
	m_graph->model()->smooth();
	Engine::getSong()->setModified();
}

void vibedView::normalizeClicked()
{
	m_graph->model()->normalize();
	Engine::getSong()->setModified();
}

void vibedView::contextMenuEvent( QContextMenuEvent * )
{

	CaptionMenu contextMenu( model()->displayName(), this );
	contextMenu.exec( QCursor::pos() );

}

extern "C"
{

// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
	return( new vibed( static_cast<InstrumentTrack *>( m ) ) );
}

}


code:
/*
 * vibed.h - combination of PluckedStringSynth and BitInvader
 *
 * Copyright (c) 2006-2008 Danny McRae <khjklujn/at/yahoo/com>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */
#ifndef _VIBED_H
#define _VIBED_H

#include "Instrument.h"
#include "InstrumentView.h"
#include "Graph.h"
#include "Knob.h"
#include "PixmapButton.h"
#include "LedCheckbox.h"
#include "nine_button_selector.h"

class vibedView;
class NotePlayHandle;

class vibed : public Instrument
{
	Q_OBJECT
public:
	vibed( InstrumentTrack * _instrument_track );
	virtual ~vibed();

	virtual void playNote( NotePlayHandle * _n,
						sampleFrame * _working_buffer );
	virtual void deleteNotePluginData( NotePlayHandle * _n );

	virtual void saveSettings( QDomDocument & _doc, QDomElement & _parent );
	virtual void loadSettings( const QDomElement & _this );

	virtual QString nodeName() const;

	virtual Flags flags() const
	{
		return IsNotBendable;
	}

	virtual PluginView * instantiateView( QWidget * _parent );

private:
	QList<FloatModel*> m_pickKnobs;
	QList<FloatModel*> m_pickupKnobs;
	QList<FloatModel*> m_stiffnessKnobs;
	QList<FloatModel*> m_volumeKnobs;
	QList<FloatModel*> m_panKnobs;
	QList<FloatModel*> m_detuneKnobs;
	QList<FloatModel*> m_randomKnobs;
	QList<FloatModel*> m_lengthKnobs;
	QList<BoolModel*> m_powerButtons;
	QList<graphModel*> m_graphs;
	QList<BoolModel*> m_impulses;
	QList<nineButtonSelectorModel*> m_harmonics;

	static const int __sampleLength = 128;

	friend class vibedView;
} ;

class vibedView : public InstrumentViewFixedSize
{
	Q_OBJECT
public:
	vibedView( Instrument * _instrument,
					QWidget * _parent );
	virtual ~vibedView() {};

public slots:
	void showString( int _string );
	void contextMenuEvent( QContextMenuEvent * );

protected slots:
	void sinWaveClicked();
	void triangleWaveClicked();
	void sawWaveClicked();
	void sqrWaveClicked();
	void noiseWaveClicked();
	void usrWaveClicked();
	void smoothClicked();
	void normalizeClicked();

private:
	virtual void modelChanged();

	// String-related
	Knob * m_pickKnob;
	Knob * m_pickupKnob;
	Knob * m_stiffnessKnob;
	Knob * m_volumeKnob;
	Knob * m_panKnob;
	Knob * m_detuneKnob;
	Knob * m_randomKnob;
	Knob * m_lengthKnob;
	Graph * m_graph;
	nineButtonSelector * m_harmonic;
	LedCheckBox * m_impulse;
	LedCheckBox * m_power;

	// Not in model
	nineButtonSelector * m_stringSelector;
	PixmapButton * m_smoothBtn;
	PixmapButton * m_normalizeBtn;

	// From impulse editor
	PixmapButton * m_sinWaveBtn;
	PixmapButton * m_triangleWaveBtn;
	PixmapButton * m_sqrWaveBtn;
	PixmapButton * m_sawWaveBtn;
	PixmapButton * m_whiteNoiseWaveBtn;
	PixmapButton * m_usrWaveBtn;

};

#endif


code:
/*
 * vibrating_sring.h - model of a vibrating string lifted from pluckedSynth
 *
 * Copyright (c) 2006-2008 Danny McRae <khjklujn/at/yahoo/com>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */
#include <math.h>

#include "vibrating_string.h"
#include "interpolation.h"
#include "Mixer.h"
#include "Engine.h"

vibratingString::vibratingString(	float _pitch,
					float _pick,
					float _pickup,
					float * _impulse,
					int _len,
					sample_rate_t _sample_rate,
					int _oversample,
					float _randomize,
					float _string_loss,
					float _detune,
					bool _state ) :
	m_oversample( 2 * _oversample / (int)( _sample_rate /
				Engine::mixer()->baseSampleRate() ) ),
	m_randomize( _randomize ),
	m_stringLoss( 1.0f - _string_loss ),
	m_state( 0.1f )
{
	m_outsamp = new sample_t[m_oversample];
	int string_length;

	string_length = static_cast<int>( m_oversample * _sample_rate /
								_pitch ) + 1;
	string_length += static_cast<int>( string_length * -_detune );

	int pick = static_cast<int>( ceil( string_length * _pick ) );

	if( ! _state )
	{
		m_impulse = new float[string_length];
		resample( _impulse, _len, string_length );
	}
	else
 	{
		m_impulse = new float[_len];
		for( int i = 0; i < _len; i++ )
		{
			m_impulse[i] = _impulse[i];
		}
	}

	m_toBridge = vibratingString::initDelayLine( string_length, pick );
	m_fromBridge = vibratingString::initDelayLine( string_length, pick );

	vibratingString::setDelayLine( m_toBridge, pick,
						m_impulse, _len, 0.5f,
						_state );
	vibratingString::setDelayLine( m_fromBridge, pick,
						m_impulse, _len, 0.5f,
						_state);

	m_choice = static_cast<int>( m_oversample *
				static_cast<float>( rand() ) / RAND_MAX );

	m_pickupLoc = static_cast<int>( _pickup * string_length );
}

vibratingString::delayLine * vibratingString::initDelayLine( int _len,
								int _pick )
{
	delayLine * dl = new vibratingString::delayLine[_len];
	dl->length = _len;
	if( _len > 0 )
	{
		dl->data = new sample_t[_len];
		float r;
		float offset = 0.0f;
		for( int i = 0; i < dl->length; i++ )
		{
			r = static_cast<float>( rand() ) /
					RAND_MAX;
			offset =  ( m_randomize / 2.0f -
					m_randomize ) * r;
			dl->data[i] = offset;
		}
	}
	else
	{
		dl->data = NULL;
	}

	dl->pointer = dl->data;
	dl->end = dl->data + _len - 1;

	return( dl );
}

void vibratingString::freeDelayLine( delayLine * _dl )
{
	if( _dl )
	{
		delete[] _dl->data;
		delete[] _dl;
	}
}

void vibratingString::resample( float *_src, f_cnt_t _src_frames,
							 f_cnt_t _dst_frames )
{
	for( f_cnt_t frame = 0; frame < _dst_frames; ++frame )
	{
		const float src_frame_float = frame *
						(float) _src_frames /
							_dst_frames;
		const float frac_pos = src_frame_float -
				static_cast<f_cnt_t>( src_frame_float );
		const f_cnt_t src_frame = qBound<f_cnt_t>(
				1, static_cast<f_cnt_t>( src_frame_float ),
							_src_frames - 3 );
		m_impulse[frame] = cubicInterpolate(
						_src[src_frame - 1],
						_src[src_frame + 0],
						_src[src_frame + 1],
						_src[src_frame + 2],
						frac_pos );
	}
}


code:
/*
 * vibrating_string.h - model of a vibrating string lifted from pluckedSynth
 *
 * Copyright (c) 2006-2007 Danny McRae <khjklujn/at/yahoo/com>
 *
 * This file is part of LMMS - https://lmms.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
 */
#ifndef _VIBRATING_STRING_H
#define _VIBRATING_STRING_H

#include <stdio.h>
#include <stdlib.h>

#include "lmms_basics.h"

class vibratingString
{

public:
	vibratingString(	float _pitch,
				float _pick,
				float _pickup,
				float * impluse,
				int _len,
				sample_rate_t _sample_rate,
				int _oversample,
				float _randomize,
				float _string_loss,
				float _detune,
				bool _state );

	inline ~vibratingString()
	{
		delete[] m_outsamp;
		delete[] m_impulse;
		vibratingString::freeDelayLine( m_fromBridge );
		vibratingString::freeDelayLine( m_toBridge );
	}

	inline sample_t nextSample()
	{
		sample_t ym0;
		sample_t ypM;
		for( int i = 0; i < m_oversample; i++)
		{
			// Output at pickup position
			m_outsamp[i] = fromBridgeAccess( m_fromBridge,
								m_pickupLoc );
			m_outsamp[i] += toBridgeAccess( m_toBridge,
								m_pickupLoc );

			// Sample traveling into "bridge"
			ym0 = toBridgeAccess( m_toBridge, 1 );
			// Sample to "nut"
			ypM = fromBridgeAccess( m_fromBridge,
						m_fromBridge->length - 2 );

			// String state update

			// Decrement pointer and then update
			fromBridgeUpdate( m_fromBridge,
						-bridgeReflection( ym0 ) );
			// Update and then increment pointer
			toBridgeUpdate( m_toBridge, -ypM );
		}
		return( m_outsamp[m_choice] );
	}

private:
	struct delayLine
	{
		sample_t * data;
		int length;
		sample_t * pointer;
		sample_t * end;
	} ;

	delayLine * m_fromBridge;
	delayLine * m_toBridge;
	int m_pickupLoc;
	int m_oversample;
	float m_randomize;
	float m_stringLoss;

	float * m_impulse;
	int m_choice;
	float m_state;

	sample_t * m_outsamp;

	delayLine * initDelayLine( int _len, int _pick );
	static void freeDelayLine( delayLine * _dl );
	void resample( float *_src, f_cnt_t _src_frames, f_cnt_t _dst_frames );

	/* setDelayLine initializes the string with an impulse at the pick
	 * position unless the impulse is longer than the string, in which
	 * case the impulse gets truncated. */
	inline void setDelayLine( delayLine * _dl,
					int _pick,
					const float * _values,
					int _len,
					float _scale,
					bool _state )
	{
		float r;
		float offset;

		if( ! _state )
		{
			for( int i = 0; i < _pick; i++ )
			{
				r = static_cast<float>( rand() ) /
						RAND_MAX;
				offset =  ( m_randomize / 2.0f -
						m_randomize ) * r;
				_dl->data[i] = _scale *
						_values[_dl->length - i - 1] +
						offset;
			}
			for( int i = _pick; i < _dl->length; i++ )
			{
				r = static_cast<float>( rand() ) /
						RAND_MAX;
				offset =  ( m_randomize / 2.0f -
						m_randomize ) * r;
				_dl->data[i] = _scale *
						_values[i - _pick]  + offset ;
			}
		}
		else
		{
			if( _len + _pick > _dl->length )
			{
				for( int i = _pick; i < _dl->length; i++ )
				{
					r = static_cast<float>( rand() ) /
							RAND_MAX;
					offset =  ( m_randomize / 2.0f -
							m_randomize ) * r;
					_dl->data[i] = _scale *
							_values[i-_pick] +
							offset;
				}
			}
			else
			{
				for( int i = 0; i < _len; i++ )
				{
					r = static_cast<float>( rand() ) /
							RAND_MAX;
					offset =  ( m_randomize / 2.0f -
							m_randomize ) * r;
					_dl->data[i+_pick] = _scale *
								_values[i] +
								offset;
				}
			}
		}
	}

	/* toBridgeUpdate(dl, insamp);
	* Places "nut-reflected" sample from upper delay-line into
	* current lower delay-line pointer position (which represents
	* x = 0 position).  The pointer is then incremented (i.e. the
	* wave travels one sample to the left), turning the previous
	* position into an "effective" x = L position for the next
	* iteration. */
	inline void toBridgeUpdate( delayLine * _dl, sample_t _insamp )
	{
		sample_t * ptr = _dl->pointer;
		*ptr = _insamp * m_stringLoss;
		++ptr;
		if( ptr > _dl->end )
		{
			ptr = _dl->data;
		}
		_dl->pointer = ptr;
	}

	/* fromBridgeUpdate(dl, insamp);
	* Decrements current upper delay-line pointer position (i.e.
	* the wave travels one sample to the right), moving it to the
	* "effective" x = 0 position for the next iteration.  The
	* "bridge-reflected" sample from lower delay-line is then placed
	* into this position. */
	inline void fromBridgeUpdate( delayLine * _dl,
							sample_t _insamp )
	{
		sample_t * ptr = _dl->pointer;
		--ptr;
		if( ptr < _dl->data )
		{
			ptr = _dl->end;
		}
		*ptr = _insamp * m_stringLoss;
		_dl->pointer = ptr;
	}

	/* dlAccess(dl, position);
	* Returns sample "position" samples into delay-line's past.
	* Position "0" points to the most recently inserted sample. */
	static inline sample_t dlAccess( delayLine * _dl, int _position )
	{
		sample_t * outpos = _dl->pointer + _position;
		while( outpos < _dl->data )
		{
			outpos += _dl->length;
		}
		while( outpos > _dl->end )
		{
			outpos -= _dl->length;
		}
		return( *outpos );
	}

	/*
	*  Right-going delay line:
	*  -->---->---->---
	*  x=0
	*  (pointer)
	*  Left-going delay line:
	*  --<----<----<---
	*  x=0
	*  (pointer)
	*/

	/* fromBridgeAccess(dl, position);
	* Returns spatial sample at position "position", where position zero
	* is equal to the current upper delay-line pointer position (x = 0).
	* In a right-going delay-line, position increases to the right, and
	* delay increases to the right => left = past and right = future. */
	static inline sample_t fromBridgeAccess( delayLine * _dl,
								int _position )
	{
		return( dlAccess( _dl, _position ) );
	}

	/* toBridgeAccess(dl, position);
	* Returns spatial sample at position "position", where position zero
	* is equal to the current lower delay-line pointer position (x = 0).
	* In a left-going delay-line, position increases to the right, and
	* delay DEcreases to the right => left = future and right = past. */
	static inline sample_t toBridgeAccess( delayLine * _dl, int _position )
	{
		return( dlAccess( _dl, _position ) );
	}

	inline sample_t bridgeReflection( sample_t _insamp )
	{
		return( m_state = ( m_state + _insamp ) * 0.5 );
	}

} ;

#endif


code:
IF(NOT LMMS_SUPPORT_VST)
	RETURN()
ENDIF()

INCLUDE(BuildPlugin)
INCLUDE(ExternalProject)

# These variables are not meant to be used normally, except packaging
SET(REMOTE_VST_PLUGIN_FILEPATH_32 "32/RemoteVstPlugin32" CACHE STRING "Relative file path to RemoteVstPlugin32")
SET(REMOTE_VST_PLUGIN_FILEPATH_64 "RemoteVstPlugin64" CACHE STRING "Relative file path to RemoteVstPlugin64")

ADD_SUBDIRECTORY(vstbase)

SET(EXTERNALPROJECT_ARGS
	SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/RemoteVstPlugin"
	#INSTALL_COMMAND ""
	BUILD_ALWAYS ON
	# Skip the install step.
	INSTALL_COMMAND ""
)

set(export_variables
		"LMMS_SOURCE_DIR"
		"LMMS_BINARY_DIR"
		"CMAKE_MODULE_PATH"
		"CMAKE_RUNTIME_OUTPUT_DIRECTORY"
		"CMAKE_BUILD_TYPE"
		"LMMS_BUILD_LINUX"
		"LMMS_BUILD_WIN32"
		"PLUGIN_DIR")

SET(EXTERNALPROJECT_CMAKE_ARGS
	"-DBUILD_WITH_EXTERNALPROJECT=ON"
)

macro(_export_var_to_external var_name)
	list(APPEND EXTERNALPROJECT_CMAKE_ARGS "-D${var_name}=${${var_name}}")
endmacro()
foreach(var ${export_variables})
	_export_var_to_external(${var})
endforeach()

# build 32 bit version of RemoteVstPlugin
IF(WANT_VST_32)
	INCLUDE("${CMAKE_CURRENT_LIST_DIR}/RemoteVstPlugin32.cmake")
ENDIF()
# build 64 bit version of RemoteVstPlugin
IF(WANT_VST_64)
	INCLUDE("${CMAKE_CURRENT_LIST_DIR}/RemoteVstPlugin64.cmake")
ENDIF()