File: ui_wrapper.h

package info (click to toggle)
lsp-plugins 1.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 91,856 kB
  • sloc: cpp: 427,831; xml: 57,779; makefile: 9,961; php: 1,005; sh: 18
file content (719 lines) | stat: -rw-r--r-- 23,618 bytes parent folder | download
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/*
 * Copyright (C) 2023 Linux Studio Plugins Project <https://lsp-plug.in/>
 *           (C) 2023 Vladimir Sadovnikov <sadko4u@gmail.com>
 *
 * This file is part of lsp-plugins-comp-delay
 * Created on: 5 янв. 2023 г.
 *
 * lsp-plugins-comp-delay is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * lsp-plugins-comp-delay is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with lsp-plugins-comp-delay. If not, see <https://www.gnu.org/licenses/>.
 */

#ifndef LSP_PLUG_IN_PLUG_FW_WRAP_CLAP_IMPL_UI_WRAPPER_H_
#define LSP_PLUG_IN_PLUG_FW_WRAP_CLAP_IMPL_UI_WRAPPER_H_

#include <lsp-plug.in/plug-fw/version.h>

#include <clap/clap.h>
#include <lsp-plug.in/ipc/NativeExecutor.h>
#include <lsp-plug.in/ipc/Thread.h>
#include <lsp-plug.in/plug-fw/wrap/clap/wrapper.h>
#include <lsp-plug.in/runtime/system.h>
#include <lsp-plug.in/stdlib/stdio.h>
#include <lsp-plug.in/tk/tk.h>

namespace lsp
{
    namespace clap
    {
        UIWrapper::UIWrapper(ui::Module *ui, clap::Wrapper *wrapper):
            ui::IWrapper(ui, wrapper->resources())
        {
            pWrapper        = wrapper;
            pExt            = wrapper->extensions();
            pUIThread       = NULL;
            fScaling        = -100.0f;
            pParent         = NULL;
            pTransientFor   = NULL;
            bUIInitialized  = false;
            bRequestProcess = false;
        }

        UIWrapper::~UIWrapper()
        {
            destroy();
        }

        status_t UIWrapper::init(void *root_widget)
        {
            lsp_trace("Initializing wrapper");

            status_t res = STATUS_OK;

            // Obtain UI metadata
            const meta::plugin_t *meta = pUI->metadata();
            if (pUI->metadata() == NULL)
                return STATUS_BAD_STATE;

            // Create list of ports and sort it in ascending order by the identifier
            lsp_trace("Creating ports for %s - %s", meta->name, meta->description);
            for (const meta::port_t *port = meta->ports ; port->id != NULL; ++port)
                create_port(port, NULL);

            // Initialize parent
            if ((res = IWrapper::init(root_widget)) != STATUS_OK)
                return res;

            // Initialize display settings
            tk::display_settings_t settings;
            resource::Environment env;

            settings.resources      = pLoader;
            settings.environment    = &env;

            LSP_STATUS_ASSERT(env.set(LSP_TK_ENV_DICT_PATH, LSP_BUILTIN_PREFIX "i18n"));
            LSP_STATUS_ASSERT(env.set(LSP_TK_ENV_LANG, "en_US"));
            LSP_STATUS_ASSERT(env.set(LSP_TK_ENV_CONFIG, "lsp-plugins"));

            // Create the display
            pDisplay = new tk::Display(&settings);
            if (pDisplay == NULL)
                return STATUS_NO_MEM;
            if ((res = pDisplay->init(0, NULL)) != STATUS_OK)
                return res;

            // Load visual schema
            if ((res = init_visual_schema()) != STATUS_OK)
                return res;

            // Initialize the UI
            if ((res = pUI->init(this, pDisplay)) != STATUS_OK)
                return res;

            return res;
        }

        void UIWrapper::destroy()
        {
            // Cleanup UI initialized flag
            bUIInitialized  = false;

            // Destroy the transient window wrapper
            if (pTransientFor != NULL)
            {
                delete pTransientFor;
                pTransientFor   = NULL;
            }

            // Stop the UI thread
            hide();

            // Call parent instance
            IWrapper::destroy();

            // Destroy UI
            if (pUI != NULL)
            {
                pUI->destroy();
                delete pUI;
                pUI = NULL;
            }
        }

        clap::UIPort *UIWrapper::create_port(const meta::port_t *port, const char *postfix)
        {
            // Find the matching port for the backend
            clap::UIPort *cup = NULL;
            clap::Port *cp    = pWrapper->find_by_id(port->id);
            if (cp == NULL)
                return cup;

            switch (port->role)
            {
                case meta::R_AUDIO: // Stub port
                    lsp_trace("creating stub audio port %s", port->id);
                    cup = new clap::UIPort(port, cp);
                    break;

                case meta::R_MESH:
                    lsp_trace("creating mesh port %s", port->id);
                    cup = new clap::UIMeshPort(cp);
                    break;

                case meta::R_STREAM:
                    lsp_trace("creating stream port %s", port->id);
                    cup = new clap::UIStreamPort(cp);
                    break;

                case meta::R_FBUFFER:
                    lsp_trace("creating fbuffer port %s", port->id);
                    cup = new clap::UIFrameBufferPort(cp);
                    break;

                case meta::R_OSC:
                    lsp_trace("creating osc port %s", port->id);
                    if (meta::is_out_port(port))
                        cup     = new clap::UIOscPortIn(port, cp);
                    else
                        cup     = new clap::UIOscPortOut(port, cp);
                    break;

                case meta::R_PATH:
                    lsp_trace("creating path port %s", port->id);
                    cup = new clap::UIPathPort(cp);
                    break;

                case meta::R_CONTROL:
                case meta::R_METER:
                case meta::R_BYPASS:
                    lsp_trace("creating regular port %s", port->id);
                    // VST specifies only INPUT parameters, output should be read in different way
                    if (meta::is_out_port(port))
                        cup     = new clap::UIMeterPort(cp);
                    else
                        cup     = new clap::UIParameterPort(static_cast<clap::ParameterPort *>(cp), &bRequestProcess);
                    break;

                case meta::R_PORT_SET:
                {
                    char postfix_buf[MAX_PARAM_ID_BYTES], param_name[MAX_PARAM_ID_BYTES];
                    lsp_trace("creating port group %s", port->id);
                    UIPortGroup *upg = new clap::UIPortGroup(static_cast<clap::PortGroup *>(cp), &bRequestProcess);

                    // Add immediately port group to list
                    vPorts.add(upg);

                    // Add nested ports
                    lsp_trace("  rows = %d", int(upg->rows()));
                    for (size_t row=0; row < upg->rows(); ++row)
                    {
                        // Generate postfix
                        snprintf(postfix_buf, sizeof(postfix_buf)-1, "%s_%d", (postfix != NULL) ? postfix : "", int(row));

                        // Obtain the related port for backend
                        for (const meta::port_t *p = port->members; p->id != NULL; ++p)
                        {
                            // Initialize port name
                            strncpy(param_name, p->id, sizeof(param_name)-1);
                            strncat(param_name, postfix_buf, sizeof(param_name)-1);
                            param_name[sizeof(param_name) - 1] = '\0';

                            // Obtain backend port and create UI port for it
                            cp    = pWrapper->find_by_id(param_name);
                            lsp_trace("find_by_id %s -> %p", param_name, cp);
                            if (cp != NULL)
                                create_port(cp->metadata(), postfix_buf);
                        }
                    }

                    break;
                }

                default:
                    break;
            }

            // Add port to the list of UI ports
            if (cup != NULL)
                vPorts.add(cup);

            return cup;
        }

        void UIWrapper::tranfet_ui_to_dsp()
        {
            if (bRequestProcess)
            {
                if ((pExt != NULL) && (pExt->host != NULL))
                    pExt->host->request_process(pExt->host);
                bRequestProcess = false;
            }
        }

        void UIWrapper::transfer_dsp_to_ui()
        {
            // Initialize DSP state
            dsp::context_t ctx;
            dsp::start(&ctx);
            lsp_finally { dsp::finish(&ctx); };

            // Try to sync position
            IWrapper::position_updated(pWrapper->position());

            // DSP -> UI communication
            for (size_t i=0, nports=vPorts.size(); i < nports; ++i)
            {
                // Get UI port
                clap::UIPort *cup   = static_cast<clap::UIPort *>(vPorts.uget(i));
                do {
                    if (cup->sync())
                        cup->notify_all();
                } while (cup->sync_again());
            } // for port_id

            // Perform KVT synchronization
            core::KVTStorage *kvt = pWrapper->kvt_lock();
            if (kvt != NULL)
            {
                // Synchronize DSP -> UI transfer
                size_t sync;
                const char *kvt_name;
                const core::kvt_param_t *kvt_value;

                do
                {
                    sync = 0;

                    core::KVTIterator *it = kvt->enum_tx_pending();
                    while (it->next() == STATUS_OK)
                    {
                        kvt_name = it->name();
                        if (kvt_name == NULL)
                            break;
                        status_t res = it->get(&kvt_value);
                        if (res != STATUS_OK)
                            break;
                        if ((res = it->commit(core::KVT_TX)) != STATUS_OK)
                            break;

                        kvt_dump_parameter("TX kvt param (DSP->UI): %s = ", kvt_value, kvt_name);
                        kvt_notify_write(kvt, kvt_name, kvt_value);
                        ++sync;
                    }
                } while (sync > 0);

                // Synchronize UI -> DSP transfer
                #ifdef LSP_DEBUG
                {
                    core::KVTIterator *it = kvt->enum_rx_pending();
                    while (it->next() == STATUS_OK)
                    {
                        kvt_name = it->name();
                        if (kvt_name == NULL)
                            break;
                        status_t res = it->get(&kvt_value);
                        if (res != STATUS_OK)
                            break;
                        if ((res = it->commit(core::KVT_RX)) != STATUS_OK)
                            break;

                        kvt_dump_parameter("RX kvt param (UI->DSP): %s = ", kvt_value, kvt_name);
                    }
                }
                #else
                    kvt-> commit_all(core::KVT_RX);    // Just clear all RX queue for non-debug version
                #endif /* LSP_DEBUG */

                // Call garbage collection and release KVT storage
                kvt->gc();
                kvt_release();
            }

            // Notify sample listeners if something has changed
            core::SamplePlayer *sp = pWrapper->sample_player();
            if (sp != NULL)
                notify_play_position(sp->position(), sp->sample_length());
        }

        core::KVTStorage *UIWrapper::kvt_lock()
        {
            return pWrapper->kvt_lock();
        }

        core::KVTStorage *UIWrapper::kvt_trylock()
        {
            return pWrapper->kvt_trylock();
        }

        bool UIWrapper::kvt_release()
        {
            return pWrapper->kvt_release();
        }

        void UIWrapper::dump_state_request()
        {
            pWrapper->request_state_dump();
        }

        const meta::package_t *UIWrapper::package() const
        {
            return pWrapper->package();
        }

        status_t UIWrapper::play_file(const char *file, wsize_t position, bool release)
        {
            core::SamplePlayer *p = pWrapper->sample_player();
            if (p != NULL)
            {
                // Trigger playback and force the position to become out-of-sync
                p->play_sample(file, position, release);
            }
            return STATUS_OK;
        }

        float UIWrapper::ui_scaling_factor(float scaling)
        {
            return (fScaling > 0.0f) ? fScaling : scaling;
        }

        bool UIWrapper::accept_window_size(size_t width, size_t height)
        {
            if (pExt == NULL)
                return IWrapper::accept_window_size(width, height);

            return pExt->gui->request_resize(pExt->host, width, height);
        }

        status_t UIWrapper::slot_ui_resize(tk::Widget *sender, void *ptr, void *data)
        {
            UIWrapper *this_    = static_cast<UIWrapper *>(ptr);
            tk::Window *wnd     = this_->window();
            if ((wnd == NULL) || (!wnd->visibility()->get()))
                return STATUS_OK;

            ws::rectangle_t rr;
            if (wnd->get_screen_rectangle(&rr) != STATUS_OK)
                return STATUS_OK;

            this_->pExt->gui->request_resize(this_->pExt->host, rr.nWidth, rr.nHeight);

            return STATUS_OK;
        }

        status_t UIWrapper::slot_ui_show(tk::Widget *sender, void *ptr, void *data)
        {
            return STATUS_OK;
        }

        status_t UIWrapper::slot_ui_realized(tk::Widget *sender, void *ptr, void *data)
        {
            UIWrapper *this_    = static_cast<UIWrapper *>(ptr);
            tk::Window *wnd     = this_->window();

            ws::rectangle_t rr;
            if (wnd->get_screen_rectangle(&rr) != STATUS_OK)
                return STATUS_OK;
            this_->pExt->gui->request_resize(this_->pExt->host, rr.nWidth, rr.nHeight);

            return STATUS_OK;
        }

        status_t UIWrapper::slot_ui_close(tk::Widget *sender, void *ptr, void *data)
        {
            UIWrapper *this_ = static_cast<UIWrapper *>(ptr);
            if (this_->pExt != NULL)
                this_->pExt->gui->closed(this_->pExt->host, false);
            return STATUS_OK;
        }

        status_t UIWrapper::ui_main_loop(void *arg)
        {
            static constexpr size_t FRAME_PERIOD    = 1000 / UI_FRAMES_PER_SECOND;

            UIWrapper *this_ = static_cast<UIWrapper *>(arg);

            lsp_trace("Entering main loop");

            // Perform main loop
            system::time_millis_t ctime = system::get_time_millis();
            while (!ipc::Thread::is_cancelled())
            {
                // Measure the time of next frame to appear
                system::time_millis_t deadline = ctime + FRAME_PERIOD;

                // Perform main iteration with locked mutex
                if (this_->sMutex.lock())
                {
                    lsp_finally { this_->sMutex.unlock(); };
                    this_->tranfet_ui_to_dsp();
                    this_->transfer_dsp_to_ui();
                    this_->main_iteration();
                }

                // Wait for the next frame to appear
                system::time_millis_t ftime = system::get_time_millis();
                if (ftime < deadline)
                    this_->pDisplay->wait_events(deadline - ftime);
                ctime   = ftime;
            }

            lsp_trace("Leaving main loop");

            return STATUS_OK;
        }

        bool UIWrapper::set_scale(double scale)
        {
            // Scale is in %
            fScaling    = scale * 100.0f;
            return true;
        }

        bool UIWrapper::get_size(uint32_t *width, uint32_t *height)
        {
            tk::Window *wnd     = window();
            if (wnd == NULL)
                return false;

            // Lock the access to the main loop
            ws::rectangle_t rr;
            rr.nWidth       = 0;
            rr.nHeight      = 0;

            if (!sMutex.lock())
                return false;
            lsp_finally { sMutex.unlock(); };

            // Obtain the window parameters
            if (!wnd->visibility()->get())
                return false;
            if (wnd->get_screen_rectangle(&rr) != STATUS_OK)
                return false;

            // Return result
            if (width != NULL)
                *width  = rr.nWidth;
            if (height != NULL)
                *height = rr.nHeight;

            return true;
        }

        bool UIWrapper::can_resize()
        {
            tk::Window *wnd     = window();
            if (wnd == NULL)
                return false;

            if (!sMutex.lock())
                return false;
            lsp_finally { sMutex.unlock(); };

            return wnd->border_style()->get() != ws::BS_DIALOG;
        }

        bool UIWrapper::get_resize_hints(clap_gui_resize_hints_t *hints)
        {
            tk::Window *wnd     = window();
            if (wnd == NULL)
                return false;

            if (!sMutex.lock())
                return false;
            lsp_finally { sMutex.unlock(); };

            // Obtain window size constraints
            ws::size_limit_t sr;
            wnd->get_padded_size_limits(&sr);

            hints->can_resize_horizontally = (sr.nMaxWidth < 0) || (sr.nMaxWidth  > sr.nMinWidth);
            hints->can_resize_vertically    = (sr.nMaxHeight< 0) || (sr.nMaxHeight > sr.nMinHeight);

            hints->preserve_aspect_ratio    = false;
            hints->aspect_ratio_width       = 1;
            hints->aspect_ratio_height      = 1;

            return true;
        }

        bool UIWrapper::adjust_size(uint32_t *width, uint32_t *height)
        {
            tk::Window *wnd     = window();
            if (wnd == NULL)
                return false;

            if (!sMutex.lock())
                return false;
            lsp_finally { sMutex.unlock(); };

            ws::size_limit_t sr;
            wnd->get_padded_size_limits(&sr);

            ws::rectangle_t r;
            r.nLeft     = 0;
            r.nTop      = 0;
            r.nWidth    = *width;
            r.nHeight   = *height;

            tk::SizeConstraints::apply(&r, &sr);

            *width      = r.nWidth;
            *height     = r.nHeight;

            return true;
        }

        bool UIWrapper::set_size(uint32_t width, uint32_t height)
        {
            tk::Window *wnd     = window();
            if (wnd == NULL)
                return false;

            if (!sMutex.lock())
                return false;
            lsp_finally { sMutex.unlock(); };

            wnd->resize_window(width, height);

            return true;
        }

        void *UIWrapper::to_native_handle(const clap_window_t *window)
        {
        #if defined(PLATFORM_WINDOWS)
            return static_cast<void *>(window->win32);
        #elif defined(PLATFORM_MACOSX)
            return static_cast<void *>(window->cocoa);
        #else
            return reinterpret_cast<void *>(window->x11);
        #endif
        }

        bool UIWrapper::set_parent(const clap_window_t *window)
        {
            pParent     = to_native_handle(window);
            return true;
        }

        bool UIWrapper::set_transient(const clap_window_t *window)
        {
            if (pDisplay == NULL)
                return false;

            if (pTransientFor != NULL)
                delete pTransientFor;

            void *handle    = to_native_handle(window);
            pTransientFor   = (handle != NULL) ? pDisplay->display()->wrap_window(handle) : NULL;

            return true;
        }

        void UIWrapper::suggest_title(const char *title)
        {
            tk::Window *wnd     = window();
            if (wnd == NULL)
                return;
            if (!sMutex.lock())
                return;
            lsp_finally { sMutex.unlock(); };

            // Update the window title
            wnd->title()->set_raw(title);
        }

        bool UIWrapper::initialize_ui()
        {
            if (bUIInitialized)
                return true;

            lsp_trace("Initializing UI contents");

            status_t res = STATUS_OK;
            const meta::plugin_t *meta = pUI->metadata();
            if (pUI->metadata() == NULL)
                return false;

            if (meta->ui_resource != NULL)
            {
                if ((res = build_ui(meta->ui_resource, pParent)) != STATUS_OK)
                {
                    lsp_error("Error building UI for resource %s: code=%d", meta->ui_resource, int(res));
                    return false;
                }
            }

            // Bind resize slot
            lsp_trace("Binding slots");
            tk::Window *wnd  = window();
            if (wnd != NULL)
            {
                wnd->slots()->bind(tk::SLOT_RESIZE, slot_ui_resize, this);
                wnd->slots()->bind(tk::SLOT_SHOW, slot_ui_show, this);
                wnd->slots()->bind(tk::SLOT_REALIZED, slot_ui_realized, this);
                wnd->slots()->bind(tk::SLOT_CLOSE, slot_ui_close, this);
            }

            // Call the post-initialization routine
            if (res == STATUS_OK)
            {
                lsp_trace("Doing post-init");
                res = pUI->post_init();
            }

            bUIInitialized = (res == STATUS_OK);
            lsp_trace("bUIInitialized = %d, res=%d", int(bUIInitialized), int(res));
            return bUIInitialized;
        }

        bool UIWrapper::ui_active() const
        {
            return pUIThread != NULL;
        }

        bool UIWrapper::show()
        {
            // Lazy initialize the UI ONLY after whe have the parent/transient settings
            if (!initialize_ui())
                return false;

            tk::Window *wnd  = window();
            if (wnd == NULL)
                return false;

            // Launch the main loop thread
            lsp_trace("Creating main loop thread");
            pUIThread   = new ipc::Thread(ui_main_loop, this);
            if (pUIThread == NULL)
                return false;

            // Show the window and start the main thread
            wnd->show(pTransientFor);
            if (pUIThread->start() != STATUS_OK)
            {
                lsp_error("Failed to start UI main loop thread");
                wnd->hide();
                delete pUIThread;
                pUIThread = NULL;
                return false;
            }

            lsp_trace("Successfully started main loop thread");

            return true;
        }

        bool UIWrapper::hide()
        {
            // Cancel the main loop thread
            if (pUIThread != NULL)
            {
                pUIThread->cancel();
                pUIThread->join();

                delete pUIThread;
                pUIThread = NULL;
            }

            // Hide the window
            tk::Window *wnd = window();
            if (wnd != NULL)
                wnd->hide();

            return true;
        }

    } /* namespace clap */
} /* namespace lsp */

#endif /* LSP_PLUG_IN_PLUG_FW_WRAP_CLAP_IMPL_UI_WRAPPER_H_ */