• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ossia / score / 43152560159

12 Nov 2026 04:05AM UTC coverage: 60.414% (+1.7%) from 58.699%
43152560159

push

github

jcelerier
Tests: the CLAP checker keeps a plug-in factory given for any id its own

A target that answers every factory id with its plug-in factory
(SpectMorph) had the checker hand the host the target's own, unwrapped,
for preset discovery: the host could not tell it from a discovery factory
as it can without the checker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdPgufUMRpkKzaYvUs9iHW

229543 of 687702 branches covered (33.38%)

247114 of 409035 relevant lines covered (60.41%)

742286.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

47.02
/src/plugins/score-plugin-clap/Clap/EffectModel.cpp
1
#include "EffectModel.hpp"
2

3
#include <Process/Dataflow/Port.hpp>
4
#include <Process/Dataflow/PortFactory.hpp>
5
#include <Process/Dataflow/WidgetInlets.hpp>
6
#include <Process/ExternalFiles.hpp>
7

8
#include <Scenario/Document/Interval/IntervalModel.hpp>
9

10
#include <Audio/Settings/Model.hpp>
11

12
#include <score/serialization/DataStreamVisitor.hpp>
13
#include <score/serialization/JSONVisitor.hpp>
14
#include <score/tools/IdentifierGeneration.hpp>
15

16
#include <ossia/dataflow/exec_pool.hpp>
17
#include <ossia/detail/json.hpp>
18
#include <ossia/detail/thread.hpp>
19
#include <ossia/network/domain/domain.hpp>
20

21
#include <QApplication>
22
#include <QDir>
23
#include <QDirIterator>
24
#include <QFileInfo>
25
#include <QDebug>
26
#include <QMenu>
27
#include <QThread>
28
#include <QTimer>
29

30
#include <Clap/ApplicationPlugin.hpp>
31
#include <Clap/Window.hpp>
32
#include <clap/all.h>
33
#include <clap/ext/state.h>
34
#include <clap/ext/preset-load.h>
35
#include <clap/factory/preset-discovery.h>
36

37
#include <score_git_info.hpp>
38
#include <wobjectimpl.h>
39

40
#include <clap/ext/context-menu.h>
41

42
#if defined(_WIN32)
43
#include <windows.h>
44
#else
45
#include <dlfcn.h>
46
#endif
47

48
W_OBJECT_IMPL(Clap::Model)
1,761 !
49

50
namespace Clap
51
{
52

53
// Some plug-ins (e.g. Octasine) don't zero-init info.name; reject garbage.
54
static QString
55
clap_safe_name(const char* raw, const QString& fallback) noexcept
113 ✔
56
{
57
  if(!raw)
113 !
58
    return fallback;
×
59
  const auto len = qstrnlen(raw, CLAP_NAME_SIZE);
113 !
60
  if(len == 0)
113 !
61
    return fallback;
×
62
  const QString name = QString::fromUtf8(raw, len);
113 !
63
  if(name.isEmpty())
113 !
64
    return fallback;
×
65
  qsizetype letters = 0;
113 ✔
66
  for(QChar c : name)
831 !
67
  {
68
    if(c == QChar::ReplacementCharacter)
718 !
69
      return fallback;
×
70
    if(!c.isPrint())
718 !
71
      return fallback;
×
72
    if(c.isLetter())
718 ✔
73
      ++letters;
666 ✔
74
  }
75
  if(letters < 2 && letters < name.length())
113 !
76
    return fallback;
×
77
  return name;
113 ✔
78
}
113 ✔
79

80
// Host GUI callbacks. clap/ext/gui.h has them all [thread-safe]: from
81
// another thread than the main one, the request is acknowledged and carried
82
// out on the main thread, where the window lives.
83
namespace
84
{
85
template <typename F>
86
bool on_window(const clap_host_t* host, F f)
4 ✔
87
{
88
  auto& h = *static_cast<Clap::PluginHandle*>(host->host_data);
4 ✔
89
  if(QThread::currentThread() == qApp->thread())
4 !
90
  {
91
    Clap::Model* model = h.model;
×
92
    return model && model->window && f(*model->window);
×
93
  }
94

95
  if(!h.model)
4 !
96
    return false;
×
97
  QMetaObject::invokeMethod(h.model, [model = QPointer<Clap::Model>{h.model}, f] {
8 !
98
    if(model && model->window)
4 !
99
      f(*model->window);
4 ✔
100
  }, Qt::QueuedConnection);
4 ✔
101
  return true;
4 ✔
102
}
4 ✔
103
}
104

105
extern "C" {
106
static void resize_hints_changed(const clap_host_t* host)
1 ✔
107
{
108
  on_window(host, [](Clap::Window& window) {
2 ✔
109
    window.resizeHintsChanged();
1 ✔
110
    return true;
1 ✔
111
  });
112
}
1 ✔
113

114
// Off the main thread, true only says that the request is taken: the window
115
// then takes a size the editor accepts, which resizeEvent gives it
116
static bool request_resize(const clap_host_t* host, uint32_t width, uint32_t height)
1 ✔
117
{
118
  return on_window(host, [width, height](Clap::Window& window) {
2 ✔
119
    window.resize(width, height);
1 ✔
120
    return true;
1 ✔
121
  });
122
}
123

124
static bool request_show(const clap_host_t* host)
1 ✔
125
{
126
  return on_window(host, [](Clap::Window& window) {
2 ✔
127
    window.show();
1 ✔
128
    return true;
1 ✔
129
  });
130
}
131

132
static bool request_hide(const clap_host_t* host)
1 ✔
133
{
134
  return on_window(host, [](Clap::Window& window) {
2 ✔
135
    window.hide();
1 ✔
136
    return true;
1 ✔
137
  });
138
}
139

140
static void closed(const clap_host_t* host, bool was_destroyed)
×
141
{
142
  // The editor destroyed its GUI: closing the window destroys it on our side
143
  on_window(host, [was_destroyed](Clap::Window& window) {
×
144
    if(was_destroyed)
×
145
      window.close();
×
146
    return true;
×
147
  });
148
}
×
149

150
static std::atomic<uint32_t> g_next_timer_id{};
151
bool register_timer(const clap_host_t* host, uint32_t period_ms, clap_id* timer_id)
×
152
{
153
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
154
  if(!m.model)
×
155
    return false;
×
156

157
  auto tm = new QTimer{};
×
158
  tm->setInterval(period_ms);
×
159
  *timer_id = g_next_timer_id.fetch_add(1, std::memory_order_relaxed);
×
160
  QObject::connect(
×
161
      tm, &QTimer::timeout, m.model,
×
162
      [h = std::weak_ptr{m.model->handle()}, tid = *timer_id] {
×
163
    if(auto hh = h.lock())
×
164
      if(auto t = hh->ext_timer_support)
×
165
        t->on_timer(hh->plugin, tid);
×
166
  });
×
167
  m.model->timers.push_back({*timer_id, tm});
×
168
  tm->start();
×
169
  return true;
×
170
}
×
171

172
// Returns true on success.
173
// [main-thread]
174
bool unregister_timer(const clap_host_t* host, clap_id timer_id)
×
175
{
176
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
177
  if(!m.model)
×
178
    return false;
×
179
  for(auto it = m.model->timers.begin(); it != m.model->timers.end(); ++it)
×
180
  {
181
    if(it->first == timer_id)
×
182
    {
183
      delete it->second;
×
184
      m.model->timers.erase(it);
×
185
      return true;
×
186
    }
187
  }
×
188
  return false;
×
189
}
×
190

191
// POSIX fd support host extension
192
bool register_fd(const clap_host_t* host, int fd, clap_posix_fd_flags_t flags)
×
193
{
194
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
195
  if(!m.model)
×
196
    return false;
×
197

198
  // Check if fd is already registered
199
  auto it = m.model->fd_notifiers.find(fd);
×
200
  if(it != m.model->fd_notifiers.end())
×
201
  {
202
    qWarning() << "CLAP: Attempted to register already registered fd" << fd;
×
203
    return false;
×
204
  }
205

206
  // Create notifier structure
207
  auto notifiers = std::make_unique<Model::FdNotifiers>();
×
208

209
  // Set up read notifier
210
  if(flags & CLAP_POSIX_FD_READ)
×
211
  {
212
    notifiers->read = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Read);
×
213
    QObject::connect(
×
214
        notifiers->read.get(), &QSocketNotifier::activated, m.model,
×
215
        [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
216
      if(auto h = handle.lock())
×
217
        if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
218
               h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
219
        {
220
          plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_READ);
×
221
        }
×
222
    });
×
223
    notifiers->read->setEnabled(true);
×
224
  }
×
225

226
  // Set up write notifier
227
  if(flags & CLAP_POSIX_FD_WRITE)
×
228
  {
229
    notifiers->write = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Write);
×
230
    QObject::connect(
×
231
        notifiers->write.get(), &QSocketNotifier::activated, m.model,
×
232
        [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
233
      if(auto h = handle.lock())
×
234
        if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
235
               h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
236
        {
237
          plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_WRITE);
×
238
        }
×
239
    });
×
240
    notifiers->write->setEnabled(true);
×
241
  }
×
242

243
  // Set up error/exception notifier
244
  if(flags & CLAP_POSIX_FD_ERROR)
×
245
  {
246
    notifiers->error = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Exception);
×
247
    QObject::connect(
×
248
        notifiers->error.get(), &QSocketNotifier::activated, m.model,
×
249
        [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
250
      if(auto h = handle.lock())
×
251
        if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
252
               h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
253
        {
254
          plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_ERROR);
×
255
        }
×
256
    });
×
257
    notifiers->error->setEnabled(true);
×
258
  }
×
259

260
  // Store the notifiers
261
  m.model->fd_notifiers[fd] = std::move(notifiers);
×
262
  return true;
×
263
}
×
264

265
bool modify_fd(const clap_host_t* host, int fd, clap_posix_fd_flags_t flags)
×
266
{
267
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
268
  if(!m.model)
×
269
    return false;
×
270

271
  auto it = m.model->fd_notifiers.find(fd);
×
272
  if(it == m.model->fd_notifiers.end())
×
273
  {
274
    qWarning() << "CLAP: Attempted to modify unregistered fd" << fd;
×
275
    return false;
×
276
  }
277

278
  auto& notifiers = it->second;
×
279

280
  // Update read notifier
281
  if(flags & CLAP_POSIX_FD_READ)
×
282
  {
283
    if(!notifiers->read)
×
284
    {
285
      notifiers->read = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Read);
×
286
      QObject::connect(
×
287
          notifiers->read.get(), &QSocketNotifier::activated, m.model,
×
288
          [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
289
        if(auto h = handle.lock())
×
290
          if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
291
                 h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
292
          {
293
            plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_READ);
×
294
          }
×
295
      });
×
296
    }
×
297
    notifiers->read->setEnabled(true);
×
298
  }
×
299
  else if(notifiers->read)
×
300
  {
301
    notifiers->read->setEnabled(false);
×
302
  }
×
303

304
  // Update write notifier
305
  if(flags & CLAP_POSIX_FD_WRITE)
×
306
  {
307
    if(!notifiers->write)
×
308
    {
309
      notifiers->write = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Write);
×
310
      QObject::connect(
×
311
          notifiers->write.get(), &QSocketNotifier::activated, m.model,
×
312
          [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
313
        if(auto h = handle.lock())
×
314
          if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
315
                 h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
316
          {
317
            plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_WRITE);
×
318
          }
×
319
      });
×
320
    }
×
321
    notifiers->write->setEnabled(true);
×
322
  }
×
323
  else if(notifiers->write)
×
324
  {
325
    notifiers->write->setEnabled(false);
×
326
  }
×
327

328
  // Update error notifier
329
  if(flags & CLAP_POSIX_FD_ERROR)
×
330
  {
331
    if(!notifiers->error)
×
332
    {
333
      notifiers->error
×
334
          = std::make_unique<QSocketNotifier>(fd, QSocketNotifier::Exception);
×
335
      QObject::connect(
×
336
          notifiers->error.get(), &QSocketNotifier::activated, m.model,
×
337
          [handle = std::weak_ptr{m.model->handle()}, fd]() {
×
338
        if(auto h = handle.lock())
×
339
          if(auto* plugin_fd_ext = static_cast<const clap_plugin_posix_fd_support_t*>(
×
340
                 h->plugin->get_extension(h->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
×
341
          {
342
            plugin_fd_ext->on_fd(h->plugin, fd, CLAP_POSIX_FD_ERROR);
×
343
          }
×
344
      });
×
345
    }
×
346
    notifiers->error->setEnabled(true);
×
347
  }
×
348
  else if(notifiers->error)
×
349
  {
350
    notifiers->error->setEnabled(false);
×
351
  }
×
352

353
  return true;
×
354
}
×
355

356
bool unregister_fd(const clap_host_t* host, int fd)
×
357
{
358
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
359
  if(!m.model)
×
360
    return false;
×
361

362
  auto it = m.model->fd_notifiers.find(fd);
×
363
  if(it == m.model->fd_notifiers.end())
×
364
  {
365
    qWarning() << "CLAP: Attempted to unregister unregistered fd" << fd;
×
366
    return false;
×
367
  }
368

369
  // QSocketNotifier objects will be automatically destroyed by unique_ptr
370
  m.model->fd_notifiers.erase(it);
×
371
  return true;
×
372
}
×
373

374
static QByteArray readCLAPState(const clap_plugin_t& plugin)
13 ✔
375
{
376
  QByteArray dat;
13 ✔
377

378
  // Get state extension
379
  auto state = (const clap_plugin_state_t*)plugin.get_extension(&plugin, CLAP_EXT_STATE);
13 !
380
  if(!state)
13 !
381
    return dat;
×
382

383
  // Create a stream to capture the state
384
  struct stream_context
385
  {
386
    QByteArray* data;
387
  };
388

389
  stream_context ctx{&dat};
13 ✔
390

391
  clap_ostream_t stream{};
13 ✔
392
  stream.ctx = &ctx;
13 ✔
393
  stream.write
13 ✔
394
      = [](const clap_ostream_t* stream, const void* buffer, uint64_t size) -> int64_t {
39 ✔
395
    auto* ctx = static_cast<stream_context*>(stream->ctx);
13 ✔
396
    auto old_size = ctx->data->size();
13 ✔
397
    ctx->data->resize(old_size + size);
13 ✔
398
    std::memcpy(ctx->data->data() + old_size, buffer, size);
13 ✔
399
    return size;
13 ✔
400
  };
401

402
  // Save plugin state
403
  if(!state->save(&plugin, &stream))
13 !
404
    dat.clear();
×
405

406
  return dat;
13 ✔
407
}
13 ✔
408
}
409

410
static constexpr clap_host_timer_support_t host_timer_ext
411
    = {.register_timer = register_timer, .unregister_timer = unregister_timer};
412

413
static constexpr clap_host_posix_fd_support_t host_posix_fd_ext = {
414
    .register_fd = register_fd, .modify_fd = modify_fd, .unregister_fd = unregister_fd};
415

416
static constexpr clap_host_state_t host_state_ext
417
    = {.mark_dirty = [](const clap_host_t* host) {
×
418
  // [main-thread] per CLAP spec. The plug-in says its state changed
419
  // (typically because the user manipulated its own UI). Forward to the
420
  // model, which debounces and snapshots. Plug-ins are known to spam
421
  // this — Vital fires it multiple times per knob movement — so the
422
  // debounce is mandatory.
423
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
424
  if(!m.model)
×
425
    return;
×
426
  m.model->markStateDirty();
×
427
}};
×
428
static constexpr clap_host_params_t host_params_ext
429
    = {.rescan = [](const clap_host_t* host, clap_param_rescan_flags flags) {
14 ✔
430
  // Spec: [main-thread]. Defer — plug-ins may call from state.load().
431
  if(!host || !host->host_data)
14 !
432
    return;
×
433
  auto& h = *static_cast<Clap::PluginHandle*>(host->host_data);
14 ✔
434
  if(!h.model)
14 !
435
    return;
×
436
  QMetaObject::invokeMethod(h.model, [model = QPointer<Model>{h.model}, flags] {
28 !
437
    if(model)
14 !
438
      model->onParamRescan(flags);
14 ✔
439
  }, Qt::AutoConnection);
14 ✔
440
}, .clear = [](const clap_host_t* host, clap_id param_id, clap_param_clear_flags flags) {
14 ✔
441
  // TODO
442
  //  qDebug(Q_FUNC_INFO);
443
}, .request_flush = [](const clap_host_t* host) {
×
444
  //  qDebug(Q_FUNC_INFO);
445
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
446
  if(!m.model)
×
447
    return;
×
448

449
  // Per CLAP spec, request_flush is [thread-safe, !audio-thread] and the host
450
  // must SCHEDULE a call to flush() — not invoke it inline. Plugins sometimes
451
  // call request_flush from inside their own state.load() / flush() / GUI
452
  // event handler, so calling flushFromPluginToHost synchronously here could
453
  // reenter clap_plugin_params.flush().
454
  QMetaObject::invokeMethod(m.model, [model = QPointer<Model>{m.model}] {
×
455
    if(model && !model->executing())
×
456
      model->flushFromPluginToHost();
×
457
  }, Qt::QueuedConnection);
×
458
}};
×
459

460
static constexpr clap_host_gui_t host_gui_ext
461
    = {.resize_hints_changed = resize_hints_changed,
462
       .request_resize = request_resize,
463
       .request_show = request_show,
464
       .request_hide = request_hide,
465
       .closed = closed};
466

467
// [main-thread] — plug-in queries the enclosing track's name/colour. We
468
// look up the closest parent interval and report its metadata. This is
469
// what AIDA-X et al. show in the title bar.
470
static constexpr clap_host_track_info_t host_track_info_ext
471
    = {.get = [](const clap_host_t* host, clap_track_info_t* info) -> bool {
×
472
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
473
  if(!m.model || !info)
×
474
    return false;
×
475
  auto* parent = Scenario::closestParentInterval(m.model);
×
476
  if(!parent)
×
477
    return false;
×
478
  info->flags = CLAP_TRACK_INFO_HAS_TRACK_NAME | CLAP_TRACK_INFO_HAS_TRACK_COLOR;
×
479
  auto& meta = parent->metadata();
×
480
  std::string name;
×
481
  if(!meta.getLabel().isEmpty())
×
482
    name = meta.getLabel().toStdString();
×
483
  else if(!meta.getName().isEmpty())
×
484
    name = meta.getName().toStdString();
×
485

486
  std::strncpy(info->name, name.c_str(), CLAP_NAME_SIZE - 1);
×
487
  if(name.size() < CLAP_NAME_SIZE)
×
488
    info->name[name.size()] = 0;
×
489
  else
490
    info->name[CLAP_NAME_SIZE - 1] = 0;
×
491

492
  QRgb col = meta.getColor().getBrush().color().rgba();
×
493
  info->color = clap_color_t{
×
494
      .alpha = (uint8_t)qAlpha(col),
×
495
      .red = (uint8_t)qRed(col),
×
496
      .green = (uint8_t)qGreen(col),
×
497
      .blue = (uint8_t)qBlue(col)};
×
498
  return true;
×
499
}};
×
500

501
static constexpr clap_host_event_registry_t host_event_registry_ext
502
    = {.query = [](const clap_host_t* host, const char* space_name,
×
503
                   uint16_t* space_id) -> bool {
504
  *space_id = UINT16_MAX;
×
505
  return false;
×
506
}};
507

508
static constexpr clap_host_latency_t host_latency_ext
509
    = {.changed = [](const clap_host_t* host) {
×
510
  // TODO
511
}};
×
512

513
static constexpr clap_host_log_t host_log_ext
514
    = {.log = [](const clap_host_t* host, clap_log_severity severity, const char* msg) {
×
515
  switch(severity)
×
516
  {
517
    case CLAP_LOG_DEBUG:
518
      qDebug() << msg;
×
519
      break;
×
520
    case CLAP_LOG_INFO:
521
      qInfo() << msg;
×
522
      break;
×
523
    case CLAP_LOG_WARNING:
524
      qWarning() << msg;
×
525
      break;
×
526
    case CLAP_LOG_HOST_MISBEHAVING:
527
    case CLAP_LOG_PLUGIN_MISBEHAVING:
528
    case CLAP_LOG_ERROR:
529
      qCritical() << msg;
×
530
      break;
×
531
    case CLAP_LOG_FATAL:
532
      qFatal("%s", msg);
×
533
      break;
534
  }
535
}};
×
536

537
static constexpr clap_host_note_name_t host_note_name_ext
538
    = {.changed = [](const clap_host_t* host) {
×
539
  // TODO
540
}};
×
541

542
static constexpr clap_host_preset_load_t host_preset_load_ext
543
    = {.on_error =
544
           [](const clap_host_t* host, uint32_t location_kind, const char* location,
×
545
              const char* load_key, int32_t os_error, const char* msg) {
546
  qWarning() << "CLAP preset load error:" << (msg ? msg : "Unknown error")
×
547
             << "Location:" << (location ? location : "null")  
×
548
             << "Load key:" << (load_key ? load_key : "null")
×
549
             << "OS error:" << os_error;
×
550
},
×
551
       .loaded = [](const clap_host_t* host, uint32_t location_kind,
×
552
                    const char* location, const char* load_key) {
553
  qDebug() << "CLAP preset loaded successfully:"
×
554
           << "Location:" << (location ? location : "null")
×
555
           << "Load key:" << (load_key ? load_key : "null");
×
556
}};
×
557

558
static constexpr clap_host_remote_controls_t host_remote_control_ext
559
    = {.changed = [](const clap_host_t* host) {
×
560
  // qDebug(Q_FUNC_INFO);
561
  // TODO
562
}, .suggest_page = [](const clap_host_t* host, clap_id page_id) {
×
563
  //  qDebug(Q_FUNC_INFO);
564
  // TODO
565
}};
×
566

567
static constexpr clap_host_tail_t host_tail_ext
568
    = {.changed = [](const clap_host_t* host) {
×
569
  //   qDebug(Q_FUNC_INFO);
570
  // TODO
571
}};
×
572

573
static constexpr clap_host_thread_check_t host_thread_check_ext = {
574
    .is_main_thread = [](const clap_host_t* host) -> bool {
239 ✔
575
  return ossia::get_current_thread_type() == ossia::thread_type::Ui;
239 ✔
576
},
577
    .is_audio_thread = [](const clap_host_t* host) -> bool {
×
578
  // The shared task pool pins its workers as AudioTask; they run plug-in
579
  // process() / thread-pool exec() under the audio thread's umbrella, so both
580
  // count as "the audio thread" for the plug-in (matches ensure_current_thread_kind).
581
  const auto t = ossia::get_current_thread_type();
×
582
  return t == ossia::thread_type::Audio || t == ossia::thread_type::AudioTask;
×
583
},
584
};
585

586
static constexpr clap_host_thread_pool host_thread_pool_ext
587
    = {.request_exec = [](const clap_host_t* host, uint32_t num_tasks) -> bool {
×
588
  if(!host || !host->host_data)
×
589
    return false;
×
590
  auto& h = *static_cast<PluginHandle*>(host->host_data);
×
591
  if(!h.plugin)
×
592
    return false;
×
593
  auto ext = static_cast<const clap_plugin_thread_pool_t*>(
×
594
      h.plugin->get_extension(h.plugin, CLAP_EXT_THREAD_POOL));
×
595
  if(!ext || !ext->exec)
×
596
    return false;
×
597
  if(num_tasks == 0)
×
598
    return false;
×
599

600
  // Synchronous fork-join on the shared realtime pool: workers are RT-pinned
601
  // AudioTask threads, the calling (audio) thread participates, and nothing is
602
  // allocated here. exec() is C ABI but some plug-ins are C++ inside, so guard
603
  // against an escaping exception terminating the audio thread.
604
  const clap_plugin_t* plugin = h.plugin;
×
605
  ossia::task_pool::instance().fork_n(
×
606
      static_cast<int>(num_tasks), [plugin, ext](int i) noexcept {
×
607
    try
608
    {
609
      ext->exec(plugin, static_cast<uint32_t>(i));
×
610
    }
×
611
    catch(...)
612
    {
613
    }
×
614
  });
×
615
  return true;
×
616
}};
×
617

618
static constexpr clap_host_voice_info_t host_voice_info_ext
619
    = {.changed = [](const clap_host_t* host) {
×
620
  //   qDebug(Q_FUNC_INFO);
621
  // TODO
622
}};
×
623

624
// Context menu builder implementation
625
struct context_menu_builder_impl
626
{
627
  QMenu* menu;
628
  QMenu* root_menu;
629
  const clap_plugin_t* plugin;
630
  const clap_plugin_context_menu_t* plugin_context_menu;
631
  const clap_context_menu_target_t* target;
632

633
  context_menu_builder_impl(
×
634
      QMenu* m, const clap_plugin_t* p, const clap_plugin_context_menu_t* pcm,
635
      const clap_context_menu_target_t* t)
636
      : menu(m)
×
637
      , root_menu(m)
×
638
      , plugin(p)
×
639
      , plugin_context_menu(pcm)
×
640
      , target(t)
×
641
  {
642
  }
×
643
};
644

645
static bool context_menu_add_item(
×
646
    const clap_context_menu_builder_t* builder, clap_context_menu_item_kind_t item_kind,
647
    const void* item_data)
648
{
649
  auto* impl = static_cast<context_menu_builder_impl*>(builder->ctx);
×
650
  if(!impl || !impl->menu)
×
651
    return false;
×
652

653
  switch(item_kind)
×
654
  {
655
    case CLAP_CONTEXT_MENU_ITEM_ENTRY: {
656
      auto* entry = static_cast<const clap_context_menu_entry_t*>(item_data);
×
657
      auto* action = impl->menu->addAction(QString::fromUtf8(entry->label));
×
658
      action->setEnabled(entry->is_enabled);
×
659

660
      clap_id action_id = entry->action_id;
×
661
      QObject::connect(action, &QAction::triggered, [action_id, builder]() {
×
662
        auto* impl = static_cast<context_menu_builder_impl*>(builder->ctx);
×
663
        if(impl && impl->plugin_context_menu)
×
664
        {
665
          impl->plugin_context_menu->perform(impl->plugin, impl->target, action_id);
×
666
        }
×
667
      });
×
668
      return true;
×
669
    }
670

671
    case CLAP_CONTEXT_MENU_ITEM_CHECK_ENTRY: {
672
      auto* entry = static_cast<const clap_context_menu_check_entry_t*>(item_data);
×
673
      auto* action = impl->menu->addAction(QString::fromUtf8(entry->label));
×
674
      action->setEnabled(entry->is_enabled);
×
675
      action->setCheckable(true);
×
676
      action->setChecked(entry->is_checked);
×
677

678
      clap_id action_id = entry->action_id;
×
679
      QObject::connect(action, &QAction::triggered, [action_id, builder]() {
×
680
        auto* impl = static_cast<context_menu_builder_impl*>(builder->ctx);
×
681
        if(impl && impl->plugin_context_menu)
×
682
        {
683
          impl->plugin_context_menu->perform(impl->plugin, impl->target, action_id);
×
684
        }
×
685
      });
×
686
      return true;
×
687
    }
688

689
    case CLAP_CONTEXT_MENU_ITEM_SEPARATOR: {
690
      impl->menu->addSeparator();
×
691
      return true;
×
692
    }
693

694
    case CLAP_CONTEXT_MENU_ITEM_BEGIN_SUBMENU: {
695
      auto* submenu_data = static_cast<const clap_context_menu_submenu_t*>(item_data);
×
696
      auto* submenu = impl->menu->addMenu(QString::fromUtf8(submenu_data->label));
×
697
      submenu->setEnabled(submenu_data->is_enabled);
×
698
      impl->menu = submenu; // Switch context to submenu
×
699
      return true;
×
700
    }
701

702
    case CLAP_CONTEXT_MENU_ITEM_END_SUBMENU: {
703
      // Switch back to parent menu
704
      if(impl->menu != impl->root_menu)
×
705
      {
706
        // Find parent menu by traversing up the object hierarchy
707
        QObject* parent = impl->menu->parent();
×
708
        while(parent && !qobject_cast<QMenu*>(parent))
×
709
          parent = parent->parent();
×
710
        if(parent)
×
711
          impl->menu = static_cast<QMenu*>(parent);
×
712
        else
713
          impl->menu = impl->root_menu;
×
714
      }
×
715
      return true;
×
716
    }
717

718
    case CLAP_CONTEXT_MENU_ITEM_TITLE: {
719
      auto* title = static_cast<const clap_context_menu_item_title_t*>(item_data);
×
720
      auto* action = impl->menu->addAction(QString::fromUtf8(title->title));
×
721
      action->setEnabled(false); // Titles are not clickable
×
722
      auto font = action->font();
×
723
      font.setBold(true);
×
724
      action->setFont(font);
×
725
      return true;
×
726
    }
×
727
  }
728
  return false;
×
729
}
×
730

731
static bool context_menu_supports(
×
732
    const clap_context_menu_builder_t* builder, clap_context_menu_item_kind_t item_kind)
733
{
734
  // We support all standard context menu item types
735
  return item_kind == CLAP_CONTEXT_MENU_ITEM_ENTRY
×
736
         || item_kind == CLAP_CONTEXT_MENU_ITEM_CHECK_ENTRY
×
737
         || item_kind == CLAP_CONTEXT_MENU_ITEM_SEPARATOR
×
738
         || item_kind == CLAP_CONTEXT_MENU_ITEM_BEGIN_SUBMENU
×
739
         || item_kind == CLAP_CONTEXT_MENU_ITEM_END_SUBMENU
×
740
         || item_kind == CLAP_CONTEXT_MENU_ITEM_TITLE;
×
741
}
742

743
static constexpr clap_host_context_menu_t host_context_menu_ext = {
744
    .populate = [](const clap_host_t* host, const clap_context_menu_target_t* target,
×
745
                   const clap_context_menu_builder_t* builder) -> bool { return true; },
×
746

747
    .perform = [](const clap_host_t* host, const clap_context_menu_target_t* target,
×
748
                  clap_id action_id) -> bool { return false; },
×
749

750
    .can_popup = [](const clap_host_t* host) -> bool { return true; },
×
751

752
    .popup = [](const clap_host_t* host, const clap_context_menu_target_t* target,
×
753
                int32_t screen_index, int32_t x, int32_t y) -> bool {
754
  auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
755
  if(!m.model)
×
756
    return false;
×
757
  auto& model = *m.model;
×
758
  // Get the plugin's context menu extension
759
  auto* plugin_context_menu = static_cast<const clap_plugin_context_menu_t*>(
×
760
      m.plugin->get_extension(m.plugin, CLAP_EXT_CONTEXT_MENU));
×
761

762
  if(!plugin_context_menu)
×
763
    return false;
×
764

765
  // Create a QMenu
766
  auto menu = std::make_unique<QMenu>();
×
767

768
  // Create builder context
769
  context_menu_builder_impl builder_ctx(
×
770
      menu.get(), m.plugin, plugin_context_menu, target);
×
771
  clap_context_menu_builder_t builder
772
      = {.ctx = &builder_ctx,
×
773
         .add_item = context_menu_add_item,
774
         .supports = context_menu_supports};
775

776
  // Let the plugin populate the menu
777
  if(!plugin_context_menu->populate(m.plugin, target, &builder))
×
778
    return false;
×
779

780
  // Show the menu at the specified position
781
  QPoint pos(x, y);
×
782
  menu->exec(pos);
×
783

784
  return true;
×
785
}};
×
786

787
PluginHandle::PluginHandle()
70 ✔
788
{
789
  host.clap_version = CLAP_VERSION;
35 ✔
790
  host.name = "ossia score";
35 ✔
791
  host.vendor = "ossia.io";
35 ✔
792
  host.url = "https://ossia.io";
35 ✔
793
  host.version = SCORE_TAG_NO_V;
35 ✔
794
  host.get_extension
35 ✔
795
      = [](const clap_host* host, const char* extension_id) -> const void* {
238 ✔
796
    if(strcmp(extension_id, CLAP_EXT_GUI) == 0)
168 ✔
797
      return &host_gui_ext;
1 ✔
798
    if(strcmp(extension_id, CLAP_EXT_STATE) == 0)
167 !
799
      return &host_state_ext;
×
800
    if(strcmp(extension_id, CLAP_EXT_PARAMS) == 0)
167 ✔
801
      return &host_params_ext;
26 ✔
802
    if(strcmp(extension_id, CLAP_EXT_TIMER_SUPPORT) == 0)
141 !
803
      return &host_timer_ext;
×
804
    if(strcmp(extension_id, CLAP_EXT_POSIX_FD_SUPPORT) == 0)
141 !
805
      return &host_posix_fd_ext;
×
806
    if(strcmp(extension_id, CLAP_EXT_TRACK_INFO) == 0)
141 !
807
      return &host_track_info_ext;
×
808
    if(strcmp(extension_id, "clap.track-info.draft/1") == 0)
141 !
809
      return &host_track_info_ext;
×
810
    if(strcmp(extension_id, CLAP_EXT_EVENT_REGISTRY) == 0)
141 !
811
      return &host_event_registry_ext;
×
812
    if(strcmp(extension_id, CLAP_EXT_LOG) == 0)
141 !
813
      return &host_log_ext;
×
814
    if(strcmp(extension_id, CLAP_EXT_LATENCY) == 0)
141 !
815
      return &host_latency_ext;
×
816
    if(strcmp(extension_id, CLAP_EXT_NOTE_NAME) == 0)
141 !
817
      return &host_note_name_ext;
×
818
    if(strcmp(extension_id, CLAP_EXT_PRESET_LOAD) == 0)
141 !
819
      return &host_preset_load_ext;
×
820
    if(strcmp(extension_id, "clap.preset-load.draft/2") == 0)
141 !
821
      return &host_preset_load_ext;
×
822
    if(strcmp(extension_id, CLAP_EXT_REMOTE_CONTROLS) == 0)
141 !
823
      return &host_remote_control_ext;
×
824
    if(strcmp(extension_id, "clap.remote-controls.draft/2") == 0)
141 !
825
      return &host_remote_control_ext;
×
826
    if(strcmp(extension_id, CLAP_EXT_TAIL) == 0)
141 !
827
      return &host_tail_ext;
×
828
    if(strcmp(extension_id, CLAP_EXT_THREAD_CHECK) == 0)
141 !
829
      return &host_thread_check_ext;
141 ✔
830
    if(strcmp(extension_id, CLAP_EXT_THREAD_POOL) == 0)
×
831
      return &host_thread_pool_ext;
×
832
    if(strcmp(extension_id, CLAP_EXT_VOICE_INFO) == 0)
×
833
      return &host_voice_info_ext;
×
834
    if(strcmp(extension_id, CLAP_EXT_CONTEXT_MENU) == 0)
×
835
      return &host_context_menu_ext;
×
836
    if(strcmp(extension_id, "clap.context-menu.draft/0") == 0)
×
837
      return &host_context_menu_ext;
×
838
    return nullptr;
×
839
  };
168 ✔
840
  host.request_restart = [](const clap_host* host) {
35 ✔
841
    // Per clap/host.h: deactivate then reactivate the plug-in. This is
842
    // [thread-safe] but the actual deactivate/activate must run on the
843
    // main thread. We refuse to do the cycle while score is executing —
844
    // a live audio thread is using the plug-in in CLAP-active state, and
845
    // tearing it down underneath would race with process(). The plug-in
846
    // sees the request as deferred (per spec it may be delayed by the
847
    // host), and will get the restart on the next stop transition.
848
    auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
849
    if(!m.model)
×
850
      return;
×
851
    QMetaObject::invokeMethod(m.model, [model = QPointer<Model>{m.model}] {
×
852
      if(!model)
×
853
        return;
×
854
      if(model->executing())
×
855
        return;
×
856
      auto h = model->handle();
×
857
      if(!h || !h->plugin)
×
858
        return;
×
859

860
      const auto plug = h->plugin;
×
861
      if(h->activated)
×
862
      {
863
        plug->deactivate(plug);
×
864
        h->activated = false;
×
865
      }
×
866
      // Re-activate with the rate/buffer the executor was last using.
867
      // We don't have an audio context outside of execution, so fall
868
      // back to the standard 44.1k / 1024 frames if nothing else is
869
      // known (matches DPF's d_nextSampleRate fallback).
870
      const double sr = 44100.0;
×
871
      const uint32_t bs = 1024;
×
872
      if(plug->activate(plug, sr, 1, bs))
×
873
      {
874
        h->activated = true;
×
875
      }
×
876
    }, Qt::QueuedConnection);
×
877
  };
×
878
  host.request_process = [](const clap_host* host) {
35 ✔
879
    auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
880
    if(!m.model)
×
881
      return;
×
882
    // unused in score
883
  };
×
884
  host.request_callback = [](const clap_host* host) {
35 ✔
885
    auto& m = *static_cast<Clap::PluginHandle*>(host->host_data);
×
886
    if(!m.model)
×
887
      return;
×
888
    QMetaObject::invokeMethod(m.model, [handle = std::weak_ptr{m.model->handle()}] {
×
889
      if(auto h = handle.lock())
×
890
      {
891
        auto plug = h->plugin;
×
892
        plug->on_main_thread(plug);
×
893
      }
×
894
    }, Qt::QueuedConnection);
×
895
  };
×
896
}
35 ✔
897

898
namespace
899
{
900
// clap/entry.h: the host calls init() once and deinit() once, in a matched
901
// pair, however many plug-ins it makes from the library. One count per
902
// library, as two processes of one .clap share its entry. [main-thread]
903
ossia::hash_map<const clap_plugin_entry_t*, int>& entry_users()
68 ✔
904
{
905
  static ossia::hash_map<const clap_plugin_entry_t*, int> users;
68 !
906
  return users;
68 ✔
907
}
×
908

909
//! clap/entry.h: what init() is given is the library on Linux and Windows,
910
//! the bundle on macOS, of which score keeps the binary in Contents/MacOS
911
std::string entry_init_path(std::string_view library)
27 ✔
912
{
913
#if defined(__APPLE__)
914
  if(auto p = library.rfind(".clap/Contents/MacOS/"); p != std::string_view::npos)
915
    return std::string(library.substr(0, p + 5));
916
#endif
917
  return std::string(library);
27 !
918
}
×
919

920
bool acquire_entry(const clap_plugin_entry_t* entry, const char* path)
34 ✔
921
{
922
  auto& users = entry_users();
34 ✔
923
  if(auto it = users.find(entry); it != users.end())
34 ✔
924
  {
925
    it->second++;
7 ✔
926
    return true;
7 ✔
927
  }
928
  if(!entry->init(entry_init_path(path).c_str()))
27 !
929
    return false;
×
930
  users[entry] = 1;
27 ✔
931
  return true;
27 ✔
932
}
34 ✔
933

934
void release_entry(const clap_plugin_entry_t* entry)
34 ✔
935
{
936
  auto& users = entry_users();
34 ✔
937
  auto it = users.find(entry);
34 ✔
938
  if(it == users.end())
34 !
939
    return;
×
940
  if(--it->second == 0)
34 ✔
941
  {
942
    users.erase(it);
27 ✔
943
    entry->deinit();
27 ✔
944
  }
27 ✔
945
}
34 ✔
946
}
947

948
PluginHandle::~PluginHandle()
35 ✔
949
{
950
  if(plugin)
35 ✔
951
  {
952
    plugin->destroy(plugin);
34 !
953
    plugin = nullptr;
34 ✔
954
  }
34 ✔
955

956
  if(entry)
35 ✔
957
  {
958
    release_entry(entry);
34 !
959
    entry = nullptr;
34 ✔
960
  }
34 ✔
961

962
  if(library)
35 ✔
963
  {
964
#if defined(_WIN32)
965
    FreeLibrary((HMODULE)library);
966
#elif defined(__APPLE__)
967
    // Never unloaded: Cocoa keeps references into the image of a plug-in
968
    // that showed an editor (its Objective-C classes, in weak tables and
969
    // notification observers) past the plug-in's life. dyld ignores
970
    // RTLD_NODELETE: the handle is kept instead.
971
#else
972
    dlclose(library);
34 ✔
973
#endif
974
    library = nullptr;
34 ✔
975
  }
34 ✔
976
}
35 ✔
977

978
static void loadCLAPState(const clap_plugin_t& plugin, const QByteArray& state)
4 ✔
979
{
980
  if(state.isEmpty())
4 !
981
    return;
×
982

983
  // Get state extension
984
  auto state_ext
4 ✔
985
      = (const clap_plugin_state_t*)plugin.get_extension(&plugin, CLAP_EXT_STATE);
4 ✔
986
  if(!state_ext)
4 !
987
    return;
×
988

989
  // Create input stream
990
  struct stream_context
991
  {
992
    const QByteArray* data;
993
    int64_t position;
994
  };
995

996
  stream_context ctx{&state, 0};
4 ✔
997

998
  clap_istream_t stream{};
4 ✔
999
  stream.ctx = &ctx;
4 ✔
1000
  stream.read
4 ✔
1001
      = [](const clap_istream_t* stream, void* buffer, uint64_t size) -> int64_t {
12 ✔
1002
    auto* ctx = static_cast<stream_context*>(stream->ctx);
4 ✔
1003
    int64_t remaining = ctx->data->size() - ctx->position;
4 ✔
1004
    int64_t to_read = std::min(static_cast<int64_t>(size), remaining);
4 ✔
1005

1006
    if(to_read <= 0)
4 !
1007
      return 0;
×
1008

1009
    std::memcpy(buffer, ctx->data->constData() + ctx->position, to_read);
4 ✔
1010
    ctx->position += to_read;
4 ✔
1011
    return to_read;
4 ✔
1012
  };
4 ✔
1013

1014
  // Load plugin state
1015
  state_ext->load(&plugin, &stream);
4 ✔
1016
}
4 ✔
1017

1018
Model::Model(
31 !
1019
    const TimeVal& duration, const QString& pluginId,
1020
    const Id<Process::ProcessModel>& id, QObject* parent)
1021
    : Process::ProcessModel{duration, id, "ClapProcess", parent}
31 !
1022
    , m_plugin{std::make_shared<PluginHandle>()}
31 !
1023
{
31 ✔
1024
  // "<path>:::<id>" is what the library gives us, but a process can also be
1025
  // created before anything is chosen -- the object gallery does exactly that,
1026
  // and so does a document that lost the setting. Stay empty instead of
1027
  // aborting the application.
1028
  auto plug = pluginId.split(":::");
31 !
1029
  if(plug.size() == 2)
31 ✔
1030
  {
1031
    m_pluginPath = plug[0];
30 !
1032
    m_pluginId = plug[1];
30 !
1033
    loadPlugin();
30 !
1034
  }
30 ✔
1035
  createControls(false);
31 !
1036
}
31 ✔
1037

1038
Model::Model(DataStream::Deserializer& vis, QObject* parent)
4 !
1039
    : Process::ProcessModel{vis, parent}
2 ✔
1040
    , m_plugin{std::make_shared<PluginHandle>()}
2 !
1041
{
2 ✔
1042
  vis.writeTo(*this);
2 !
1043
  loadPlugin();
2 !
1044
  createControls(true);
2 !
1045
}
2 ✔
1046

1047
Model::Model(JSONObject::Deserializer& vis, QObject* parent)
4 !
1048
    : Process::ProcessModel{vis, parent}
2 ✔
1049
    , m_plugin{std::make_shared<PluginHandle>()}
2 !
1050
{
2 ✔
1051
  vis.writeTo(*this);
2 !
1052
  loadPlugin();
2 !
1053
  createControls(true);
2 !
1054
}
2 ✔
1055

1056
Model::Model(DataStream::Deserializer&& vis, QObject* parent)
×
1057
    : Process::ProcessModel{vis, parent}
×
1058
    , m_plugin{std::make_shared<PluginHandle>()}
×
1059
{
×
1060
  vis.writeTo(*this);
×
1061
  loadPlugin();
×
1062
  createControls(true);
×
1063
}
×
1064

1065
Model::Model(JSONObject::Deserializer&& vis, QObject* parent)
×
1066
    : Process::ProcessModel{vis, parent}
×
1067
    , m_plugin{std::make_shared<PluginHandle>()}
×
1068
{
×
1069
  vis.writeTo(*this);
×
1070
  loadPlugin();
×
1071
  createControls(true);
×
1072
}
×
1073

1074
Model::~Model()
70 ✔
1075
{
35 ✔
1076
  closeUI();
35 !
1077

1078
  if(m_plugin->plugin && m_plugin->activated)
35 ✔
1079
  {
1080
    m_plugin->plugin->deactivate(m_plugin->plugin);
1 !
1081
    m_plugin->activated = false;
1 ✔
1082
  }
1 ✔
1083

1084
  // Clean up timers
1085
  for(auto& [id, timer] : timers)
35 !
1086
  {
1087
    delete timer;
×
1088
  }
1089
  timers.clear();
35 ✔
1090

1091
  // Clean up fd notifiers (automatically handled by unique_ptr destructors)
1092
  fd_notifiers.clear();
35 !
1093
}
70 ✔
1094

1095
bool Model::hasExternalUI() const noexcept
56 ✔
1096
{
1097
  if(!m_plugin->plugin)
56 ✔
1098
    return false;
2 ✔
1099

1100
  auto gui = (const clap_plugin_gui_t*)m_plugin->plugin->get_extension(
108 !
1101
      m_plugin->plugin, CLAP_EXT_GUI);
54 ✔
1102
  return gui != nullptr;
54 ✔
1103
}
56 ✔
1104

1105
void Model::closeUI() const
35 ✔
1106
{
1107
  if(this->externalUI)
35 !
1108
    this->externalUI->close();
×
1109
}
35 ✔
1110

1111
void PluginHandle::load(Model& context, QByteArray path, QByteArray id)
34 ✔
1112
{
1113
  this->model = &context;
34 ✔
1114

1115
  // Helper to roll back partial-load state. CLAP entry init/deinit is
1116
  // refcounted (see clap/entry.h): we must NOT call deinit unless init
1117
  // returned true, otherwise we corrupt the refcount and eventually crash
1118
  // other plug-ins that share the .clap bundle. Same idea for
1119
  // dlclose(library) — only meaningful if dlopen succeeded.
1120
  auto rollback = [this](bool entry_inited) {
34 ✔
1121
    if(!entry_inited)
×
1122
      entry = nullptr;
×
1123
    if(!library)
×
1124
      return;
×
1125
    // If we never reached entry->init() successfully, don't deinit; just
1126
    // release the library handle so ~PluginHandle doesn't redo it.
1127
  };
×
1128

1129
  // Load the library
1130
#if defined(_WIN32)
1131
  library = LoadLibraryA(path.data());
1132
  if(!library)
1133
    return;
1134
  entry = (const clap_plugin_entry_t*)GetProcAddress((HMODULE)library, "clap_entry");
1135
#else
1136
  library = dlopen(path.data(), RTLD_LAZY);
34 ✔
1137
  if(!library)
34 !
1138
    return;
×
1139
  entry = (const clap_plugin_entry_t*)dlsym(library, "clap_entry");
34 ✔
1140
#endif
1141

1142
  if(!entry)
34 !
1143
  {
1144
    // No clap_entry symbol — drop the library handle and bail.
1145
    rollback(false);
×
1146
    return;
×
1147
  }
1148

1149
  if(!acquire_entry(entry, path.data()))
34 !
1150
  {
1151
    // init() failed: entry pointer is valid but the DSO is uninitialized,
1152
    // so we must NOT call entry->deinit() later. Forget the entry pointer
1153
    // so ~PluginHandle's `if(entry) entry->deinit();` is skipped.
1154
    rollback(false);
×
1155
    return;
×
1156
  }
1157

1158
  factory = (const clap_plugin_factory_t*)entry->get_factory(CLAP_PLUGIN_FACTORY_ID);
34 ✔
1159
  if(!factory)
34 !
1160
    return;
×
1161

1162
  host.host_data = this;
34 ✔
1163
  plugin = factory->create_plugin(factory, &host, id.data());
34 ✔
1164
  if(!plugin)
34 !
1165
    return;
×
1166

1167
  if(!plugin->init(plugin))
34 !
1168
  {
1169
    plugin->destroy(plugin);
×
1170
    plugin = nullptr;
×
1171
    return;
×
1172
  }
1173

1174
  // Juce calls it during init??
1175
  ext_timer_support = (const clap_plugin_timer_support_t*)plugin->get_extension(
68 ✔
1176
      plugin, CLAP_EXT_TIMER_SUPPORT);
34 ✔
1177
  ext_params
34 ✔
1178
      = (const clap_plugin_params_t*)plugin->get_extension(plugin, CLAP_EXT_PARAMS);
68 ✔
1179

1180
  desc = plugin->desc;
34 ✔
1181
}
34 ✔
1182

1183
void Model::loadPlugin()
34 ✔
1184
{
1185
  if(m_pluginPath.isEmpty() || m_pluginId.isEmpty())
34 !
1186
    return;
×
1187

1188
  m_plugin->load(*this, m_pluginPath.toUtf8(), m_pluginId.toUtf8());
34 !
1189

1190
  if(m_plugin->plugin && !m_loadedState.isEmpty())
34 !
1191
  {
1192
    loadCLAPState(*m_plugin->plugin, m_loadedState);
4 ✔
1193
  }
4 ✔
1194

1195
  m_plugin->activated = false;
34 ✔
1196

1197
  // Connect parameter value feedback from executor to GUI
1198
  if(auto params = m_plugin->ext_params)
34 ✔
1199
  {
1200
    auto& ctx = score::IDocument::documentContext(*this);
26 ✔
1201
    auto c = connect(&ctx.coarseUpdateTimer, &QTimer::timeout, this, [this] {
42 ✔
1202
      auto h = handle();
16 ✔
1203
      if(!h)
16 !
1204
        return;
×
1205
      auto plugin = h->plugin;
16 ✔
1206
      if(!plugin)
16 !
1207
        return;
×
1208
      auto params = m_plugin->ext_params;
16 ✔
1209
      if(!params || !params->get_value)
16 !
1210
        return;
×
1211

1212
      // Writable params -> ControlInlets.
1213
      std::size_t inlet_idx = 0;
16 ✔
1214
      for(auto* inlet : inlets())
51 ✔
1215
      {
1216
        if(auto* control = qobject_cast<Process::ControlInlet*>(inlet))
35 !
1217
        {
1218
          if(inlet_idx < m_plugin->m_parameters_ins.size())
19 !
1219
          {
1220
            const auto& param_info = m_plugin->m_parameters_ins[inlet_idx];
19 ✔
1221
            double current_value = 0.0;
19 ✔
1222
            if(params->get_value(plugin, param_info.id, &current_value))
19 !
1223
            {
1224
              currentlyReadingValues = true;
19 ✔
1225
              control->setValue(current_value);
19 !
1226
              currentlyReadingValues = false;
19 ✔
1227
            }
19 ✔
1228
          }
19 ✔
1229
          inlet_idx++;
19 ✔
1230
        }
19 ✔
1231
      }
1232

1233
      // Read-only params -> ControlOutlets (Bargraph meters etc.).
1234
      std::size_t outlet_idx = 0;
16 ✔
1235
      for(auto* outlet : outlets())
47 ✔
1236
      {
1237
        if(auto* control = qobject_cast<Process::ControlOutlet*>(outlet))
31 !
1238
        {
1239
          if(outlet_idx < m_plugin->m_parameters_outs.size())
15 !
1240
          {
1241
            const auto& param_info = m_plugin->m_parameters_outs[outlet_idx];
15 ✔
1242
            double current_value = 0.0;
15 ✔
1243
            if(params->get_value(plugin, param_info.id, &current_value))
15 !
1244
            {
1245
              currentlyReadingValues = true;
15 ✔
1246
              control->setValue(current_value);
15 !
1247
              currentlyReadingValues = false;
15 ✔
1248
            }
15 ✔
1249
          }
15 ✔
1250
          outlet_idx++;
15 ✔
1251
        }
15 ✔
1252
      }
1253
    });
16 !
1254
  }
26 ✔
1255

1256
  // Connect the restart signal
1257
  connect(this, &Process::ProcessModel::resetExecution, this, [this] {
61 ✔
1258
    if(m_plugin->plugin && m_plugin->activated)
27 !
1259
    {
1260
      m_plugin->plugin->deactivate(m_plugin->plugin);
3 ✔
1261
      m_plugin->activated = false;
3 ✔
1262
    }
3 ✔
1263
    // Drain RESCAN_ALL deferred during execution (spec needs deactivate).
1264
    if(m_pendingRescanFlags != 0)
27 !
1265
    {
1266
      auto pending = std::exchange(m_pendingRescanFlags, 0u);
×
1267
      onParamRescan(pending);
×
1268
    }
×
1269
  }, Qt::QueuedConnection);
27 ✔
1270
}
34 ✔
1271

1272
namespace
1273
{
1274
// Build a clap_input_events_t backed by a std::vector of event pointers.
1275
struct ParamInputCtx
1276
{
1277
  std::vector<const clap_event_header_t*> events;
1278
};
1279
inline clap_input_events_t make_input_events(ParamInputCtx& ctx)
7 ✔
1280
{
1281
  return {
28 ✔
1282
      .ctx = &ctx,
7 ✔
1283
      .size = +[](const clap_input_events* list) -> uint32_t {
14 ✔
1284
    return static_cast<const ParamInputCtx*>(list->ctx)->events.size();
7 ✔
1285
  },
1286
      .get = +[](const clap_input_events* list,
14 ✔
1287
                 uint32_t index) -> const clap_event_header_t* {
1288
    auto* c = static_cast<const ParamInputCtx*>(list->ctx);
7 ✔
1289
    return index < c->events.size() ? c->events[index] : nullptr;
7 !
1290
  }};
1291
}
1292

1293
inline clap_event_param_value_t
1294
make_param_value(const clap_param_info_t& info, double value)
7 ✔
1295
{
1296
  clap_event_param_value_t ev{};
7 ✔
1297
  ev.header.size = sizeof(clap_event_param_value_t);
7 ✔
1298
  ev.header.time = 0;
7 ✔
1299
  ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
7 ✔
1300
  ev.header.type = CLAP_EVENT_PARAM_VALUE;
7 ✔
1301
  ev.header.flags = CLAP_EVENT_IS_LIVE;
7 ✔
1302
  ev.param_id = info.id;
7 ✔
1303
  ev.cookie = info.cookie;
7 ✔
1304
  ev.note_id = -1;
7 ✔
1305
  ev.port_index = -1;
7 ✔
1306
  ev.channel = -1;
7 ✔
1307
  ev.key = -1;
7 ✔
1308
  ev.value = value;
7 ✔
1309
  return ev;
7 ✔
1310
}
1311
} // namespace
1312

1313
// clap/ext/params.h: a knob turned on the host's interface is a value sent
1314
// through process() or flush(). Gestures are the plug-in telling the host its
1315
// own editor is being used: they are not sent to it.
1316
void Model::sendParamChange(const clap_param_info_t& info, double value)
7 ✔
1317
{
1318
  auto plugin = m_plugin->plugin;
7 ✔
1319
  if(!plugin)
7 !
1320
    return;
×
1321
  auto params
7 ✔
1322
      = (const clap_plugin_params_t*)plugin->get_extension(plugin, CLAP_EXT_PARAMS);
7 ✔
1323
  if(!params || !params->flush)
7 !
1324
    return;
×
1325

1326
  clap_event_param_value_t value_ev = make_param_value(info, value);
7 ✔
1327
  ParamInputCtx ctx;
7 ✔
1328
  ctx.events.push_back(&value_ev.header);
7 !
1329

1330
  clap_input_events_t ip = make_input_events(ctx);
7 !
1331
  clap_output_events_t op{
14 ✔
1332
      .ctx = this,
1333
      .try_push = [](const struct clap_output_events*,
7 ✔
1334
                     const clap_event_header_t*) { return false; }};
×
1335
  params->flush(plugin, &ip, &op);
7 !
1336
}
7 ✔
1337

1338
void Model::setupControlInlet(
72 ✔
1339
    const clap_plugin_params_t& params, const clap_param_info_t& info, int index,
1340
    Process::ControlInlet* inlet)
1341
{
1342
  inlet->displayHandledExplicitly = true; //(info.flags & CLAP_PARAM_IS_HIDDEN) != 0;
72 ✔
1343

1344
  // Set default value, min, and max for the control inlet
1345
  double val{};
72 ✔
1346
  // FIXME if we load we do not want to change the GUI inlet value, instead we
1347
  // want to reapply it to the state (so that an inlet with a LFO as input does not
1348
  // change its value randomly on every load
1349
  if(params.get_value && params.get_value(m_plugin->plugin, info.id, &val))
72 !
1350
  {
1351
    inlet->setValue(val);
72 !
1352
  }
72 ✔
1353
  else
1354
  {
1355
    inlet->setValue(info.default_value);
×
1356
  }
1357

1358
  inlet->setDomain(ossia::make_domain(info.min_value, info.max_value));
72 !
1359

1360
  connect(
72 ✔
1361
      inlet, &Process::ControlInlet::valueChanged, this,
72 ✔
1362
      [this, i = index](const ossia::value& v) {
81 ✔
1363
    if(executing())
9 !
1364
      return;
×
1365
    if(currentlyReadingValues)
9 ✔
1366
      return;
2 ✔
1367
    SCORE_ASSERT(this->parameterInputs().size() > i);
7 !
1368
    auto& param_info = this->parameterInputs()[i];
7 ✔
1369
    double val
7 ✔
1370
        = std::clamp(ossia::convert<double>(v), param_info.min_value, param_info.max_value);
7 ✔
1371
    sendParamChange(param_info, val);
7 ✔
1372
  });
9 ✔
1373
}
72 ✔
1374

1375
void Model::setupControlOutlet(
8 ✔
1376
    const clap_plugin_params_t& params, const clap_param_info_t& info, int index,
1377
    Process::ControlOutlet* port)
1378
{
1379
  port->displayHandledExplicitly = true; //(info.flags & CLAP_PARAM_IS_HIDDEN) != 0;
8 ✔
1380

1381
  // Set default value, min, and max for the control inlet
1382
  double val{};
8 ✔
1383
  // FIXME if we load we do not want to change the GUI inlet value, instead we
1384
  // want to reapply it to the state (so that an inlet with a LFO as input does not
1385
  // change its value randomly on every load
1386
  if(params.get_value && params.get_value(m_plugin->plugin, info.id, &val))
8 !
1387
  {
1388
    port->setValue(val);
8 !
1389
  }
8 ✔
1390
  else
1391
  {
1392
    port->setValue(info.default_value);
×
1393
  }
1394

1395
  port->setDomain(ossia::make_domain(info.min_value, info.max_value));
8 !
1396
}
8 ✔
1397

1398
void Model::createControls(bool loading)
35 ✔
1399
{
1400
  if(!m_plugin->plugin)
35 ✔
1401
    return;
1 ✔
1402

1403
  int cur_inlet = 0;
34 ✔
1404
  int cur_outlet = 0;
34 ✔
1405

1406
  // Get audio ports extension
1407
  auto audio_ports = (const clap_plugin_audio_ports_t*)m_plugin->plugin->get_extension(
68 ✔
1408
      m_plugin->plugin, CLAP_EXT_AUDIO_PORTS);
34 ✔
1409
  m_supports64 = true;
34 ✔
1410
  m_plugin->m_audio_ins.clear();
34 ✔
1411
  m_plugin->m_audio_outs.clear();
34 ✔
1412
  if(audio_ports)
34 ✔
1413
  {
1414
    auto input_count = audio_ports->count(m_plugin->plugin, true);
26 ✔
1415
    for(uint32_t i = 0; i < input_count; ++i)
44 ✔
1416
    {
1417
      clap_audio_port_info_t info{};
18 ✔
1418
      if(audio_ports->get(m_plugin->plugin, i, true, &info))
18 !
1419
      {
1420
        m_supports64 &= (info.flags & CLAP_AUDIO_PORT_SUPPORTS_64BITS);
18 ✔
1421

1422
        if(!loading)
18 ✔
1423
        {
1424
          QString name = clap_safe_name(
16 !
1425
              info.name, input_count == 1 ? QStringLiteral("Audio In")
16 !
1426
                                          : QStringLiteral("Audio In %1").arg(i + 1));
×
1427
          if(i == 0 && name.toLower() == "audio input")
16 !
1428
            name = "Audio In";
9 !
1429
          auto inlet = new Process::AudioInlet(
32 !
1430
              name, Id<Process::Port>(getStrongId(m_inlets)), this);
16 !
1431
          m_inlets.push_back(inlet);
16 !
1432
        }
16 ✔
1433

1434
        m_plugin->m_audio_ins.push_back(info);
18 ✔
1435
        cur_inlet++;
18 ✔
1436
      }
18 ✔
1437
    }
18 ✔
1438
    auto output_count = audio_ports->count(m_plugin->plugin, false);
26 ✔
1439
    for(uint32_t i = 0; i < output_count; ++i)
52 ✔
1440
    {
1441
      clap_audio_port_info_t info{};
26 ✔
1442
      if(audio_ports->get(m_plugin->plugin, i, false, &info))
26 !
1443
      {
1444
        m_supports64 &= (info.flags & CLAP_AUDIO_PORT_SUPPORTS_64BITS);
26 ✔
1445

1446
        if(!loading)
26 ✔
1447
        {
1448
          QString name = clap_safe_name(
22 !
1449
              info.name, output_count == 1 ? QStringLiteral("Audio Out")
22 !
1450
                                           : QStringLiteral("Audio Out %1").arg(i + 1));
×
1451
          if(i == 0 && name.toLower() == "audio output")
22 !
1452
            name = "Audio Out";
14 !
1453
          auto outlet = new Process::AudioOutlet(
44 !
1454
              name, Id<Process::Port>(getStrongId(m_outlets)), this);
22 !
1455
          if(info.flags & CLAP_AUDIO_PORT_IS_MAIN)
22 !
1456
          {
1457
            outlet->setPropagate(true);
22 !
1458
          }
22 ✔
1459
          m_outlets.push_back(outlet);
22 !
1460
        }
22 ✔
1461

1462
        m_plugin->m_audio_outs.push_back(info);
26 ✔
1463
        cur_outlet++;
26 ✔
1464
      }
26 ✔
1465
    }
26 ✔
1466
  }
26 ✔
1467

1468
  // Get note ports extension
1469
  m_plugin->m_midi_ins.clear();
34 ✔
1470
  m_plugin->m_midi_outs.clear();
34 ✔
1471
  auto note_ports = (const clap_plugin_note_ports_t*)m_plugin->plugin->get_extension(
68 ✔
1472
      m_plugin->plugin, CLAP_EXT_NOTE_PORTS);
34 ✔
1473
  if(note_ports)
34 ✔
1474
  {
1475
    uint32_t input_count = note_ports->count(m_plugin->plugin, true);
8 ✔
1476
    for(uint32_t i = 0; i < input_count; ++i)
16 ✔
1477
    {
1478
      clap_note_port_info_t info{};
8 ✔
1479
      if(note_ports->get(m_plugin->plugin, i, true, &info))
8 !
1480
      {
1481
        if(!loading)
8 ✔
1482
        {
1483
          QString name = clap_safe_name(
6 !
1484
              info.name, input_count == 1 ? QStringLiteral("MIDI In")
6 !
1485
                                          : QStringLiteral("MIDI In %1").arg(i + 1));
×
1486
          if(i == 0 && name.toLower() == "midi input")
6 !
1487
            name = "MIDI In";
×
1488
          auto inlet = new Process::MidiInlet(
12 !
1489
              name, Id<Process::Port>(getStrongId(m_inlets)), this);
6 !
1490
          m_inlets.push_back(inlet);
6 !
1491
        }
6 ✔
1492

1493
        m_plugin->m_midi_ins.push_back(info);
8 ✔
1494
        cur_inlet++;
8 ✔
1495
      }
8 ✔
1496
    }
8 ✔
1497
    uint32_t output_count = note_ports->count(m_plugin->plugin, false);
8 ✔
1498
    for(uint32_t i = 0; i < output_count; ++i)
9 ✔
1499
    {
1500
      clap_note_port_info_t info{};
1 ✔
1501
      if(note_ports->get(m_plugin->plugin, i, false, &info))
1 !
1502
      {
1503
        if(!loading)
1 !
1504
        {
1505
          QString name = clap_safe_name(
1 !
1506
              info.name, output_count == 1 ? QStringLiteral("MIDI Out")
1 !
1507
                                           : QStringLiteral("MIDI Out %1").arg(i + 1));
×
1508
          if(i == 0 && name.toLower() == "midi output")
1 !
1509
            name = "MIDI Out";
×
1510
          auto outlet = new Process::MidiOutlet(
2 !
1511
              name, Id<Process::Port>(getStrongId(m_outlets)), this);
1 !
1512
          m_outlets.push_back(outlet);
1 !
1513
        }
1 ✔
1514

1515
        m_plugin->m_midi_outs.push_back(info);
1 ✔
1516
        cur_outlet++;
1 ✔
1517
      }
1 ✔
1518
    }
1 ✔
1519
  }
8 ✔
1520

1521
  // Get params extension
1522
  auto params = (const clap_plugin_params_t*)m_plugin->plugin->get_extension(
68 ✔
1523
      m_plugin->plugin, CLAP_EXT_PARAMS);
34 ✔
1524
  if(params)
34 ✔
1525
  {
1526
    uint32_t param_count = params->count(m_plugin->plugin);
26 ✔
1527
    for(uint32_t i = 0; i < param_count; ++i)
113 ✔
1528
    {
1529
      clap_param_info_t info{};
87 ✔
1530
      if(params->get_info(m_plugin->plugin, i, &info))
87 !
1531
      {
1532
        if(info.flags & CLAP_PARAM_IS_HIDDEN)
87 ✔
1533
          continue;
7 ✔
1534
        // A control finds its parameter by its rank among the writable
1535
        // parameters, an outlet among the read-only ones
1536
        const int index = int(
80 ✔
1537
            info.flags & CLAP_PARAM_IS_READONLY ? m_plugin->m_parameters_outs.size()
80 ✔
1538
                                                : m_plugin->m_parameters_ins.size());
72 ✔
1539
        if(!(info.flags & CLAP_PARAM_IS_READONLY))
80 ✔
1540
        {
1541
          if(!loading)
72 ✔
1542
          {
1543
            const QString param_name = clap_safe_name(
58 ✔
1544
                info.name, QStringLiteral("Param %1").arg(i + 1));
58 !
1545
            Process::ControlInlet* inlet{};
58 ✔
1546
            if(info.flags & CLAP_PARAM_IS_STEPPED)
58 ✔
1547
              inlet = new Process::IntSlider(
10 !
1548
                  param_name, Id<Process::Port>(getStrongId(m_inlets)), this);
5 !
1549
            else
1550
              inlet = new Process::FloatSlider(
106 !
1551
                  param_name, Id<Process::Port>(getStrongId(m_inlets)), this);
53 !
1552

1553
            setupControlInlet(*params, info, index, inlet);
58 !
1554

1555
            m_inlets.push_back(inlet);
58 !
1556
          }
58 ✔
1557
          else
1558
          {
1559
            setupControlInlet(
14 ✔
1560
                *params, info, index,
14 ✔
1561
                qobject_cast<Process::ControlInlet*>(m_inlets[cur_inlet]));
14 ✔
1562
          }
1563

1564
          // Store parameter info for executor
1565
          m_plugin->m_parameters_ins.push_back(info);
72 ✔
1566
          cur_inlet++;
72 ✔
1567
        }
72 ✔
1568
        else
1569
        {
1570
          if(!loading)
8 !
1571
          {
1572
            const QString param_name = clap_safe_name(
8 ✔
1573
                info.name, QStringLiteral("Out %1").arg(i + 1));
8 !
1574
            Process::ControlOutlet* port{};
8 ✔
1575
            port = new Process::Bargraph(
16 !
1576
                param_name, Id<Process::Port>(getStrongId(m_outlets)), this);
8 !
1577

1578
            setupControlOutlet(*params, info, index, port);
8 !
1579

1580
            m_outlets.push_back(port);
8 !
1581
          }
8 ✔
1582
          else
1583
          {
1584
            setupControlOutlet(
×
1585
                *params, info, index,
×
1586
                qobject_cast<Process::ControlOutlet*>(m_outlets[cur_outlet]));
×
1587
          }
1588

1589
          // Store parameter info for executor
1590
          m_plugin->m_parameters_outs.push_back(info);
8 ✔
1591
          cur_outlet++;
8 ✔
1592
        }
1593
      }
80 ✔
1594
    }
80 ✔
1595
  }
26 ✔
1596

1597
  m_plugin->param_outs_by_id.clear();
34 ✔
1598
  m_plugin->param_outs_by_id.reserve(m_plugin->m_parameters_outs.size());
34 ✔
1599
  for(std::size_t i = 0; i < m_plugin->m_parameters_outs.size(); ++i)
42 ✔
1600
    m_plugin->param_outs_by_id.emplace(
16 ✔
1601
        m_plugin->m_parameters_outs[i].id, static_cast<std::uint32_t>(i));
8 ✔
1602

1603
  inletsChanged();
34 ✔
1604
  outletsChanged();
34 ✔
1605
}
35 ✔
1606

1607
void Model::mapExternalFiles(Process::ExternalFileMap& map)
×
1608
{
1609
  Process::ProcessModel::mapExternalFiles(map);
×
1610

1611
  // Same as VST3: the plug-in binary has to exist on the other machine, it
1612
  // cannot travel with the project. Report it.
1613
  if(!m_pluginPath.isEmpty())
×
1614
    map.readOnly(m_pluginPath, score::FileKind::Plugin);
×
1615
}
×
1616

1617
QString Model::effect() const noexcept
94 ✔
1618
{
1619
  if(m_pluginPath.isEmpty() || m_pluginId.isEmpty())
94 !
1620
    return {};
5 ✔
1621
  return m_pluginPath + QStringLiteral(":::") + m_pluginId;
89 !
1622
}
94 ✔
1623

1624
Process::ProcessFlags Model::flags() const noexcept
466 ✔
1625
{
1626
  auto flags = Metadata<Process::ProcessFlags_k, Model>::get();
466 !
1627
  return flags;
466 ✔
1628
}
1629

1630
void Model::loadPreset(const Process::Preset& preset)
2 ✔
1631
{
1632
  if(!m_plugin || !m_plugin->plugin)
2 !
1633
    return;
×
1634

1635
  const rapidjson::Document doc = readJson(preset.data);
2 ✔
1636
  if(!doc.IsObject())
2 !
1637
    return;
×
1638
  auto obj = doc.GetObject();
2 !
1639

1640
  // Try to load using CLAP state (preferred method)
1641
  if(auto it = obj.FindMember("State"); it != obj.MemberEnd())
2 !
1642
  {
1643
    QByteArray data = QByteArray::fromBase64(JsonValue{it->value}.toByteArray());
2 !
1644
    if(!data.isEmpty())
2 !
1645
    {
1646
      // Get state extension and load the state
1647
      auto state = (const clap_plugin_state_t*)m_plugin->plugin->get_extension(
4 !
1648
          m_plugin->plugin, CLAP_EXT_STATE);
2 ✔
1649
      if(state)
2 !
1650
      {
1651
        struct stream_context
1652
        {
1653
          const char* data;
1654
          size_t size;
1655
          size_t pos;
1656
        };
1657

1658
        stream_context ctx{data.constData(), static_cast<size_t>(data.size()), 0};
2 ✔
1659

1660
        clap_istream_t stream{};
2 ✔
1661
        stream.ctx = &ctx;
2 ✔
1662
        stream.read
2 ✔
1663
            = [](const clap_istream_t* stream, void* buffer, uint64_t size) -> int64_t {
6 ✔
1664
          auto* ctx = static_cast<stream_context*>(stream->ctx);
2 ✔
1665
          if(ctx->pos >= ctx->size)
2 !
1666
            return 0;
×
1667

1668
          uint64_t to_read = std::min(int64_t(size), int64_t(ctx->size - ctx->pos));
2 ✔
1669
          std::memcpy(buffer, ctx->data + ctx->pos, to_read);
2 ✔
1670
          ctx->pos += to_read;
2 ✔
1671
          return static_cast<int64_t>(to_read);
2 ✔
1672
        };
2 ✔
1673

1674
        // Load the state, then show the values it set: the controls are in
1675
        // the order of the parameters, their ids are score's
1676
        if(state->load(m_plugin->plugin, &stream))
2 !
1677
          refreshParamValues();
2 !
1678
      }
2 ✔
1679
    }
2 ✔
1680
  }
2 ✔
1681
  // Try preset load extension (for file-based and builtin presets)
1682
  else if(auto loc_it = obj.FindMember("PresetLocation"); loc_it != obj.MemberEnd())
×
1683
  {
1684
    auto preset_load = (const clap_plugin_preset_load_t*)m_plugin->plugin->get_extension(
×
1685
        m_plugin->plugin, CLAP_EXT_PRESET_LOAD);
×
1686
    if(!preset_load)
×
1687
      preset_load = (const clap_plugin_preset_load_t*)m_plugin->plugin->get_extension(
×
1688
          m_plugin->plugin, "clap.preset-load.draft/2");
×
1689
    if(preset_load)
×
1690
    {
1691
      QString location = JsonValue{loc_it->value}.toString();
×
1692
      QString load_key;
×
1693
      uint32_t location_kind = CLAP_PRESET_DISCOVERY_LOCATION_FILE; // Default to file
×
1694

1695
      // Check for location kind (for builtin presets)
1696
      if(auto kind_it = obj.FindMember("LocationKind"); kind_it != obj.MemberEnd())
×
1697
      {
1698
        location_kind = static_cast<uint32_t>(JsonValue{kind_it->value}.toInt());
×
1699
      }
×
1700

1701
      if(auto key_it = obj.FindMember("LoadKey"); key_it != obj.MemberEnd())
×
1702
      {
1703
        load_key = JsonValue{key_it->value}.toString();
×
1704
      }
×
1705

1706
      // A file's path; nothing for a preset inside the plug-in
1707
      const QByteArray location_utf8 = location.toUtf8();
×
1708
      const QByteArray key_utf8 = load_key.toUtf8();
×
1709
      const char* location_str
×
1710
          = location_kind == CLAP_PRESET_DISCOVERY_LOCATION_FILE && !location.isEmpty()
×
1711
                ? location_utf8.constData()
×
1712
                : nullptr;
1713

1714
      if(preset_load->from_location(
×
1715
             m_plugin->plugin, location_kind, location_str,
×
1716
             load_key.isEmpty() ? nullptr : key_utf8.constData()))
×
1717
        refreshParamValues();
×
1718
    }
×
1719
  }
×
1720
}
2 ✔
1721

1722
bool Model::presetMatches(const Process::Preset& preset) const noexcept
6 ✔
1723
{
1724
  return preset.key.key == concreteKey()
12 !
1725
         && (preset.key.effect.isEmpty() || preset.key.effect == effect());
6 !
1726
}
1727

1728
Process::Preset Model::savePreset() const noexcept
5 ✔
1729
{
1730
  Process::Preset p;
5 ✔
1731
  p.name = this->metadata().getName();
5 ✔
1732
  p.key.key = this->concreteKey();
5 ✔
1733
  p.key.effect = this->effect();
5 ✔
1734

1735
  if(!m_plugin || !m_plugin->plugin)
5 !
1736
  {
1737
    p.data = "{}";
×
1738
    return p;
×
1739
  }
1740

1741
  // Save using CLAP state extension
1742
  QByteArray data = readCLAPState(*m_plugin->plugin);
5 !
1743

1744
  JSONReader r;
5 !
1745
  r.stream.StartObject();
5 !
1746
  r.obj["State"] = data.toBase64();
5 !
1747
  r.stream.EndObject();
5 !
1748
  p.data = r.toByteArray();
5 !
1749
  return p;
5 ✔
1750
}
5 ✔
1751

1752
std::vector<Process::Preset> Model::builtinPresets() const noexcept
2 ✔
1753
{
1754
  // A plug-in can index thousands of preset files: once per instance
1755
  if(!m_builtinPresets)
2 !
1756
    m_builtinPresets = discoverPresets();
2 ✔
1757
  return *m_builtinPresets;
2 !
1758
}
1759

1760
std::vector<Process::Preset> Model::discoverPresets() const noexcept
2 ✔
1761
{
1762
  std::vector<Process::Preset> presets;
2 ✔
1763

1764
  if(!m_plugin || !m_plugin->plugin || !m_plugin->entry)
2 !
1765
    return presets;
×
1766

1767
  auto preset_discovery_factory = static_cast<const clap_preset_discovery_factory_t*>(
2 ✔
1768
      m_plugin->entry->get_factory(CLAP_PRESET_DISCOVERY_FACTORY_ID));
2 !
1769
  if(!preset_discovery_factory)
2 ✔
1770
    preset_discovery_factory = static_cast<const clap_preset_discovery_factory_t*>(
1 ✔
1771
        m_plugin->entry->get_factory("clap.preset-discovery-factory/draft-2"));
1 !
1772
  // Some entries give their plug-in factory for any id
1773
  if(!preset_discovery_factory
2 ✔
1774
     || static_cast<const void*>(preset_discovery_factory)
2 !
1775
            == m_plugin->entry->get_factory(CLAP_PLUGIN_FACTORY_ID))
1 !
1776
    return presets;
2 ✔
1777

1778
  // What the providers declare, copied: their structs only live during the
1779
  // call that declares them
1780
  struct location
1781
  {
1782
    uint32_t kind{};
1783
    QString name;
1784
    QString path;
1785
  };
1786
  struct collector_t
1787
  {
1788
    std::vector<Process::Preset>* target_presets{};
1789
    UuidKey<Process::ProcessModel> process_key;
1790
    QString effect_name;
1791
    std::vector<location> locations;
1792
    QStringList extensions;
1793
    // The location being read, for the presets it gives
1794
    uint32_t kind{};
1795
    QString path;
1796
    QString category;
1797
  };
1798
  collector_t collector{&presets, this->concreteKey(), this->effect()};
×
1799

1800
  clap_preset_discovery_indexer_t indexer{};
×
1801
  indexer.clap_version = CLAP_VERSION;
×
1802
  indexer.name = "ossia score";
×
1803
  indexer.vendor = "ossia.io";
×
1804
  indexer.url = "https://ossia.io";
×
1805
  indexer.version = SCORE_TAG_NO_V;
×
1806
  indexer.indexer_data = &collector;
×
1807

1808
  indexer.declare_filetype = [](const clap_preset_discovery_indexer_t* indexer,
×
1809
                                const clap_preset_discovery_filetype_t* filetype) -> bool {
1810
    auto& self = *(collector_t*)indexer->indexer_data;
×
1811
    if(filetype && filetype->file_extension && *filetype->file_extension)
×
1812
      self.extensions.push_back(QString::fromUtf8(filetype->file_extension));
×
1813
    return true;
×
1814
  };
×
1815
  indexer.declare_location = [](const clap_preset_discovery_indexer_t* indexer,
×
1816
                                const clap_preset_discovery_location_t* loc) -> bool {
1817
    auto& self = *(collector_t*)indexer->indexer_data;
×
1818
    if(!loc)
×
1819
      return false;
×
1820
    self.locations.push_back(
×
1821
        {loc->kind, QString::fromUtf8(loc->name ? loc->name : ""),
×
1822
         QString::fromUtf8(loc->location ? loc->location : "")});
×
1823
    return true;
×
1824
  };
×
1825
  indexer.declare_soundpack
×
1826
      = [](const clap_preset_discovery_indexer_t*,
×
1827
           const clap_preset_discovery_soundpack_t*) -> bool { return true; };
×
1828
  indexer.get_extension
×
1829
      = [](const clap_preset_discovery_indexer_t*, const char*) -> const void* {
×
1830
    return nullptr;
×
1831
  };
1832

1833
  clap_preset_discovery_metadata_receiver_t receiver{};
×
1834
  receiver.receiver_data = &collector;
×
1835
  receiver.on_error = [](const clap_preset_discovery_metadata_receiver_t*, int32_t,
×
1836
                         const char* error_message) {
1837
    qWarning() << "CLAP preset discovery error:"
×
1838
               << (error_message ? error_message : "Unknown error");
×
1839
  };
×
1840
  receiver.begin_preset = [](const clap_preset_discovery_metadata_receiver_t* r,
×
1841
                             const char* name, const char* load_key) -> bool {
1842
    auto& self = *static_cast<collector_t*>(r->receiver_data);
×
1843

1844
    Process::Preset preset;
×
1845
    preset.name = QString::fromUtf8(name && *name ? name : "Unnamed Preset");
×
1846
    preset.category = self.category;
×
1847
    preset.key.key = self.process_key;
×
1848
    preset.key.effect = self.effect_name;
×
1849

1850
    // What preset-load needs to find it again
1851
    JSONReader w;
×
1852
    w.stream.StartObject();
×
1853
    w.obj["LocationKind"] = static_cast<int>(self.kind);
×
1854
    w.obj["PresetLocation"] = self.path;
×
1855
    if(load_key)
×
1856
      w.obj["LoadKey"] = QString::fromUtf8(load_key);
×
1857
    w.stream.EndObject();
×
1858
    preset.data = w.toByteArray();
×
1859

1860
    self.target_presets->push_back(std::move(preset));
×
1861
    return true;
1862
  };
×
1863
  // Metadata score does not show
1864
  receiver.add_plugin_id
×
1865
      = [](const clap_preset_discovery_metadata_receiver_t*,
×
1866
           const clap_universal_plugin_id_t*) { };
×
1867
  receiver.set_soundpack_id
×
1868
      = [](const clap_preset_discovery_metadata_receiver_t*, const char*) { };
×
1869
  receiver.set_flags = [](const clap_preset_discovery_metadata_receiver_t*, uint32_t) { };
×
1870
  receiver.add_creator = [](const clap_preset_discovery_metadata_receiver_t*, const char*) { };
×
1871
  receiver.set_description = [](const clap_preset_discovery_metadata_receiver_t* r,
×
1872
                                const char* description) {
1873
    auto& self = *static_cast<collector_t*>(r->receiver_data);
×
1874
    if(description && !self.target_presets->empty())
×
1875
      self.target_presets->back().description = QString::fromUtf8(description);
×
1876
  };
×
1877
  receiver.set_timestamps
×
1878
      = [](const clap_preset_discovery_metadata_receiver_t*, clap_timestamp,
×
1879
           clap_timestamp) { };
×
1880
  receiver.add_feature = [](const clap_preset_discovery_metadata_receiver_t*, const char*) { };
×
1881
  receiver.add_extra_info
×
1882
      = [](const clap_preset_discovery_metadata_receiver_t*, const char*, const char*) { };
×
1883

1884
  const uint32_t provider_count = preset_discovery_factory->count(preset_discovery_factory);
×
1885
  for(uint32_t i = 0; i < provider_count; ++i)
×
1886
  {
1887
    auto desc = preset_discovery_factory->get_descriptor(preset_discovery_factory, i);
×
1888
    if(!desc)
×
1889
      continue;
×
1890
    collector.locations.clear();
×
1891
    collector.extensions.clear();
×
1892
    auto provider
×
1893
        = preset_discovery_factory->create(preset_discovery_factory, &indexer, desc->id);
×
1894
    if(!provider)
×
1895
      continue;
×
1896

1897
    if(provider->init && provider->init(provider) && provider->get_metadata)
×
1898
    {
1899
      for(const auto& loc : collector.locations)
×
1900
      {
1901
        if(loc.kind == CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN)
×
1902
        {
1903
          collector.kind = loc.kind;
×
1904
          collector.path.clear();
×
1905
          collector.category.clear();
×
1906
          provider->get_metadata(provider, loc.kind, nullptr, &receiver);
×
1907
          continue;
×
1908
        }
1909

1910
        // A file location is a file, or a folder the host walks: each file
1911
        // of a declared type is asked about, in a folder named after where it is
1912
        const auto read = [&](const QString& file, const QString& category) {
×
1913
          collector.kind = CLAP_PRESET_DISCOVERY_LOCATION_FILE;
×
1914
          collector.path = file;
×
1915
          collector.category = category;
×
1916
          const QByteArray utf8 = file.toUtf8();
×
1917
          provider->get_metadata(provider, loc.kind, utf8.constData(), &receiver);
×
1918
        };
×
1919
        const QFileInfo root{loc.path};
×
1920
        if(root.isFile())
×
1921
        {
1922
          read(root.absoluteFilePath(), loc.name);
×
1923
          continue;
×
1924
        }
1925
        if(!root.isDir())
×
1926
          continue;
×
1927
        QStringList filters;
×
1928
        for(const auto& ext : collector.extensions)
×
1929
          filters.push_back("*." + ext);
×
1930
        QDirIterator it{
×
1931
            root.absoluteFilePath(), filters, QDir::Files | QDir::Readable,
×
1932
            QDirIterator::Subdirectories | QDirIterator::FollowSymlinks};
×
1933
        const QDir base{root.absoluteFilePath()};
×
1934
        while(it.hasNext())
×
1935
        {
1936
          const QString file = it.next();
×
1937
          QString sub = QFileInfo{base.relativeFilePath(file)}.path();
×
1938
          if(sub == ".")
×
1939
            sub.clear();
×
1940
          read(file, sub.isEmpty() ? loc.name : loc.name + "/" + sub);
×
1941
        }
×
1942
      }
×
1943
    }
×
1944

1945
    if(provider->destroy)
×
1946
      provider->destroy(provider);
×
1947
  }
×
1948

1949
  return presets;
×
1950
}
2 ✔
1951

1952
namespace
1953
{
1954
// Find and update the i-th ControlInlet / ControlOutlet on a Model under
1955
// the currentlyReadingValues guard, so the GUI handler does not echo the
1956
// value back into a fresh params->flush() call.
1957
template <typename Port>
1958
void apply_value_at(Model& self, std::size_t idx, double v)
×
1959
{
1960
  std::size_t found = 0;
×
1961
  if constexpr(std::is_same_v<Port, Process::ControlInlet>)
1962
  {
1963
    for(auto* inlet : self.inlets())
×
1964
    {
1965
      if(auto* ctl = qobject_cast<Process::ControlInlet*>(inlet))
×
1966
      {
1967
        if(found == idx)
×
1968
        {
1969
          self.currentlyReadingValues = true;
×
1970
          ctl->setValue(v);
×
1971
          self.currentlyReadingValues = false;
×
1972
          return;
×
1973
        }
1974
        ++found;
×
1975
      }
×
1976
    }
1977
  }
1978
  else
1979
  {
1980
    for(auto* outlet : self.outlets())
×
1981
    {
1982
      if(auto* ctl = qobject_cast<Process::ControlOutlet*>(outlet))
×
1983
      {
1984
        if(found == idx)
×
1985
        {
1986
          self.currentlyReadingValues = true;
×
1987
          ctl->setValue(v);
×
1988
          self.currentlyReadingValues = false;
×
1989
          return;
×
1990
        }
1991
        ++found;
×
1992
      }
×
1993
    }
1994
  }
1995
}
×
1996
} // namespace
1997

1998
void Model::refreshParamValues()
15 ✔
1999
{
2000
  if(!m_plugin || !m_plugin->plugin)
15 !
2001
    return;
×
2002
  auto* plugin = m_plugin->plugin;
15 ✔
2003
  auto params = m_plugin->ext_params;
15 ✔
2004
  if(!params || !params->get_value)
15 !
2005
    return;
×
2006

2007
  std::size_t inlet_idx = 0;
15 ✔
2008
  for(auto* inlet : inlets())
88 ✔
2009
  {
2010
    if(auto* control = qobject_cast<Process::ControlInlet*>(inlet))
73 ✔
2011
    {
2012
      if(inlet_idx < m_plugin->m_parameters_ins.size())
58 ✔
2013
      {
2014
        const auto& info = m_plugin->m_parameters_ins[inlet_idx];
44 ✔
2015
        double v = 0.0;
44 ✔
2016
        if(params->get_value(plugin, info.id, &v))
44 !
2017
        {
2018
          currentlyReadingValues = true;
44 ✔
2019
          control->setValue(v);
44 !
2020
          currentlyReadingValues = false;
44 ✔
2021
        }
44 ✔
2022
      }
44 ✔
2023
      ++inlet_idx;
58 ✔
2024
    }
58 ✔
2025
  }
2026

2027
  std::size_t outlet_idx = 0;
15 ✔
2028
  for(auto* outlet : outlets())
30 ✔
2029
  {
2030
    if(auto* control = qobject_cast<Process::ControlOutlet*>(outlet))
15 !
2031
    {
2032
      if(outlet_idx < m_plugin->m_parameters_outs.size())
×
2033
      {
2034
        const auto& info = m_plugin->m_parameters_outs[outlet_idx];
×
2035
        double v = 0.0;
×
2036
        if(params->get_value(plugin, info.id, &v))
×
2037
        {
2038
          currentlyReadingValues = true;
×
2039
          control->setValue(v);
×
2040
          currentlyReadingValues = false;
×
2041
        }
×
2042
      }
×
2043
      ++outlet_idx;
×
2044
    }
×
2045
  }
2046
}
15 ✔
2047

2048
bool Model::refreshParamInfoIfStable()
1 ✔
2049
{
2050
  if(!m_plugin || !m_plugin->plugin)
1 !
2051
    return true;
×
2052
  auto* plugin = m_plugin->plugin;
1 ✔
2053
  auto params = m_plugin->ext_params;
1 ✔
2054
  if(!params || !params->count || !params->get_info)
1 !
2055
    return true;
×
2056

2057
  // The hidden parameters have no port: only the shown ones are compared
2058
  const uint32_t new_count = params->count(plugin);
1 ✔
2059
  std::size_t in_idx = 0, out_idx = 0;
1 ✔
2060
  for(uint32_t i = 0; i < new_count; ++i)
4 ✔
2061
  {
2062
    clap_param_info_t info{};
3 ✔
2063
    if(!params->get_info(plugin, i, &info))
3 !
2064
      return false;
×
2065
    if(info.flags & CLAP_PARAM_IS_HIDDEN)
3 ✔
2066
      continue;
1 ✔
2067
    if(!(info.flags & CLAP_PARAM_IS_READONLY))
2 ✔
2068
    {
2069
      if(in_idx >= m_plugin->m_parameters_ins.size())
1 !
2070
        return false;
×
2071
      if(m_plugin->m_parameters_ins[in_idx].id != info.id)
1 !
2072
        return false;
×
2073
      m_plugin->m_parameters_ins[in_idx] = info;
1 ✔
2074
      ++in_idx;
1 ✔
2075
    }
1 ✔
2076
    else
2077
    {
2078
      if(out_idx >= m_plugin->m_parameters_outs.size())
1 !
2079
        return false;
×
2080
      if(m_plugin->m_parameters_outs[out_idx].id != info.id)
1 !
2081
        return false;
×
2082
      m_plugin->m_parameters_outs[out_idx] = info;
1 ✔
2083
      ++out_idx;
1 ✔
2084
    }
2085
  }
2 ✔
2086
  if(in_idx != m_plugin->m_parameters_ins.size()
1 ✔
2087
     || out_idx != m_plugin->m_parameters_outs.size())
1 !
2088
    return false;
×
2089

2090
  // Don't re-invoke setupControlInlet: it would duplicate valueChanged connections.
2091
  std::size_t inlet_idx = 0, outlet_idx = 0;
1 ✔
2092
  for(auto* inlet : inlets())
3 ✔
2093
  {
2094
    if(auto* ctl = qobject_cast<Process::ControlInlet*>(inlet))
2 ✔
2095
    {
2096
      if(inlet_idx < m_plugin->m_parameters_ins.size())
1 !
2097
      {
2098
        const auto& info = m_plugin->m_parameters_ins[inlet_idx];
1 ✔
2099
        ctl->setName(clap_safe_name(
2 !
2100
            info.name, QStringLiteral("Param %1").arg(inlet_idx + 1)));
1 !
2101
        ctl->setDomain(ossia::make_domain(info.min_value, info.max_value));
1 !
2102
      }
1 ✔
2103
      ++inlet_idx;
1 ✔
2104
    }
1 ✔
2105
  }
2106
  for(auto* outlet : outlets())
3 ✔
2107
  {
2108
    if(auto* ctl = qobject_cast<Process::ControlOutlet*>(outlet))
2 ✔
2109
    {
2110
      if(outlet_idx < m_plugin->m_parameters_outs.size())
1 !
2111
      {
2112
        const auto& info = m_plugin->m_parameters_outs[outlet_idx];
1 ✔
2113
        ctl->setName(clap_safe_name(
2 !
2114
            info.name, QStringLiteral("Out %1").arg(outlet_idx + 1)));
1 !
2115
        ctl->setDomain(ossia::make_domain(info.min_value, info.max_value));
1 !
2116
      }
1 ✔
2117
      ++outlet_idx;
1 ✔
2118
    }
1 ✔
2119
  }
2120
  return true;
1 ✔
2121
}
1 ✔
2122

2123
void Model::onParamRescan(clap_param_rescan_flags flags)
14 ✔
2124
{
2125
  if(!m_plugin || !m_plugin->plugin)
14 !
2126
    return;
×
2127

2128
  // RESCAN_ALL needs deactivation; defer if executing.
2129
  if((flags & CLAP_PARAM_RESCAN_ALL) && executing())
14 !
2130
  {
2131
    m_pendingRescanFlags |= flags;
×
2132
    return;
×
2133
  }
2134

2135
  // RESCAN_TEXT: nothing cached, display strings fetched on demand.
2136
  (void)CLAP_PARAM_RESCAN_TEXT;
2137

2138
  if(flags & CLAP_PARAM_RESCAN_INFO)
14 ✔
2139
  {
2140
    if(!refreshParamInfoIfStable())
1 !
2141
      flags |= CLAP_PARAM_RESCAN_ALL;
×
2142
  }
1 ✔
2143

2144
  if(flags & CLAP_PARAM_RESCAN_ALL)
14 !
2145
  {
2146
    if(refreshParamInfoIfStable())
×
2147
    {
2148
      refreshParamValues();
×
2149
      return;
×
2150
    }
2151
    // FIXME score does not rebuild inlets dynamically (see VST2/VST3 backends).
2152
    qWarning() << "CLAP: parameter layout changed at runtime for"
×
2153
               << m_pluginId
×
2154
               << "— score doesn't yet rebuild inlets dynamically. "
×
2155
                  "Remove and re-add the plug-in to pick up the new "
2156
                  "parameter set.";
2157
    restartPlugin();
×
2158
    return;
×
2159
  }
2160

2161
  if(flags & CLAP_PARAM_RESCAN_VALUES)
14 ✔
2162
    refreshParamValues();
13 ✔
2163
}
14 ✔
2164

2165
void Model::markStateDirty()
×
2166
{
2167
  // Plug-ins (Vital, Surge XT) fire this on every UI tweak; debounce.
2168
  constexpr int kStateDirtyDebounceMs = 400;
×
2169

2170
  if(!m_stateDirtyTimer)
×
2171
  {
2172
    m_stateDirtyTimer = new QTimer(this);
×
2173
    m_stateDirtyTimer->setSingleShot(true);
×
2174
    m_stateDirtyTimer->setInterval(kStateDirtyDebounceMs);
×
2175
    connect(m_stateDirtyTimer, &QTimer::timeout, this, [this] {
×
2176
      if(!m_plugin || !m_plugin->plugin)
×
2177
        return;
×
2178
      QByteArray blob = Clap::readCLAPState(*m_plugin->plugin);
×
2179
      if(!blob.isEmpty())
×
2180
        stateSnapshotChanged(blob);
×
2181
    });
×
2182
  }
×
2183
  m_stateDirtyTimer->start();
×
2184
}
×
2185

2186
void Model::flushFromPluginToHost()
×
2187
{
2188
  auto plugin = m_plugin->plugin;
×
2189
  if(!plugin)
×
2190
    return;
×
2191
  auto params
×
2192
      = (const clap_plugin_params_t*)plugin->get_extension(plugin, CLAP_EXT_PARAMS);
×
2193
  if(!params || !params->flush)
×
2194
    return;
×
2195
  if(this->executing())
×
2196
    return;
×
2197

2198
  ParamInputCtx in_ctx; // empty
×
2199
  clap_input_events_t ip = make_input_events(in_ctx);
×
2200

2201
  clap_output_events_t op{
×
2202
      .ctx = this,
2203
      .try_push = [](const struct clap_output_events* list,
×
2204
                     const clap_event_header_t* event) -> bool {
2205
    auto* self = static_cast<Model*>(list->ctx);
×
2206
    if(!event || event->space_id != CLAP_CORE_EVENT_SPACE_ID)
×
2207
      return true;
×
2208
    if(event->type != CLAP_EVENT_PARAM_VALUE)
×
2209
      return true;
×
2210
    if(event->size < sizeof(clap_event_param_value_t))
×
2211
      return true;
×
2212

2213
    auto* pv = reinterpret_cast<const clap_event_param_value_t*>(event);
×
2214

2215
    std::size_t idx = 0;
×
2216
    for(auto& info : self->m_plugin->m_parameters_ins)
×
2217
    {
2218
      if(info.id == pv->param_id)
×
2219
      {
2220
        apply_value_at<Process::ControlInlet>(*self, idx, pv->value);
×
2221
        return true;
×
2222
      }
2223
      ++idx;
×
2224
    }
2225
    idx = 0;
×
2226
    for(auto& info : self->m_plugin->m_parameters_outs)
×
2227
    {
2228
      if(info.id == pv->param_id)
×
2229
      {
2230
        apply_value_at<Process::ControlOutlet>(*self, idx, pv->value);
×
2231
        return true;
×
2232
      }
2233
      ++idx;
×
2234
    }
2235
    return true;
×
2236
  }};
×
2237

2238
  params->flush(plugin, &ip, &op);
×
2239

2240
  // Plugins that update internal state silently (without pushing events
2241
  // through `out`) still expose fresh values via get_value(); poll them so
2242
  // the GUI mirrors the plugin state, for both writable and read-only params.
2243
  std::size_t inlet_idx = 0;
×
2244
  for(auto* inlet : inlets())
×
2245
  {
2246
    if(auto* control = qobject_cast<Process::ControlInlet*>(inlet))
×
2247
    {
2248
      if(inlet_idx < m_plugin->m_parameters_ins.size())
×
2249
      {
2250
        const auto& param_info = m_plugin->m_parameters_ins[inlet_idx];
×
2251
        double current_value = 0.0;
×
2252
        if(params->get_value(plugin, param_info.id, &current_value))
×
2253
        {
2254
          currentlyReadingValues = true;
×
2255
          control->setValue(current_value);
×
2256
          currentlyReadingValues = false;
×
2257
        }
×
2258
      }
×
2259
      inlet_idx++;
×
2260
    }
×
2261
  }
2262
  std::size_t outlet_idx = 0;
×
2263
  for(auto* outlet : outlets())
×
2264
  {
2265
    if(auto* control = qobject_cast<Process::ControlOutlet*>(outlet))
×
2266
    {
2267
      if(outlet_idx < m_plugin->m_parameters_outs.size())
×
2268
      {
2269
        const auto& param_info = m_plugin->m_parameters_outs[outlet_idx];
×
2270
        double current_value = 0.0;
×
2271
        if(params->get_value(plugin, param_info.id, &current_value))
×
2272
        {
2273
          currentlyReadingValues = true;
×
2274
          control->setValue(current_value);
×
2275
          currentlyReadingValues = false;
×
2276
        }
×
2277
      }
×
2278
      outlet_idx++;
×
2279
    }
×
2280
  }
2281
}
×
2282
}
2283

2284
template <>
2285
QString
2286
Process::EffectProcessFactory_T<Clap::Model>::customConstructionData() const noexcept
×
2287
{
2288
  return "";
×
2289
}
2290
template <>
2291
Process::Descriptor
2292
Process::EffectProcessFactory_T<Clap::Model>::descriptor(QString txt) const noexcept
81 ✔
2293
{
2294
  Process::Descriptor d;
81 !
2295

2296
  auto t = txt.split(":::");
81 !
2297
  if(t.size() != 2)
81 ✔
2298
    return d;
5 ✔
2299
  auto pluginPath = t[0];
76 !
2300
  auto pluginId = t[1];
76 !
2301

2302
  auto& plug = score::GUIAppContext().guiApplicationPlugin<Clap::ApplicationPlugin>();
76 !
2303
  for(const auto& plugin : plug.plugins())
84 ✔
2304
  {
2305
    if(plugin.path == pluginPath && plugin.id == pluginId)
24 !
2306
    {
2307
      d.author = plugin.vendor;
16 ✔
2308
      d.prettyName = plugin.name;
16 ✔
2309
      d.description = plugin.description;
16 ✔
2310
      d.documentationLink = plugin.manual_url;
16 !
2311
      if(d.documentationLink.isEmpty())
16 !
2312
        d.documentationLink = plugin.url;
16 !
2313
      if(d.documentationLink.isEmpty())
16 !
2314
        d.documentationLink = plugin.support_url;
16 !
2315
      d.tags = plugin.features;
16 ✔
2316
      break;
16 ✔
2317
    }
2318
  }
2319
  return d;
76 ✔
2320
}
81 ✔
2321
template <>
2322
Process::Descriptor Process::EffectProcessFactory_T<Clap::Model>::descriptor(
80 ✔
2323
    const Process::ProcessModel& d) const noexcept
2324
{
2325
  Process::Descriptor desc;
80 !
2326
  return descriptor(d.effect());
80 ✔
2327
}
80 ✔
2328

2329
template <>
2330
void DataStreamReader::read(const Clap::Model& proc)
4 ✔
2331
{
2332
  QByteArray state;
4 ✔
2333
  if(proc.m_plugin && proc.m_plugin->plugin)
4 !
2334
  {
2335
    state = Clap::readCLAPState(*proc.m_plugin->plugin);
4 !
2336
  }
4 ✔
2337

2338
  m_stream << proc.m_pluginPath << proc.m_pluginId << state;
4 !
2339

2340
  readPorts(*this, proc.m_inlets, proc.m_outlets);
4 !
2341
  insertDelimiter();
4 !
2342
}
4 ✔
2343

2344
template <>
2345
void DataStreamWriter::write(Clap::Model& proc)
2 ✔
2346
{
2347
  m_stream >> proc.m_pluginPath >> proc.m_pluginId >> proc.m_loadedState;
2 ✔
2348

2349
  writePorts(
2 ✔
2350
      *this, components.interfaces<Process::PortFactoryList>(), proc.m_inlets,
2 ✔
2351
      proc.m_outlets, &proc);
2 ✔
2352

2353
  checkDelimiter();
2 ✔
2354
}
2 ✔
2355

2356
template <>
2357
void JSONReader::read(const Clap::Model& proc)
4 ✔
2358
{
2359
  obj["PluginPath"] = proc.m_pluginPath;
4 ✔
2360
  obj["PluginId"] = proc.m_pluginId;
4 ✔
2361

2362
  // FIXME CLAP_STATE_CONTEXT_FOR_PROJECT
2363
  // Save plugin state
2364
  QByteArray state;
4 ✔
2365
  if(proc.m_plugin && proc.m_plugin->plugin)
4 !
2366
  {
2367
    state = Clap::readCLAPState(*proc.m_plugin->plugin);
4 !
2368
  }
4 ✔
2369
  obj["State"] = state.toBase64();
4 !
2370

2371
  readPorts(*this, proc.m_inlets, proc.m_outlets);
4 !
2372
}
4 ✔
2373

2374
template <>
2375
void JSONWriter::write(Clap::Model& proc)
2 ✔
2376
{
2377
  proc.m_pluginPath = obj["PluginPath"].toString();
2 ✔
2378
  proc.m_pluginId = obj["PluginId"].toString();
2 ✔
2379
  proc.m_loadedState = QByteArray::fromBase64(obj["State"].toByteArray());
2 !
2380

2381
  writePorts(
2 ✔
2382
      *this, components.interfaces<Process::PortFactoryList>(), proc.m_inlets,
2 ✔
2383
      proc.m_outlets, &proc);
2 ✔
2384
}
2 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc