Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurihostshimjwvst3.cpp

1.4.2Released Nov 21, 2026

jwvst3.cpp

1,532 lines47.5 KBC++
// The plugin host's VST 3 side (see jwvst3.h): Steinberg's own hosting classes from the VST 3 SDK (MIT, vendored in// host/vst3sdk) for modules, process data, parameter changes and the component/controller connection, and the parts a// host has to supply itself: the component handler, the plug frame and the editor windows.//// The order of calls follows the SDK's documentation and its audiohost/editorhost samples: initialize the component,// make and initialize the controller, connect the two, hand the component's state to the controller; then bus// arrangements, setupProcessing, setActive(true), and setProcessing on the audio thread around process(). Teardown runs// the same steps backwards.#ifndef NOMINMAX#define NOMINMAX#endif#include <windows.h>#include <dwmapi.h>#include "jwvst3.h"#include "pluginterfaces/base/funknownimpl.h"#include "pluginterfaces/gui/iplugview.h"#include "pluginterfaces/gui/iplugviewcontentscalesupport.h"#include "pluginterfaces/vst/ivstaudioprocessor.h"#include "pluginterfaces/vst/ivstcomponent.h"#include "pluginterfaces/vst/ivsteditcontroller.h"#include "pluginterfaces/vst/ivstmessage.h"#include "pluginterfaces/vst/ivstprocesscontext.h"#include "public.sdk/source/common/memorystream.h"#include "public.sdk/source/vst/hosting/connectionproxy.h"#include "public.sdk/source/vst/hosting/eventlist.h"#include "public.sdk/source/vst/hosting/hostclasses.h"#include "public.sdk/source/vst/hosting/module.h"#include "public.sdk/source/vst/hosting/parameterchanges.h"#include "public.sdk/source/vst/hosting/processdata.h"#include "public.sdk/source/vst/utility/stringconvert.h"#include <fcntl.h>#include <io.h>#include <atomic>#include <cstdio>#include <cstring>#include <memory>#include <string>#include <vector>#pragma comment(lib, "user32")#pragma comment(lib, "gdi32")#pragma comment(lib, "dwmapi")#pragma comment(lib, "ole32")#pragma comment(lib, "shell32")using namespace Steinberg;using namespace Steinberg::Vst;namespace {JwCallbacks g_cb {};/// Test runs: editors open without focus, at the back (jw_set_quiet_windows).bool g_quietWindows = false;/// The host process's private handle to the app's log (jw_set_log), and whether jw_module_load reports its steps.HANDLE g_log = nullptr;bool g_stages = false;/// One line to the app's log: the text and its newline in one WriteFile, so lines from different threads never mix./// No allocation for a line that fits the stack buffer (the exit report runs as the process ends).void logLine (const char* text, size_t n){	if (!g_log)		return;	char onStack[1024];	std::string onHeap;	char* buf = onStack;	if (n + 1 > sizeof (onStack))	{		onHeap.resize (n + 1);		buf = onHeap.data ();	}	memcpy (buf, text, n);	buf[n] = '\n';	DWORD written = 0;	WriteFile (g_log, buf, static_cast<DWORD> (n + 1), &written, nullptr);}void logLine (const std::string& s) { logLine (s.data (), s.size ()); }void stage (const std::string& step){	if (g_stages)		logLine ("[stage] " + step);}/// Shows an editor's window: brought forward and focused, as the user asked for it; or, in a test run, shown at the/// back of the other windows without taking focus.void showEditorWindow (HWND hwnd){	if (g_quietWindows)	{		ShowWindow (hwnd, SW_SHOWNOACTIVATE);		SetWindowPos (hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);		return;	}	ShowWindow (hwnd, SW_SHOWNORMAL);	SetForegroundWindow (hwnd);}/// The host context every plugin is initialized with: IHostApplication (and the SDK's IMessage and IAttributeList/// factory behind it), under the app's name.class JwHostApplication : public HostApplication{public:	tresult PLUGIN_API getName (String128 name) override	{		return StringConvert::convert ("juicewrld.io", name) ? kResultTrue : kInternalError;	}};JwHostApplication* g_host = nullptr;void setError (char* err, size_t len, const std::string& msg){	if (!err || len == 0)		return;	size_t n = msg.size () < len - 1 ? msg.size () : len - 1;	// Never cut a UTF-8 sequence in half.	while (n > 0 && n < msg.size () && (static_cast<unsigned char> (msg[n]) & 0xC0) == 0x80)		n--;	memcpy (err, msg.data (), n);	err[n] = 0;}void copyString (char* dst, size_t len, const std::string& s) { setError (dst, len, s); }std::wstring wide (const char* utf8){	if (!utf8 || !*utf8)		return {};	int n = MultiByteToWideChar (CP_UTF8, 0, utf8, -1, nullptr, 0);	std::wstring w (n > 0 ? n - 1 : 0, L'\0');	if (n > 1)		MultiByteToWideChar (CP_UTF8, 0, utf8, -1, w.data (), n);	return w;}std::string narrow (const TChar* s, size_t max){	return StringConvert::convert (s, static_cast<uint32> (max));}/// The newest value of each parameter on its way from one thread to the other (the page's and the editor's edits to/// the audio thread; the processor's meters back to the controller). Not a queue: a thousand moves of one knob while no/// audio flows leave one value to deliver, the newest, so it never fills up and the processor never plays an older/// value than the controller shows. Lock-free on both sides (a plugin calling performEdit off the main thread is a/// second producer, which is fine): a slot per parameter ID, claimed once, its value and a "changed" flag.struct ParamTable{	uint32_t mask = 0;	std::unique_ptr<std::atomic<uint64_t>[]> keys; // (1 << 32) | ID once claimed, 0 while free	std::unique_ptr<std::atomic<double>[]> values;	std::unique_ptr<std::atomic<uint8_t>[]> changed;	std::atomic<uint32_t> any {0}; // set after a value changes: the consumer looks only then	/// Room for twice the plugin's parameters and at least 2048: a plugin that edits IDs it never declared still fits.	void init (int32 params)	{		uint32_t n = 2048;		while (n < static_cast<uint32_t> (params > 0 ? params : 0) * 2 && n < (1u << 20))			n <<= 1;		keys.reset (new std::atomic<uint64_t>[n]);		values.reset (new std::atomic<double>[n]);		changed.reset (new std::atomic<uint8_t>[n]);		for (uint32_t i = 0; i < n; i++)		{			keys[i].store (0, std::memory_order_relaxed);			values[i].store (0, std::memory_order_relaxed);			changed[i].store (0, std::memory_order_relaxed);		}		mask = n - 1;	}	/// The slot for `id`, claimed if it's new; -1 only when every slot is taken.	int32_t slot (ParamID id)	{		const uint64_t key = (uint64_t (1) << 32) | id;		uint32_t h = (id * 2654435761u) & mask;		for (uint32_t i = 0; i <= mask; i++)		{			uint32_t at = (h + i) & mask;			uint64_t k = keys[at].load (std::memory_order_acquire);			if (k == 0)			{				uint64_t expected = 0;				if (keys[at].compare_exchange_strong (expected, key, std::memory_order_acq_rel))					return static_cast<int32_t> (at);				k = expected;			}			if (k == key)				return static_cast<int32_t> (at);		}		return -1;	}	/// Producer: `id` is now `value`. False only if the table is full (it never is for a plugin's own parameters).	bool push (ParamID id, ParamValue value)	{		if (!keys)			return false;		int32_t at = slot (id);		if (at < 0)			return false;		values[at].store (value, std::memory_order_relaxed);		changed[at].store (1, std::memory_order_release);		any.store (1, std::memory_order_release);		return true;	}	/// Consumer: each parameter changed since the last drain, once, with its newest value.	template <typename F>	void drain (F f)	{		if (!keys || any.exchange (0, std::memory_order_acquire) == 0)			return;		for (uint32_t i = 0; i <= mask; i++)			if (changed[i].load (std::memory_order_relaxed) && changed[i].exchange (0, std::memory_order_acquire))				f (static_cast<ParamID> (keys[i].load (std::memory_order_relaxed) & 0xFFFFFFFFu), values[i].load (std::memory_order_relaxed));	}	bool pending () const { return keys && any.load (std::memory_order_acquire) != 0; }	/// Producer: what's waiting no longer counts (a state restore supersedes it).	void discardPending ()	{		if (!keys)			return;		for (uint32_t i = 0; i <= mask; i++)			changed[i].store (0, std::memory_order_relaxed);	}};const wchar_t* kEditorClass = L"JuiceWRLDPluginEditor";const COLORREF kBackground = RGB (11, 11, 14);} // namespacestruct JwModule{	VST3::Hosting::Module::Ptr module;	std::vector<VST3::Hosting::ClassInfo> classes;};struct JwPlugin;/// IComponentHandler(2): the plugin telling the host about edits made in its own editor, and asking for restarts.class JwHandler : public IComponentHandler, public IComponentHandler2{public:	JwPlugin* plugin = nullptr;	tresult PLUGIN_API beginEdit (ParamID id) override;	tresult PLUGIN_API performEdit (ParamID id, ParamValue value) override;	tresult PLUGIN_API endEdit (ParamID id) override;	tresult PLUGIN_API restartComponent (int32 flags) override;	tresult PLUGIN_API setDirty (TBool) override { return kResultOk; }	tresult PLUGIN_API requestOpenEditor (FIDString) override;	tresult PLUGIN_API startGroupEdit () override { return kResultOk; }	tresult PLUGIN_API finishGroupEdit () override { return kResultOk; }	tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override	{		QUERY_INTERFACE (iid, obj, FUnknown::iid, IComponentHandler)		QUERY_INTERFACE (iid, obj, IComponentHandler::iid, IComponentHandler)		QUERY_INTERFACE (iid, obj, IComponentHandler2::iid, IComponentHandler2)		*obj = nullptr;		return kNoInterface;	}	// Owned by its instance, which outlives every plugin object holding it.	uint32 PLUGIN_API addRef () override { return 1000; }	uint32 PLUGIN_API release () override { return 1000; }};/// IPlugFrame: the editor asking for a new size.class JwFrame : public IPlugFrame{public:	JwPlugin* plugin = nullptr;	tresult PLUGIN_API resizeView (IPlugView* view, ViewRect* newSize) override;	tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override	{		QUERY_INTERFACE (iid, obj, FUnknown::iid, IPlugFrame)		QUERY_INTERFACE (iid, obj, IPlugFrame::iid, IPlugFrame)		*obj = nullptr;		return kNoInterface;	}	uint32 PLUGIN_API addRef () override { return 1000; }	uint32 PLUGIN_API release () override { return 1000; }};struct JwPlugin{	uint32_t tag = 0;	VST3::Hosting::Module::Ptr module; // keeps the DLL loaded while the instance lives	std::string name;	IPtr<IComponent> component;	IPtr<IAudioProcessor> processor;	IPtr<IEditController> controller;	bool single = false;	IPtr<ConnectionProxy> componentCP;	IPtr<ConnectionProxy> controllerCP;	JwHandler handler;	JwFrame frame;	double rate = 48000;	int32 maxBlock = 0;	bool active = false;	bool processing = false;	int32 processMode = kRealtime;	HostProcessData data;	ParameterChanges inChanges {64};	ParameterChanges outChanges {64};	EventList events {64};	ProcessContext context {};	ParamID bypassId = kNoParamId;	/// The controller makes an editor view (checked once, at setup: a view made and let go, never attached).	bool hasEditor = false;	ParamTable toAudio;	ParamTable toMain;	/// An edit was dropped (a full table: a plugin editing tens of thousands of undeclared IDs); said once.	bool dropWarned = false;	// The editor.	HWND hwnd = nullptr;	IPtr<IPlugView> view;	bool resizable = false;	bool inResize = false;	UINT dpi = 96;	DWORD style = 0;	DWORD exStyle = 0;};tresult PLUGIN_API JwHandler::beginEdit (ParamID id){	if (g_cb.param_edit)		g_cb.param_edit (g_cb.ctx, plugin->tag, id, 0, 0);	return kResultOk;}tresult PLUGIN_API JwHandler::performEdit (ParamID id, ParamValue value){	// The processor hears of it with the next block (or a parameter flush when no audio flows), the page through the	// callback.	if (!plugin->toAudio.push (id, value) && !plugin->dropWarned)	{		plugin->dropWarned = true;		logLine ("[host] " + plugin->name + ": too many parameter IDs; an edit didn't reach the processor");	}	if (g_cb.param_edit)		g_cb.param_edit (g_cb.ctx, plugin->tag, id, value, 1);	return kResultOk;}tresult PLUGIN_API JwHandler::endEdit (ParamID id){	if (g_cb.param_edit)		g_cb.param_edit (g_cb.ctx, plugin->tag, id, 0, 2);	return kResultOk;}tresult PLUGIN_API JwHandler::restartComponent (int32 flags){	if (g_cb.restart)		g_cb.restart (g_cb.ctx, plugin->tag, flags);	return kResultOk;}tresult PLUGIN_API JwHandler::requestOpenEditor (FIDString){	if (g_cb.open_editor)		g_cb.open_editor (g_cb.ctx, plugin->tag);	return kResultOk;}namespace {/// The non-client size the frame adds at this DPI.SIZE frameExtra (JwPlugin* p){	RECT r {0, 0, 0, 0};	AdjustWindowRectExForDpi (&r, p->style, FALSE, p->exStyle, p->dpi);	return {r.right - r.left, r.bottom - r.top};}void sizeWindowToView (JwPlugin* p, const ViewRect& vr, const RECT* at){	SIZE extra = frameExtra (p);	int w = vr.getWidth () + extra.cx;	int h = vr.getHeight () + extra.cy;	p->inResize = true;	if (at)		SetWindowPos (p->hwnd, nullptr, at->left, at->top, w, h, SWP_NOZORDER | SWP_NOACTIVATE);	else		SetWindowPos (p->hwnd, nullptr, 0, 0, w, h, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);	p->inResize = false;}bool sameSize (const ViewRect& a, const ViewRect& b){	return a.getWidth () == b.getWidth () && a.getHeight () == b.getHeight ();}void closeEditor (JwPlugin* p, bool notify){	if (!p->hwnd)		return;	RECT wr {};	GetWindowRect (p->hwnd, &wr);	HWND hwnd = p->hwnd;	if (p->view)	{		p->view->setFrame (nullptr);		p->view->removed ();		p->view = nullptr;	}	p->hwnd = nullptr;	SetWindowLongPtrW (hwnd, GWLP_USERDATA, 0);	DestroyWindow (hwnd);	if (notify && g_cb.editor_closed)		g_cb.editor_closed (g_cb.ctx, p->tag, wr.left, wr.top);}LRESULT CALLBACK editorProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){	if (msg == WM_NCCREATE)	{		auto cs = reinterpret_cast<CREATESTRUCTW*> (lParam);		SetWindowLongPtrW (hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR> (cs->lpCreateParams));	}	auto p = reinterpret_cast<JwPlugin*> (GetWindowLongPtrW (hwnd, GWLP_USERDATA));	if (!p)		return DefWindowProcW (hwnd, msg, wParam, lParam);	switch (msg)	{		case WM_ERASEBKGND:		{			RECT r;			GetClientRect (hwnd, &r);			HBRUSH brush = CreateSolidBrush (kBackground);			FillRect (reinterpret_cast<HDC> (wParam), &r, brush);			DeleteObject (brush);			return 1;		}		case WM_SIZING:		{			// The user drags an edge: the plugin gets a say in the size (checkSizeConstraint), the dragged edge moves.			if (!p->view || !p->resizable)				break;			auto wr = reinterpret_cast<RECT*> (lParam);			SIZE extra = frameExtra (p);			ViewRect vr (0, 0, (wr->right - wr->left) - extra.cx, (wr->bottom - wr->top) - extra.cy);			p->view->checkSizeConstraint (&vr);			int w = vr.getWidth () + extra.cx;			int h = vr.getHeight () + extra.cy;			if (wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT)				wr->left = wr->right - w;			else				wr->right = wr->left + w;			if (wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT)				wr->top = wr->bottom - h;			else				wr->bottom = wr->top + h;			return TRUE;		}		case WM_SIZE:		{			if (p->view && !p->inResize && wParam != SIZE_MINIMIZED)			{				ViewRect now;				ViewRect want (0, 0, LOWORD (lParam), HIWORD (lParam));				if (p->view->getSize (&now) != kResultTrue || !sameSize (now, want))					p->view->onSize (&want);			}			return 0;		}		case WM_DPICHANGED:		{			// Moved to a monitor of another scale: tell the plugin, then take the size it settles on at the place Windows			// suggests.			p->dpi = HIWORD (wParam);			auto suggested = reinterpret_cast<RECT*> (lParam);			if (p->view)			{				if (auto css = U::cast<IPlugViewContentScaleSupport> (p->view))					css->setContentScaleFactor (static_cast<float> (p->dpi) / USER_DEFAULT_SCREEN_DPI);				ViewRect vr;				if (p->view->getSize (&vr) == kResultTrue)				{					sizeWindowToView (p, vr, suggested);					return 0;				}			}			SetWindowPos (hwnd, nullptr, suggested->left, suggested->top, suggested->right - suggested->left,			              suggested->bottom - suggested->top, SWP_NOZORDER | SWP_NOACTIVATE);			return 0;		}		case WM_SETFOCUS:		{			// Keys go to the plugin's own window inside the frame.			if (HWND child = GetWindow (hwnd, GW_CHILD))				SetFocus (child);			return 0;		}		case WM_EXITSIZEMOVE:		{			RECT wr;			if (g_cb.editor_moved && GetWindowRect (hwnd, &wr))				g_cb.editor_moved (g_cb.ctx, p->tag, wr.left, wr.top, wr.right - wr.left, wr.bottom - wr.top);			return 0;		}		case WM_CLOSE:			closeEditor (p, true);			return 0;	}	return DefWindowProcW (hwnd, msg, wParam, lParam);}void registerEditorClass (){	static bool done = false;	if (done)		return;	done = true;	HINSTANCE inst = GetModuleHandleW (nullptr);	WNDCLASSEXW wc {sizeof (wc)};	wc.style = CS_HREDRAW | CS_VREDRAW;	wc.lpfnWndProc = editorProc;	wc.hInstance = inst;	wc.hCursor = LoadCursorW (nullptr, IDC_ARROW);	wc.hbrBackground = nullptr;	wc.lpszClassName = kEditorClass;	// The app's own icon, the first one in this exe.	wchar_t exe[MAX_PATH];	if (GetModuleFileNameW (nullptr, exe, MAX_PATH))	{		HICON bigIcon = nullptr, smallIcon = nullptr; // "small" is a macro in the Windows headers		if (ExtractIconExW (exe, 0, &bigIcon, &smallIcon, 1) > 0)		{			wc.hIcon = bigIcon;			wc.hIconSm = smallIcon;		}	}	RegisterClassExW (&wc);}void setDarkFrame (HWND hwnd){	// The app's dark caption: immersive dark mode, and on Windows 11 the bar's own colour behind the title.	BOOL dark = TRUE;	DwmSetWindowAttribute (hwnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &dark, sizeof (dark));	COLORREF caption = RGB (13, 13, 17);	DwmSetWindowAttribute (hwnd, 35 /* DWMWA_CAPTION_COLOR */, &caption, sizeof (caption));	COLORREF text = RGB (244, 244, 246);	DwmSetWindowAttribute (hwnd, 36 /* DWMWA_TEXT_COLOR */, &text, sizeof (text));}bool onSomeMonitor (int x, int y){	// The title bar, a little in from the window's corner, must be on a monitor to be draggable.	POINT pt {x + 48, y + 12};	return MonitorFromPoint (pt, MONITOR_DEFAULTTONULL) != nullptr;}void fillInfo (JwPlugin* p, JwPluginInfo* out){	if (!out)		return;	memset (out, 0, sizeof (*out));	BusInfo bi {};	out->in_buses = p->component->getBusCount (kAudio, kInput);	out->out_buses = p->component->getBusCount (kAudio, kOutput);	if (out->in_buses > 0 && p->component->getBusInfo (kAudio, kInput, 0, bi) == kResultTrue)		out->in_channels = bi.channelCount;	if (out->out_buses > 0 && p->component->getBusInfo (kAudio, kOutput, 0, bi) == kResultTrue)		out->out_channels = bi.channelCount;	out->latency = p->processor ? static_cast<int32_t> (p->processor->getLatencySamples ()) : 0;	out->tail = p->processor ? p->processor->getTailSamples () : 0;	out->has_editor = p->hasEditor ? 1 : 0;	out->param_count = p->controller ? p->controller->getParameterCount () : 0;	out->single = p->single ? 1 : 0;	out->bypass_param = p->bypassId != kNoParamId ? 1 : 0;	copyString (out->name, sizeof (out->name), p->name);}/// Zeroes every input buffer (side chains the host never fills stay silent) and sets the process data's pointers.void prepareBuffers (JwPlugin* p){	p->data.prepare (*p->component, p->maxBlock, kSample32);	for (int32 b = 0; b < p->data.numInputs; b++)		for (int32 c = 0; c < p->data.inputs[b].numChannels; c++)			if (p->data.inputs[b].channelBuffers32 && p->data.inputs[b].channelBuffers32[c])				memset (p->data.inputs[b].channelBuffers32[c], 0, sizeof (float) * p->maxBlock);	p->data.processMode = p->processMode;	p->data.symbolicSampleSize = kSample32;	p->data.inputParameterChanges = &p->inChanges;	p->data.outputParameterChanges = &p->outChanges;	p->data.inputEvents = &p->events;	p->data.processContext = &p->context;}/// The parameter changes waiting for the processor, into the next process call's input changes (each at the start of/// the block: a host moving a knob, not automation).void takeParamChanges (JwPlugin* p){	p->inChanges.clearQueue ();	p->toAudio.drain ([p] (ParamID id, ParamValue v) {		int32 qi = 0;		if (auto q = p->inChanges.addParameterData (id, qi))		{			int32 pi = 0;			q->addPoint (0, v, pi);		}	});}/// What the processor reported back (meters, gain reduction), for the controller on the main thread: the last value/// of each.void giveParamChanges (JwPlugin* p){	for (int32 i = 0; i < p->outChanges.getParameterCount (); i++)	{		auto q = p->outChanges.getParameterData (i);		int32 n = q ? q->getPointCount () : 0;		int32 offset = 0;		ParamValue v = 0;		if (n > 0 && q->getPoint (n - 1, offset, v) == kResultTrue)			p->toMain.push (q->getParameterId (), v);	}}} // namespacetresult PLUGIN_API JwFrame::resizeView (IPlugView* view, ViewRect* newSize){	JwPlugin* p = plugin;	if (!view || !newSize || view != p->view.get ())		return kInvalidArgument;	if (!p->hwnd)		return kInternalError;	if (p->inResize)		return kResultFalse;	sizeWindowToView (p, *newSize, nullptr);	ViewRect now;	if (view->getSize (&now) != kResultTrue || !sameSize (now, *newSize))		view->onSize (newSize);	return kResultTrue;}namespace {/// A fixed-size 8-bit field of a class's info, up to its first 0.std::string field (const char8* s, size_t max) { return std::string (s, strnlen (s, max)); }/// A fixed-size UTF-16 field, as UTF-8 by Windows' own converter: a character outside the BMP (an emoji in a name)/// comes out whole, and half a surrogate pair as U+FFFD. The SDK's StringConvert converts one code unit at a time, so/// such a character came out as two broken halves (and std::wstring_convert may throw on them, inside a noexcept/// constructor, which would end the process).std::string field (const char16* s, size_t max){	size_t n = 0;	while (n < max && s[n])		n++;	if (!n)		return {};	auto w = reinterpret_cast<const wchar_t*> (s);	int len = WideCharToMultiByte (CP_UTF8, 0, w, static_cast<int> (n), nullptr, 0, nullptr, nullptr);	std::string out (len > 0 ? len : 0, '\0');	if (len > 0)		WideCharToMultiByte (CP_UTF8, 0, w, static_cast<int> (n), out.data (), len, nullptr, nullptr);	return out;}/// Every class a module's factory lists, read as the SDK's PluginFactory::classInfos reads them (IPluginFactory3's/// Unicode info, else IPluginFactory2's, else IPluginFactory's; the factory's vendor for a class without one), except/// that a class whose info can't be read at all is skipped and said so (the SDK's loop then sets the vendor of the/// class before it, or of an element before its vector when it's the first: undefined behaviour), and Unicode text is/// converted by `field`. In a scan, each class is reported to the log before it's read.std::vector<VST3::Hosting::ClassInfo> readClasses (const VST3::Hosting::PluginFactory& factory){	std::vector<VST3::Hosting::ClassInfo> classes;	const auto& f1 = factory.get ();	if (!f1)		return classes;	auto f3 = U::cast<IPluginFactory3> (f1);	auto f2 = U::cast<IPluginFactory2> (f1);	const int32 count = f1->countClasses ();	classes.reserve (count > 0 ? count : 0);	std::string factoryVendor;	bool haveVendor = false;	for (int32 i = 0; i < count; i++)	{		stage ("class " + std::to_string (i + 1) + " of " + std::to_string (count));		VST3::Hosting::ClassInfo c;		PClassInfoW w {};		PClassInfo2 c2 {};		PClassInfo c1 {};		if (f3 && f3->getClassInfoUnicode (i, &w) == kResultTrue)		{			auto& d = c.get ();			d.classID = VST3::UID::fromTUID (w.cid);			d.cardinality = w.cardinality;			d.category = field (w.category, PClassInfo::kCategorySize);			d.name = field (w.name, PClassInfo::kNameSize);			d.vendor = field (w.vendor, PClassInfo2::kVendorSize);			d.version = field (w.version, PClassInfo2::kVersionSize);			d.sdkVersion = field (w.sdkVersion, PClassInfo2::kVersionSize);			std::string subs = field (w.subCategories, PClassInfo2::kSubCategoriesSize);			for (size_t at = 0; at <= subs.size ();)			{				size_t bar = subs.find ('|', at);				if (bar == std::string::npos)					bar = subs.size ();				if (bar > at)					d.subCategories.push_back (subs.substr (at, bar - at));				at = bar + 1;			}			d.classFlags = w.classFlags;		}		else if (f2 && f2->getClassInfo2 (i, &c2) == kResultTrue)			c = VST3::Hosting::ClassInfo (c2);		else if (f1->getClassInfo (i, &c1) == kResultTrue)			c = VST3::Hosting::ClassInfo (c1);		else		{			logLine ("[host] class " + std::to_string (i + 1) + " of " + std::to_string (count) + " couldn't be read; skipped");			continue;		}		if (c.vendor ().empty ())		{			if (!haveVendor)			{				factoryVendor = factory.info ().vendor ();				haveVendor = true;			}			c.get ().vendor = factoryVendor;		}		classes.push_back (std::move (c));	}	return classes;}/// Appends `s` to the fixed buffer `out` (of `cap` bytes, `len` used), as JSON string content, never past its end.void appendJson (char* out, size_t cap, size_t& len, const char* s){	for (; *s && len + 7 < cap; s++)	{		unsigned char c = static_cast<unsigned char> (*s);		if (c == '"' || c == '\\')		{			out[len++] = '\\';			out[len++] = static_cast<char> (c);		}		else if (c >= 0x20)			out[len++] = static_cast<char> (c);	}}void append (char* out, size_t cap, size_t& len, const char* s){	for (; *s && len + 1 < cap; s++)		out[len++] = *s;}/// Windows' own modules and the C runtime's: on the stack of whoever ends the process, but never the one asking.bool systemModule (const wchar_t* base){	static const wchar_t* const names[] = {L"ntdll.dll", L"kernel32.dll", L"kernelbase.dll", L"ucrtbase.dll", L"msvcrt.dll"};	for (auto n : names)		if (_wcsicmp (base, n) == 0)			return true;	return _wcsnicmp (base, L"vcruntime", 9) == 0 || _wcsnicmp (base, L"msvcp", 5) == 0 || _wcsnicmp (base, L"api-ms-win-", 11) == 0;}/// The process is ending through ExitProcess. This process only ever ends itself with TerminateProcess (host/main.rs/// `exit`), which runs nothing, so this is a plugin (or its C runtime's exit()) ending it: one "[exit] {...}" line/// naming the modules on the calling thread's stack, nearest first, past Windows' and the C runtime's own, and the exit/// code when Windows has it already (259, STILL_ACTIVE, when not). Runs under the loader lock with the other threads/// gone, so it takes no lock and allocates nothing: fixed buffers, one WriteFile.void NTAPI onProcessExit (PVOID, DWORD reason, PVOID){	// An exe is never unloaded: its DLL_PROCESS_DETACH is the process ending.	if (reason != DLL_PROCESS_DETACH || !g_log)		return;	void* frames[96];	USHORT n = RtlCaptureStackBackTrace (0, 96, frames, nullptr);	HMODULE self = GetModuleHandleW (nullptr);	HMODULE seen[8] {};	int listed = 0;	char line[2048];	size_t len = 0;	DWORD code = 0;	GetExitCodeProcess (GetCurrentProcess (), &code);	char head[64];	sprintf_s (head, "[exit] {\"code\":\"0x%08lX\",\"modules\":[", code);	append (line, sizeof (line), len, head);	for (USHORT i = 0; i < n && listed < 8; i++)	{		HMODULE m = nullptr;		if (!GetModuleHandleExW (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,		                         static_cast<LPCWSTR> (frames[i]), &m) ||		    m == self)			continue;		bool again = false;		for (int k = 0; k < listed; k++)			again = again || seen[k] == m;		if (again)			continue;		wchar_t path[MAX_PATH];		DWORD plen = GetModuleFileNameW (m, path, MAX_PATH);		if (!plen || plen >= MAX_PATH)			continue;		const wchar_t* base = path;		for (const wchar_t* p = path; *p; p++)			if (*p == L'\\' || *p == L'/')				base = p + 1;		if (systemModule (base))			continue;		char utf8[MAX_PATH * 3];		int u = WideCharToMultiByte (CP_UTF8, 0, path, -1, utf8, sizeof (utf8), nullptr, nullptr);		if (u <= 0)			continue;		append (line, sizeof (line), len, listed ? ",\"" : "\"");		appendJson (line, sizeof (line), len, utf8);		append (line, sizeof (line), len, "\"");		seen[listed++] = m;	}	append (line, sizeof (line), len, "]}");	logLine (line, len);}} // namespace// The exit report runs as one of this exe's TLS callbacks, which Windows calls as the process ends through// ExitProcess (and never for TerminateProcess). The linker keeps it through the two /INCLUDE directives.#pragma comment(linker, "/INCLUDE:_tls_used")#pragma comment(linker, "/INCLUDE:jw_tls_on_exit")#pragma const_seg(".CRT$XLY")extern "C" const PIMAGE_TLS_CALLBACK jw_tls_on_exit = onProcessExit;#pragma const_seg()extern "C" {void jw_set_quiet_windows (int32_t on) { g_quietWindows = on != 0; }void jw_set_log (void* handle) { g_log = static_cast<HANDLE> (handle); }void jw_set_stages (int32_t on) { g_stages = on != 0; }void jw_init (const JwCallbacks* callbacks){	if (callbacks)		g_cb = *callbacks;	if (!g_host)		g_host = new JwHostApplication ();	registerEditorClass ();}JwModule* jw_module_load (const char* path, char* err, size_t errLen){	std::string error;	try	{		// LoadLibrary (the DLL's own start-up code), InitDll, GetPluginFactory.		stage ("load");		auto module = VST3::Hosting::Module::create (path, error);		if (!module)		{			setError (err, errLen, error.empty () ? "the module wouldn't load" : error);			return nullptr;		}		stage ("context");		if (g_host)			module->getFactory ().setHostContext (g_host);		auto m = new JwModule ();		m->module = module;		m->classes = readClasses (module->getFactory ());		stage ("done");		return m;	}	catch (const std::exception& e)	{		setError (err, errLen, std::string ("the module threw: ") + e.what ());	}	catch (...)	{		setError (err, errLen, "the module threw an exception");	}	return nullptr;}void jw_module_free (JwModule* m) { delete m; }int32_t jw_module_factory_info (JwModule* m, JwFactoryInfo* out){	if (!m || !out)		return -1;	memset (out, 0, sizeof (*out));	auto info = m->module->getFactory ().info ();	copyString (out->vendor, sizeof (out->vendor), info.vendor ());	copyString (out->url, sizeof (out->url), info.url ());	copyString (out->email, sizeof (out->email), info.email ());	out->flags = info.flags ();	return 0;}int32_t jw_module_class_count (JwModule* m) { return m ? static_cast<int32_t> (m->classes.size ()) : 0; }int32_t jw_module_class_info (JwModule* m, int32_t index, JwClassInfo* out){	if (!m || !out || index < 0 || index >= static_cast<int32_t> (m->classes.size ()))		return -1;	memset (out, 0, sizeof (*out));	const auto& c = m->classes[index];	copyString (out->cid, sizeof (out->cid), c.ID ().toString ());	copyString (out->category, sizeof (out->category), c.category ());	copyString (out->name, sizeof (out->name), c.name ());	copyString (out->vendor, sizeof (out->vendor), c.vendor ());	copyString (out->version, sizeof (out->version), c.version ());	copyString (out->sdk_version, sizeof (out->sdk_version), c.sdkVersion ());	copyString (out->sub_categories, sizeof (out->sub_categories), c.subCategoriesString ());	out->class_flags = c.classFlags ();	out->cardinality = c.cardinality ();	return 0;}JwPlugin* jw_plugin_create (JwModule* m, const char* cid, uint32_t tag, char* err, size_t errLen){	if (!m || !cid)	{		setError (err, errLen, "no module");		return nullptr;	}	auto uid = VST3::UID::fromString (std::string (cid));	if (!uid)	{		setError (err, errLen, "not a class ID");		return nullptr;	}	auto p = new JwPlugin ();	p->tag = tag;	p->module = m->module;	p->handler.plugin = p;	p->frame.plugin = p;	for (const auto& c : m->classes)		if (c.ID () == *uid)			p->name = c.name ();	const auto& factory = m->module->getFactory ();	auto fail = [&] (const std::string& msg) {		setError (err, errLen, msg);		jw_plugin_destroy (p);		return nullptr;	};	try	{		p->component = factory.createInstance<IComponent> (*uid);		if (!p->component)			return fail ("the plugin didn't make its component");		if (p->component->initialize (g_host) != kResultOk)		{			p->component = nullptr;			return fail ("the plugin's component didn't initialize");		}		// One object (a single-component effect), or a controller of its own.		if (auto ctrl = U::cast<IEditController> (p->component))		{			p->controller = ctrl;			p->single = true;		}		else		{			TUID controllerCid;			if (p->component->getControllerClassId (controllerCid) == kResultTrue)			{				auto ctrl = factory.createInstance<IEditController> (VST3::UID::fromTUID (controllerCid));				if (ctrl && ctrl->initialize (g_host) == kResultOk)					p->controller = ctrl;			}		}		if (p->controller && !p->single)		{			auto compCP = U::cast<IConnectionPoint> (p->component);			auto ctrlCP = U::cast<IConnectionPoint> (p->controller);			if (compCP && ctrlCP)			{				p->componentCP = owned (new ConnectionProxy (compCP));				p->controllerCP = owned (new ConnectionProxy (ctrlCP));				p->componentCP->connect (ctrlCP);				p->controllerCP->connect (compCP);			}		}		// Room for the parameter changes before the plugin has a handler to report its own edits to (some report the		// component's state as edits when they get it).		int32 params = p->controller ? p->controller->getParameterCount () : 0;		p->toAudio.init (params);		p->toMain.init (params);		if (p->controller)		{			p->controller->setComponentHandler (&p->handler);			if (!p->single)			{				MemoryStream state;				if (p->component->getState (&state) == kResultOk)				{					state.seek (0, IBStream::kIBSeekSet, nullptr);					p->controller->setComponentState (&state);				}			}		}		p->processor = U::cast<IAudioProcessor> (p->component);		if (!p->processor)			return fail ("not an audio processor");	}	catch (...)	{		return fail ("the plugin threw an exception while starting");	}	return p;}int32_t jw_plugin_setup (JwPlugin* p, double rate, int32_t maxBlock, int32_t offline, JwPluginInfo* out, char* err, size_t errLen){	if (!p || !p->processor)		return -1;	p->rate = rate;	p->maxBlock = maxBlock;	p->processMode = offline ? kOffline : kRealtime;	auto& c = *p->component;	// Stereo main buses where the plugin takes them; a mono plugin keeps mono (the host downmixes into it and doubles	// its output); anything else stays as the plugin has it.	int32 nIn = c.getBusCount (kAudio, kInput);	int32 nOut = c.getBusCount (kAudio, kOutput);	std::vector<SpeakerArrangement> ins (nIn > 0 ? nIn : 1, SpeakerArr::kEmpty);	std::vector<SpeakerArrangement> outs (nOut > 0 ? nOut : 1, SpeakerArr::kEmpty);	for (int32 i = 0; i < nIn; i++)		p->processor->getBusArrangement (kInput, i, ins[i]);	for (int32 i = 0; i < nOut; i++)		p->processor->getBusArrangement (kOutput, i, outs[i]);	auto tryArrangement = [&] (SpeakerArrangement in, SpeakerArrangement outArr) {		auto i2 = ins;		auto o2 = outs;		if (nIn > 0)			i2[0] = in;		if (nOut > 0)			o2[0] = outArr;		return p->processor->setBusArrangements (i2.data (), nIn, o2.data (), nOut) == kResultTrue;	};	if (!tryArrangement (SpeakerArr::kStereo, SpeakerArr::kStereo))		if (!tryArrangement (SpeakerArr::kMono, SpeakerArr::kStereo))			tryArrangement (SpeakerArr::kMono, SpeakerArr::kMono);	if (p->processor->canProcessSampleSize (kSample32) != kResultTrue)	{		setError (err, errLen, "the plugin can't process 32-bit audio");		return -1;	}	ProcessSetup setup {p->processMode, kSample32, maxBlock, rate};	if (p->processor->setupProcessing (setup) != kResultOk)	{		setError (err, errLen, "the plugin refused the sample rate or block size");		return -1;	}	// The main buses on, side chains and extra outputs off; an instrument's note input on. After setupProcessing and	// before setActive, as the SDK's headers have it ("Setup Done").	for (int32 i = 0; i < nIn; i++)		c.activateBus (kAudio, kInput, i, i == 0);	for (int32 i = 0; i < nOut; i++)		c.activateBus (kAudio, kOutput, i, i == 0);	if (c.getBusCount (kEvent, kInput) > 0)		c.activateBus (kEvent, kInput, 0, true);	prepareBuffers (p);	p->context = {};	p->context.sampleRate = rate;	// Whether it has an editor of its own (the SDK's ADelay, for one, has none: a host shows its parameters instead).	if (p->controller)	{		try		{			IPtr<IPlugView> view = owned (p->controller->createView (ViewType::kEditor));			p->hasEditor = view && view->isPlatformTypeSupported (kPlatformTypeHWND) == kResultTrue;		}		catch (...)		{		}	}	// The plugin's own bypass, if it has one.	if (p->controller)	{		int32 n = p->controller->getParameterCount ();		for (int32 i = 0; i < n; i++)		{			ParameterInfo pi {};			if (p->controller->getParameterInfo (i, pi) == kResultOk && (pi.flags & ParameterInfo::kIsBypass))			{				p->bypassId = pi.id;				break;			}		}	}	if (c.setActive (true) != kResultOk)	{		setError (err, errLen, "the plugin wouldn't switch on");		return -1;	}	p->active = true;	fillInfo (p, out);	return 0;}int32_t jw_plugin_reactivate (JwPlugin* p, JwPluginInfo* out){	if (!p || !p->component)		return -1;	if (p->active)		p->component->setActive (false);	ProcessSetup setup {p->processMode, kSample32, p->maxBlock, p->rate};	p->processor->setupProcessing (setup);	prepareBuffers (p);	p->active = p->component->setActive (true) == kResultOk;	fillInfo (p, out);	return p->active ? 0 : -1;}int32_t jw_plugin_latency (JwPlugin* p) { return p && p->processor ? static_cast<int32_t> (p->processor->getLatencySamples ()) : 0; }int32_t jw_plugin_set_processing (JwPlugin* p, int32_t on){	if (!p || !p->processor || !p->active)		return -1;	if ((on != 0) == p->processing)		return 0;	p->processing = on != 0;	// Some plugins answer kNotImplemented; that's fine.	p->processor->setProcessing (on ? 1 : 0);	return 0;}int32_t jw_plugin_process (JwPlugin* p, const float* inL, const float* inR, float* outL, float* outR, int32_t frames, const JwTransport* t){	if (!p || !p->processor || frames <= 0 || frames > p->maxBlock)		return kInvalidArgument;	auto& d = p->data;	// In: stereo as is, downmixed for a mono input bus.	if (d.numInputs > 0 && d.inputs[0].channelBuffers32)	{		auto& b = d.inputs[0];		if (b.numChannels == 1)		{			float* m = b.channelBuffers32[0];			for (int32 i = 0; i < frames; i++)				m[i] = 0.5f * (inL[i] + inR[i]);		}		else if (b.numChannels >= 2)		{			memcpy (b.channelBuffers32[0], inL, sizeof (float) * frames);			memcpy (b.channelBuffers32[1], inR, sizeof (float) * frames);		}		b.silenceFlags = 0;	}	// Parameter values set since the last block, at its start.	takeParamChanges (p);	p->outChanges.clearQueue ();	p->events.clear ();	// Time: the page's tempo and position when it gives them.	auto& ctx = p->context;	ctx.sampleRate = p->rate;	ctx.state = ProcessContext::kContTimeValid | ProcessContext::kTimeSigValid;	ctx.timeSigNumerator = 4;	ctx.timeSigDenominator = 4;	ctx.tempo = 120;	if (t)	{		if (t->tempo > 0)		{			ctx.tempo = t->tempo;			ctx.state |= ProcessContext::kTempoValid | ProcessContext::kProjectTimeMusicValid;		}		if (t->playing)			ctx.state |= ProcessContext::kPlaying;		ctx.projectTimeSamples = t->position;		ctx.projectTimeMusic = static_cast<double> (t->position) / p->rate * ctx.tempo / 60.0;	}	d.numSamples = frames;	tresult r = p->processor->process (d);	ctx.continousTimeSamples += frames;	// Out: the main bus, a mono one doubled.	if (d.numOutputs > 0 && d.outputs[0].channelBuffers32 && d.outputs[0].numChannels > 0)	{		auto& b = d.outputs[0];		memcpy (outL, b.channelBuffers32[0], sizeof (float) * frames);		memcpy (outR, b.channelBuffers32[b.numChannels > 1 ? 1 : 0], sizeof (float) * frames);	}	else	{		memset (outL, 0, sizeof (float) * frames);		memset (outR, 0, sizeof (float) * frames);	}	giveParamChanges (p);	return r;}int32_t jw_plugin_params_pending (JwPlugin* p) { return p && p->toAudio.pending () ? 1 : 0; }int32_t jw_plugin_flush (JwPlugin* p){	if (!p || !p->processor || !p->active || !p->processing)		return kInvalidArgument;	if (!p->toAudio.pending ())		return kResultOk;	// A parameter flush, as the VST 3 SDK's validator does it: process() with no audio at all, only the changes.	takeParamChanges (p);	p->outChanges.clearQueue ();	p->events.clear ();	ProcessData d {};	d.processMode = p->processMode;	d.symbolicSampleSize = kSample32;	d.numSamples = 0;	d.numInputs = 0;	d.numOutputs = 0;	d.inputs = nullptr;	d.outputs = nullptr;	d.inputParameterChanges = &p->inChanges;	d.outputParameterChanges = &p->outChanges;	d.inputEvents = &p->events;	d.processContext = &p->context;	tresult r = p->processor->process (d);	giveParamChanges (p);	return r;}int32_t jw_plugin_get_state (JwPlugin* p, int32_t which, uint8_t** data, int64_t* len, char* err, size_t errLen){	*data = nullptr;	*len = 0;	if (!p || !p->component)		return -1;	if (which == 1 && (!p->controller || p->single))		return 0; // nothing more than the component's	MemoryStream s;	tresult r = which == 0 ? p->component->getState (&s) : p->controller->getState (&s);	if (r != kResultOk && r != kNotImplemented)	{		setError (err, errLen, which == 0 ? "the plugin wouldn't give its state" : "the plugin's controller wouldn't give its state");		return -1;	}	TSize size = 0;	s.seek (0, IBStream::kIBSeekEnd, &size);	if (size > 0)	{		*data = static_cast<uint8_t*> (malloc (static_cast<size_t> (size)));		memcpy (*data, s.getData (), static_cast<size_t> (size));		*len = size;	}	return 0;}int32_t jw_plugin_set_state (JwPlugin* p, const uint8_t* comp, int64_t compLen, const uint8_t* ctrl, int64_t ctrlLen, char* err, size_t errLen){	if (!p || !p->component)		return -1;	// Parameter changes still on their way to the processor are older than this state: they mustn't undo it.	p->toAudio.discardPending ();	MemoryStream cs;	if (compLen > 0)	{		cs.write (const_cast<uint8_t*> (comp), static_cast<int32> (compLen), nullptr);		cs.seek (0, IBStream::kIBSeekSet, nullptr);		if (p->component->setState (&cs) != kResultOk)		{			setError (err, errLen, "the plugin refused the state");			return -1;		}		if (p->controller && !p->single)		{			cs.seek (0, IBStream::kIBSeekSet, nullptr);			p->controller->setComponentState (&cs);		}	}	if (ctrlLen > 0 && p->controller && !p->single)	{		MemoryStream ts;		ts.write (const_cast<uint8_t*> (ctrl), static_cast<int32> (ctrlLen), nullptr);		ts.seek (0, IBStream::kIBSeekSet, nullptr);		p->controller->setState (&ts);	}	return 0;}int32_t jw_plugin_param_count (JwPlugin* p) { return p && p->controller ? p->controller->getParameterCount () : 0; }int32_t jw_plugin_param_info (JwPlugin* p, int32_t index, JwParamInfo* out){	if (!p || !p->controller || !out)		return -1;	memset (out, 0, sizeof (*out));	ParameterInfo pi {};	if (p->controller->getParameterInfo (index, pi) != kResultOk)		return -1;	out->id = pi.id;	copyString (out->title, sizeof (out->title), narrow (pi.title, 128));	copyString (out->short_title, sizeof (out->short_title), narrow (pi.shortTitle, 128));	copyString (out->units, sizeof (out->units), narrow (pi.units, 128));	out->step_count = pi.stepCount;	out->default_value = pi.defaultNormalizedValue;	out->value = p->controller->getParamNormalized (pi.id);	out->flags = pi.flags;	String128 text {};	if (p->controller->getParamStringByValue (pi.id, out->value, text) == kResultOk)		copyString (out->display, sizeof (out->display), narrow (text, 128));	return 0;}int32_t jw_plugin_set_param (JwPlugin* p, uint32_t id, double value){	if (!p)		return -1;	if (value < 0)		value = 0;	if (value > 1)		value = 1;	if (p->controller)		p->controller->setParamNormalized (id, value);	return p->toAudio.push (id, value) ? 0 : -1;}int32_t jw_plugin_set_bypass (JwPlugin* p, int32_t on){	if (!p || p->bypassId == kNoParamId)		return -1;	return jw_plugin_set_param (p, p->bypassId, on ? 1.0 : 0.0);}void jw_plugin_idle (JwPlugin* p){	if (!p || !p->controller)		return;	p->toMain.drain ([p] (ParamID id, ParamValue v) { p->controller->setParamNormalized (id, v); });}void jw_plugin_destroy (JwPlugin* p){	if (!p)		return;	try	{		closeEditor (p, false);		if (p->active && p->component)			p->component->setActive (false);		p->active = false;		if (p->controller)			p->controller->setComponentHandler (nullptr);		if (p->componentCP)			p->componentCP->disconnect ();		if (p->controllerCP)			p->controllerCP->disconnect ();		p->componentCP = nullptr;		p->controllerCP = nullptr;		if (p->controller && !p->single)			p->controller->terminate ();		if (p->component)			p->component->terminate ();	}	catch (...)	{	}	p->processor = nullptr;	p->controller = nullptr;	p->component = nullptr;	p->data.unprepare ();	delete p;}int32_t jw_editor_open (JwPlugin* p, intptr_t owner, const char* title, int32_t x, int32_t y, int32_t usePos, char* err, size_t errLen){	if (!p)		return -1;	if (p->hwnd)	{		showEditorWindow (p->hwnd);		return 0;	}	if (!p->controller)	{		setError (err, errLen, "this plugin has no editor");		return -1;	}	IPtr<IPlugView> view;	try	{		view = owned (p->controller->createView (ViewType::kEditor));	}	catch (...)	{	}	if (!view)	{		setError (err, errLen, "this plugin has no editor");		return -1;	}	if (view->isPlatformTypeSupported (kPlatformTypeHWND) != kResultTrue)	{		setError (err, errLen, "the plugin's editor doesn't run in a Windows window");		return -1;	}	ViewRect vr (0, 0, 400, 300);	view->getSize (&vr);	p->resizable = view->canResize () == kResultTrue;	p->style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN | (p->resizable ? WS_THICKFRAME | WS_MAXIMIZEBOX : 0);	p->exStyle = 0;	// Where: the remembered place if it's still on a monitor, else centred over the app's window.	HWND ownerHwnd = reinterpret_cast<HWND> (owner);	POINT at {x, y};	bool placed = usePos && onSomeMonitor (x, y);	HMONITOR monitor = placed ? MonitorFromPoint (at, MONITOR_DEFAULTTONEAREST)	                          : (ownerHwnd ? MonitorFromWindow (ownerHwnd, MONITOR_DEFAULTTONEAREST) : MonitorFromPoint (at, MONITOR_DEFAULTTOPRIMARY));	UINT mdpiX = 96, mdpiY = 96;	using GetDpiForMonitorFn = HRESULT (WINAPI*) (HMONITOR, int, UINT*, UINT*);	if (HMODULE shcore = LoadLibraryW (L"shcore.dll"))		if (auto f = reinterpret_cast<GetDpiForMonitorFn> (GetProcAddress (shcore, "GetDpiForMonitor")))			f (monitor, 0, &mdpiX, &mdpiY);	p->dpi = mdpiX;	SIZE extra = frameExtra (p);	int w = vr.getWidth () + extra.cx;	int h = vr.getHeight () + extra.cy;	if (!placed)	{		RECT orc {0, 0, 1280, 820};		MONITORINFO mi {sizeof (mi)};		GetMonitorInfoW (monitor, &mi);		if (!ownerHwnd || !GetWindowRect (ownerHwnd, &orc))			orc = mi.rcWork;		at.x = orc.left + ((orc.right - orc.left) - w) / 2;		at.y = orc.top + ((orc.bottom - orc.top) - h) / 3;		if (at.x < mi.rcWork.left)			at.x = mi.rcWork.left;		if (at.y < mi.rcWork.top)			at.y = mi.rcWork.top;	}	std::wstring wtitle = wide (title);	p->hwnd = CreateWindowExW (p->exStyle, kEditorClass, wtitle.c_str (), p->style, at.x, at.y, w, h, ownerHwnd, nullptr,	                           GetModuleHandleW (nullptr), p);	if (!p->hwnd)	{		setError (err, errLen, "couldn't make the editor's window");		return -1;	}	setDarkFrame (p->hwnd);	p->dpi = GetDpiForWindow (p->hwnd);	p->view = view;	view->setFrame (&p->frame);	if (auto css = U::cast<IPlugViewContentScaleSupport> (view))		css->setContentScaleFactor (static_cast<float> (p->dpi) / USER_DEFAULT_SCREEN_DPI);	if (view->getSize (&vr) == kResultTrue)		sizeWindowToView (p, vr, nullptr);	tresult attached = kResultFalse;	try	{		attached = view->attached (p->hwnd, kPlatformTypeHWND);	}	catch (...)	{	}	if (attached != kResultTrue)	{		view->setFrame (nullptr);		p->view = nullptr;		SetWindowLongPtrW (p->hwnd, GWLP_USERDATA, 0);		DestroyWindow (p->hwnd);		p->hwnd = nullptr;		setError (err, errLen, "the plugin's editor didn't open");		return -1;	}	// Some editors settle on their size only once attached.	if (view->getSize (&vr) == kResultTrue)		sizeWindowToView (p, vr, nullptr);	showEditorWindow (p->hwnd);	return 0;}void jw_editor_close (JwPlugin* p){	if (p)		closeEditor (p, false);}int32_t jw_editor_is_open (JwPlugin* p) { return p && p->hwnd ? 1 : 0; }void jw_editor_set_title (JwPlugin* p, const char* title){	if (p && p->hwnd)		SetWindowTextW (p->hwnd, wide (title).c_str ());}int32_t jw_editor_rect (JwPlugin* p, int32_t* rect){	RECT wr;	if (!p || !p->hwnd || !GetWindowRect (p->hwnd, &wr))		return -1;	rect[0] = wr.left;	rect[1] = wr.top;	rect[2] = wr.right - wr.left;	rect[3] = wr.bottom - wr.top;	return 0;}void jw_free (void* data) { free (data); }void jw_redirect_stdio (){	fflush (stdout);	fflush (stderr);	int nul = _open ("NUL", _O_RDWR);	if (nul >= 0)	{		for (int fd = 0; fd <= 2; fd++)			if (fd != nul)				_dup2 (nul, fd);		if (nul > 2)			_close (nul);	}}} // extern "C"