-
-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathCanvas.cpp
More file actions
2766 lines (2302 loc) · 92.5 KB
/
Canvas.cpp
File metadata and controls
2766 lines (2302 loc) · 92.5 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 "Utility/Config.h"
#include "Utility/Fonts.h"
#include "Sidebar/Sidebar.h"
#include "Statusbar.h"
#include "Canvas.h"
#include "Object.h"
#include "Connection.h"
#include "PluginProcessor.h"
#include "PluginEditor.h"
#include "LookAndFeel.h"
#include "Components/SuggestionComponent.h"
#include "CanvasViewport.h"
#include "Objects/ObjectBase.h"
#include "Dialogs/Dialogs.h"
#include "Components/GraphArea.h"
#include "Components/CanvasBorderResizer.h"
#include "Components/CanvasSearchHighlight.h"
extern "C" {
void canvas_setgraph(t_glist* x, int flag, int nogoprect);
}
class ObjectsResizer final : public Component
, NVGComponent
, Value::Listener {
public:
enum class ResizerMode { Horizontal,
Vertical };
ObjectsResizer(Canvas* parentCanvas, std::function<float(Rectangle<int> bounds)> onResize, std::function<void(Point<int> pos)> onMove, ResizerMode const mode = ResizerMode::Horizontal)
: NVGComponent(this)
, border(this, &constrainer)
, cnv(parentCanvas)
, mode(mode)
, onResize(std::move(onResize))
, onMove(std::move(onMove))
{
cnv->addAndMakeVisible(this);
setAlwaysOnTop(true);
cnv->zoomScale.addListener(this);
auto selectedObjectBounds = Rectangle<int>();
auto smallestObjectWidthOrHeight = std::numeric_limits<int>::max();
auto largestObjectWidthOrHeight = 0;
// work out the bounds for all objects, and also the bounds for the largest object (used for min size of constrainer)
for (auto* obj : cnv->getSelectionOfType<Object>()) {
obj->hideHandles(true);
selectedObjectBounds = selectedObjectBounds.getUnion(obj->getBounds().reduced(Object::margin, Object::margin));
// Find the smallest object to make the min constrainer size
if (mode == ResizerMode::Horizontal) {
auto const objWidth = obj->getObjectBounds().getWidth();
if (objWidth < smallestObjectWidthOrHeight) {
smallestObjectWidthOrHeight = objWidth;
}
if (objWidth > largestObjectWidthOrHeight) {
largestObjectWidthOrHeight = objWidth;
}
} else {
auto const objHeight = obj->getObjectBounds().getHeight();
if (objHeight < smallestObjectWidthOrHeight) {
smallestObjectWidthOrHeight = objHeight;
}
if (objHeight > largestObjectWidthOrHeight) {
largestObjectWidthOrHeight = objHeight;
}
}
}
setBorderScale(cnv->zoomScale);
if (mode == ResizerMode::Horizontal) {
constrainer.setMinimumWidth(largestObjectWidthOrHeight + tabMargin * 2);
} else {
constrainer.setMinimumHeight(largestObjectWidthOrHeight + tabMargin * 2);
}
addAndMakeVisible(border);
setBounds(selectedObjectBounds.expanded(tabMargin));
}
~ObjectsResizer() override
{
for (auto* obj : cnv->getSelectionOfType<Object>()) {
obj->hideHandles(false);
}
if (cnv) {
cnv->zoomScale.removeListener(this);
}
}
void setBorderScale(Value const& canvasScale)
{
auto const scale = getValue<float>(canvasScale);
auto const borderSize = std::max(12.0f, 12 / scale);
if (mode == ResizerMode::Horizontal) {
border.setBorderThickness(BorderSize<int>(0, borderSize, 0, borderSize));
} else {
border.setBorderThickness(BorderSize<int>(borderSize, 0, borderSize, 0));
}
}
void valueChanged(Value& v) override
{
if (v.refersToSameSourceAs(cnv->zoomScale)) {
setBorderScale(cnv->zoomScale);
}
}
bool hitTest(int x, int y) override
{
if (cnv->panningModifierDown() || (cnv->viewport && cnv->viewport->isPerformingGesture()) || ModifierKeys::getCurrentModifiers().isAnyModifierKeyDown())
return false;
return true;
}
void mouseDown(MouseEvent const& e) override
{
if (e.mods.isLeftButtonDown())
originalPos = getPosition();
// We can allow launching the right-click menu, however we would need to turn off alignment etc...
// if (e.mods.isRightButtonDown()){
// cnv->objectLayer.getComponentAt(e.getEventRelativeTo(cnv).getPosition())->mouseDown(e);
//}
}
void mouseDrag(MouseEvent const& e) override
{
if (e.originalComponent == &border)
return;
if (e.mods.isLeftButtonDown()) {
auto const delta = e.getPosition() - e.getMouseDownPosition();
auto const newPos = originalPos + delta;
setTopLeftPosition(newPos);
}
}
void moved() override
{
onMove(getPosition());
}
void resized() override
{
border.setBounds(getLocalBounds().expanded(tabMargin));
spacer = onResize(getBounds().reduced(tabMargin));
}
void render(NVGcontext* nvg) override
{
// draw background and outline
auto const b = getBounds().reduced(tabMargin);
auto iCol = nvgColour(PlugDataColours::objectSelectedOutlineColour);
iCol.a = 5; // Make the inner colour semi-transparent
nvgDrawRoundedRect(nvg, b.getX(), b.getY(), b.getWidth(), b.getHeight(), iCol, nvgColour(PlugDataColours::objectSelectedOutlineColour), Corners::objectCornerRadius);
// Draw handles at edge
auto getCorners = [this] {
auto const rect = getBounds().reduced(tabMargin);
constexpr float offset = 2.0f;
Array<Rectangle<float>> corners = { Rectangle<float>(9.0f, 9.0f).withCentre(rect.getTopLeft().toFloat()).translated(offset, offset), Rectangle<float>(9.0f, 9.0f).withCentre(rect.getBottomLeft().toFloat()).translated(offset, -offset),
Rectangle<float>(9.0f, 9.0f).withCentre(rect.getBottomRight().toFloat()).translated(-offset, -offset), Rectangle<float>(9.0f, 9.0f).withCentre(rect.getTopRight().toFloat()).translated(-offset, offset) };
return corners;
};
auto& resizeHandleImage = cnv->resizeHandleImage;
int angle = 360;
for (auto& corner : getCorners()) {
NVGScopedState scopedState(nvg);
// Rotate around centre
nvgTranslate(nvg, corner.getCentreX(), corner.getCentreY());
nvgRotate(nvg, degreesToRadians<float>(angle));
nvgTranslate(nvg, -4.5f, -4.5f);
nvgBeginPath(nvg);
nvgRect(nvg, 0, 0, 9, 9);
nvgFillPaint(nvg, nvgImageAlphaPattern(nvg, 0, 0, 9, 9, 0, resizeHandleImage.getImageId(), nvgColour(PlugDataColours::objectSelectedOutlineColour)));
nvgFill(nvg);
angle -= 90;
}
// #define SPACER_TEXT
#ifdef SPACER_TEXT
nvgBeginPath(nvg);
auto textPos = getPosition().translated(0, -25);
nvgFontSize(nvg, 20.0f);
nvgTextAlign(nvg, NVG_ALIGN_LEFT | NVG_ALIGN_TOP);
nvgFillColor(nvg, nvgRGBA(240, 240, 240, 255));
nvgText(nvg, textPos.x, textPos.y, String("Spacer size: " + String(spacer + 1.0f)).toRawUTF8(), nullptr);
#endif
}
private:
ResizableBorderComponent border;
ComponentBoundsConstrainer constrainer;
Canvas* cnv;
int tabMargin = Object::margin;
Point<int> originalPos;
float spacer = 0;
ResizerMode mode;
std::function<float(Rectangle<int>)> onResize;
std::function<void(Point<int>)> onMove;
};
Canvas::Canvas(PluginEditor* parent, pd::Patch::Ptr p, Component* parentGraph)
: NVGComponent(this)
, editor(parent)
, pd(parent->pd)
, refCountedPatch(p)
, patch(*p)
, canvasOrigin(Point<int>(infiniteCanvasSize / 2, infiniteCanvasSize / 2))
, graphArea(nullptr)
, pathUpdater(new ConnectionPathUpdater(this))
, globalMouseListener(this)
{
selectedComponents.addChangeListener(this);
addAndMakeVisible(objectLayer);
addAndMakeVisible(connectionLayer);
objectLayer.setInterceptsMouseClicks(false, true);
connectionLayer.setInterceptsMouseClicks(false, true);
if (auto patchPtr = patch.getPointer()) {
isGraphChild = glist_isgraph(patchPtr.get());
hideNameAndArgs = static_cast<bool>(patchPtr->gl_hidetext);
xRange = VarArray { var(patchPtr->gl_x1), var(patchPtr->gl_x2) };
yRange = VarArray { var(patchPtr->gl_y2), var(patchPtr->gl_y1) };
}
pd->registerMessageListener(patch.getUncheckedPointer(), this);
isGraphChild.addListener(this);
hideNameAndArgs.addListener(this);
xRange.addListener(this);
yRange.addListener(this);
auto const patchBounds = patch.getBounds();
patchWidth = patchBounds.getWidth();
patchHeight = patchBounds.getHeight();
patchWidth.addListener(this);
patchHeight.addListener(this);
globalMouseListener.globalMouseMove = [this](MouseEvent const& e) {
lastMouseX = e.x;
lastMouseY = e.y;
};
globalMouseListener.globalMouseDrag = [this](MouseEvent const& e) {
lastMouseX = e.x;
lastMouseY = e.y;
};
suggestor = std::make_unique<SuggestionComponent>();
canvasBorderResizer = std::make_unique<BorderResizer>(this);
canvasBorderResizer->onDrag = [this] {
patchWidth = std::max(0, canvasBorderResizer->getBounds().getCentreX() - canvasOrigin.x);
patchHeight = std::max(0, canvasBorderResizer->getBounds().getCentreY() - canvasOrigin.y);
};
canvasBorderResizer->setCentrePosition(canvasOrigin.x + patchBounds.getWidth(), canvasOrigin.y + patchBounds.getHeight());
addAndMakeVisible(canvasBorderResizer.get());
// initialize to default zoom
auto const defaultZoom = SettingsFile::getInstance()->getPropertyAsValue("default_zoom");
zoomScale.setValue(getValue<float>(defaultZoom) / 100.0f);
zoomScale.addListener(this);
setSize(infiniteCanvasSize, infiniteCanvasSize);
// Check if canvas belongs to a graph
if (parentGraph) {
setLookAndFeel(&editor->getLookAndFeel());
parentGraph->addAndMakeVisible(this);
setInterceptsMouseClicks(false, true);
isGraph = true;
} else {
isGraph = false;
}
if (!isGraph) {
auto* canvasViewport = new CanvasViewport(editor, this);
canvasViewport->onScroll = [this] {
if (suggestor) {
suggestor->updateBounds();
}
if (graphArea) {
graphArea->updateBounds();
}
};
viewport.reset(canvasViewport); // Owned by the tabbar, but doesn't exist for graph!
restoreViewportState();
}
commandLocked.referTo(pd->commandLocked);
commandLocked.addListener(this);
// pd->commandLocked doesn't get updated when a canvas isn't active
// So we set it to false here when a canvas is remade
// Otherwise the last canvas could have set it true, and it would still be
// in that state without command actually being locked
if (!isGraph)
commandLocked.setValue(false);
// Add draggable border for setting graph position
if (getValue<bool>(isGraphChild) && !isGraph) {
graphArea = std::make_unique<GraphArea>(this);
addAndMakeVisible(*graphArea);
graphArea->setAlwaysOnTop(true);
}
if (!isGraph) {
editor->nvgSurface.addBufferedObject(this);
}
// Add lasso component
addAndMakeVisible(&lasso);
lasso.setAlwaysOnTop(true);
setWantsKeyboardFocus(true);
if (!isGraph) {
presentationMode.addListener(this);
} else {
presentationMode = false;
}
performSynchronise();
// Start in unlocked mode if the patch is empty
if (objects.empty()) {
locked = false;
if (auto patchPtr = patch.getPointer())
patchPtr->gl_edit = false;
} else {
if (auto patchPtr = patch.getPointer())
locked = !patchPtr->gl_edit;
}
locked.addListener(this);
editor->addModifierKeyListener(this);
updateOverlays();
orderConnections();
parameters.addParamBool("Is graph", cGeneral, &isGraphChild, { "No", "Yes" }, 0);
parameters.addParamBool("Hide name and arguments", cGeneral, &hideNameAndArgs, { "No", "Yes" }, 0);
parameters.addParamRange("X range", cGeneral, &xRange, { 0.0f, 1.0f });
parameters.addParamRange("Y range", cGeneral, &yRange, { 1.0f, 0.0f });
auto onInteractionFn = [this](bool const state) {
dimensionsAreBeingEdited = state;
repaint();
};
parameters.addParamInt("Width", cDimensions, &patchWidth, 527, true, 0, 1 << 30, onInteractionFn);
parameters.addParamInt("Height", cDimensions, &patchHeight, 327, true, 0, 1 << 30, onInteractionFn);
lookAndFeelChanged();
}
Canvas::~Canvas()
{
for (auto* object : objects) {
object->hideEditor();
}
if (!isGraph) {
editor->nvgSurface.removeBufferedObject(this);
}
saveViewportState();
zoomScale.removeListener(this);
editor->removeModifierKeyListener(this);
pd->unregisterMessageListener(this);
if(getValue<bool>(isGraphChild) && isGraph)
patch.setVisible(false);
selectedComponents.removeChangeListener(this);
}
void Canvas::changeListenerCallback(ChangeBroadcaster* c)
{
if (c == &selectedComponents) {
auto isSelectedDifferent = [](SelectedItemSet<WeakReference<Component>> const& set1, SelectedItemSet<WeakReference<Component>> const& set2) -> bool {
if (set1.getNumSelected() != set2.getNumSelected())
return true;
for (int i = 0; i < set1.getNumSelected(); i++) {
if (!set2.isSelected(set1.getSelectedItem(i)))
return true;
}
return false; // identical
};
if (isSelectedDifferent(selectedComponents, previousSelectedComponents)) {
previousSelectedComponents = selectedComponents;
editor->updateSelection(this);
}
}
}
void Canvas::lookAndFeelChanged()
{
dotsLargeImage.setDirty(); // Make sure bg colour actually gets updated
}
void Canvas::parentHierarchyChanged()
{
// If the canvas has been added back into the editor, update the look and feel
// We need to do this because canvases are removed from the parent hierarchy when not visible
// TODO: consider setting a flag when look and feel actually changes, and read that here
if (getParentComponent()) {
sendLookAndFeelChange();
}
}
void Canvas::updateFramebuffers(NVGcontext* nvg)
{
auto const pixelScale = editor->getRenderScale();
auto zoom = getValue<float>(zoomScale);
constexpr int resizerLogicalSize = 9;
float const viewScale = pixelScale * zoom;
int const resizerBufferSize = resizerLogicalSize * viewScale;
if (resizeHandleImage.needsUpdate(resizerBufferSize, resizerBufferSize)) {
resizeHandleImage = NVGImage(nvg, resizerBufferSize, resizerBufferSize, [viewScale](Graphics& g) {
g.addTransform(AffineTransform::scale(viewScale, viewScale));
auto const b = Rectangle<int>(0, 0, 9, 9);
// use the path with a hole in it to exclude the inner rounded rect from painting
Path outerArea;
outerArea.addRectangle(b);
outerArea.setUsingNonZeroWinding(false);
Path innerArea;
auto const innerRect = b.translated(Object::margin / 2, Object::margin / 2);
innerArea.addRoundedRectangle(innerRect, Corners::objectCornerRadius);
outerArea.addPath(innerArea);
g.reduceClipRegion(outerArea);
g.setColour(Colours::white); // For alpha image colour isn't important
g.fillRoundedRectangle(0.0f, 0.0f, 9.0f, 9.0f, Corners::resizeHanleCornerRadius); }, NVGImage::AlphaImage);
}
auto gridLogicalSize = objectGrid.gridSize ? objectGrid.gridSize : 25;
auto gridSizeCommon = 300;
auto const gridBufferSize = gridSizeCommon * pixelScale * zoom;
if (dotsLargeImage.needsUpdate(gridBufferSize, gridBufferSize) || lastObjectGridSize != gridLogicalSize) {
lastObjectGridSize = gridLogicalSize;
dotsLargeImage = NVGImage(nvg, gridBufferSize, gridBufferSize, [zoom, viewScale, gridLogicalSize, gridSizeCommon](Graphics& g) {
g.addTransform(AffineTransform::scale(viewScale, viewScale));
float const ellipseRadius = zoom < 1.0f ? jmap(zoom, 0.25f, 1.0f, 3.0f, 1.0f) : 1.0f;
int decim = 0;
switch (gridLogicalSize) {
case 5:
case 10:
if (zoom < 1.0f)
decim = 4;
if (zoom < 0.5f)
decim = 6;
break;
case 15:
if (zoom < 1.0f)
decim = 4;
if (zoom < 0.5f)
decim = 8;
break;
case 20:
case 25:
if (zoom < 1.0f)
decim = 3;
if (zoom < 0.5f)
decim = 6;
break;
case 30:
if (zoom < 1.0f)
decim = 12;
if (zoom < 0.5f)
decim = 12;
break;
default: break;
}
auto markingColour = PlugDataColours::canvasDotsColour.interpolatedWith(PlugDataColours::canvasBackgroundColour, 0.2f);
auto const majorDotColour = markingColour.withAlpha(std::min(zoom * 0.8f, 1.0f));
g.setColour(majorDotColour);
// Draw ellipses on the grid
for (int x = 0; x <= gridSizeCommon; x += gridLogicalSize)
{
for (int y = 0; y <= gridSizeCommon; y += gridLogicalSize)
{
if (decim != 0) {
if (x % decim && y % decim)
continue;
g.setColour(majorDotColour);
if (x % decim == 0 && y % decim == 0)
g.setColour(markingColour);
}
// Add half smallest dot offset so the dot isn't at the edge of the texture
// We remove this when we position the texture on the canvas
float const centerX = static_cast<float>(x) + 2.5f;
float const centerY = static_cast<float>(y) + 2.5f;
g.fillEllipse(centerX - ellipseRadius, centerY - ellipseRadius, ellipseRadius * 2.0f, ellipseRadius * 2.0f);
}
} }, NVGImage::RepeatImage, PlugDataColours::canvasBackgroundColour);
}
}
// Callback from canvasViewport to perform actual rendering
void Canvas::performRender(NVGcontext* nvg, Rectangle<int> invalidRegion)
{
constexpr auto halfSize = infiniteCanvasSize / 2;
auto const zoom = getValue<float>(zoomScale);
bool const isLocked = getValue<bool>(locked);
nvgSave(nvg);
if (viewport) {
nvgTranslate(nvg, -viewport->getViewPositionX(), -viewport->getViewPositionY());
nvgScale(nvg, zoom, zoom);
invalidRegion = invalidRegion.translated(viewport->getViewPositionX(), viewport->getViewPositionY());
invalidRegion /= zoom;
if (isLocked) {
nvgFillColor(nvg, nvgColour(PlugDataColours::canvasBackgroundColour));
nvgFillRect(nvg, invalidRegion.getX(), invalidRegion.getY(), invalidRegion.getWidth(), invalidRegion.getHeight());
} else {
nvgBeginPath(nvg);
nvgRect(nvg, 0, 0, infiniteCanvasSize, infiniteCanvasSize);
// Use least common multiple of grid sizes: 5,10,15,20,25,30 for texture size for now
// We repeat the texture on GPU, this is so the texture does not become too small for GPU processing
// There will be a best fit depending on CPU/GPU calcuations.
// But currently 300 works well on GPU.
{
constexpr auto gridSizeCommon = 300;
NVGScopedState scopedState(nvg);
// offset image texture by 2.5f so no dots are on the edge of the texture
nvgTranslate(nvg, canvasOrigin.x - 2.5f, canvasOrigin.x - 2.5f);
nvgFillColor(nvg, nvgColour(PlugDataColours::canvasBackgroundColour)); // This fixes some glitches but I'm not sure why
nvgFill(nvg);
nvgFillPaint(nvg, nvgImagePattern(nvg, 0, 0, gridSizeCommon, gridSizeCommon, 0, dotsLargeImage.getImageId(), 1));
nvgFill(nvg);
}
}
}
currentRenderArea = invalidRegion;
auto drawBorder = [this, nvg](bool const bg, bool const fg) {
if (viewport && (showOrigin || showBorder) && !::getValue<bool>(presentationMode)) {
NVGScopedState scopedState(nvg);
nvgBeginPath(nvg);
auto const borderWidth = getValue<float>(patchWidth);
auto const borderHeight = getValue<float>(patchHeight);
constexpr auto pos = Point<int>(halfSize, halfSize);
if (bg) {
nvgBeginPath(nvg);
nvgMoveTo(nvg, pos.x, pos.y);
nvgLineTo(nvg, pos.x, pos.y + (showOrigin ? halfSize : borderHeight));
nvgMoveTo(nvg, pos.x, pos.y);
nvgLineTo(nvg, pos.x + (showOrigin ? halfSize : borderWidth), pos.y);
if (showBorder) {
nvgMoveTo(nvg, pos.x + borderWidth, pos.y);
nvgLineTo(nvg, pos.x + borderWidth, pos.y + borderHeight);
nvgLineTo(nvg, pos.x, pos.y + borderHeight);
}
nvgLineStyle(nvg, NVG_LINE_SOLID);
nvgStrokeColor(nvg, nvgColour(PlugDataColours::canvasBackgroundColour));
nvgStrokeWidth(nvg, 8.0f);
nvgStroke(nvg);
nvgFillColor(nvg, nvgColour(PlugDataColours::canvasBackgroundColour));
nvgFillRect(nvg, pos.x - 1.0f, pos.y - 1.0f, 2, 2);
}
nvgStrokeColor(nvg, nvgColour(PlugDataColours::canvasDotsColour.interpolatedWith(PlugDataColours::canvasBackgroundColour, 0.2f)));
nvgStrokeWidth(nvg, 1.5f);
nvgDashLength(nvg, 8.0f);
nvgLineStyle(nvg, NVG_LINE_DASHED);
if (fg) {
nvgBeginPath(nvg);
nvgMoveTo(nvg, pos.x, pos.y);
nvgLineTo(nvg, pos.x, pos.y + (showOrigin ? halfSize : borderHeight));
nvgStroke(nvg);
nvgBeginPath(nvg);
nvgMoveTo(nvg, pos.x, pos.y);
nvgLineTo(nvg, pos.x + (showOrigin ? halfSize : borderWidth), pos.y);
nvgStroke(nvg);
}
if (showBorder && fg) {
nvgStrokeWidth(nvg, 1.5f);
nvgLineStyle(nvg, NVG_LINE_DASHED);
nvgBeginPath(nvg);
nvgMoveTo(nvg, pos.x + borderWidth, pos.y + borderHeight);
nvgLineTo(nvg, pos.x + borderWidth, pos.y);
nvgStroke(nvg);
nvgBeginPath(nvg);
nvgMoveTo(nvg, pos.x + borderWidth, pos.y + borderHeight);
nvgLineTo(nvg, pos.x, pos.y + borderHeight);
nvgStroke(nvg);
canvasBorderResizer->render(nvg);
}
}
};
if (!dimensionsAreBeingEdited)
drawBorder(true, true);
else
drawBorder(true, false);
// Render objects like [drawcurve], [fillcurve] etc. at the back
for (auto drawable : drawables) {
if (drawable) {
auto const* component = dynamic_cast<Component*>(drawable.get());
if (invalidRegion.intersects(component->getBounds())) {
drawable->render(nvg);
}
}
}
if (::getValue<bool>(presentationMode) || isGraph) {
renderAllObjects(nvg, invalidRegion);
// render presentation mode as clipped 'virtual' plugin view
if (::getValue<bool>(presentationMode)) {
auto const borderWidth = getValue<float>(patchWidth);
auto const borderHeight = getValue<float>(patchHeight);
constexpr auto pos = Point<int>(halfSize, halfSize);
auto const scale = getValue<float>(zoomScale);
auto const windowCorner = Corners::windowCornerRadius / scale;
NVGScopedState scopedState(nvg);
// background colour to crop outside of border area
nvgBeginPath(nvg);
nvgRect(nvg, 0, 0, infiniteCanvasSize, infiniteCanvasSize);
nvgPathWinding(nvg, NVG_HOLE);
nvgRoundedRect(nvg, pos.getX(), pos.getY(), borderWidth, borderHeight, windowCorner);
nvgFillColor(nvg, nvgColour(PlugDataColours::presentationBackgroundColour));
nvgFill(nvg);
// background drop shadow to simulate a virtual plugin
nvgBeginPath(nvg);
nvgRect(nvg, 0, 0, infiniteCanvasSize, infiniteCanvasSize);
nvgPathWinding(nvg, NVG_HOLE);
nvgRoundedRect(nvg, pos.getX(), pos.getY(), borderWidth, borderHeight, windowCorner);
int const shadowSize = 24 / scale;
auto borderArea = Rectangle<int>(0, 0, borderWidth, borderHeight).expanded(shadowSize);
if (presentationShadowImage.needsUpdate(borderArea.getWidth(), borderArea.getHeight())) {
presentationShadowImage = NVGImage(nvg, borderArea.getWidth(), borderArea.getHeight(), [borderArea, shadowSize, windowCorner](Graphics& g) { StackShadow::drawShadowForRect(g, borderArea.reduced(shadowSize).withPosition(shadowSize, shadowSize), shadowSize, windowCorner, 0.3f, 2); }, NVGImage::AlphaImage);
}
auto const shadowImage = nvgImageAlphaPattern(nvg, pos.getX() - shadowSize, pos.getY() - shadowSize, borderArea.getWidth(), borderArea.getHeight(), 0, presentationShadowImage.getImageId(), nvgColour(Colours::black));
nvgStrokeColor(nvg, nvgColour(PlugDataColours::presentationBackgroundColour.contrasting(0.3f)));
nvgStrokeWidth(nvg, 0.5f / scale);
nvgFillPaint(nvg, shadowImage);
nvgFill(nvg);
nvgStroke(nvg);
}
}
// render connections infront or behind objects depending on lock mode or overlay setting
else {
if (connectionsBehind) {
renderAllConnections(nvg, invalidRegion);
renderAllObjects(nvg, invalidRegion);
} else {
renderAllObjects(nvg, invalidRegion);
renderAllConnections(nvg, invalidRegion);
}
}
for (auto* connection : connectionsBeingCreated) {
NVGScopedState scopedState(nvg);
connection->render(nvg);
}
if (graphArea) {
NVGScopedState scopedState(nvg);
nvgTranslate(nvg, graphArea->getX(), graphArea->getY());
graphArea->render(nvg);
}
objectGrid.render(nvg);
if (viewport && lasso.isVisible() && !lasso.getBounds().isEmpty()) {
auto lassoBounds = lasso.getBounds();
lassoBounds = lassoBounds.withSize(jmax(lasso.getWidth(), 2), jmax(lasso.getHeight(), 2));
nvgDrawRoundedRect(nvg, lassoBounds.getX(), lassoBounds.getY(), lassoBounds.getWidth(), lassoBounds.getHeight(), nvgColour(PlugDataColours::objectSelectedOutlineColour.withAlpha(0.075f)), nvgColour(PlugDataColours::canvasBackgroundColour.interpolatedWith(PlugDataColours::objectSelectedOutlineColour, 0.65f)), 0.0f);
}
suggestor->renderAutocompletion(nvg);
// Draw the search panel's selected object over all other objects
// Because objects can be underneath others
if (canvasSearchHighlight)
canvasSearchHighlight->render(nvg);
if (dimensionsAreBeingEdited) {
bool borderWasShown = showBorder;
showBorder = true;
drawBorder(false, true);
showBorder = borderWasShown;
}
if (objectsDistributeResizer)
objectsDistributeResizer->render(nvg);
nvgRestore(nvg);
// Draw scrollbars
if (viewport) {
viewport->render(nvg, viewport->getLocalArea(this, invalidRegion));
}
}
void Canvas::renderAllObjects(NVGcontext* nvg, Rectangle<int> const area)
{
for (auto* obj : objects) {
{
auto b = obj->getBounds();
if (b.intersects(area) && obj->isVisible()) {
NVGScopedState scopedState(nvg);
nvgTranslate(nvg, b.getX(), b.getY());
obj->render(nvg);
}
}
// Draw label in canvas coordinates
obj->renderLabel(nvg);
}
}
void Canvas::renderAllConnections(NVGcontext* nvg, Rectangle<int> const area)
{
if (!connectionLayer.isVisible())
return;
SmallArray<Connection*> connectionsToDraw;
SmallArray<Connection*> connectionsToDrawSelected;
Connection* hovered = nullptr;
for (auto* connection : connections) {
NVGScopedState scopedState(nvg);
if (connection->intersectsRectangle(area) && connection->isVisible()) {
if (connection->isMouseHovering())
hovered = connection;
else if (!connection->isSelected())
connection->render(nvg);
else
connectionsToDrawSelected.add(connection);
if (showConnectionOrder) {
connectionsToDraw.add(connection);
}
}
}
// Draw all selected connections in front
if (connectionsToDrawSelected.not_empty()) {
for (auto* connection : connectionsToDrawSelected) {
NVGScopedState scopedState(nvg);
connection->render(nvg);
}
}
if (hovered) {
NVGScopedState scopedState(nvg);
hovered->render(nvg);
}
if (connectionsToDraw.not_empty()) {
for (auto const* connection : connectionsToDraw) {
NVGScopedState scopedState(nvg);
connection->renderConnectionOrder(nvg);
}
}
}
void Canvas::settingsChanged(String const& name, var const& value)
{
switch (hash(name)) {
case hash("grid_size"):
repaint();
break;
case hash("border"):
showBorder = static_cast<int>(value);
repaint();
break;
case hash("overlays"): {
updateOverlays();
break;
}
default:
break;
}
}
bool Canvas::shouldShowObjectActivity() const
{
return showObjectActivity && !presentationMode.getValue() && !isGraph;
}
bool Canvas::shouldShowIndex() const
{
return showIndex && !presentationMode.getValue();
}
bool Canvas::shouldShowConnectionDirection() const
{
return showConnectionDirection;
}
bool Canvas::shouldShowConnectionActivity() const
{
return showConnectionActivity;
}
int Canvas::getOverlays() const
{
int overlayState = 0;
auto const overlaysTree = SettingsFile::getInstance()->getProperty<DynamicObject>("overlays");
auto const altModeEnabled = overlaysTree->getProperty("alt_mode") && !isGraph;
if (!locked.getValue()) {
overlayState = overlaysTree->getProperty("edit");
}
if (locked.getValue() || commandLocked.getValue()) {
overlayState = overlaysTree->getProperty("lock");
}
if (altModeEnabled) {
overlayState = overlaysTree->getProperty("alt");
}
return overlayState;
}
void Canvas::updateOverlays()
{
int const overlayState = getOverlays();
showBorder = overlayState & Border;
showOrigin = overlayState & Origin;
showConnectionOrder = overlayState & Order;
connectionsBehind = overlayState & Behind;
showObjectActivity = overlayState & ActivationState;
showIndex = overlayState & Index;
showConnectionDirection = overlayState & Direction;
showConnectionActivity = overlayState & ConnectionActivity;
set_plugdata_activity_enabled(showObjectActivity);
orderConnections();
repaint();
}
void Canvas::jumpToOrigin()
{
if (viewport)
viewport->setViewPositionAnimated((canvasOrigin.toFloat() + Point<float>(1, 1)) * getValue<float>(zoomScale));
}
void Canvas::restoreViewportState()
{
if (viewport) {
zoomScale.setValue(patch.lastViewportScale);
viewport->setViewPosition((patch.lastViewportPosition + canvasOrigin.toFloat()) * patch.lastViewportScale);
}
}
void Canvas::saveViewportState()
{
if (viewport) {
patch.lastViewportScale = getValue<float>(zoomScale);
patch.lastViewportPosition = ((viewport->getViewPosition() / patch.lastViewportScale) - canvasOrigin.toFloat());
}
}
void Canvas::zoomToFitAll()
{
if (objects.empty() || !viewport)
return;
auto regionOfInterest = Rectangle<float>(canvasOrigin.x, canvasOrigin.y, 20, 20);
if (!presentationMode.getValue()) {
for (auto const* object : objects) {
regionOfInterest = regionOfInterest.getUnion(object->getBounds().toFloat());
}
}
regionOfInterest = regionOfInterest.expanded(24); // Nice margin
auto const viewportW = static_cast<float>(viewport->getWidth());
auto const viewportH = static_cast<float>(viewport->getHeight());
auto const scaleX = viewportW / regionOfInterest.getWidth();
auto const scaleY = viewportH / regionOfInterest.getHeight();
auto targetScale = std::clamp(jmin(scaleX, scaleY), 0.25f, 3.0f);
// zoomScale = targetScale;
auto const roiCentreScaled = regionOfInterest.getCentre() * targetScale;
auto const screenCentre = Point<float>(viewportW * 0.5f, viewportH * 0.5f);
auto const targetViewPos = roiCentreScaled - screenCentre;
viewport->setViewPositionAnimated(targetViewPos, targetScale);
}
void Canvas::tabChanged()
{
synchronise();
updateDrawables();
for (auto const* obj : objects) {
if (!obj->gui)
continue;
obj->gui->tabChanged();
}
editor->statusbar->updateZoomLevel();
editor->repaint(); // Make sure everything it up to date
}
void Canvas::save(std::function<void()> const& nestedCallback)
{
auto const* canvasToSave = this;
if (patch.isSubpatch()) {
for (auto const& parentCanvas : editor->getCanvases()) {
if (patch.getRoot() == parentCanvas->patch.getRawPointer()) {
canvasToSave = parentCanvas;
}
}
}
if (canvasToSave->patch.getCurrentFile().existsAsFile()) {
canvasToSave->patch.savePatch();
SettingsFile::getInstance()->addToRecentlyOpened(canvasToSave->patch.getCurrentURL());
pd->titleChanged();
nestedCallback();
} else {
saveAs(nestedCallback);
}
}
void Canvas::saveAs(std::function<void()> const& nestedCallback)
{
Dialogs::showSaveDialog([this, nestedCallback](URL const& resultURL) mutable {
auto result = resultURL.getLocalFile();
if (result.getFullPathName().isNotEmpty()) {
if (result.exists())
result.deleteFile();
patch.savePatch(resultURL);
SettingsFile::getInstance()->addToRecentlyOpened(resultURL);
pd->titleChanged();
}
nestedCallback();
},
"*.pd", "Patch", this, false, patch.getPatchFile().getFileNameWithoutExtension());
}
void Canvas::handleAsyncUpdate()
{
performSynchronise();
}