-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathPluginEditor.cpp
More file actions
1996 lines (1736 loc) · 69.1 KB
/
PluginEditor.cpp
File metadata and controls
1996 lines (1736 loc) · 69.1 KB
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
// Copyright (c) 2021-2025 Timothy Schoen
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/
#include <juce_gui_basics/juce_gui_basics.h>
#include <juce_audio_processors/juce_audio_processors.h>
#include <juce_animation/juce_animation.h>
#include "Utility/Config.h"
#include "Utility/Fonts.h"
#include "Utility/OSUtils.h"
#include "PluginEditor.h"
#include "PluginProcessor.h"
#include "Pd/Patch.h"
#include "LookAndFeel.h"
#include "Sidebar/Palettes.h"
#include "Utility/Autosave.h"
#include "Utility/RateReducer.h"
#include "Utility/StackShadow.h"
#include "Canvas.h"
#include "Connection.h"
#include "Components/ConnectionMessageDisplay.h"
#include "Components/ConsoleMessageDisplay.h"
#include "Dialogs/Dialogs.h"
#include "Statusbar.h"
#include "Toolbar.h"
#include "Components/WelcomePanel.h"
#include "Sidebar/Sidebar.h"
#include "Object.h"
#include "PluginMode.h"
#include "Components/TouchSelectionHelper.h"
#include "NVGSurface.h"
#if ENABLE_TESTING
void runTests(PluginEditor* editor);
#endif
#include <juce_opengl/juce_opengl.h>
using namespace juce::gl;
#include <nanovg.h>
class CalloutArea final : public Component
, public Timer {
public:
explicit CalloutArea(Component* parent)
: target(parent)
, tooltipWindow(this)
{
setVisible(true);
setAlwaysOnTop(true);
setInterceptsMouseClicks(false, true);
startTimerHz(3);
}
~CalloutArea() override = default;
void timerCallback() override
{
#if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
setBounds(target->getScreenBounds() / getApproximateScaleFactorForComponent(target));
#else
setBounds(target->getScreenBounds());
#endif
}
void paint(Graphics& g) override
{
if (!ProjectInfo::canUseSemiTransparentWindows()) {
g.fillAll(PlugDataColours::popupMenuBackgroundColour);
}
}
#if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
float getDesktopScaleFactor() const override
{
return getApproximateScaleFactorForComponent(target) * Desktop::getInstance().getGlobalScaleFactor();
};
#endif
private:
WeakReference<Component> target;
TooltipWindow tooltipWindow;
};
PluginEditor::PluginEditor(PluginProcessor& p)
: AudioProcessorEditor(&p)
, pd(&p)
, sidebar(std::make_unique<Sidebar>(&p, this))
, statusbar(std::make_unique<Statusbar>(&p, this))
, nvgSurface(this)
, openedDialog(nullptr)
, pluginConstrainer(*getConstrainer())
, tooltipWindow([this] { return std::sqrt(std::abs(getTransform().getDeterminant())) * SettingsFile::getInstance()->getProperty<float>("global_scale"); }, [](Component const* c) {
if (auto const* cnv = c->findParentComponentOfClass<Canvas>()) {
return !getValue<bool>(cnv->locked);
}
return true; })
, tabComponent(this)
, pluginMode(nullptr)
, consoleMessageDisplay(std::make_unique<ConsoleMessageDisplay>(this))
, touchSelectionHelper(std::make_unique<TouchSelectionHelper>(this))
, recentlyOpenedPanelSelector(Icons::Home, "Home")
, libraryPanelSelector(Icons::ItemGrid, "Library")
{
keyboardLayout = OSUtils::getKeyboardLayout();
#if !JUCE_IOS
// if we are inside a DAW / host set up the border resizer now
if (!ProjectInfo::isStandalone) {
// NEVER touch pluginConstrainer outside of plugin mode!
pluginConstrainer.setMinimumSize(890, 660);
setUseBorderResizer(true);
} else {
constrainer.setMinimumSize(890, 660);
}
#endif
mainMenuButton.setButtonText(Icons::Menu);
undoButton.setButtonText(Icons::Undo);
redoButton.setButtonText(Icons::Redo);
welcomePanelSearchButton.setButtonText(Icons::Search);
addKeyListener(commandManager.getKeyMappings());
welcomePanel = std::make_unique<WelcomePanel>(this);
addChildComponent(*welcomePanel);
welcomePanel->setAlwaysOnTop(true);
welcomePanelSearchButton.setClickingTogglesState(true);
welcomePanelSearchButton.onClick = [this] {
if (welcomePanelSearchButton.getToggleState()) {
welcomePanelSearchInput.setVisible(true);
welcomePanelSearchInput.grabKeyboardFocus();
welcomePanel->setSearchQuery("");
} else {
welcomePanelSearchInput.setVisible(false);
}
};
welcomePanelSearchInput.onTextChange = [this] {
welcomePanel->setSearchQuery(welcomePanelSearchInput.getText());
};
// Hide the search input bar if the text is empty and focus is lost
welcomePanelSearchInput.onFocusLost = [this] {
if (welcomePanelSearchButton.isMouseOver()) {
return;
}
if (welcomePanelSearchInput.getText().isEmpty()) {
welcomePanelSearchButton.setToggleState(false, dontSendNotification);
welcomePanelSearchInput.setVisible(false);
}
};
welcomePanelSearchInput.setTextToShowWhenEmpty("Type to search patches", PlugDataColours::panelTextColour.withAlpha(0.5f));
welcomePanelSearchInput.setBorder({ 1, 3, 5, 1 });
welcomePanelSearchInput.setJustification(Justification::centredLeft);
addChildComponent(welcomePanelSearchInput);
setWantsKeyboardFocus(true);
commandManager.registerAllCommandsForTarget(this);
auto* settingsFile = SettingsFile::getInstance();
PlugDataLook::setDefaultFont(settingsFile->getProperty<String>("default_font"));
if (auto const elt = XmlDocument(settingsFile->getKeyMap()).getDocumentElement()) {
commandManager.getKeyMappings()->restoreFromXml(*elt);
}
autoconnect.referTo(settingsFile->getPropertyAsValue("autoconnect"));
theme.referTo(settingsFile->getPropertyAsValue("theme"));
theme.addListener(this);
addChildComponent(*sidebar);
addAndMakeVisible(tabComponent);
calloutArea = std::make_unique<CalloutArea>(this);
calloutArea->setVisible(true);
calloutArea->setAlwaysOnTop(true);
calloutArea->setInterceptsMouseClicks(true, true);
setOpaque(false);
// Show settings
mainMenuButton.setTooltip("Main menu");
mainMenuButton.onClick = [this] {
Dialogs::showMainMenu(this, &mainMenuButton);
};
addAndMakeVisible(mainMenuButton);
// Undo button
undoButton.isUndo = true;
undoButton.onClick = [this] { getCurrentCanvas()->undo(); };
addChildComponent(undoButton);
// Redo button
redoButton.isRedo = true;
redoButton.onClick = [this] { getCurrentCanvas()->redo(); };
addChildComponent(redoButton);
// New object button
addObjectMenuButton.setButtonText(Icons::AddObject);
addObjectMenuButton.setTooltip("Add object");
addObjectMenuButton.onClick = [this] { Dialogs::showObjectMenu(this, &addObjectMenuButton); };
addChildComponent(addObjectMenuButton);
recentlyOpenedPanelSelector.setClickingTogglesState(true);
libraryPanelSelector.setClickingTogglesState(true);
recentlyOpenedPanelSelector.setRadioGroupId(hash("welcome_panel_selectors"));
libraryPanelSelector.setRadioGroupId(hash("welcome_panel_selectors"));
addChildComponent(recentlyOpenedPanelSelector);
addChildComponent(libraryPanelSelector);
recentlyOpenedPanelSelector.onClick = [this, settingsFile] {
settingsFile->setProperty("last_welcome_panel", var(0));
welcomePanel->setShownTab(WelcomePanel::Home);
};
libraryPanelSelector.onClick = [this, settingsFile] {
settingsFile->setProperty("last_welcome_panel", var(1));
welcomePanel->setShownTab(WelcomePanel::Library);
};
auto const lastWelcomePanel = settingsFile->getProperty<int>("last_welcome_panel");
recentlyOpenedPanelSelector.setToggleState(!lastWelcomePanel, sendNotification);
libraryPanelSelector.setToggleState(lastWelcomePanel, sendNotification);
sidebar->setSize(250, pd->lastUIHeight);
sidebar->toFront(false);
// Make sure existing console messages are processed
sidebar->updateConsole(0, false);
updateCommandStatus();
addModifierKeyListener(this);
connectionMessageDisplay = std::make_unique<ConnectionMessageDisplay>(this);
ObjectThemeManager::get()->updateTheme(pd);
addChildComponent(nvgSurface);
nvgSurface.toBehind(&tabComponent);
editorIndex = ProjectInfo::isStandalone ? numEditors++ : 0;
if (SettingsFile::getInstance()->isUsingTouchMode()) {
addAndMakeVisible(touchSelectionHelper.get());
}
touchSelectionHelper->setAlwaysOnTop(true);
statusbar->setAlwaysOnTop(true);
addAndMakeVisible(statusbar.get());
consoleMessageDisplay->setAlwaysOnTop(true);
addChildComponent(consoleMessageDisplay.get());
audioToolbar = std::make_unique<AudioToolbar>(pd, this);
audioToolbar->setAlwaysOnTop(true);
addAndMakeVisible(audioToolbar.get());
for (auto* button : SmallArray<MainToolbarButton*> {
&mainMenuButton,
&undoButton,
&redoButton,
&addObjectMenuButton,
&welcomePanelSearchButton
}) {
addChildComponent(button);
}
setSize(pd->lastUIWidth, pd->lastUIHeight);
#if ENABLE_TESTING
// Call after window is ready
::Timer::callAfterDelay(200, [this]() {
runTests(this);
});
#endif
pd->messageDispatcher->setBlockMessages(false);
lookAndFeelChanged();
::Timer::callAfterDelay(100, [this, settingsFile] {
if (settingsFile->getSettingsState() != SettingsFile::SettingsState::UserSettings) {
String errorText = "Corrupt settings detected and fixed\n";
if (settingsFile->getSettingsState() == SettingsFile::SettingsState::DefaultSettings) {
errorText += "plugdata will use default settings.\n\n";
} else {
errorText += "plugdata will use last good settings.\n\n";
}
auto corruptedSettingsLocation = settingsFile->getCorruptBackupSettingsLocation();
errorText += " Previous settings backed up to:\n\n" + settingsFile->getCorruptBackupSettingsLocation();
Dialogs::showMultiChoiceDialog(&openedDialog, this, errorText, [corruptedSettingsLocation](int const result) {
if (result) {
File(corruptedSettingsLocation).revealToUser();
}
},
{ "Dismiss", "Reveal corrupted file" });
settingsFile->resetSettingsState();
}
});
#if JUCE_IOS
pd->lnf->setMainComponent(this);
#endif
startTimerHz(90);
}
PluginEditor::~PluginEditor()
{
nvgSurface.detachContext();
theme.removeListener(this);
if (auto* window = dynamic_cast<PlugDataWindow*>(getTopLevelComponent())) {
SettingsFile::getInstance()->setProperty("window_size", Array<var>{window->getWidth(), window->getHeight()});
SettingsFile::getInstance()->saveSettings();
ProjectInfo::closeWindow(window); // Make sure plugdatawindow gets cleaned up
}
if (!ProjectInfo::isStandalone) {
// Block incoming gui messages from pd if there is no active editor
pd->messageDispatcher->setBlockMessages(true);
}
stopTimer();
}
void PluginEditor::setUseBorderResizer(bool const shouldUse)
{
if (shouldUse) {
if (ProjectInfo::isStandalone) {
if (!borderResizer) {
borderResizer = std::make_unique<MouseRateReducedComponent<ResizableBorderComponent>>(getTopLevelComponent(), &constrainer);
borderResizer->setAlwaysOnTop(true);
addAndMakeVisible(borderResizer.get());
}
borderResizer->setVisible(true);
resized(); // Makes sure resizer gets resized
if (isInPluginMode()) {
borderResizer->toBehind(pluginMode.get());
}
} else {
if (!cornerResizer) {
cornerResizer = std::make_unique<MouseRateReducedComponent<ResizableCornerComponent>>(this, &pluginConstrainer);
cornerResizer->setAlwaysOnTop(true);
}
addAndMakeVisible(cornerResizer.get());
}
} else {
if (ProjectInfo::isStandalone && borderResizer) {
borderResizer->setVisible(false);
}
}
}
void PluginEditor::paint(Graphics& g)
{
auto baseColour = PlugDataColours::toolbarBackgroundColour;
if (ProjectInfo::isStandalone && !isActiveWindow()) {
baseColour = baseColour.brighter(baseColour.getBrightness() / 2.5f);
}
#if JUCE_MAC || JUCE_LINUX || JUCE_BSD
if (wantsRoundedCorners()) {
g.setColour(baseColour);
g.fillRoundedRectangle(getLocalBounds().toFloat(), Corners::windowCornerRadius);
} else {
g.fillAll(baseColour);
}
#else
g.fillAll(baseColour);
#endif
// Paint a background only for the welcome panel.
// We need to do this because we can't push the NVG window to the edge
// as it will block the DnD highlight of the window border
// This is easier than having to replicate the DnD highlight at the edge of the NVG window.
if (welcomePanel->isVisible()) {
g.setColour(PlugDataColours::panelBackgroundColour);
g.fillRect(workArea.withTrimmedTop(5));
}
// Update dialog background visibility, synced with repaint for smoothness
nvgSurface.updateWindowContextVisibility();
}
// Paint file drop outline
void PluginEditor::paintOverChildren(Graphics& g)
{
// Never want to be drawing over a dialog window
if (openedDialog)
return;
if (isDraggingFile) {
g.setColour(PlugDataColours::dataColour);
g.drawRoundedRectangle(getLocalBounds().reduced(1).toFloat(), Corners::windowCornerRadius, 2.0f);
}
auto const welcomePanelVisible = !getCurrentCanvas();
auto const tabbarDepth = welcomePanelVisible ? toolbarHeight + 5.5f : toolbarHeight + 30.0f;
auto const sidebarLeft = sidebar->isVisible() ? sidebar->getX() + 1.0f : getWidth();
g.setColour(PlugDataColours::toolbarOutlineColour);
g.drawLine(0, tabbarDepth, sidebarLeft, tabbarDepth);
// Draw extra lines in case tabbar is not visible. Otherwise some outlines will stop too soon
if (!getCurrentCanvas()) {
auto const toolbarDepth = welcomePanelVisible ? toolbarHeight + 6 : toolbarHeight;
g.drawLine(0, toolbarDepth, 0, toolbarDepth + 30);
if (sidebar->isVisible())
g.drawLine(sidebar->getX() + 0.5f, toolbarDepth, sidebar->getX() + 0.5f, toolbarHeight + 30);
}
if (pluginMode) {
g.setColour(PlugDataColours::canvasBackgroundColour);
g.fillRect(getLocalBounds().withTrimmedTop(40));
}
}
void PluginEditor::renderArea(NVGcontext* nvg, Rectangle<int> const area)
{
auto renderScale = nvgSurface.getRenderScale();
if (!nvgCtx || nvgCtx->getContext() != nvg || !approximatelyEqual(nvgCtx->getPhysicalPixelScaleFactor(), renderScale)) {
nvgCtx = std::make_unique<NVGGraphicsContext>(nvg);
nvgCtx->setPhysicalPixelScaleFactor(renderScale);
}
if (isInPluginMode()) {
nvgFillColor(nvg, nvgColour(PlugDataColours::canvasBackgroundColour));
nvgFillRect(nvg, 0, 0, getWidth(), getHeight());
pluginMode->render(nvg, area);
} else {
if (welcomePanel->isVisible()) {
NVGScopedState scopedState(nvg);
welcomePanel->render(nvg);
} else {
tabComponent.renderArea(nvg, area);
if(sidebar->isHidden())
sidebar->renderButtonsOnCanvas(nvg);
Graphics g(*getNanoLLGC());
if (touchSelectionHelper && touchSelectionHelper->getParentComponent() && touchSelectionHelper->isVisible() && area.intersects(touchSelectionHelper->getBounds() - nvgSurface.getPosition())) {
NVGScopedState scopedState(nvg);
nvgTranslate(nvg, touchSelectionHelper->getX() - nvgSurface.getX(), touchSelectionHelper->getY() - nvgSurface.getY());
touchSelectionHelper->paintEntireComponent(g, false);
}
{
NVGScopedState scopedState(nvg);
nvgTranslate(nvg, statusbar->getX() - nvgSurface.getX(), statusbar->getY() - nvgSurface.getY());
statusbar->paintEntireComponent(g, false);
}
if(consoleMessageDisplay->isVisible())
{
NVGScopedState scopedState(nvg);
nvgTranslate(nvg, consoleMessageDisplay->getX() - nvgSurface.getX(), consoleMessageDisplay->getY() - nvgSurface.getY());
consoleMessageDisplay->paintEntireComponent(g, false);
}
}
}
}
CallOutBox& PluginEditor::showCalloutBox(std::unique_ptr<Component> content, Rectangle<int> const screenBounds)
{
class CalloutDeletionListener : public ComponentListener {
PluginEditor* editor;
public:
explicit CalloutDeletionListener(PluginEditor* e)
: editor(e)
{
}
void componentBeingDeleted(Component& c) override
{
c.removeComponentListener(this);
editor->calloutArea->removeFromDesktop();
delete this;
}
};
if (ProjectInfo::canUseSemiTransparentWindows()) {
content->addComponentListener(new CalloutDeletionListener(this));
calloutArea->addToDesktop(ComponentPeer::windowIsTemporary, OSUtils::getDesktopParentPeer(this));
calloutArea->toFront(true);
auto const bounds = calloutArea->getLocalArea(nullptr, screenBounds);
return CallOutBox::launchAsynchronously(std::move(content), bounds, calloutArea.get());
}
return CallOutBox::launchAsynchronously(std::move(content), screenBounds, nullptr);
}
void PluginEditor::showWelcomePanel(bool const shouldShow)
{
addObjectMenuButton.setVisible(!shouldShow);
undoButton.setVisible(!shouldShow);
redoButton.setVisible(!shouldShow);
sidebar->setVisible(!shouldShow);
welcomePanelSearchButton.setVisible(shouldShow);
recentlyOpenedPanelSelector.setVisible(shouldShow);
libraryPanelSelector.setVisible(shouldShow);
if (shouldShow) {
welcomePanel->show();
sidebar->showSidebar(true);
} else {
welcomePanel->hide();
welcomePanelSearchButton.setToggleState(false, sendNotification);
welcomePanel->setSearchQuery("");
}
}
void PluginEditor::dragOperationEnded (DragAndDropTarget::SourceDetails const& details)
{
if(!ProjectInfo::isStandalone) return;
auto wasDroppedOnTarget = static_cast<bool>(details.description.getDynamicObject()->getProperty("dropped"));
if(!wasDroppedOnTarget) {
tabComponent.createNewWindowFromTab(details.sourceComponent);
}
}
void PluginEditor::resized()
{
#if JUCE_IOS
static bool alreadyResized = false;
if (auto* window = dynamic_cast<PlugDataWindow*>(getTopLevelComponent())) {
if (!alreadyResized) {
ScopedValueSetter recursionBlock(alreadyResized, true);
auto totalArea = Desktop::getInstance().getDisplays().getPrimaryDisplay()->totalArea;
totalArea = OSUtils::getSafeAreaInsets().subtractedFrom(totalArea);
setBounds(totalArea);
window->setFullScreen(true);
}
}
#endif
pd->lastUIWidth = getWidth();
pd->lastUIHeight = getHeight();
if (isInPluginMode()) {
nvgSurface.updateBounds(getLocalBounds().withTrimmedTop(pluginMode->isWindowFullscreen() ? 0 : 40));
return;
}
#if JUCE_LINUX || JUCE_BSD
nvgSurface.setRoundedBottomCorners(true, sidebar->isHidden());
#endif
auto const workAreaHeight = getHeight() - toolbarHeight;
auto const sidebarWidth = (sidebar->isVisible() && !sidebar->isHidden()) ? sidebar->getWidth() : 0;
workArea = Rectangle<int>(0, toolbarHeight, getWidth() - sidebarWidth, workAreaHeight);
auto insetWorkArea = workArea;
if (welcomePanel->isVisible())
insetWorkArea.reduce(2, 0);
nvgSurface.updateBounds(welcomePanel->isVisible() ? insetWorkArea.withTrimmedTop(6) : insetWorkArea.withTrimmedTop(31));
welcomePanel->setBounds(insetWorkArea.withTrimmedTop(4));
tabComponent.setBounds(insetWorkArea);
sidebar->setBounds(getWidth() - sidebar->getWidth(), toolbarHeight, sidebar->getWidth(), workAreaHeight);
#if JUCE_MAC
auto useLeftButtons = true;
#else
auto useLeftButtons = false;
#endif
auto const useNonNativeTitlebar = ProjectInfo::isStandalone && !SettingsFile::getInstance()->getProperty<bool>("native_window");
auto offset = useLeftButtons && useNonNativeTitlebar ? 80 : 15;
#if JUCE_MAC
if (auto const standalone = ProjectInfo::isStandalone ? dynamic_cast<DocumentWindow*>(getTopLevelComponent()) : nullptr)
offset = standalone->isFullScreen() ? 20 : offset;
#endif
constexpr auto buttonDistance = 46;
auto const buttonSize = toolbarHeight + 5;
mainMenuButton.setBounds(offset, 0, buttonSize, buttonSize);
undoButton.setBounds(buttonDistance + offset, 0, buttonSize, buttonSize);
redoButton.setBounds(2 * buttonDistance + offset, 0, buttonSize, buttonSize);
addObjectMenuButton.setBounds(3 * buttonDistance + offset, 0, buttonSize, buttonSize);
auto statusbarBounds = getLocalBounds().removeFromBottom(46).translated(0, -12);
if (SettingsFile::getInstance()->isUsingTouchMode()) {
touchSelectionHelper->setBounds(statusbarBounds.withSizeKeepingCentre(192, 46));
statusbar->setBounds(statusbarBounds.removeFromLeft(208).translated(4, 0));
consoleMessageDisplay->setBounds(statusbarBounds.removeFromRight(consoleMessageDisplay->getDesiredWidth() + 2).translated(-8, 0));
}
else {
statusbar->setBounds(statusbarBounds.withSizeKeepingCentre(204, 46));
consoleMessageDisplay->setBounds(statusbarBounds.removeFromRight(consoleMessageDisplay->getDesiredWidth() + 2).translated(-8, 0));
}
#if JUCE_IOS
auto windowControlsOffset = 45.0f;
#else
auto windowControlsOffset = useNonNativeTitlebar && !useLeftButtons ? 90.f : 0.f;
#endif
auto audioToolbarWidth = welcomePanelSearchButton.isVisible() ? 210 : getWidth() - addObjectMenuButton.getRight();
if(audioToolbar) audioToolbar->setBounds(getLocalBounds().removeFromTop(toolbarHeight).removeFromRight(audioToolbarWidth).translated(-windowControlsOffset, 2));
auto welcomeSelectorBounds = getLocalBounds().removeFromTop(toolbarHeight + 8).withSizeKeepingCentre(200, toolbarHeight).translated(0, -1);
recentlyOpenedPanelSelector.setBounds(welcomeSelectorBounds.removeFromLeft(100));
libraryPanelSelector.setBounds(welcomeSelectorBounds.removeFromLeft(100));
if (borderResizer && ProjectInfo::isStandalone) {
borderResizer->setBounds(getLocalBounds());
} else if (cornerResizer) {
constexpr int resizerSize = 18;
cornerResizer->setBounds(getWidth() - resizerSize + 1,
getHeight() - resizerSize + 1,
resizerSize, resizerSize);
}
welcomePanelSearchButton.setBounds(audioToolbar->getX() - buttonSize + 12, 0, buttonSize, buttonSize);
welcomePanelSearchInput.setBounds(libraryPanelSelector.getRight() + 10, 4, welcomePanelSearchButton.getX() - libraryPanelSelector.getRight() - 20, toolbarHeight - 4);
repaint(); // Some outlines are dependent on whether or not the sidebars are expanded, or whether or not a patch is opened
}
bool PluginEditor::isInPluginMode() const
{
return static_cast<bool>(pluginMode);
}
Canvas* PluginEditor::getPluginModeCanvas() const
{
if (isInPluginMode())
return pluginMode->getCanvas();
return nullptr;
}
void PluginEditor::parentSizeChanged()
{
if (!ProjectInfo::isStandalone)
return;
auto* standalone = dynamic_cast<PlugDataWindow*>(getTopLevelComponent());
// Hide TitleBar Buttons in Plugin Mode
bool visible = !isInPluginMode();
#if JUCE_MAC
if (!standalone->useNativeTitlebar() && !visible && !standalone->isFullScreen()) {
// Hide TitleBar Buttons in Plugin Mode if using native title bar
if (ComponentPeer* peer = standalone->getPeer())
OSUtils::hideTitlebarButtons(peer, true, true, true);
} else {
// Show TitleBar Buttons
if (ComponentPeer* peer = standalone->getPeer())
OSUtils::hideTitlebarButtons(peer, false, false, false);
}
#else
if (!standalone->useNativeTitlebar()) {
// Hide/Show TitleBar Buttons in Plugin Mode
standalone->getCloseButton()->setVisible(visible);
standalone->getMinimiseButton()->setVisible(visible);
standalone->getMaximiseButton()->setVisible(visible);
}
#endif
resized();
}
void PluginEditor::updateIoletGeometryForAllObjects(PluginProcessor const* pd)
{
// update all object's iolet position
for (auto const& editor : pd->getEditors()) {
for (auto const& cnv : editor->getCanvases()) {
for (auto const& obj : cnv->objects) {
obj->updateIoletGeometry();
}
}
}
// update all connections to make sure they attach to the correct iolet positions
for (auto const& editor : pd->getEditors()) {
for (auto const& cnv : editor->getCanvases()) {
for (auto const& con : cnv->connections) {
con->forceUpdate();
}
}
}
}
void PluginEditor::mouseDown(MouseEvent const& e)
{
// no window dragging by toolbar in plugin!
if (!ProjectInfo::isStandalone || !e.mods.isLeftButtonDown())
return;
if (e.getNumberOfClicks() >= 2) {
#if JUCE_MAC
if (isMaximised) {
getPeer()->setBounds(unmaximisedSize, false);
} else {
unmaximisedSize = getTopLevelComponent()->getBounds();
auto const userArea = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
getPeer()->setBounds(userArea, false);
}
isMaximised = !isMaximised;
#else
findParentComponentOfClass<DocumentWindow>()->maximiseButtonPressed();
#endif
}
#if !JUCE_MAC && !JUCE_IOS
if (e.getPosition().getY() < toolbarHeight) {
if (auto* window = findParentComponentOfClass<PlugDataWindow>()) {
if (!window->useNativeTitlebar())
windowDragger.startDraggingWindow(window, e.getEventRelativeTo(window));
}
}
#endif
}
void PluginEditor::mouseDrag(MouseEvent const& e)
{
if (!ProjectInfo::isStandalone)
return;
#if !JUCE_MAC && !JUCE_IOS
if (!isMaximised) {
if (auto* window = findParentComponentOfClass<PlugDataWindow>()) {
if (!window->useNativeTitlebar())
windowDragger.dragWindow(window, e.getEventRelativeTo(window));
}
}
#endif
}
bool PluginEditor::isInterestedInFileDrag(StringArray const& files)
{
if (openedDialog)
return false;
for (auto& path : files) {
auto file = File(path);
if (file.exists()) {
return true;
}
}
return false;
}
void PluginEditor::fileDragMove(StringArray const& files, int const x, int const y)
{
for (auto& path : files) {
auto file = File(path);
if (file.exists() && file.hasFileExtension("pd") && !isDraggingFile) {
isDraggingFile = true;
repaint();
return;
}
}
bool const wasDraggingFile = isDraggingFile;
if (auto* cnv = tabComponent.getCanvasAtScreenPosition(localPointToGlobal(Point<int>(x, y)))) {
if (wasDraggingFile) {
isDraggingFile = false;
repaint();
}
tabComponent.setActiveSplit(cnv);
return;
}
if (!wasDraggingFile) {
isDraggingFile = true;
}
repaint();
}
void PluginEditor::filesDropped(StringArray const& files, int const x, int const y)
{
// First check for .pd files
bool openedPdFiles = false;
for (auto& path : files) {
auto file = File(path);
if (file.exists() && file.hasFileExtension("pd")) {
openedPdFiles = true;
tabComponent.openPatch(URL(file));
}
if (file.exists() && file.hasFileExtension("plugdata")) {
installPackage(file);
}
}
if (auto* cnv = tabComponent.getCanvasAtScreenPosition(localPointToGlobal(Point<int>(x, y)))) {
for (auto& path : files) {
auto file = File(path);
if (file.exists() && !openedPdFiles) {
auto position = cnv->getLocalPoint(this, Point<int>(x, y));
auto filePath = file.getFullPathName().replaceCharacter('\\', '/').replace(" ", "\\ ");
auto* object = cnv->objects.add(cnv, "msg " + filePath, position);
object->hideEditor();
}
}
}
isDraggingFile = false;
repaint();
}
void PluginEditor::fileDragEnter(StringArray const&, int, int)
{
isDraggingFile = true;
repaint();
}
void PluginEditor::fileDragExit(StringArray const&)
{
isDraggingFile = false;
repaint();
}
void PluginEditor::installPackage(File const& file)
{
auto install = [this, file] {
auto zip = ZipFile(file);
auto patchesDir = ProjectInfo::appDataDir.getChildFile("Patches");
auto extractedDir = File::createTempFile("");
auto const result = zip.uncompressTo(extractedDir, false);
if (result.wasOk()) {
auto const macOSTrash = ProjectInfo::appDataDir.getChildFile("Patches").getChildFile("__MACOSX");
if (macOSTrash.isDirectory()) {
macOSTrash.deleteRecursively();
}
for (auto extractedLocation : OSUtils::iterateDirectory(extractedDir, false, false)) {
if (!extractedLocation.isDirectory() || extractedLocation.getFileName() == "__MACOSX")
continue;
auto const metaFile = extractedLocation.getChildFile("meta.json");
if (!metaFile.existsAsFile()) {
PatchInfo info;
info.title = file.getFileNameWithoutExtension();
auto json = info.json;
metaFile.replaceWithText(info.json);
} else {
auto info = PatchInfo(JSON::fromString(metaFile.loadFileAsString()));
auto json = info.json;
metaFile.replaceWithText(info.json);
OSUtils::moveFileTo(extractedLocation, patchesDir.getChildFile(info.getNameInPatchFolder()));
}
}
MessageManager::callAsync([this, file] {
Dialogs::showMultiChoiceDialog(&openedDialog, this, "Successfully installed " + file.getFileNameWithoutExtension(), [](int) { }, { "Dismiss" }, Icons::Checkmark);
});
} else {
MessageManager::callAsync([this, file] {
Dialogs::showMultiChoiceDialog(&openedDialog, this, "Failed to install " + file.getFileNameWithoutExtension(), [](int) { }, { "Dismiss" });
});
}
};
if (OSUtils::isFileQuarantined(file)) {
Dialogs::showMultiChoiceDialog(&openedDialog, this, "This patch was downloaded from the internet. Installing patches from untrusted sources may pose security risks. Do you want to proceed?", [install, file](int const choice) {
if (choice == 0) {
OSUtils::removeFromQuarantine(file);
install();
} }, { "Trust and Install", "Cancel" }, Icons::Warning);
} else {
install();
}
}
void PluginEditor::updateConsole(SmallString const& message, bool messageIsWarning, int numMessages, bool newWarning)
{
sidebar->updateConsole(numMessages, newWarning);
if(sidebar->isHidden())
consoleMessageDisplay->showMessage(message, messageIsWarning);
}
TabComponent& PluginEditor::getTabComponent()
{
return tabComponent;
}
bool PluginEditor::isActiveWindow()
{
bool const isDraggingTab = DragAndDropContainer::isDragAndDropActive();
return !ProjectInfo::isStandalone || isDraggingTab || TopLevelWindow::getActiveTopLevelWindow() == getTopLevelComponent();
}
SmallArray<Canvas*> PluginEditor::getCanvases()
{
return tabComponent.getCanvases();
}
Canvas* PluginEditor::getCurrentCanvas()
{
return tabComponent.getCurrentCanvas();
}
float PluginEditor::getRenderScale() const
{
return nvgSurface.getRenderScale();
}
void PluginEditor::valueChanged(Value& v)
{
// Update theme
if (v.refersToSameSourceAs(theme)) {
pd->setTheme(theme.toString());
getTopLevelComponent()->repaint();
}
}
void PluginEditor::settingsChanged(String const& name, var const& value)
{
if (name == "touch_mode") {
if (static_cast<bool>(value)) {
addChildComponent(touchSelectionHelper.get());
} else {
removeChildComponent(touchSelectionHelper.get());
}
triggerAsyncUpdate();
resized();
}
}
void PluginEditor::modifierKeysChanged(ModifierKeys const& modifiers)
{
setModifierKeys(modifiers);
}
// Updates command status asynchronously
void PluginEditor::handleAsyncUpdate()
{
tabComponent.repaint(); // So tab dirty titles can be reflected
if (auto const* cnv = getCurrentCanvas()) {
bool locked = getValue<bool>(cnv->locked);
bool const commandLocked = getValue<bool>(cnv->commandLocked);
bool const isDragging = cnv->dragState.didStartDragging && !cnv->isDraggingLasso && cnv->locked == var(false);
if (getValue<bool>(cnv->presentationMode)) {
statusbar->setEditButtonState(true, true);
} else if (locked || commandLocked) {
statusbar->setEditButtonState(true);
} else {
statusbar->setEditButtonState(false);
}
auto const currentUndoState = cnv->patch.canUndo() && !isDragging && !locked;
auto const currentRedoState = cnv->patch.canRedo() && !isDragging && !locked;
undoButton.setEnabled(currentUndoState);
redoButton.setEnabled(currentRedoState);
// Application commands need to be updated when undo state changes
commandManager.commandStatusChanged();
addObjectMenuButton.setEnabled(true);
if (touchSelectionHelper) {
if (!locked) {
touchSelectionHelper->show();
} else {
touchSelectionHelper->setVisible(false);
}
}
} else {
undoButton.setEnabled(false);
redoButton.setEnabled(false);
addObjectMenuButton.setEnabled(false);
if (touchSelectionHelper)
touchSelectionHelper->setVisible(false);
}
if (touchSelectionHelper)
touchSelectionHelper->repaint();
}