-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathConnection.cpp
More file actions
1344 lines (1089 loc) · 42 KB
/
Connection.cpp
File metadata and controls
1344 lines (1089 loc) · 42 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_opengl/juce_opengl.h>
using namespace juce::gl;
#include <nanovg.h>
#include "Utility/Config.h"
#include "Utility/NVGUtils.h"
#include "Utility/SettingsFile.h"
#include "Connection.h"
#include "Canvas.h"
#include "Iolet.h"
#include "Object.h"
#include "PluginProcessor.h"
#include "PluginEditor.h" // might not need this?
#include "CanvasViewport.h"
#include "Pd/Patch.h"
#include "Components/ConnectionMessageDisplay.h"
Connection::Connection(Canvas* parent, Iolet* s, Iolet* e, t_outconnect* oc)
: NVGComponent(this)
, inlet(s->isInlet ? s : e)
, outlet(s->isInlet ? e : s)
, inobj(inlet->object)
, outobj(outlet->object)
, cnv(parent)
, ptr(parent->pd)
{
cnv->selectedComponents.addChangeListener(this);
locked.referTo(parent->locked);
presentationMode.referTo(parent->presentationMode);
// Make sure it's not 2x the same iolet
if (!outlet || !inlet || outlet->isInlet == inlet->isInlet) {
outlet = nullptr;
inlet = nullptr;
jassertfalse;
return;
}
cableType = DataCable;
if (outlet && outlet->isSignal) {
cableType = SignalCable;
}
if (outlet && outlet->isGemState) {
cableType = GemCable;
}
setStrokeThickness(12.0f); // This will make sure the DrawablePath's bounds get expanded, which we use for hit detection and drawing reconnect handles
inIdx = inlet->ioletIdx;
outIdx = outlet->ioletIdx;
outlet->repaint();
inlet->repaint();
// If it doesn't already exist in pd, create connection in pd
if (!oc) {
auto* checkedOut = pd::Interface::checkObject(outobj->getPointer());
auto* checkedIn = pd::Interface::checkObject(inobj->getPointer());
if (checkedOut && checkedIn) {
oc = parent->patch.createAndReturnConnection(checkedOut, outIdx, checkedIn, inIdx);
setPointer(oc);
} else {
jassertfalse;
return;
}
} else {
setPointer(oc);
popPathState();
}
// Listen to changes at iolets
outobj->addComponentListener(this);
inobj->addComponentListener(this);
setInterceptsMouseClicks(true, true);
addMouseListener(cnv, true);
cnv->connectionLayer.addAndMakeVisible(this);
updater.addAnimator(activityStateAnimator);
setAccessible(false);
lookAndFeelChanged();
}
Connection::~Connection()
{
if (cnv->pd->connectionListener)
cnv->pd->connectionListener.load()->setConnection(nullptr);
cnv->pd->unregisterMessageListener(this);
cnv->selectedComponents.removeChangeListener(this);
if (outlet) {
outlet->repaint();
outlet->removeComponentListener(this);
}
if (outobj) {
outobj->removeComponentListener(this);
}
if (inlet) {
inlet->repaint();
inlet->removeComponentListener(this);
}
if (inobj) {
inobj->removeComponentListener(this);
}
}
void Connection::changeListenerCallback(ChangeBroadcaster* source)
{
if (auto const selectedItems = dynamic_cast<SelectedItemSet<WeakReference<Component>>*>(source))
setSelected(selectedItems->isSelected(this));
}
void Connection::lookAndFeelChanged()
{
handleColour = outlet->isSignal ? nvgColour(PlugDataColours::dataColour) : nvgColour(PlugDataColours::signalColour);
shadowColour = nvgColour(PlugDataColours::canvasBackgroundColour.contrasting(0.06f).withAlpha(0.24f));
outlineColour = nvgColour(PlugDataColours::objectOutlineColour);
textColour = nvgColour(PlugDataColours::objectSelectedOutlineColour.contrasting());
if (connectionStyle != PlugDataLook::getConnectionStyle()) {
connectionStyle = PlugDataLook::getConnectionStyle();
cachedPath.clear();
}
updatePath();
repaint();
}
NVGcolor Connection::getConnectionColour() const
{
Colour c = PlugDataColours::connectionColour;
if (isSelected() || isHovering) {
if (outlet->isSignal) {
c = PlugDataColours::signalColour;
}
else if (outlet->isGemState) {
c = PlugDataColours::gemColour;
}
else {
c = PlugDataColours::dataColour;
}
}
return nvgColour(isHovering ? c.brighter() : c);
}
void Connection::render(NVGcontext* nvg)
{
auto connectionColour = getConnectionColour();
nvgSave(nvg);
nvgTranslate(nvg, getX(), getY());
bool isSignalCable = cableType == SignalCable && connectionStyle != PlugDataLook::ConnectionStyleVanilla;
auto dashColor = shadowColour;
if (isSignalCable) {
dashColor.a = 255;
dashColor.r *= 0.4f;
dashColor.g *= 0.4f;
dashColor.b *= 0.4f;
}
float cableThickness = getPathWidth();
// Draw a fake path dot if the path is less than 1pt in length.
// Paths don't draw currently if they have length of zero points
if (pathLength < 1.0f) {
auto pathFromOrigin = getPath();
pathFromOrigin.applyTransform(AffineTransform::translation(-getX(), -getY()));
auto startPoint = pathFromOrigin.getPointAlongPath(0.0);
nvgBeginPath(nvg);
nvgFillColor(nvg, shadowColour);
nvgCircle(nvg, startPoint.x, startPoint.y, cableThickness * 0.5f); // cableThickness is diameter, while circle is radius
nvgFill(nvg);
nvgBeginPath(nvg);
nvgFillColor(nvg, connectionColour);
nvgCircle(nvg, startPoint.x, startPoint.y, cableThickness * 0.25f);
nvgFill(nvg);
return;
}
float dashSize = isSignalCable ? numSignalChannels <= 1 ? 2.5f : 1.5f : 0.0f;
auto useGradientLook = PlugDataLook::getUseGradientConnectionLook() && !(isSelected() || isHovering);
auto showActivity = cableType == DataCable && cnv->shouldShowConnectionActivity();
nvgStrokePaint(nvg, nvgDoubleStroke(nvg, connectionColour, shadowColour, dashColor, dashSize, useGradientLook, showActivity, offset));
nvgStrokeWidth(nvg, cableThickness);
bool cacheHit = cachedPath.stroke();
if (!cacheHit) {
auto pathFromOrigin = getPath();
pathFromOrigin.applyTransform(AffineTransform::translation(-getX(), -getY()));
setJUCEPath(nvg, pathFromOrigin);
nvgStroke(nvg);
cachedPath.save(nvg);
}
nvgRestore(nvg);
if (isSelected() && isHovering) {
auto expandedStartHandle = isInStartReconnectHandle ? startReconnectHandle.expanded(3.0f) : startReconnectHandle;
auto expandedEndHandle = isInEndReconnectHandle ? endReconnectHandle.expanded(3.0f) : endReconnectHandle;
nvgFillColor(nvg, handleColour);
nvgBeginPath(nvg);
nvgCircle(nvg, expandedStartHandle.getCentreX(), expandedStartHandle.getCentreY(), expandedStartHandle.getWidth() / 2);
nvgFill(nvg);
nvgBeginPath(nvg);
nvgCircle(nvg, expandedEndHandle.getCentreX(), expandedEndHandle.getCentreY(), expandedEndHandle.getWidth() / 2);
nvgFill(nvg);
}
// draw direction arrow if activated in overlay menu
// c
// |\
// | \
// | \
// ___path___ | \a ___path___
// | /
// | /
// | /
// |/
// b
// setup arrow parameters
constexpr float arrowWidth = 8.0f;
constexpr float arrowLength = 12.0f;
auto renderArrow = [this, nvg, connectionColour](Path const& path, float const connectionLength) {
// get the center point of the connection path
auto const arrowCenter = connectionLength * 0.5f;
auto const arrowBase = path.getPointAlongPath(arrowCenter - arrowLength * 0.5f);
auto const arrowTip = path.getPointAlongPath(arrowCenter + arrowLength * 0.5f);
Line<float> const arrowLine(arrowBase, arrowTip);
auto const point_a = cnv->getLocalPoint(this, arrowTip);
auto const point_b = cnv->getLocalPoint(this, arrowLine.getPointAlongLine(0.0f, -(arrowWidth * 0.5f)));
auto const point_c = cnv->getLocalPoint(this, arrowLine.getPointAlongLine(0.0f, arrowWidth * 0.5f));
// draw the arrow
nvgBeginPath(nvg);
nvgStrokeColor(nvg, outlineColour);
nvgFillColor(nvg, connectionColour);
nvgMoveTo(nvg, point_a.x, point_a.y);
nvgLineTo(nvg, point_b.x, point_b.y);
nvgLineTo(nvg, point_c.x, point_c.y);
nvgClosePath(nvg);
nvgStrokeWidth(nvg, 1.0f);
nvgFill(nvg);
nvgStroke(nvg);
};
if (cnv->shouldShowConnectionDirection()) {
if (isSegmented()) {
for (int i = 1; i < currentPlan.size(); i++) {
auto const pathLine = Line<float>(currentPlan[i - 1], currentPlan[i]);
auto const length = pathLine.getLength();
// don't show arrow if start or end segment is too small, to give room for the reconnect handle
auto const isStartOrEnd = i == 1 || i == currentPlan.size() - 1;
if (length > arrowLength * (isStartOrEnd ? 3 : 2)) {
Path segmentedPath;
segmentedPath.addLineSegment(pathLine, 0.0f);
segmentedPath.applyTransform(AffineTransform::translation(-getX(), -getY()));
renderArrow(segmentedPath, length);
}
}
} else {
auto connectionPath = getPath();
connectionPath.applyTransform(AffineTransform::translation(-getX(), -getY()));
if (pathLength > arrowLength * 2) {
renderArrow(connectionPath, pathLength);
}
}
}
}
void Connection::renderConnectionOrder(NVGcontext* nvg) const
{
if (cableType == DataCable && getNumberOfConnections() > 1) {
auto connectionPath = getPath();
connectionPath.applyTransform(AffineTransform::translation(-getX(), -getY()));
auto const pos = cnv->getLocalPoint(this, connectionPath.getPointAlongPath(jmax(pathLength - 8.5f * 3, 9.5f)));
// circle background
nvgBeginPath(nvg);
nvgStrokeColor(nvg, outlineColour);
nvgFillColor(nvg, getConnectionColour());
constexpr auto radius = 7.0f;
constexpr auto diameter = radius * 2.0f;
auto const circleTopLeft = pos - Point<float>(radius, radius);
nvgRoundedRect(nvg, circleTopLeft.getX(), circleTopLeft.getY(), diameter, diameter, radius);
nvgStrokeWidth(nvg, 1.0f);
nvgFill(nvg);
nvgStroke(nvg);
// connection index number
nvgFillColor(nvg, textColour);
nvgFontSize(nvg, 9.0f);
nvgTextAlign(nvg, NVG_ALIGN_MIDDLE | NVG_ALIGN_CENTER);
nvgText(nvg, pos.getX(), pos.getY(), String(getMultiConnectNumber()).toUTF8(), nullptr);
}
}
void Connection::pushPathState(bool const force)
{
if (!inlet || !outlet)
return;
t_symbol* newPathState;
if (segmented) {
MemoryOutputStream stream;
for (auto const& point : currentPlan) {
stream.writeInt(point.x - outlet->getCanvasBounds().getCentre().x);
stream.writeInt(point.y - outlet->getCanvasBounds().getCentre().y);
}
auto const base64 = stream.getMemoryBlock().toBase64Encoding();
newPathState = cnv->pd->generateSymbol(base64);
} else {
newPathState = cnv->pd->generateSymbol("empty");
}
cnv->pathUpdater->pushPathState(this, newPathState);
if (force)
cnv->pathUpdater->timerCallback();
}
void Connection::popPathState()
{
if (!inlet || !outlet)
return;
String state;
if (auto oc = ptr.get<t_outconnect>()) {
auto const* pathData = outconnect_get_path_data(oc.get());
if (!pathData || !pathData->s_name)
return;
state = String::fromUTF8(pathData->s_name);
}
auto block = MemoryBlock();
auto const succeeded = block.fromBase64Encoding(state);
auto plan = PathPlan();
if (succeeded) {
auto stream = MemoryInputStream(block, false);
while (!stream.isExhausted()) {
auto const x = stream.readInt();
auto const y = stream.readInt();
plan.emplace_back(x + outlet->getCanvasBounds().getCentreX(), y + outlet->getCanvasBounds().getCentreY());
}
segmented = !plan.empty();
} else {
segmented = false;
}
currentPlan = plan;
numSignalChannels = getNumSignalChannels();
updatePath();
}
void Connection::setPointer(t_outconnect* newPtr)
{
auto const originalPointer = ptr.getRawUnchecked<t_outconnect>();
if (originalPointer != newPtr) {
ptr = pd::WeakReference(newPtr, cnv->pd);
cnv->pd->unregisterMessageListener(this);
cnv->pd->registerMessageListener(newPtr, this);
}
}
t_outconnect* Connection::getPointer() const
{
return ptr.getRaw<t_outconnect>();
}
t_symbol* Connection::getPathState() const
{
if (auto oc = ptr.get<t_outconnect>()) {
return outconnect_get_path_data(oc.get());
}
return nullptr;
}
bool Connection::hitTest(int const x, int const y)
{
if (inlet == nullptr || outlet == nullptr)
return false;
if (cnv->panningModifierDown())
return false;
if (cnv->commandLocked == var(true) || locked == var(true) || !cnv->connectionsBeingCreated.empty())
return false;
Point<float> const position = Point<float>(static_cast<float>(x), static_cast<float>(y)) + getPosition().toFloat();
Point<float> nearestPoint;
auto const path = getPath();
path.getNearestPoint(position, nearestPoint);
// Get outlet and inlet point
auto const pstart = getStartPoint();
auto const pend = getEndPoint();
if (selectedFlag && (startReconnectHandle.contains(position) || endReconnectHandle.contains(position))) {
repaint();
return true;
}
// If we click too close to the inlet, don't register the click on the connection
if (pstart.getDistanceFrom(position) < 8.0f || pend.getDistanceFrom(position) < 8.0f)
return false;
return nearestPoint.getDistanceFrom(position) < 3;
}
bool Connection::intersects(Rectangle<float> const toCheck, int const accuracy) const
{
PathFlatteningIterator i(getPath());
while (i.next()) {
auto const point1 = Point<float>(i.x1, i.y1);
// Skip points to reduce accuracy a bit for better performance
// We can only skip points if there are many points!
if (!PlugDataLook::getUseStraightConnections()) {
for (int n = 0; n < accuracy; n++) {
auto const next = i.next();
if (!next)
break;
}
}
auto const point2 = Point<float>(i.x2, i.y2);
auto currentLine = Line<float>(point1, point2);
if (toCheck.intersects(currentLine)) {
return true;
}
}
return false;
}
void Connection::forceUpdate()
{
updatePath();
repaint();
}
bool Connection::isSegmented() const
{
return segmented;
}
void Connection::setSegmented(bool const isSegmented)
{
segmented = isSegmented;
updatePath();
repaint();
pushPathState();
}
void Connection::setSelected(bool const shouldBeSelected)
{
if (selectedFlag != shouldBeSelected) {
selectedFlag = shouldBeSelected;
// Make the connection rise to the top of the connection layer
// This is so resize handles can easily be hit when the connection is selected
setAlwaysOnTop(shouldBeSelected);
repaint();
}
}
bool Connection::isSelected() const
{
return selectedFlag;
}
void Connection::mouseMove(MouseEvent const& e)
{
auto setReconnectFlag = [this](bool const start, bool const end) {
if (isInStartReconnectHandle != start || isInEndReconnectHandle != end) {
isInStartReconnectHandle = start;
isInEndReconnectHandle = end;
repaint();
}
};
if (startReconnectHandle.contains(e.getPosition().toFloat().translated(getX(), getY()))) {
setReconnectFlag(selectedFlag, false);
} else if (endReconnectHandle.contains(e.getPosition().toFloat().translated(getX(), getY()))) {
setReconnectFlag(false, selectedFlag);
} else {
setReconnectFlag(false, false);
}
if (isInStartReconnectHandle || isInEndReconnectHandle) {
setMouseCursor(MouseCursor::NormalCursor);
return;
}
int const n = getClosestLineIdx(e.getPosition().toFloat(), currentPlan);
if (isSegmented() && currentPlan.size() > 2 && n > 0) {
auto const line = Line<float>(currentPlan[n - 1], currentPlan[n]);
if (line.isVertical()) {
setMouseCursor(MouseCursor::LeftRightResizeCursor);
} else if (line.isHorizontal()) {
setMouseCursor(MouseCursor::UpDownResizeCursor);
} else {
setMouseCursor(MouseCursor::NormalCursor);
}
} else {
setMouseCursor(MouseCursor::NormalCursor);
}
}
StringArray Connection::getMessageFormated() const
{
auto const& args = lastValue;
auto const numArgs = args.size();
auto const name = lastSelector ? String::fromUTF8(lastSelector->s_name) : "";
StringArray formatedMessage;
if (name == "float" && numArgs > 0) {
formatedMessage.add("float:");
formatedMessage.add(args[0].toString());
} else if (name == "symbol" && numArgs > 0) {
formatedMessage.add("symbol:");
formatedMessage.add(args[0].toString());
} else if (name == "list") {
if (numArgs >= 15) {
formatedMessage.add("list (14+):");
} else {
formatedMessage.add("list (" + String(numArgs) + "):");
}
for (int arg = 0; arg < numArgs; arg++) {
if (args[arg].isFloat()) {
formatedMessage.add(String(args[arg].getFloat()));
} else if (args[arg].isSymbol()) {
formatedMessage.add(args[arg].toString());
}
}
if (numArgs >= 15) {
formatedMessage.add("...");
}
} else {
formatedMessage.add(name);
for (int arg = 0; arg < numArgs; arg++) {
if (args[arg].isFloat()) {
formatedMessage.add(String(args[arg].getFloat()));
} else if (args[arg].isSymbol()) {
formatedMessage.add(args[arg].toString());
}
}
}
return formatedMessage;
}
void Connection::mouseEnter(MouseEvent const& e)
{
isHovering = true;
if (plugdata_debugging_enabled()) {
Point<float> nearest;
getPath().getNearestPoint(cnv->getLocalPoint(this, e.position), nearest);
cnv->editor->connectionMessageDisplay->setConnection(this, cnv->localPointToGlobal(nearest).roundToInt().translated(20, 15));
}
repaint();
}
void Connection::mouseExit(MouseEvent const& e)
{
cnv->editor->connectionMessageDisplay->setConnection(nullptr);
isHovering = false;
repaint();
}
void Connection::mouseDown(MouseEvent const& e)
{
if (e.mods.isShiftDown() && e.getNumberOfClicks() == 2 && cnv->getSelectionOfType<Connection>().size() == 2) {
if (auto oc = ptr.get<t_outconnect>()) {
auto* patch = cnv->patch.getRawPointer();
auto* other = cnv->getSelectionOfType<Connection>()[0]->getPointer();
if (patch && other) {
pd::Interface::swapConnections(patch, oc.get(), other);
}
}
cnv->synchronise();
return;
}
cnv->editor->connectionMessageDisplay->setConnection(nullptr);
// Deselect all other connection if shift or command is not down
if (!e.mods.isCommandDown() && !e.mods.isShiftDown() && !e.mods.isPopupMenu()) {
cnv->deselectAll();
}
wasSelected = selectedFlag;
cnv->setSelected(this, true);
repaint();
if (currentPlan.size() <= 2)
return;
int const n = getClosestLineIdx(e.position, currentPlan);
if (n < 0)
return;
if (Line<float>(currentPlan[n - 1], currentPlan[n]).isVertical()) {
mouseDownPosition = currentPlan[n].x;
} else {
mouseDownPosition = currentPlan[n].y;
}
dragIdx = n;
}
void Connection::mouseDrag(MouseEvent const& e)
{
cnv->editor->connectionMessageDisplay->setConnection(nullptr);
bool const isDragging = e.getDistanceFromDragStart() > 6;
if (wasSelected && isInStartReconnectHandle) {
if (isDragging) {
cnv->connectingWithDrag = true;
reconnect(inlet);
}
return;
}
if (wasSelected && isInEndReconnectHandle) {
if (isDragging) {
cnv->connectingWithDrag = true;
reconnect(outlet);
}
return;
}
if (currentPlan.empty())
return;
if (isSegmented() && dragIdx != -1) {
auto const n = dragIdx;
auto const delta = e.getPosition() - e.getMouseDownPosition();
auto const line = Line<float>(currentPlan[n - 1], currentPlan[n]);
if (line.isVertical()) {
currentPlan[n - 1].x = mouseDownPosition + delta.x;
currentPlan[n].x = mouseDownPosition + delta.x;
} else {
currentPlan[n - 1].y = mouseDownPosition + delta.y;
currentPlan[n].y = mouseDownPosition + delta.y;
}
updatePath();
repaint();
}
}
void Connection::mouseUp(MouseEvent const& e)
{
if (dragIdx != -1) {
pushPathState();
dragIdx = -1;
}
if (selectedFlag && startReconnectHandle.contains(e.getMouseDownPosition().toFloat()) && startReconnectHandle.contains(e.position)) {
reconnect(inlet);
}
if (selectedFlag && endReconnectHandle.contains(e.getMouseDownPosition().toFloat()) && endReconnectHandle.contains(e.position)) {
reconnect(outlet);
}
if (reconnecting.size()) {
// Async to safely self-destruct
MessageManager::callAsync([canvas = SafePointer(cnv), r = reconnecting]() mutable {
for (auto& c : r) {
if (c && canvas) {
canvas->connections.remove_one(c.getComponent());
}
}
});
reconnecting.clear();
}
}
int Connection::getClosestLineIdx(Point<float> const& position, PathPlan const& plan) const
{
if (plan.size() < 2)
return -1;
for (int n = 2; n < plan.size() - 1; n++) {
auto line = Line<float>(plan[n - 1], plan[n]);
Point<float> nearest;
if (line.getDistanceFromPoint(cnv->getLocalPoint(this, position), nearest) < 3) {
return n;
}
}
return -1;
}
void Connection::pathChanged()
{
strokePath.clear();
strokeType.createStrokedPath(strokePath, path, AffineTransform(), 1.0f);
setBoundsToEnclose(getDrawableBounds());
repaint();
}
float Connection::getPathWidth() const
{
switch (connectionStyle) {
case PlugDataLook::ConnectionStyleVanilla:
return cableType == SignalCable ? 4.5f : 2.5f;
case PlugDataLook::ConnectionStyleThin:
return 3.0f;
default:
return 4.5f;
}
}
void Connection::reconnect(Iolet const* target)
{
if (!reconnecting.empty() || !target)
return;
auto const& otherIolet = target == inlet ? outlet : inlet;
SmallArray<Connection*> connections = { this };
if (Desktop::getInstance().getMainMouseSource().getCurrentModifiers().isShiftDown()) {
for (auto* c : otherIolet->object->getConnections()) {
if (c == this || !c->isSelected())
continue;
connections.add(c);
}
}
for (auto* c : connections) {
auto* checkedOut = pd::Interface::checkObject(c->outobj->getPointer());
auto* checkedIn = pd::Interface::checkObject(c->inobj->getPointer());
if (checkedOut && checkedIn && cnv->patch.hasConnection(checkedOut, c->outIdx, checkedIn, c->inIdx)) {
// Delete connection from pd if we haven't done that yet
cnv->patch.removeConnection(checkedOut, c->outIdx, checkedIn, c->inIdx, c->getPathState());
}
// Create new connection
cnv->connectionsBeingCreated.add(target->isInlet ? c->inlet : c->outlet, cnv);
c->setVisible(false);
reconnecting.add(SafePointer(c));
// Make sure we're deselected and remove object
cnv->setSelected(c, false, false);
}
}
void Connection::componentMovedOrResized(Component& component, bool wasMoved, bool const wasResized)
{
if (!inlet || !outlet)
return;
auto const pstart = getStartPoint();
auto const pend = getEndPoint();
// If both inlet and outlet are selected we can move the connection
if (outobj->isSelected() && inobj->isSelected() && !wasResized) {
// calculate the offset for moving the whole connection
auto const pointOffset = pstart - previousPStart;
// Prevent a repaint if we're not moving
// This will happen often since there's a move callback from both inlet and outlet
if (pointOffset.isOrigin())
return;
previousPStart = pstart;
setTopLeftPosition(getPosition() + pointOffset.toInt());
for (auto& point : currentPlan) {
point += pointOffset;
}
auto const translation = AffineTransform::translation(pointOffset.x, pointOffset.y);
auto offsetPath = getPath();
offsetPath.applyTransform(translation);
setPath(offsetPath);
updateReconnectHandle();
clipRegion.transformAll(translation);
return;
}
previousPStart = pstart;
cachedPath.clear();
if (currentPlan.size() <= 2) {
updatePath();
repaint();
return;
}
bool const isInlet = &component == inlet || &component == inobj;
int const idx1 = isInlet ? static_cast<int>(currentPlan.size() - 1) : 0;
int const idx2 = isInlet ? static_cast<int>(currentPlan.size() - 2) : 1;
auto const& position = isInlet ? pend : pstart;
if (Line<float>(currentPlan[idx1], currentPlan[idx2]).isVertical()) {
currentPlan[idx2].x = position.x;
} else {
currentPlan[idx2].y = position.y;
}
currentPlan[idx1] = position;
if (Line<float>(currentPlan[idx1], currentPlan[idx2]).isVertical()) {
currentPlan[idx2].x = position.x;
} else {
currentPlan[idx2].y = position.y;
}
currentPlan[idx1] = position;
updatePath();
repaint();
}
Point<float> Connection::getStartPoint() const
{
auto const outletBounds = outlet->getCanvasBounds().toFloat();
if (PlugDataLook::isFixedIoletPosition()) {
return { outletBounds.getX() + PlugDataLook::getIoletSize() * 0.5f, outletBounds.getCentreY() };
}
return outletBounds.getCentre();
}
Point<float> Connection::getEndPoint() const
{
auto const inletBounds = inlet->getCanvasBounds().toFloat();
if (PlugDataLook::isFixedIoletPosition()) {
return Point<float>(inletBounds.getX() + PlugDataLook::getIoletSize() * 0.5f, inletBounds.getCentreY());
}
return inletBounds.getCentre();
}
Path Connection::getNonSegmentedPath(Point<float> const start, Point<float> const end)
{
Path connectionPath;
connectionPath.startNewSubPath(start);
if (!PlugDataLook::getUseStraightConnections()) {
float const width = std::max(start.x, end.x) - std::min(start.x, end.x);
float const height = std::max(start.y, end.y) - std::min(start.y, end.y);
// Hack for now to hide really poor control point maths
// So we draw a straight line
if (end.getDistanceFrom(start) < 4.0f) {
connectionPath.lineTo(end);
goto returnPath;
}
float const min = std::min<float>(width, height);
float const max = std::max<float>(width, height);
constexpr float maxShiftY = 20.f;
constexpr float maxShiftX = 20.f;
float shiftY = std::min<float>(maxShiftY, max * 0.5);
float const shiftX = (start.y >= end.y ? std::min<float>(maxShiftX, min * 0.5) : 0.f) * (start.x < end.x ? -1. : 1.);
// Adjust control points if they are pointing away from the path
auto const xPointOffset = std::abs(start.x - end.x);
auto const yPointOffset = start.y - end.y;
auto const pathInverted = start.y > end.y;
if (xPointOffset <= 40.0f && pathInverted) {
float const xFactor = pow(1.0f - xPointOffset / 40.0f, 0.9f);
float const yFactor = pow(jmin(1.0f, yPointOffset / 20.0f), 0.9f);
shiftY = shiftY - xFactor * yFactor * jmax(maxShiftY, yPointOffset * 0.5f);
if ((xPointOffset <= 1.0f && yPointOffset <= 1.0f) || xPointOffset <= 1.0f || shiftY <= (end.y - start.y) * 0.5f) {
connectionPath.lineTo(end);
goto returnPath;
}
Point<float> const ctrlPoint1 { start.x - shiftX, start.y + shiftY };
Point<float> const ctrlPoint2 { end.x + shiftX, end.y - shiftY };
connectionPath.cubicTo(ctrlPoint1, ctrlPoint2, end);
} else {
Point<float> const ctrlPoint1 { start.x - shiftX, start.y + shiftY };
Point<float> const ctrlPoint2 { end.x + shiftX, end.y - shiftY };
connectionPath.cubicTo(ctrlPoint1, ctrlPoint2, end);
}
} else {
connectionPath.lineTo(end);
}
returnPath:
return connectionPath;
}
int Connection::getNumberOfConnections() const
{
int count = 0;
for (auto const* connection : cnv->connections) {
if (outlet == connection->outlet) {
count++;
}
}
return count;
}
int Connection::getMultiConnectNumber() const
{
int count = 0;
for (auto const* connection : cnv->connections) {
if (outlet == connection->outlet) {
count++;
if (this == connection)
return count;
}
}
return -1;
}
int Connection::getNumSignalChannels() const
{
if (auto oc = ptr.get<t_outconnect>()) {
if (auto const* signal = outconnect_get_signal(oc.get())) {
return signal->s_nchans;
}
}
if (outlet) {
return outlet->isSignal ? 1 : 0;
}
return 0;
}
void Connection::updateReconnectHandle()
{
startReconnectHandle = Rectangle<float>(5, 5).withCentre(path.getPointAlongPath(8.5f));
endReconnectHandle = Rectangle<float>(5, 5).withCentre(path.getPointAlongPath(jmax(pathLength - 8.5f, 9.5f)));
}
void Connection::updatePath()
{
if (!outlet || !inlet)
return;
auto const pstart = getStartPoint();
auto const pend = getEndPoint();
Path toDraw;
if (!segmented) {
toDraw = getNonSegmentedPath(pstart, pend);
currentPlan.clear();
} else {
if (currentPlan.empty()) {
findPath();
}
auto snap = [this](Point<float> const point, int const idx1, int const idx2) {
if (Line<float>(currentPlan[idx1], currentPlan[idx2]).isVertical()) {