File size: 12,320 Bytes
6063997
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#include "PluginBridgeEditor.h"

#if JUCE_MAC
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
#endif

#include "json.hpp"
using json = nlohmann::json;

static const juce::Colour kBgDark       (0xff0d0d1a);
static const juce::Colour kBgPanel      (0xff1a1a2e);
static const juce::Colour kAccent       (0xff6c63ff);
static const juce::Colour kTextPrimary  (0xffe8e8f0);
static const juce::Colour kTextSecondary(0xff8888aa);
static const juce::Colour kGreen        (0xff4cef50);
static const juce::Colour kRed          (0xffef5350);

PluginBridgeEditor::PluginBridgeEditor(PluginBridgeProcessor& p)
    : AudioProcessorEditor(&p), processorRef(p)
{
    setSize(kDefaultWidth, kDefaultHeight);
    setResizable(true, true);

    titleLabel.setText("PluginBridge", juce::dontSendNotification);
    titleLabel.setFont(juce::FontOptions(13.0f));
    titleLabel.setJustificationType(juce::Justification::centredLeft);
    titleLabel.setColour(juce::Label::textColourId, kTextPrimary);
    addAndMakeVisible(titleLabel);

    mcpStatusLabel.setFont(juce::FontOptions(10.0f));
    mcpStatusLabel.setJustificationType(juce::Justification::centredRight);
    addAndMakeVisible(mcpStatusLabel);

    pluginStatusLabel.setFont(juce::FontOptions(10.0f));
    pluginStatusLabel.setJustificationType(juce::Justification::centredLeft);
    pluginStatusLabel.setColour(juce::Label::textColourId, kTextSecondary);
    addAndMakeVisible(pluginStatusLabel);

    selectButton.onClick = [this]() { showPluginMenu(); };
    selectButton.setColour(juce::TextButton::buttonColourId, kAccent);
    selectButton.setColour(juce::TextButton::textColourOffId, kTextPrimary);
    addAndMakeVisible(selectButton);

    // Callbacks
    processorRef.onPluginLoaded = [this]()
    {
        juce::MessageManager::callAsync([this]()
        {
            showingError = false;
            // Request GUI display
            processorRef.showPluginGui();
        });
    };

    processorRef.onPluginUnloaded = [this]()
    {
        juce::MessageManager::callAsync([this]()
        {
            disconnectRemoteLayer();
            setSize(kDefaultWidth, kDefaultHeight);
        });
    };

    processorRef.onGuiReady = [this]()
    {
        juce::MessageManager::callAsync([this]() { connectRemoteLayer(); });
    };

    processorRef.onGuiResized = [this](int w, int h)
    {
        juce::MessageManager::callAsync([this, w, h]()
        {
            setSize(std::max(w, kDefaultWidth), h + kTopBarHeight);
        });
    };

    processorRef.onLoadFailed = [this](const juce::String& error)
    {
        juce::MessageManager::callAsync([this, error]()
        {
            pluginStatusLabel.setText(error, juce::dontSendNotification);
            pluginStatusLabel.setColour(juce::Label::textColourId, kRed);
            showingError = true;
        });
    };

    // If already loaded (restoring state)
    if (processorRef.isPluginLoaded() && processorRef.getRemoteLayerPortName().isNotEmpty())
        connectRemoteLayer();

    startTimerHz(4);
}

PluginBridgeEditor::~PluginBridgeEditor()
{
    stopTimer();
    processorRef.onPluginLoaded = nullptr;
    processorRef.onPluginUnloaded = nullptr;
    processorRef.onGuiReady = nullptr;
    processorRef.onGuiResized = nullptr;
    processorRef.onLoadFailed = nullptr;
    disconnectRemoteLayer();
}

void PluginBridgeEditor::paint(juce::Graphics& g)
{
    g.fillAll(kBgDark);

    auto topBar = getLocalBounds().removeFromTop(kTopBarHeight);
    g.setColour(kBgPanel);
    g.fillRect(topBar);

    g.setColour(kAccent.withAlpha(0.3f));
    g.drawHorizontalLine(kTopBarHeight - 1, 0.0f, (float)getWidth());

    // If no remote layer connected, show message in the body area
    if (!layerConnected && !processorRef.isPluginLoaded())
    {
        g.setColour(kTextSecondary);
        g.setFont(juce::FontOptions(12.0f));
        auto body = getLocalBounds().withTrimmedTop(kTopBarHeight);
        if (body.getHeight() > 20)
            g.drawText("Select a plugin to load", body, juce::Justification::centred);
    }
}

void PluginBridgeEditor::resized()
{
    auto area = getLocalBounds();
    auto topBar = area.removeFromTop(kTopBarHeight).reduced(4, 2);

    titleLabel.setBounds(topBar.removeFromLeft(80));
    selectButton.setBounds(topBar.removeFromLeft(100).reduced(0, 2));
    topBar.removeFromLeft(4);
    pluginStatusLabel.setBounds(topBar.removeFromLeft(topBar.getWidth() - 60));
    mcpStatusLabel.setBounds(topBar);

#if JUCE_MAC
    // Resize the remote CALayer to fill the area below the top bar
    if (layerConnected && remoteLayerClient)
    {
        CARemoteLayerClient* client = (__bridge CARemoteLayerClient*)remoteLayerClient;
        if (client.layer)
        {
            auto body = getLocalBounds().withTrimmedTop(kTopBarHeight);
            client.layer.frame = CGRectMake(0, 0, body.getWidth(), body.getHeight());
        }
    }
#endif
}

void PluginBridgeEditor::timerCallback()
{
    if (processorRef.isMcpServerRunning())
    {
        mcpStatusLabel.setText("MCP:" + juce::String(processorRef.getMcpServerPort()), juce::dontSendNotification);
        mcpStatusLabel.setColour(juce::Label::textColourId, kGreen);
    }
    else
    {
        mcpStatusLabel.setText("MCP:off", juce::dontSendNotification);
        mcpStatusLabel.setColour(juce::Label::textColourId, kRed);
    }

    if (processorRef.isPluginLoaded())
    {
        selectButton.setButtonText(processorRef.getLoadedPluginName());
        if (!showingError)
        {
            pluginStatusLabel.setText(juce::String(processorRef.getLoadedPluginParamCount()) + " params", juce::dontSendNotification);
            pluginStatusLabel.setColour(juce::Label::textColourId, kGreen);
        }
    }
    else if (!showingError)
    {
        selectButton.setButtonText("Select Plugin");
        pluginStatusLabel.setText("", juce::dontSendNotification);
    }

    // Check for crash
    if (processorRef.getConnectionState() == HelperConnection::State::Crashed)
    {
        disconnectRemoteLayer();
        pluginStatusLabel.setText("Plugin crashed — select again to retry", juce::dontSendNotification);
        pluginStatusLabel.setColour(juce::Label::textColourId, kRed);
        showingError = true;
    }
}

// --- Remote Layer Connection ---

void PluginBridgeEditor::connectRemoteLayer()
{
#if JUCE_MAC
    disconnectRemoteLayer();

    auto portName = processorRef.getRemoteLayerPortName();
    if (portName.isEmpty()) return;

    int guiW = processorRef.getRemoteGuiWidth();
    int guiH = processorRef.getRemoteGuiHeight();
    if (guiW <= 0 || guiH <= 0) return;

    // Look up the Mach port from the bootstrap server
    NSString* nsPortName = [NSString stringWithUTF8String:portName.toRawUTF8()];
    NSMachPort* machPort = (NSMachPort*)[[NSMachBootstrapServer sharedInstance]
        portForName:nsPortName];

    if (!machPort)
    {
        DBG("PluginBridgeEditor: Failed to look up Mach port: " + portName);
        return;
    }

    mach_port_t port = [machPort machPort];

    // Create remote layer client
    CARemoteLayerClient* client = [[CARemoteLayerClient alloc] initWithServerPort:port];
    if (!client)
    {
        DBG("PluginBridgeEditor: Failed to create CARemoteLayerClient");
        return;
    }

    remoteLayerClient = (__bridge_retained void*)client;

    // Get our NSView and make it layer-backed
    if (auto* peer = getPeer())
    {
        NSView* nsView = (NSView*)peer->getNativeHandle();
        [nsView setWantsLayer:YES];

        // Add remote layer as sublayer, positioned below the top bar
        CALayer* remoteLayer = client.layer;
        if (remoteLayer)
        {
            remoteLayer.frame = CGRectMake(0, 0, guiW, guiH);
            // Position at the bottom of the view (below top bar)
            // NSView coordinates are flipped (0,0 = bottom-left)
            [nsView.layer addSublayer:remoteLayer];
        }
    }

    layerConnected = true;

    // Resize editor to fit plugin GUI + top bar
    setSize(std::max(guiW, kDefaultWidth), guiH + kTopBarHeight);

    DBG("PluginBridgeEditor: Remote layer connected (" + juce::String(guiW) + "x" + juce::String(guiH) + ")");
#endif
}

void PluginBridgeEditor::disconnectRemoteLayer()
{
#if JUCE_MAC
    if (remoteLayerClient)
    {
        CARemoteLayerClient* client = (__bridge_transfer CARemoteLayerClient*)remoteLayerClient;
        if (client.layer)
            [client.layer removeFromSuperlayer];
        remoteLayerClient = nullptr;
    }
    layerConnected = false;
#endif
}

// --- Mouse Event Forwarding ---

void PluginBridgeEditor::sendMouseEvent(const juce::String& type, float x, float y, int button)
{
    // Adjust Y for top bar offset
    float adjustedY = y - kTopBarHeight;
    if (adjustedY < 0) return; // Click is in top bar, not plugin area

    json cmd = {{"cmd", "mouse"}, {"type", type.toStdString()},
                {"x", x}, {"y", adjustedY}, {"button", button}};
    processorRef.getHelperConnection().sendCommand(cmd.dump());
}

void PluginBridgeEditor::mouseDown(const juce::MouseEvent& e)
{
    if (e.y >= kTopBarHeight && layerConnected)
        sendMouseEvent("down", (float)e.x, (float)e.y, e.mods.isLeftButtonDown() ? 0 : 1);
    else
        juce::AudioProcessorEditor::mouseDown(e);
}

void PluginBridgeEditor::mouseUp(const juce::MouseEvent& e)
{
    if (e.y >= kTopBarHeight && layerConnected)
        sendMouseEvent("up", (float)e.x, (float)e.y, 0);
    else
        juce::AudioProcessorEditor::mouseUp(e);
}

void PluginBridgeEditor::mouseMove(const juce::MouseEvent& e)
{
    if (e.y >= kTopBarHeight && layerConnected)
        sendMouseEvent("move", (float)e.x, (float)e.y);
    else
        juce::AudioProcessorEditor::mouseMove(e);
}

void PluginBridgeEditor::mouseDrag(const juce::MouseEvent& e)
{
    if (e.y >= kTopBarHeight && layerConnected)
        sendMouseEvent("drag", (float)e.x, (float)e.y, 0);
    else
        juce::AudioProcessorEditor::mouseDrag(e);
}

void PluginBridgeEditor::mouseWheelMove(const juce::MouseEvent& e, const juce::MouseWheelDetails& w)
{
    if (e.y >= kTopBarHeight && layerConnected)
    {
        json cmd = {{"cmd", "mouse"}, {"type", "scroll"},
                    {"x", (float)e.x}, {"y", (float)(e.y - kTopBarHeight)},
                    {"dx", w.deltaX}, {"dy", w.deltaY}};
        processorRef.getHelperConnection().sendCommand(cmd.dump());
    }
    else
    {
        juce::AudioProcessorEditor::mouseWheelMove(e, w);
    }
}

// --- Plugin Menu ---

void PluginBridgeEditor::showPluginMenu()
{
    auto files = processorRef.getInstalledPluginFiles();

    juce::PopupMenu menu;

    if (files.isEmpty())
    {
        menu.addItem(-1, "(No plugins found)", false);
        menu.showMenuAsync(juce::PopupMenu::Options().withTargetComponent(&selectButton), [](int) {});
        return;
    }

    juce::PopupMenu vst3Menu;
    juce::PopupMenu auMenu;
    int itemId = 1;

    for (int i = 0; i < files.size(); ++i)
    {
        const auto& file = files[i];
        auto name = file.getFileNameWithoutExtension();
        auto path = file.getFullPathName();
        bool blocked = processorRef.isBlocked(path);

        if (file.getFileExtension() == ".vst3")
            vst3Menu.addItem(itemId, blocked ? name + " (not compatible)" : name, !blocked);
        else
            auMenu.addItem(itemId, blocked ? name + " (not compatible)" : name, !blocked);

        itemId++;
    }

    if (vst3Menu.getNumItems() > 0)
        menu.addSubMenu("VST3", vst3Menu);
    if (auMenu.getNumItems() > 0)
        menu.addSubMenu("Audio Units", auMenu);

    menu.addSeparator();
    menu.addItem(9999, "Clear blocklist");

    menu.showMenuAsync(juce::PopupMenu::Options().withTargetComponent(&selectButton),
        [this, files](int result)
        {
            if (result == 9999)
            {
                processorRef.getBlocklist().clear();
                return;
            }

            if (result > 0 && result <= files.size())
            {
                showingError = false;
                pluginStatusLabel.setText("Loading...", juce::dontSendNotification);
                pluginStatusLabel.setColour(juce::Label::textColourId, kTextSecondary);
                processorRef.loadPlugin(files[result - 1].getFullPathName());
            }
        });
}