GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — plugdata/Source/Connection.cpp at develop · plugdata-team/plugdata Expand file tree/ Copy pathConnection.cppMore file actions 1718 lines (1393 loc) · 57.4 KB / Copy pathConnection.cppFile metadata and controls1718 lines (1393 loc) · 57.4 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 <queue> #include <nanovg_async.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->getObject()) , outobj(outlet->getObject()) , 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; } inIdx = inlet->getIndex(); outIdx = outlet->getIndex(); 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); setPaintingIsUnclipped(true); 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() { auto const& colours = getThemeColours(*this); handleColour = outlet->isSignal() ? nvgColour(colours.dataColour) : nvgColour(colours.signalColour); shadowColour = nvgColour(colours.canvasBackgroundColour.contrasting(0.06f).withAlpha(0.24f)); outlineColour = nvgColour(colours.objectOutlineColour); if (connectionStyle != getPlugDataLook(*this).getConnectionStyle()) { connectionStyle = getPlugDataLook(*this).getConnectionStyle(); cachedPath.clear(); } updatePath(); repaint(); } NVGcolor Connection::getConnectionColour() const { auto const& colours = getThemeColours(*this); Colour c = colours.connectionColour; if (isSelected() || isHovering) { if (outlet->isSignal()) { c = colours.signalColour; } else if (outlet->isGemState()) { c = colours.gemColour; } else { c = colours.dataColour; } } return nvgColour(isHovering ? c.brighter() : c); } void Connection::render(NVGcontext* nvg) { auto connectionColour = getConnectionColour(); nanovg::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); nanovg::nvgBeginPath(nvg); nanovg::nvgFillColor(nvg, shadowColour); nanovg::nvgCircle(nvg, startPoint.x, startPoint.y, cableThickness * 0.5f); // cableThickness is diameter, while circle is radius nanovg::nvgFill(nvg); nanovg::nvgBeginPath(nvg); nanovg::nvgFillColor(nvg, connectionColour); nanovg::nvgCircle(nvg, startPoint.x, startPoint.y, cableThickness * 0.25f); nanovg::nvgFill(nvg); return; } float dashSize = isSignalCable ? numSignalChannels <= 1 ? 2.5f : 1.5f : 0.0f; auto useGradientLook = getPlugDataLook(*this).getUseGradientConnectionLook() && !(isSelected() || isHovering); auto showActivity = cableType == DataCable && cnv->shouldShowConnectionActivity(); nanovg::nvgStrokePaint(nvg, nanovg::nvgDoubleStroke(nvg, connectionColour, shadowColour, dashColor, dashSize, useGradientLook, showActivity, offset)); nanovg::nvgStrokeWidth(nvg, cableThickness); bool cacheHit = cachedPath.stroke(); if (!cacheHit) { auto pathFromOrigin = getPath(); pathFromOrigin.applyTransform(AffineTransform::translation(-getX(), -getY())); setJUCEPath(nvg, pathFromOrigin); nanovg::nvgStroke(nvg); cachedPath.save(nvg); } if (isSelected() && isHovering) { auto expandedStartHandle = isInStartReconnectHandle ? startReconnectHandle.expanded(3.0f) : startReconnectHandle; auto expandedEndHandle = isInEndReconnectHandle ? endReconnectHandle.expanded(3.0f) : endReconnectHandle; nanovg::nvgFillColor(nvg, handleColour); nanovg::nvgBeginPath(nvg); nanovg::nvgCircle(nvg, expandedStartHandle.getCentreX() - getX(), expandedStartHandle.getCentreY() - getY(), expandedStartHandle.getWidth() / 2); nanovg::nvgCircle(nvg, expandedEndHandle.getCentreX() - getX(), expandedEndHandle.getCentreY() - getY(), expandedEndHandle.getWidth() / 2); nanovg::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 = [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 = arrowTip; auto const point_b = arrowLine.getPointAlongLine(0.0f, -(arrowWidth * 0.5f)); auto const point_c = arrowLine.getPointAlongLine(0.0f, arrowWidth * 0.5f); // draw the arrow nanovg::nvgBeginPath(nvg); nanovg::nvgFillColor(nvg, connectionColour); nanovg::nvgMoveTo(nvg, point_a.x, point_a.y); nanovg::nvgLineTo(nvg, point_b.x, point_b.y); nanovg::nvgLineTo(nvg, point_c.x, point_c.y); nanovg::nvgClosePath(nvg); nanovg::nvgStrokeWidth(nvg, 1.0f); nanovg::nvgFill(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 nanovg::nvgBeginPath(nvg); nanovg::nvgStrokeColor(nvg, outlineColour); nanovg::nvgFillColor(nvg, getConnectionColour()); constexpr auto radius = 7.0f; constexpr auto diameter = radius * 2.0f; auto const circleTopLeft = pos - Point<float>(radius, radius); nanovg::nvgRoundedRect(nvg, circleTopLeft.getX(), circleTopLeft.getY(), diameter, diameter, radius); nanovg::nvgStrokeWidth(nvg, 1.0f); nanovg::nvgFill(nvg); nanovg::nvgStroke(nvg); // connection index number Fonts::drawText(cnv->editor->getNanoLLGC(), String(getMultiConnectNumber()), Rectangle<float>(radius, radius).withCentre(pos.toFloat()), Fonts::getDefaultFont().withHeight(9), getThemeColours(*this).objectSelectedOutlineColour.contrasting(), Justification::centred); } } 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 (!getPlugDataLook(*this).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") { 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()); } } } 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(); static auto getClosestCornerIdx = [](PathPlan const& plan, Point<float> const position) { int closestIdx = -1; auto closestDistance = 8.0f; for (int n = 1; n < static_cast<int>(plan.size()) - 1; n++) { auto const distance = plan[n].getDistanceFrom(position); if (distance < closestDistance) { closestDistance = distance; closestIdx = n; } } return closestIdx; }; // Double-clicking adds a corner, or removes the one under the mouse auto const position = cnv->getLocalPoint(this, e.position); auto const isOnReconnectHandle = startReconnectHandle.contains(position) || endReconnectHandle.contains(position); if (e.getNumberOfClicks() == 2 && e.mods.isLeftButtonDown() && !e.mods.isAnyModifierKeyDown() && !isOnReconnectHandle) { if (auto const cornerIdx = getClosestCornerIdx(currentPlan, position); cornerIdx >= 0) { removeCorner(cornerIdx); } else { addCorner(position); } return; } 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; // Zero-length segments have no direction to drag in if (line.getLength() < 1.0f) continue; if (line.getDistanceFromPoint(cnv->getLocalPoint(this, position), nearest) < 3) { return n; } } return -1; } int Connection::getNumCorners() const { int numCorners = 0; auto lastDirection = ZeroLength; for (int n = 0; n < static_cast<int>(currentPlan.size()) - 1; n++) { auto const delta = currentPlan[n + 1] - currentPlan[n]; // Sub-pixel segments don't count as a corner if (delta.getDistanceFromOrigin() < 1.0f) continue; auto const direction = std::abs(delta.y) > std::abs(delta.x) ? Vertical : Horizontal; if (lastDirection != ZeroLength && direction != lastDirection) numCorners++; lastDirection = direction; } return numCorners; } // Direction of the segment between point idx and idx + 1 Connection::SegmentDirection Connection::getSegmentDirection(int const idx) const { auto const delta = currentPlan[idx + 1] - currentPlan[idx]; if (delta.getDistanceFromOrigin() < 0.01f) return ZeroLength; return std::abs(delta.y) > std::abs(delta.x) ? Vertical : Horizontal; } // Removes points that would make the path go diagonal when it gets dragged or an object moves, // without changing the shape of the path void Connection::sanitisePlan() { for (int n = 1; n < static_cast<int>(currentPlan.size()) - 1;) { auto const lastIdx = static_cast<int>(currentPlan.size()) - 1; auto const before = currentPlan[n - 1]; auto const point = currentPlan[n]; auto const after = currentPlan[n + 1]; auto const isOnTopOfBefore = getSegmentDirection(n - 1) == ZeroLength; auto const isOnTopOfAfter = getSegmentDirection(n) == ZeroLength; // A zero-length segment can only turn into a corner if the segments around it run the same way. // At the iolets, updatePath() snaps it vertically, so the segment next to it has to be horizontal bool isUnusable; if (isOnTopOfBefore && isOnTopOfAfter) { isUnusable = true; } else if (isOnTopOfBefore) { isUnusable = n == 1 ? getSegmentDirection(n) != Horizontal : getSegmentDirection(n - 2) != getSegmentDirection(n); } else if (isOnTopOfAfter) { isUnusable = n == lastIdx - 1 ? getSegmentDirection(n - 1) != Horizontal : getSegmentDirection(n + 1) != getSegmentDirection(n - 1); } else { isUnusable = (approximatelyEqual(before.x, point.x) && approximatelyEqual(point.x, after.x)) || (approximatelyEqual(before.y, point.y) && approximatelyEqual(point.y, after.y)); } if (isUnusable) { // Line up the remaining points exactly, so no segment ends up slightly off-axis if (isOnTopOfBefore) { currentPlan[n - 1] = point; if (isOnTopOfAfter) currentPlan[n + 1] = point; } else if (isOnTopOfAfter) { currentPlan[n + 1] = point; } else if (approximatelyEqual(before.x, point.x)) { currentPlan[n + 1].x = before.x; } else { currentPlan[n + 1].y = before.y; } currentPlan.remove_at(n); n = std::max(1, n - 1); } else { n++; } } } void Connection::addCorner(Point<float> const& position) { if (!inlet || !outlet) return; if (!segmented) { auto const pstart = getStartPoint(); auto const pend = getEndPoint(); auto plan = PathPlan(); plan.add(pstart); // Run the middle segment through the clicked position, in the direction the connection mostly goes if (std::abs(pend.y - pstart.y) >= std::abs(pend.x - pstart.x)) { plan.emplace_back(position.x, pstart.y); plan.emplace_back(position.x, pend.y); } else { plan.emplace_back(pstart.x, position.y); plan.emplace_back(pend.x, position.y); } plan.add(pend); currentPlan = plan; segmented = true; } else { static auto getClosestSegmentIdx = [](PathPlan const& plan, Point<float> const position) { int closestIdx = -1; auto closestDistance = std::numeric_limits<float>::max(); for (int n = 0; n < static_cast<int>(plan.size()) - 1; n++) { Point<float> nearest; auto const distance = Line<float>(plan[n], plan[n + 1]).getDistanceFromPoint(position, nearest); if (distance < closestDistance) { closestDistance = distance; closestIdx = n; } } return closestIdx; }; auto const segmentIdx = getClosestSegmentIdx(currentPlan, position); if (segmentIdx < 0) return; auto const direction = getSegmentDirection(segmentIdx); // Insert the corner twice, the zero-length segment in between becomes the new step Point<float> corner; Line<float>(currentPlan[segmentIdx], currentPlan[segmentIdx + 1]).getDistanceFromPoint(position, corner); currentPlan.insert(segmentIdx + 1, corner); currentPlan.insert(segmentIdx + 1, corner); // Move one half of the segment halfway towards its neighbour to make the step visible. // The half that's attached to an iolet can't move auto const lastIdx = static_cast<int>(currentPlan.size()) - 1; int startIdx = -1, endIdx = 0, beforeIdx = 0, afterIdx = 0; if (segmentIdx + 3 < lastIdx) { // The half after the corner startIdx = segmentIdx + 2; endIdx = segmentIdx + 3; beforeIdx = segmentIdx + 1; afterIdx = segmentIdx + 4; } else if (segmentIdx > 0) { // The half before the corner startIdx = segmentIdx; endIdx = segmentIdx + 1; beforeIdx = segmentIdx - 1; afterIdx = segmentIdx + 2; } if (startIdx >= 0) { if (direction == Vertical) { auto const halfway = (currentPlan[beforeIdx].x + currentPlan[afterIdx].x) * 0.5f; currentPlan[startIdx].x = halfway; currentPlan[endIdx].x = halfway; } else { auto const halfway = (currentPlan[beforeIdx].y + currentPlan[afterIdx].y) * 0.5f; currentPlan[startIdx].y = halfway; currentPlan[endIdx].y = halfway; } } } sanitisePlan(); updatePath(); repaint(); pushPathState(); } void Connection::removeCorner(int const cornerIdx) { if (cornerIdx < 1 || cornerIdx >= static_cast<int>(currentPlan.size()) - 1) return; // Removing the last corner would leave a diagonal, so go back to a curve if (getNumCorners() <= 1) { setSegmented(false); return; } // Points on top of each other form a single corner int first = cornerIdx, last = cornerIdx; while (first > 1 && currentPlan[first - 1].getDistanceFrom(currentPlan[cornerIdx]) < 1.0f) first--; while (last < static_cast<int>(currentPlan.size()) - 2 && currentPlan[last + 1].getDistanceFrom(currentPlan[cornerIdx]) < 1.0f) last++; currentPlan.remove_range(first, last + 1); // Line up the two points that are now connected. A point can only move along its other segment, // otherwise the rest of the path breaks auto const prevIdx = first - 1; auto const nextIdx = first; auto const lastIdx = static_cast<int>(currentPlan.size()) - 1; if (!approximatelyEqual(currentPlan[prevIdx].x, currentPlan[nextIdx].x) && !approximatelyEqual(currentPlan[prevIdx].y, currentPlan[nextIdx].y)) { if (nextIdx < lastIdx) { if (approximatelyEqual(currentPlan[nextIdx].x, currentPlan[nextIdx + 1].x)) { currentPlan[nextIdx].y = currentPlan[prevIdx].y; } else { currentPlan[nextIdx].x = currentPlan[prevIdx].x; } } else if (prevIdx > 0) { if (approximatelyEqual(currentPlan[prevIdx].x, currentPlan[prevIdx - 1].x)) { currentPlan[prevIdx].y = currentPlan[nextIdx].y; } else { currentPlan[prevIdx].x = currentPlan[nextIdx].x; } } } sanitisePlan(); if (getNumCorners() == 0) { setSegmented(false); return; } updatePath(); repaint(); pushPathState(); } void Connection::setPath(Path const& newPath) { path = newPath; updateBounds(); } void Connection::updateBounds() { // Resize the component to enclose the path, expanded by the stroke thickness. // The extra margin is used for hit detection and drawing the reconnect handles. if (path.isEmpty()) { setBounds({}); return; } setBounds(path.getBounds().expanded(6.0f).getSmallestIntegerContainer()); } float Connection::getPathWidth() const { switch (connectionStyle) { case PlugDataLook::ConnectionStyleVanilla: return cableType == SignalCable ? 4.5f : 2.5f; case PlugDataLook::ConnectionStyleThin: return 3.0f; default: |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |