-
-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathTabComponent.cpp
More file actions
1519 lines (1269 loc) · 51.8 KB
/
TabComponent.cpp
File metadata and controls
1519 lines (1269 loc) · 51.8 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
#include <juce_gui_basics/juce_gui_basics.h>
#include "PluginEditor.h"
#include "PluginProcessor.h"
#include "Canvas.h"
#include "Sidebar/Sidebar.h"
#include "Dialogs/Dialogs.h"
#include "Utility/Autosave.h"
#include "Components/TouchPopupMenu.h"
#include "NVGSurface.h"
#include "PluginMode.h"
#include "Standalone/PlugDataWindow.h"
class TabComponent::TabBarButtonComponent final : public Component {
class TabDragConstrainer final : public ComponentBoundsConstrainer {
public:
explicit TabDragConstrainer(TabComponent* parent)
: parent(parent)
{
}
void checkBounds(Rectangle<int>& bounds, Rectangle<int> const&, Rectangle<int> const& limits, bool, bool, bool, bool) override
{
bounds = bounds.withPosition(std::clamp(bounds.getX(), 30, parent->getWidth() - bounds.getWidth()), 0);
}
private:
TabComponent* parent;
};
class CloseTabButton final : public SmallIconButton {
using SmallIconButton::SmallIconButton;
void paint(Graphics& g) override
{
auto const font = Fonts::getIconFont().withHeight(12);
g.setFont(font);
if (!isEnabled()) {
g.setColour(Colours::grey);
} else if (getToggleState()) {
g.setColour(PlugDataColours::toolbarActiveColour);
} else if (isMouseOver()) {
g.setColour(PlugDataColours::toolbarTextColour.brighter(0.8f));
} else {
g.setColour(PlugDataColours::toolbarTextColour);
}
int const yIndent = jmin(4, proportionOfHeight(0.3f));
int const cornerSize = jmin(getHeight(), getWidth()) / 2;
int const fontHeight = roundToInt(font.getHeight() * 0.6f);
int const leftIndent = jmin(fontHeight, 2 + cornerSize / (isConnectedOnLeft() ? 4 : 2));
int const rightIndent = jmin(fontHeight, 2 + cornerSize / (isConnectedOnRight() ? 4 : 2));
int const textWidth = getWidth() - leftIndent - rightIndent;
if (textWidth > 0)
g.drawFittedText(getButtonText(), leftIndent, yIndent, textWidth, getHeight() - yIndent * 2, Justification::centred, 2);
}
};
public:
TabBarButtonComponent(Canvas* cnv, TabComponent* parent)
: cnv(cnv)
, parent(parent)
, tabDragConstrainer(parent)
{
closeButton.onClick = [cnv = SafePointer(cnv), parent] {
if (cnv)
parent->askToCloseTab(cnv);
};
closeButton.addMouseListener(this, false);
closeButton.setSize(28, 28);
addAndMakeVisible(closeButton);
setRepaintsOnMouseActivity(true);
updater.addAnimator(tabAnimator);
}
void paint(Graphics& g) override
{
auto const mouseOver = isMouseOver();
auto const active = isActive();
if (active) {
g.setColour(PlugDataColours::activeTabBackgroundColour);
} else if (mouseOver) {
g.setColour(PlugDataColours::activeTabBackgroundColour.interpolatedWith(PlugDataColours::toolbarBackgroundColour, 0.4f));
} else {
g.setColour(PlugDataColours::toolbarBackgroundColour);
}
g.fillRoundedRectangle(getLocalBounds().toFloat().reduced(4.5f), Corners::defaultCornerRadius);
auto const area = getLocalBounds().reduced(4, 1).toFloat();
// Use a gradient to make it fade out when it gets near to the close button
auto const fadeX = mouseOver || active ? area.getRight() - 25 : area.getRight() - 8;
auto const textColour = PlugDataColours::toolbarTextColour;
g.setGradientFill(ColourGradient(textColour, fadeX - 18, area.getY(), Colours::transparentBlack, fadeX, area.getY(), false));
if (cnv) {
auto const text = cnv->patch.getTitle() + (cnv->patch.isDirty() ? String("*") : String());
g.setFont(Fonts::getCurrentFont().withHeight(14.0f));
g.drawText(text, area.reduced(4, 0), Justification::centred, false);
}
}
void resized() override
{
closeButton.setCentrePosition(getLocalBounds().getCentre().withX(getWidth() - 15).translated(0, 1));
}
ScaledImage generateTabBarButtonImage() const
{
if (!cnv)
return { };
constexpr auto scale = 2.0f;
// we calculate the best size for the tab DnD image
auto const text = cnv->patch.getTitle();
Font const font(Fonts::getCurrentFont());
auto const length = Fonts::getStringWidth(text, font) + 32;
constexpr auto boundsOffset = 10;
// we need to expand the bounds, but reset the position to top left
// then we offset the mouse drag by the same amount
// this is to allow area for the shadow to render correctly
auto const textBounds = Rectangle<int>(0, 0, length, 28);
auto const bounds = textBounds.expanded(boundsOffset).withZeroOrigin();
auto const image = Image(Image::PixelFormat::ARGB, bounds.getWidth() * scale, bounds.getHeight() * scale, true);
auto g = Graphics(image);
g.addTransform(AffineTransform::scale(scale));
StackShadow::drawShadowForRect(g, bounds.reduced(12), 7, Corners::defaultCornerRadius, 0.2f, 1);
g.setOpacity(1.0f);
g.setColour(PlugDataColours::activeTabBackgroundColour);
g.fillRoundedRectangle(textBounds.withPosition(10, 10).reduced(2).toFloat(), Corners::defaultCornerRadius);
g.setColour(PlugDataColours::toolbarTextColour);
g.setFont(font);
g.drawText(text, textBounds.withPosition(10, 10), Justification::centred, false);
return { image, scale };
}
void mouseDown(MouseEvent const& e) override
{
if (e.mods.isPopupMenu() && cnv) {
PopupMenu tabMenu;
bool const canReveal = cnv->patch.getCurrentFile().existsAsFile();
tabMenu.addItem(PlatformStrings::getBrowserTip(), canReveal, false, [this] {
cnv->patch.getCurrentFile().revealToUser();
});
tabMenu.addSeparator();
PopupMenu parentPatchMenu;
if (auto patch = cnv->patch.getPointer()) {
auto* parentPatch = patch.get();
while ((parentPatch = parentPatch->gl_owner)) {
parentPatchMenu.addItem(String::fromUTF8(parentPatch->gl_name->s_name), [this, parentPatch] {
auto* pdInstance = dynamic_cast<pd::Instance*>(parent->pd);
parent->openPatch(new pd::Patch(pd::WeakReference(parentPatch, pdInstance), pdInstance, false));
});
}
}
tabMenu.addSubMenu("Parent patches", parentPatchMenu, parentPatchMenu.getNumItems());
tabMenu.addSeparator();
auto const splitIndex = parent->splits[1] && parent->tabbars[1].contains(this);
auto const canSplitTab = parent->splits[1] || parent->tabbars[splitIndex].size() > 1;
tabMenu.addItem("Split left", canSplitTab, false, [this] {
parent->moveToLeftSplit(this);
parent->closeEmptySplits();
parent->saveTabPositions();
});
tabMenu.addItem("Split right", canSplitTab, false, [this] {
parent->moveToRightSplit(this);
parent->closeEmptySplits();
parent->saveTabPositions();
});
tabMenu.addSeparator();
tabMenu.addItem("Close patch", true, false, [this] {
parent->closeTab(cnv);
});
tabMenu.addItem("Close all other patches", true, false, [this] {
parent->closeAllTabs(false, cnv);
});
tabMenu.addItem("Close all patches", true, false, [this] {
parent->closeAllTabs(false);
});
// Show the popup menu at the mouse position
auto const position = e.getScreenPosition();
tabMenu.showMenuAsync(PopupMenu::Options().withMinimumWidth(150).withMaximumNumColumns(1).withTargetComponent(this).withTargetScreenArea(Rectangle<int>(position, position.translated(1, 1))));
} else if (cnv && e.originalComponent == this) {
toFront(false);
parent->showTab(cnv, parent->tabbars[1].contains(this));
dragger.startDraggingComponent(this, e);
}
}
void mouseDrag(MouseEvent const& e) override
{
if (e.getDistanceFromDragStart() > 10 && !isDragging) {
isDragging = true;
auto const dragContainer = DragAndDropContainer::findParentDragContainerFor(this);
tabImage = generateTabBarButtonImage();
var description = var(new DynamicObject());
description.getDynamicObject()->setProperty("dropped", false);
dragContainer->startDragging(description, this, tabImage, true);
} else if (parent->draggingOverTabbar) {
dragger.dragComponent(this, e, &tabDragConstrainer);
}
}
void mouseUp(MouseEvent const& e) override
{
isDragging = false;
setVisible(true);
parent->resized(); // call resized so the dropped tab will animate into its correct position
}
bool isActive() const
{
return cnv && (parent->splits[0] == cnv || parent->splits[1] == cnv);
}
void animate(Rectangle<int> targetBounds)
{
animationStartBounds = getBounds();
animationEndBounds = targetBounds;
tabAnimator.complete();
tabAnimator.start();
}
// close button, etc.
SafePointer<Canvas> cnv;
TabComponent* parent;
ScaledImage tabImage;
ComponentDragger dragger;
TabDragConstrainer tabDragConstrainer;
CloseTabButton closeButton = CloseTabButton(Icons::Clear);
bool isDragging : 1 = false;
Rectangle<int> animationStartBounds, animationEndBounds;
VBlankAnimatorUpdater updater { this };
Animator tabAnimator = ValueAnimatorBuilder { }
.withEasing(Easings::createEaseInOut())
.withDurationMs(220)
.withValueChangedCallback([this](float v) {
auto start = std::make_tuple(animationStartBounds.getX(), animationStartBounds.getY(), animationStartBounds.getWidth(), animationStartBounds.getHeight());
auto end = std::make_tuple(animationEndBounds.getX(), animationEndBounds.getY(), animationEndBounds.getWidth(), animationEndBounds.getHeight());
auto const [x, y, w, h] = makeAnimationLimits(start, end).lerp(v);
setBounds(x, y, w, h);
})
.build();
};
TabComponent::TabComponent(PluginEditor* editor)
: editor(editor)
, pd(editor->pd)
{
for (int i = 0; i < tabbars.size(); i++) {
addChildComponent(newTabButtons[i]);
newTabButtons[i].onClick = [this, i] {
activeSplitIndex = i;
newPatch();
};
addChildComponent(tabOverflowButtons[i]);
tabOverflowButtons[i].onClick = [this, i] {
showHiddenTabsMenu(i);
};
}
addMouseListener(this, true);
// Dequeue messages to "pd" symbol to make sure the "pluginmode" message always arrives earlier than the tab update.
// Without this, FL Studio (and possibly others) will fail to init the pluginmode theme!
editor->pd->triggerAsyncUpdate();
triggerAsyncUpdate();
}
TabComponent::~TabComponent()
{
sendTabUpdateToVisibleCanvases();
clearCanvases();
}
Canvas* TabComponent::newPatch()
{
return openPatch(pd::Instance::defaultPatch);
}
void TabComponent::openHelpPatch(const URL& path)
{
for (auto* editor : pd->getEditors()) {
for (auto* cnv : editor->getCanvases()) {
if (cnv->patch.getCurrentFile() == path.getLocalFile()) {
pd->logError("Patch is already open");
editor->getTopLevelComponent()->toFront(true);
editor->getTabComponent().showTab(cnv, cnv->patch.splitViewIndex);
editor->getTabComponent().setActiveSplit(cnv);
return;
}
}
}
auto const patch = pd->loadPatch(path);
if (auto p = patch->getPointer()) {
p->gl_edit = 0;
}
openPatch(patch, true);
}
void TabComponent::openPatch(const URL& path)
{
editor->pd->autosave->checkForMoreRecentAutosave(path, editor, [this](URL const& file, URL const& patchPath) {
auto checkQuarantine = [this](File const& f, std::function<void()> callback) {
if (OSUtils::isFileQuarantined(f)) {
Dialogs::showMultiChoiceDialog(&editor->openedDialog, editor, "This patch was downloaded from the internet. Opening patches from untrusted sources may pose security risks. Do you want to proceed?", [callback, f](int const choice) {
if (choice == 0) {
OSUtils::removeFromQuarantine(f);
callback();
} }, { "Trust and Open", "Cancel" }, Icons::Warning);
} else {
callback();
}
};
auto const patchFile = file.getLocalFile();
for (auto* editor : pd->getEditors()) {
for (auto* cnv : editor->getCanvases()) {
if (cnv->patch.getCurrentFile() == patchFile) {
pd->logError("Patch is already open");
editor->getTopLevelComponent()->toFront(true);
editor->getTabComponent().showTab(cnv, cnv->patch.splitViewIndex);
editor->getTabComponent().setActiveSplit(cnv);
return;
}
}
}
checkQuarantine(patchFile, [this, url = file, patchPath]() mutable {
#if JUCE_IOS
url.setBookmarkData(patchPath.getBookmarkData());
#endif
auto const patch = pd->loadPatch(url);
// If we're opening a temp file, assume it's dirty upon opening
// This is so that you can recover an autosave without directly overewriting it, but still be prompted to save if you close the autosaved patch
if (url.getLocalFile().getParentDirectory() == File::getSpecialLocation(File::tempDirectory)) {
if (auto p = patch->getPointer()) {
canvas_dirty(p.get(), 1.0f);
}
}
if (auto* cnv = openPatch(patch, true)) {
cnv->patch.setCurrentFile(patchPath);
}
SettingsFile::getInstance()->addToRecentlyOpened(patchPath);
});
});
}
Canvas* TabComponent::openPatch(String const& patchContent)
{
auto const patch = pd->loadPatch(patchContent);
patch->setUntitled();
return openPatch(patch);
}
Canvas* TabComponent::openPatch(pd::Patch::Ptr existingPatch, bool const warnIfAlreadyOpen, bool const sendVisMessage)
{
if (!existingPatch)
return nullptr;
// Check if subpatch is already opened
for (auto* editor : pd->getEditors()) {
for (auto* cnv : editor->getCanvases()) {
if (cnv->patch == *existingPatch) {
if (warnIfAlreadyOpen)
pd->logError("Patch is already open");
editor->getTopLevelComponent()->toFront(true);
editor->getTabComponent().showTab(cnv, cnv->patch.splitViewIndex);
editor->getTabComponent().setActiveSplit(cnv);
return cnv;
}
}
}
pd->patches.add_unique(existingPatch, [](auto const& ptr1, auto const& ptr2) {
return *ptr1 == *ptr2;
});
existingPatch->splitViewIndex = activeSplitIndex;
existingPatch->windowIndex = editor->editorIndex;
if (existingPatch->openInPluginMode) {
triggerAsyncUpdate();
return nullptr;
}
auto* cnv = canvases.add(new Canvas(editor, existingPatch));
auto const patchTitle = existingPatch->getTitle();
// Open help files and references in Locked Mode
if (patchTitle.contains("-help") || patchTitle.equalsIgnoreCase("reference"))
cnv->locked.setValue(true);
showTab(cnv, activeSplitIndex);
cnv->restoreViewportState();
triggerAsyncUpdate();
tabVisibilityMessageUpdater.triggerAsyncUpdate();
static bool alreadyOpeningInNewWindow = false;
if (canvases.size() > 1 && !alreadyOpeningInNewWindow && ProjectInfo::isStandalone && SettingsFile::getInstance()->getProperty<bool>("open_patches_in_window")) {
alreadyOpeningInNewWindow = true;
cnv = createNewWindow(cnv);
alreadyOpeningInNewWindow = false;
}
if (sendVisMessage && !cnv->isGraph) {
cnv->patch.setVisible(true);
}
return cnv;
}
void TabComponent::openPatch()
{
Dialogs::showOpenDialog([this](URL resultURL) {
auto result = resultURL.getLocalFile();
if (result.exists() && result.getFileExtension().equalsIgnoreCase(".pd")) {
openPatch(resultURL);
}
},
true, false, "*.pd", "Patch", this);
}
#if JUCE_IOS
void TabComponent::openPatchFolder()
{
Dialogs::showOpenDialog([this](URL resultURL) {
auto result = resultURL.getLocalFile();
HeapArray<File> pdFiles;
StringArray pdFileNames;
for (auto file : OSUtils::iterateDirectory(result, false, false)) {
if (file.hasFileExtension("pd")) {
pdFiles.add(file);
pdFileNames.add(file.getFileName());
}
}
if (pdFiles.size() == 1) {
auto patchURL = URL(pdFiles[0]);
patchURL.setBookmarkData(resultURL.getBookmarkData());
openPatch(patchURL);
} else if (pdFiles.size() != 0) {
TouchPopupMenu patchChoiceMenu;
for (int i = 0; i < pdFiles.size(); i++) {
patchChoiceMenu.addItem(pdFileNames[i], [this, resultURL, patchURL = URL(pdFiles[0])]() mutable {
patchURL.setBookmarkData(resultURL.getBookmarkData());
openPatch(patchURL);
});
}
patchChoiceMenu.showMenu(editor, editor, "Choose patch");
}
},
false, true, "", "PatchFolder", this);
}
#endif
void TabComponent::moveToLeftSplit(TabBarButtonComponent const* tab)
{
if (tab->parent != this) // Move to another window
{
if (tab->parent->tabbars[0].contains(tab)) {
auto const patch = tab->cnv->refCountedPatch;
patch->windowIndex = editor->editorIndex;
auto* oldTabbar = tab->parent;
oldTabbar->canvases.removeObject(tab->cnv);
oldTabbar->tabbars[0].removeObject(tab);
auto* cnv = canvases.add(new Canvas(editor, patch));
tabbars[0].add(new TabBarButtonComponent(cnv, this));
showTab(cnv, 0);
cnv->restoreViewportState();
triggerAsyncUpdate();
oldTabbar->triggerAsyncUpdate();
} else if (tab->parent->tabbars[1].contains(tab)) {
auto const patch = tab->cnv->refCountedPatch;
patch->windowIndex = editor->editorIndex;
auto* oldTabbar = tab->parent;
oldTabbar->canvases.removeObject(tab->cnv);
oldTabbar->tabbars[1].removeObject(tab);
auto* cnv = canvases.add(new Canvas(editor, patch));
tabbars[0].add(new TabBarButtonComponent(cnv, this));
showTab(cnv, 0);
cnv->restoreViewportState();
triggerAsyncUpdate();
oldTabbar->triggerAsyncUpdate();
}
return;
}
if (tabbars[1].size() && splits[1] && tabbars[1].indexOf(tab) >= 0) {
tabbars[0].add(tabbars[1].removeAndReturn(tabbars[1].indexOf(tab))); // Move tab to left tabbar
if (tabbars[1].size())
showTab(tabbars[1][0]->cnv, 1); // Show first tab of right tabbar, if there are any tabs left
else
showTab(nullptr, 1); // If no tabs are left on right tabbar
showTab(tab->cnv, 0); // Show moved tab on left split
} else if (tabbars[0].size() > 1 && splits[0] && !splits[1] && tabbars[0].indexOf(tab) >= 0) // If we try to create a left splits when there are no splits open
{
showTab(tab->cnv, 0); // Show dragged tab on left split
// Move all other tabs to right split
for (int i = tabbars[0].size() - 1; i >= 0; i--) {
if (tab != tabbars[0][i]) {
tabbars[0][i]->cnv->patch.splitViewIndex = 1; // Save split index
tabbars[1].insert(0, tabbars[0].removeAndReturn(i)); // Move to other split
}
}
showTab(tabbars[1][0]->cnv, 1); // Show first tab of right split
}
}
void TabComponent::moveToRightSplit(TabBarButtonComponent const* tab)
{
if (tab->parent != this) // Move to another window
{
if (tab->parent->tabbars[0].contains(tab)) {
auto const patch = tab->cnv->refCountedPatch;
patch->windowIndex = editor->editorIndex;
auto* oldTabbar = tab->parent;
oldTabbar->canvases.removeObject(tab->cnv);
oldTabbar->tabbars[0].removeObject(tab);
auto* cnv = canvases.add(new Canvas(editor, patch));
cnv->restoreViewportState();
tabbars[1].add(new TabBarButtonComponent(cnv, this));
showTab(cnv, 1);
triggerAsyncUpdate();
oldTabbar->triggerAsyncUpdate();
} else if (tab->parent->tabbars[1].contains(tab)) {
auto const patch = tab->cnv->refCountedPatch;
patch->windowIndex = editor->editorIndex;
auto* oldTabbar = tab->parent;
oldTabbar->canvases.removeObject(tab->cnv);
oldTabbar->tabbars[1].removeObject(tab);
auto* cnv = canvases.add(new Canvas(editor, patch));
cnv->restoreViewportState();
tabbars[1].add(new TabBarButtonComponent(cnv, this));
showTab(cnv, 1);
triggerAsyncUpdate();
oldTabbar->triggerAsyncUpdate();
}
return;
}
if ((tabbars[0].size() > 1 || splits[1]) && splits[0] && tabbars[0].indexOf(tab) >= 0) {
tabbars[1].add(tabbars[0].removeAndReturn(tabbars[0].indexOf(tab))); // Move tab to right tabbar
if (tabbars[0].size())
showTab(tabbars[0][0]->cnv, 0); // Show first tab of left tabbar
showTab(tab->cnv, 1); // Show the moved tab on right tabbar
}
}
void TabComponent::nextTab()
{
auto const splitIndex = activeSplitIndex && splits[1];
auto const& tabbar = tabbars[splitIndex];
auto oldTabIndex = 0;
for (int i = 0; i < tabbar.size(); i++) {
if (tabbar[i]->cnv == splits[splitIndex]) {
oldTabIndex = i;
}
}
auto const newTabIndex = oldTabIndex + 1;
showTab(newTabIndex < tabbar.size() ? tabbar[newTabIndex]->cnv : tabbar[0]->cnv, splitIndex);
}
void TabComponent::previousTab()
{
auto const splitIndex = activeSplitIndex && splits[1];
auto const& tabbar = tabbars[splitIndex];
auto oldTabIndex = 0;
for (int i = 0; i < tabbar.size(); i++) {
if (tabbar[i]->cnv == splits[splitIndex]) {
oldTabIndex = i;
}
}
auto const newTabIndex = oldTabIndex - 1;
showTab(newTabIndex >= 0 ? tabbar[newTabIndex]->cnv : tabbar[tabbar.size() - 1]->cnv, splitIndex);
}
void TabComponent::createNewWindowFromTab(Component* draggedTab)
{
if (auto const* tab = dynamic_cast<TabBarButtonComponent*>(draggedTab)) {
if (canvases.size() > 1) {
createNewWindow(tab->cnv);
}
}
}
Canvas* TabComponent::createNewWindow(Canvas* cnv)
{
if (!ProjectInfo::isStandalone)
return nullptr;
auto* newEditor = new PluginEditor(*pd);
auto* newWindow = ProjectInfo::createNewWindow(newEditor);
auto const* window = dynamic_cast<PlugDataWindow*>(getTopLevelComponent());
pd->openedEditors.add(newEditor);
newWindow->addToDesktop(window->getDesktopWindowStyleFlags());
newWindow->setVisible(true);
auto const patch = cnv->refCountedPatch;
closeTab(cnv);
patch->windowIndex = newEditor->editorIndex;
auto* newCanvas = newEditor->getTabComponent().openPatch(patch);
newCanvas->restoreViewportState();
newWindow->setTopLeftPosition(Desktop::getInstance().getMousePosition() - Point<int>(500, 60));
newWindow->toFront(true);
newEditor->nvgSurface.detachContext();
if (SettingsFile::getInstance()->getProperty<bool>("open_patches_in_window")) {
auto const patchBounds = newCanvas->patch.getBounds() * (SettingsFile::getInstance()->getProperty<float>("default_zoom") / 100.0f);
auto const screenBounds = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
auto const windowBounds = screenBounds.withSizeKeepingCentre(patchBounds.getWidth() + newEditor->sidebar->getWidth() + 30, patchBounds.getHeight() + 94);
newEditor->getTopLevelComponent()->setBounds(windowBounds);
}
return newCanvas;
}
void TabComponent::openInPluginMode(pd::Patch::Ptr patch)
{
patch->openInPluginMode = true;
triggerAsyncUpdate();
}
// Deleting a canvas can lead to subpatches of that canvas being deleted as well
// This means that clearing all elements from the canvases array by calling 'clear()' is unsafe
// instead, we must check if they still exist before deleting
void TabComponent::clearCanvases()
{
SmallArray<SafePointer<Canvas>, 16> safeCanvases;
for (int i = canvases.size() - 1; i >= 0; i--) {
safeCanvases.add(canvases[i]);
}
for (auto safeCnv : safeCanvases) {
if (safeCnv)
canvases.removeObject(safeCnv.getComponent());
}
}
void TabComponent::updateNow()
{
handleAsyncUpdate();
}
void TabComponent::handleAsyncUpdate()
{
if (canvases.isEmpty() && pd->getEditors().size() > 1) {
bool editorHasPatches = false;
for (auto const& patch : pd->patches) {
if (patch->windowIndex == editor->editorIndex)
editorHasPatches = true;
}
if (!editorHasPatches) {
auto* pdInstance = pd; // Copy pd because we might self-destruct
pdInstance->openedEditors.removeObject(editor);
auto const* editor = pdInstance->openedEditors.getFirst();
if (auto* topLevel = editor->getTopLevelComponent())
topLevel->toFront(true);
return;
}
}
pd->setThis();
auto const editorIndex = editor->editorIndex;
// save the patch from the canvases that were the two splits
for (int i = 0; i < splits.size(); i++) {
if (splits[i]) {
lastSplitPatches[i] = &splits[i]->patch;
}
}
if (getCurrentCanvas())
lastActiveCanvas = getCurrentCanvas()->patch.getUncheckedPointer();
for (auto* cnv : getCanvases()) {
cnv->saveViewportState();
}
UnorderedMap<Canvas*, Rectangle<int>> oldTabBounds;
for (auto& tabbar : tabbars) {
for (auto* tab : tabbar) {
oldTabBounds.insert({ tab->cnv, tab->getBounds() });
}
}
animateTabs = oldTabBounds.size() > 0;
tabbars[0].clear();
tabbars[1].clear();
// Check if there is a patch that should be in plugin mode for this tabComponents editor
// If so, we create a new pluginmode object, and delete all canvases from this editor
if (auto patchInPluginMode = pd->findPatchInPluginMode(editor->editorIndex)) {
if (patchInPluginMode->windowIndex == editorIndex) {
// Initialise plugin mode
clearCanvases();
editor->showWelcomePanel(false);
if (!editor->isInPluginMode() || editor->pluginMode->getPatch()->getPointer().get() != patchInPluginMode->getUncheckedPointer()) {
editor->pluginMode = std::make_unique<PluginMode>(editor, patchInPluginMode);
}
editor->pluginMode->updateSize();
editor->parentSizeChanged(); // hack to force the window title buttons to hide
return;
}
// if the editor is in pluginmode
} else if (editor->isInPluginMode()) {
editor->pluginMode.reset(nullptr);
}
// First, remove canvases that no longer exist
for (int i = canvases.size() - 1; i >= 0; i--) {
bool exists = false;
{
for (auto& patch : pd->patches) {
if (canvases[i]->patch == *patch && canvases[i]->patch.windowIndex == editorIndex) {
exists = true;
}
}
}
if (!exists) {
canvases.remove(i);
}
}
for (auto& patch : pd->patches) {
if (patch->windowIndex != editorIndex)
continue;
Canvas* cnv = nullptr;
for (auto* canvas : canvases) {
if (canvas->patch == *patch) {
cnv = canvas;
}
}
if (!cnv) {
cnv = canvases.add(new Canvas(editor, patch));
resized();
cnv->restoreViewportState();
}
// Create tab buttons
auto* newTabButton = new TabBarButtonComponent(cnv, this);
if (oldTabBounds.contains(cnv)) {
newTabButton->setBounds(oldTabBounds[cnv]);
} else {
newTabButton->setBounds(getWidth(), 0, 0, 30);
}
tabbars[patch->splitViewIndex == 1].add(newTabButton);
addAndMakeVisible(newTabButton);
}
closeEmptySplits();
// Show welcome panel if there are no tabs
if (tabbars[0].size() == 0 && tabbars[1].size() == 0) {
editor->showWelcomePanel(true);
editor->resized();
editor->parentSizeChanged();
} else {
editor->showWelcomePanel(false);
editor->resized();
editor->parentSizeChanged();
}
resized(); // Update tab and canvas layout
for (auto* cnv : getCanvases()) {
cnv->restoreViewportState();
}
// Show plugin mode tab after closing pluginmode
for (int i = 0; i < tabbars.size(); i++) {
for (auto* canvas : getCanvases()) {
if (!tabbars[i].isEmpty() && &canvas->patch == lastSplitPatches[i]) {
showTab(canvas, i);
break;
}
}
}
if (lastActiveCanvas) {
for (auto* cnv : getCanvases()) {
if (cnv->patch.getUncheckedPointer() == lastActiveCanvas) {
setActiveSplit(cnv);
break;
}
}
}
editor->updateCommandStatus();
sendTabUpdateToVisibleCanvases();
repaint();
}
void TabComponent::closeEmptySplits()
{
if (!tabbars[0].size() && tabbars[1].size()) // Check if split can be closed
{
// Move all tabs to left split
for (int i = tabbars[1].size() - 1; i >= 0; i--) {
tabbars[1][i]->cnv->patch.splitViewIndex = 0; // Save split index
tabbars[0].insert(0, tabbars[1].removeAndReturn(i)); // Move to other split
}
showTab(tabbars[0][0]->cnv, 0);
}
if (tabbars[0].size() && !splits[0]) {
showTab(tabbars[0][0]->cnv, 0);
}
if (tabbars[1].size() && !splits[1]) {
showTab(tabbars[1][0]->cnv, 1);
}
if (!tabbars[1].size() && splits[1]) // Check if right split is valid
{
showTab(nullptr, 1);
}
if (!tabbars[0].size() && splits[0]) // Check if left split is valid
{
showTab(nullptr, 0);
}
// Check for tabs that are shown inside the wrong split, dragging tabs can cause that
for (int i = 0; i < tabbars.size(); i++) {
for (auto const* tab : tabbars[i]) {
if (tab->cnv == splits[!i] && tabbars[!i].size()) {
showTab(tabbars[!i][0]->cnv, !i);
break;
}
}
}
}
void TabComponent::showTab(Canvas* cnv, int const splitIndex)
{
if (cnv == splits[splitIndex] && cnv && cnv->getParentComponent()) {
return;
}
if (cnv && cnv != getCurrentCanvas()) {
cnv->deselectAll();
editor->sidebar->updateSearch(true);
}
if (splits[splitIndex] && splits[splitIndex] != splits[!splitIndex]) {
splits[splitIndex]->saveViewportState();
removeChildComponent(splits[splitIndex]->viewport.get());
}
splits[splitIndex] = cnv;
if (cnv) {
editor->showWelcomePanel(false);
addAndMakeVisible(cnv->viewport.get());
cnv->setVisible(true);
cnv->patch.splitViewIndex = splitIndex;
activeSplitIndex = splitIndex;
}
resized();
repaint();
tabVisibilityMessageUpdater.triggerAsyncUpdate();
editor->sidebar->hideParameters();
editor->sidebar->clearSearchOutliner();
editor->updateCommandStatus();
addLastShownTab(cnv, splitIndex);
}
void TabComponent::TabVisibilityMessageUpdater::handleAsyncUpdate()
{
parent->sendTabUpdateToVisibleCanvases();
}
Canvas* TabComponent::getCurrentCanvas()
{
if (editor->pluginMode) {
return editor->pluginMode->getCanvas();
}
return activeSplitIndex && splits[1] ? splits[1] : splits[0];
}
SmallArray<Canvas*> TabComponent::getCanvases()
{
SmallArray<Canvas*> allCanvases;
allCanvases.reserve(canvases.size());
for (auto& canvas : canvases)
allCanvases.add(canvas);
return allCanvases;
}
void TabComponent::renderArea(NVGcontext* nvg, Rectangle<int> area)
{
if (splits[0]) {
NVGScopedState scopedState(nvg);
nvgScissor(nvg, 0, 0, splits[1] ? splitSize - 3 : getWidth(), getHeight());
splits[0]->performRender(nvg, area);
}
if (splits[1]) {
NVGScopedState scopedState(nvg);
nvgTranslate(nvg, splitSize + 3, 0);
nvgScissor(nvg, 0, 0, getWidth() - (splitSize + 3), getHeight());
splits[1]->performRender(nvg, area.translated(-(splitSize + 3), 0));
}
if (!splitDropBounds.isEmpty()) {
nvgFillColor(nvg, nvgColour(PlugDataColours::dataColour.withAlpha(0.1f)));
nvgFillRect(nvg, splitDropBounds.getX(), splitDropBounds.getY(), splitDropBounds.getWidth(), splitDropBounds.getHeight());
}
if (splits[1]) {
nvgFillColor(nvg, nvgColour(PlugDataColours::canvasBackgroundColour));
nvgFillRect(nvg, splitSize - 3, 0, 6, getHeight());
auto const activeSplitBounds = activeSplitIndex ? Rectangle<int>(splitSize, 0, getWidth() - splitSize, getHeight() - 31) : Rectangle<int>(0, 0, splitSize, getHeight() - 31);
nvgStrokeWidth(nvg, 3.0f);
nvgStrokeColor(nvg, nvgColour(PlugDataColours::objectSelectedOutlineColour.withAlpha(0.25f)));
nvgStrokeRect(nvg, activeSplitBounds.getX(), activeSplitBounds.getY(), activeSplitBounds.getWidth(), activeSplitBounds.getHeight());
}
}
void TabComponent::mouseDown(MouseEvent const& e)
{
auto const localPos = e.getEventRelativeTo(this).getPosition();
if (localPos.x > splitSize - 3 && localPos.x < splitSize + 3) {
draggingSplitResizer = true;
setMouseCursor(MouseCursor::LeftRightResizeCursor);
} else if (splits[1] && localPos.x > splitSize) {
setActiveSplit(splits[1]);
} else {
setActiveSplit(splits[0]);
}
}
void TabComponent::mouseUp(MouseEvent const& e)
{