The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2240 lines
78KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. #define JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED \
  18. jassert (juce::MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  19. #if DUMP_BANDWIDTH_STATS
  20. namespace
  21. {
  22. struct PortIOStats
  23. {
  24. PortIOStats (const char* nm) : name (nm) {}
  25. const char* const name;
  26. int byteCount = 0;
  27. int messageCount = 0;
  28. int bytesPerSec = 0;
  29. int largestMessageBytes = 0;
  30. int lastMessageBytes = 0;
  31. void update (double elapsedSec)
  32. {
  33. if (byteCount > 0)
  34. {
  35. bytesPerSec = (int) (byteCount / elapsedSec);
  36. byteCount = 0;
  37. juce::Logger::writeToLog (getString());
  38. }
  39. }
  40. juce::String getString() const
  41. {
  42. return juce::String (name) + ": "
  43. + "count=" + juce::String (messageCount).paddedRight (' ', 7)
  44. + "rate=" + (juce::String (bytesPerSec / 1024.0f, 1) + " Kb/sec").paddedRight (' ', 11)
  45. + "largest=" + (juce::String (largestMessageBytes) + " bytes").paddedRight (' ', 11)
  46. + "last=" + (juce::String (lastMessageBytes) + " bytes").paddedRight (' ', 11);
  47. }
  48. void registerMessage (int numBytes) noexcept
  49. {
  50. byteCount += numBytes;
  51. ++messageCount;
  52. lastMessageBytes = numBytes;
  53. largestMessageBytes = juce::jmax (largestMessageBytes, numBytes);
  54. }
  55. };
  56. static PortIOStats inputStats { "Input" }, outputStats { "Output" };
  57. static uint32 startTime = 0;
  58. static inline void resetOnSecondBoundary()
  59. {
  60. auto now = juce::Time::getMillisecondCounter();
  61. double elapsedSec = (now - startTime) / 1000.0;
  62. if (elapsedSec >= 1.0)
  63. {
  64. inputStats.update (elapsedSec);
  65. outputStats.update (elapsedSec);
  66. startTime = now;
  67. }
  68. }
  69. static inline void registerBytesOut (int numBytes)
  70. {
  71. outputStats.registerMessage (numBytes);
  72. resetOnSecondBoundary();
  73. }
  74. static inline void registerBytesIn (int numBytes)
  75. {
  76. inputStats.registerMessage (numBytes);
  77. resetOnSecondBoundary();
  78. }
  79. }
  80. juce::String getMidiIOStats()
  81. {
  82. return inputStats.getString() + " " + outputStats.getString();
  83. }
  84. #endif
  85. //==============================================================================
  86. struct PhysicalTopologySource::Internal
  87. {
  88. struct Detector;
  89. struct BlockImplementation;
  90. struct ControlButtonImplementation;
  91. struct RotaryDialImplementation;
  92. struct TouchSurfaceImplementation;
  93. struct LEDGridImplementation;
  94. struct LEDRowImplementation;
  95. //==============================================================================
  96. struct MIDIDeviceConnection : public DeviceConnection,
  97. public juce::MidiInputCallback
  98. {
  99. MIDIDeviceConnection() {}
  100. ~MIDIDeviceConnection()
  101. {
  102. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  103. listeners.call (&Listener::connectionBeingDeleted, *this);
  104. if (midiInput != nullptr)
  105. midiInput->stop();
  106. if (interprocessLock != nullptr)
  107. interprocessLock->exit();
  108. }
  109. bool lockAgainstOtherProcesses (const String& midiInName, const String& midiOutName)
  110. {
  111. interprocessLock.reset (new juce::InterProcessLock ("blocks_sdk_"
  112. + File::createLegalFileName (midiInName)
  113. + "_" + File::createLegalFileName (midiOutName)));
  114. if (interprocessLock->enter (500))
  115. return true;
  116. interprocessLock = nullptr;
  117. return false;
  118. }
  119. struct Listener
  120. {
  121. virtual ~Listener() {}
  122. virtual void handleIncomingMidiMessage (const juce::MidiMessage& message) = 0;
  123. virtual void connectionBeingDeleted (const MIDIDeviceConnection&) = 0;
  124. };
  125. void addListener (Listener* l)
  126. {
  127. listeners.add (l);
  128. }
  129. void removeListener (Listener* l)
  130. {
  131. listeners.remove (l);
  132. }
  133. bool sendMessageToDevice (const void* data, size_t dataSize) override
  134. {
  135. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  136. jassert (dataSize > sizeof (BlocksProtocol::roliSysexHeader) + 2);
  137. jassert (memcmp (data, BlocksProtocol::roliSysexHeader, sizeof (BlocksProtocol::roliSysexHeader)) == 0);
  138. jassert (static_cast<const uint8*> (data)[dataSize - 1] == 0xf7);
  139. if (midiOutput != nullptr)
  140. {
  141. midiOutput->sendMessageNow (juce::MidiMessage (data, (int) dataSize));
  142. return true;
  143. }
  144. return false;
  145. }
  146. void handleIncomingMidiMessage (juce::MidiInput*, const juce::MidiMessage& message) override
  147. {
  148. const auto data = message.getRawData();
  149. const int dataSize = message.getRawDataSize();
  150. const int bodySize = dataSize - (int) (sizeof (BlocksProtocol::roliSysexHeader) + 1);
  151. if (bodySize > 0 && memcmp (data, BlocksProtocol::roliSysexHeader, sizeof (BlocksProtocol::roliSysexHeader)) == 0)
  152. if (handleMessageFromDevice != nullptr)
  153. handleMessageFromDevice (data + sizeof (BlocksProtocol::roliSysexHeader), (size_t) bodySize);
  154. listeners.call (&Listener::handleIncomingMidiMessage, message);
  155. }
  156. std::unique_ptr<juce::MidiInput> midiInput;
  157. std::unique_ptr<juce::MidiOutput> midiOutput;
  158. private:
  159. juce::ListenerList<Listener> listeners;
  160. std::unique_ptr<juce::InterProcessLock> interprocessLock;
  161. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MIDIDeviceConnection)
  162. };
  163. struct MIDIDeviceDetector : public DeviceDetector
  164. {
  165. MIDIDeviceDetector() {}
  166. juce::StringArray scanForDevices() override
  167. {
  168. juce::StringArray result;
  169. for (auto& pair : findDevices())
  170. result.add (pair.inputName + " & " + pair.outputName);
  171. return result;
  172. }
  173. DeviceConnection* openDevice (int index) override
  174. {
  175. auto pair = findDevices()[index];
  176. if (pair.inputIndex >= 0 && pair.outputIndex >= 0)
  177. {
  178. std::unique_ptr<MIDIDeviceConnection> dev (new MIDIDeviceConnection());
  179. if (dev->lockAgainstOtherProcesses (pair.inputName, pair.outputName))
  180. {
  181. dev->midiInput.reset (juce::MidiInput::openDevice (pair.inputIndex, dev.get()));
  182. dev->midiOutput.reset (juce::MidiOutput::openDevice (pair.outputIndex));
  183. if (dev->midiInput != nullptr)
  184. {
  185. dev->midiInput->start();
  186. return dev.release();
  187. }
  188. }
  189. }
  190. return nullptr;
  191. }
  192. static bool isBlocksMidiDeviceName (const juce::String& name)
  193. {
  194. return name.indexOf (" BLOCK") > 0 || name.indexOf (" Block") > 0;
  195. }
  196. static String cleanBlocksDeviceName (juce::String name)
  197. {
  198. name = name.trim();
  199. if (name.endsWith (" IN)"))
  200. return name.dropLastCharacters (4);
  201. if (name.endsWith (" OUT)"))
  202. return name.dropLastCharacters (5);
  203. const int openBracketPosition = name.lastIndexOfChar ('[');
  204. if (openBracketPosition != -1 && name.endsWith ("]"))
  205. return name.dropLastCharacters (name.length() - openBracketPosition);
  206. return name;
  207. }
  208. struct MidiInputOutputPair
  209. {
  210. juce::String outputName, inputName;
  211. int outputIndex = -1, inputIndex = -1;
  212. };
  213. static juce::Array<MidiInputOutputPair> findDevices()
  214. {
  215. juce::Array<MidiInputOutputPair> result;
  216. auto midiInputs = juce::MidiInput::getDevices();
  217. auto midiOutputs = juce::MidiOutput::getDevices();
  218. for (int j = 0; j < midiInputs.size(); ++j)
  219. {
  220. if (isBlocksMidiDeviceName (midiInputs[j]))
  221. {
  222. MidiInputOutputPair pair;
  223. pair.inputName = midiInputs[j];
  224. pair.inputIndex = j;
  225. String cleanedInputName = cleanBlocksDeviceName (pair.inputName);
  226. for (int i = 0; i < midiOutputs.size(); ++i)
  227. {
  228. if (cleanBlocksDeviceName (midiOutputs[i]) == cleanedInputName)
  229. {
  230. pair.outputName = midiOutputs[i];
  231. pair.outputIndex = i;
  232. break;
  233. }
  234. }
  235. result.add (pair);
  236. }
  237. }
  238. return result;
  239. }
  240. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MIDIDeviceDetector)
  241. };
  242. //==============================================================================
  243. struct DeviceInfo
  244. {
  245. Block::UID uid;
  246. BlocksProtocol::TopologyIndex index;
  247. BlocksProtocol::BlockSerialNumber serial;
  248. BlocksProtocol::VersionNumber version;
  249. bool isMaster;
  250. };
  251. static Block::Timestamp deviceTimestampToHost (uint32 timestamp) noexcept
  252. {
  253. return static_cast<Block::Timestamp> (timestamp);
  254. }
  255. static juce::Array<DeviceInfo> getArrayOfDeviceInfo (const juce::Array<BlocksProtocol::DeviceStatus>& devices)
  256. {
  257. juce::Array<DeviceInfo> result;
  258. bool isFirst = true;
  259. for (auto& device : devices)
  260. {
  261. BlocksProtocol::VersionNumber version;
  262. result.add ({ getBlockUIDFromSerialNumber (device.serialNumber),
  263. device.index,
  264. device.serialNumber,
  265. version,
  266. isFirst });
  267. isFirst = false;
  268. }
  269. return result;
  270. }
  271. static bool containsBlockWithUID (const juce::Array<DeviceInfo>& devices, Block::UID uid) noexcept
  272. {
  273. for (auto&& d : devices)
  274. if (d.uid == uid)
  275. return true;
  276. return false;
  277. }
  278. static bool containsBlockWithUID (const Block::Array& blocks, Block::UID uid) noexcept
  279. {
  280. for (auto&& block : blocks)
  281. if (block->uid == uid)
  282. return true;
  283. return false;
  284. }
  285. static bool versionNumberAddedToBlock (const juce::Array<DeviceInfo>& devices, Block::UID uid, juce::String version) noexcept
  286. {
  287. if (version.length() == 0)
  288. for (auto&& d : devices)
  289. if (d.uid == uid && d.version.length)
  290. return true;
  291. return false;
  292. }
  293. static void setVersionNumberForBlock (const juce::Array<DeviceInfo>& devices, Block& block) noexcept
  294. {
  295. for (auto&& d : devices)
  296. if (d.uid == block.uid)
  297. block.versionNumber = juce::String ((const char*) d.version.version, d.version.length);
  298. }
  299. //==============================================================================
  300. struct ConnectedDeviceGroup : private juce::AsyncUpdater,
  301. private juce::Timer
  302. {
  303. ConnectedDeviceGroup (Detector& d, const juce::String& name, DeviceConnection* connection)
  304. : detector (d), deviceName (name), deviceConnection (connection)
  305. {
  306. lastGlobalPingTime = juce::Time::getCurrentTime();
  307. deviceConnection->handleMessageFromDevice = [this] (const void* data, size_t dataSize)
  308. {
  309. this->handleIncomingMessage (data, dataSize);
  310. };
  311. startTimer (200);
  312. sendTopologyRequest();
  313. }
  314. bool isStillConnected (const juce::StringArray& detectedDevices) const noexcept
  315. {
  316. return detectedDevices.contains (deviceName)
  317. && ! failedToGetTopology()
  318. && lastGlobalPingTime > juce::Time::getCurrentTime() - juce::RelativeTime::seconds (pingTimeoutSeconds);
  319. }
  320. Block::UID getDeviceIDFromIndex (BlocksProtocol::TopologyIndex index) const noexcept
  321. {
  322. for (auto& d : currentDeviceInfo)
  323. if (d.index == index)
  324. return d.uid;
  325. return {};
  326. }
  327. int getIndexFromDeviceID (Block::UID uid) const noexcept
  328. {
  329. for (auto& d : currentDeviceInfo)
  330. if (d.uid == uid)
  331. return d.index;
  332. return -1;
  333. }
  334. DeviceInfo* getDeviceInfoFromUID (Block::UID uid) const noexcept
  335. {
  336. for (auto& d : currentDeviceInfo)
  337. if (d.uid == uid)
  338. return &d;
  339. return nullptr;
  340. }
  341. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  342. {
  343. for (auto&& status : currentTopologyDevices)
  344. if (getBlockUIDFromSerialNumber (status.serialNumber) == deviceID)
  345. return &status;
  346. return nullptr;
  347. }
  348. //==============================================================================
  349. juce::Time lastTopologyRequestTime, lastTopologyReceiveTime;
  350. int numTopologyRequestsSent = 0;
  351. void sendTopologyRequest()
  352. {
  353. ++numTopologyRequestsSent;
  354. lastTopologyRequestTime = juce::Time::getCurrentTime();
  355. sendCommandMessage (0, BlocksProtocol::requestTopologyMessage);
  356. }
  357. void scheduleNewTopologyRequest()
  358. {
  359. numTopologyRequestsSent = 0;
  360. lastTopologyReceiveTime = juce::Time();
  361. }
  362. bool failedToGetTopology() const noexcept
  363. {
  364. return numTopologyRequestsSent > 4 && lastTopologyReceiveTime == juce::Time();
  365. }
  366. bool hasAnyBlockStoppedPinging() const noexcept
  367. {
  368. auto now = juce::Time::getCurrentTime();
  369. for (auto& ping : blockPings)
  370. if (ping.lastPing < now - juce::RelativeTime::seconds (pingTimeoutSeconds))
  371. return true;
  372. return false;
  373. }
  374. void timerCallback() override
  375. {
  376. auto now = juce::Time::getCurrentTime();
  377. if ((now > lastTopologyReceiveTime + juce::RelativeTime::seconds (30.0) || hasAnyBlockStoppedPinging())
  378. && now > lastTopologyRequestTime + juce::RelativeTime::seconds (1.0)
  379. && numTopologyRequestsSent < 4)
  380. sendTopologyRequest();
  381. }
  382. //==============================================================================
  383. // The following methods will be called by the DeviceToHostPacketDecoder:
  384. void beginTopology (int numDevices, int numConnections)
  385. {
  386. incomingTopologyDevices.clearQuick();
  387. incomingTopologyDevices.ensureStorageAllocated (numDevices);
  388. incomingTopologyConnections.clearQuick();
  389. incomingTopologyConnections.ensureStorageAllocated (numConnections);
  390. }
  391. void extendTopology (int numDevices, int numConnections)
  392. {
  393. incomingTopologyDevices.ensureStorageAllocated (incomingTopologyDevices.size() + numDevices);
  394. incomingTopologyConnections.ensureStorageAllocated (incomingTopologyConnections.size() + numConnections);
  395. }
  396. void handleTopologyDevice (BlocksProtocol::DeviceStatus status)
  397. {
  398. incomingTopologyDevices.add (status);
  399. }
  400. void handleTopologyConnection (BlocksProtocol::DeviceConnection connection)
  401. {
  402. incomingTopologyConnections.add (connection);
  403. }
  404. void endTopology()
  405. {
  406. currentDeviceInfo = getArrayOfDeviceInfo (incomingTopologyDevices);
  407. currentDeviceConnections = getArrayOfConnections (incomingTopologyConnections);
  408. currentTopologyDevices = incomingTopologyDevices;
  409. currentTopologyConnections = incomingTopologyConnections;
  410. detector.handleTopologyChange();
  411. lastTopologyReceiveTime = juce::Time::getCurrentTime();
  412. blockPings.clear();
  413. }
  414. void handleVersion (BlocksProtocol::DeviceVersion version)
  415. {
  416. for (auto& d : currentDeviceInfo)
  417. {
  418. if (d.index == version.index)
  419. {
  420. d.version = version.version;
  421. detector.handleTopologyChange();
  422. return;
  423. }
  424. }
  425. }
  426. void handleControlButtonUpDown (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp,
  427. BlocksProtocol::ControlButtonID buttonID, bool isDown)
  428. {
  429. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  430. detector.handleButtonChange (deviceID, deviceTimestampToHost (timestamp), buttonID.get(), isDown);
  431. }
  432. void handleCustomMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp, const int32* data)
  433. {
  434. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  435. detector.handleCustomMessage (deviceID, deviceTimestampToHost (timestamp), data);
  436. }
  437. void handleTouchChange (BlocksProtocol::TopologyIndex deviceIndex,
  438. uint32 timestamp,
  439. BlocksProtocol::TouchIndex touchIndex,
  440. BlocksProtocol::TouchPosition position,
  441. BlocksProtocol::TouchVelocity velocity,
  442. bool isStart, bool isEnd)
  443. {
  444. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  445. {
  446. TouchSurface::Touch touch;
  447. touch.index = (int) touchIndex.get();
  448. touch.x = position.x.toUnipolarFloat();
  449. touch.y = position.y.toUnipolarFloat();
  450. touch.z = position.z.toUnipolarFloat();
  451. touch.xVelocity = velocity.vx.toBipolarFloat();
  452. touch.yVelocity = velocity.vy.toBipolarFloat();
  453. touch.zVelocity = velocity.vz.toBipolarFloat();
  454. touch.eventTimestamp = deviceTimestampToHost (timestamp);
  455. touch.isTouchStart = isStart;
  456. touch.isTouchEnd = isEnd;
  457. touch.blockUID = deviceID;
  458. setTouchStartPosition (touch);
  459. detector.handleTouchChange (deviceID, touch);
  460. }
  461. }
  462. void setTouchStartPosition (TouchSurface::Touch& touch)
  463. {
  464. auto& startPos = touchStartPositions.getValue (touch);
  465. if (touch.isTouchStart)
  466. startPos = { touch.x, touch.y };
  467. touch.startX = startPos.x;
  468. touch.startY = startPos.y;
  469. }
  470. void handlePacketACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::PacketCounter counter)
  471. {
  472. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  473. detector.handleSharedDataACK (deviceID, counter);
  474. }
  475. void handleFirmwareUpdateACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::FirmwareUpdateACKCode resultCode)
  476. {
  477. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  478. detector.handleFirmwareUpdateACK (deviceID, (uint8) resultCode.get());
  479. }
  480. void handleConfigUpdateMessage (BlocksProtocol::TopologyIndex deviceIndex, int32 item, int32 value, int32 min, int32 max)
  481. {
  482. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  483. detector.handleConfigUpdateMessage (deviceID, item, value, min, max);
  484. }
  485. void handleConfigSetMessage (BlocksProtocol::TopologyIndex deviceIndex, int32 item, int32 value)
  486. {
  487. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  488. detector.handleConfigSetMessage (deviceID, item, value);
  489. }
  490. void handleConfigFactorySyncEndMessage (BlocksProtocol::TopologyIndex deviceIndex)
  491. {
  492. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  493. detector.handleConfigFactorySyncEndMessage (deviceID);
  494. }
  495. void handleLogMessage (BlocksProtocol::TopologyIndex deviceIndex, const String& message)
  496. {
  497. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  498. detector.handleLogMessage (deviceID, message);
  499. }
  500. //==============================================================================
  501. template <typename PacketBuilder>
  502. bool sendMessageToDevice (const PacketBuilder& builder) const
  503. {
  504. if (deviceConnection->sendMessageToDevice (builder.getData(), (size_t) builder.size()))
  505. {
  506. #if DUMP_BANDWIDTH_STATS
  507. registerBytesOut (builder.size());
  508. #endif
  509. return true;
  510. }
  511. return false;
  512. }
  513. bool sendCommandMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 commandID) const
  514. {
  515. BlocksProtocol::HostPacketBuilder<64> p;
  516. p.writePacketSysexHeaderBytes (deviceIndex);
  517. p.deviceControlMessage (commandID);
  518. p.writePacketSysexFooter();
  519. return sendMessageToDevice (p);
  520. }
  521. bool broadcastCommandMessage (uint32 commandID) const
  522. {
  523. return sendCommandMessage (BlocksProtocol::topologyIndexForBroadcast, commandID);
  524. }
  525. DeviceConnection* getDeviceConnection()
  526. {
  527. return deviceConnection.get();
  528. }
  529. Detector& detector;
  530. juce::String deviceName;
  531. juce::Array<DeviceInfo> currentDeviceInfo;
  532. juce::Array<BlockDeviceConnection> currentDeviceConnections;
  533. static constexpr double pingTimeoutSeconds = 6.0;
  534. private:
  535. //==============================================================================
  536. std::unique_ptr<DeviceConnection> deviceConnection;
  537. juce::Array<BlocksProtocol::DeviceStatus> incomingTopologyDevices, currentTopologyDevices;
  538. juce::Array<BlocksProtocol::DeviceConnection> incomingTopologyConnections, currentTopologyConnections;
  539. juce::CriticalSection incomingPacketLock;
  540. juce::Array<juce::MemoryBlock> incomingPackets;
  541. struct TouchStart
  542. {
  543. float x, y;
  544. };
  545. TouchList<TouchStart> touchStartPositions;
  546. juce::Time lastGlobalPingTime;
  547. struct BlockPingTime
  548. {
  549. Block::UID blockUID;
  550. juce::Time lastPing;
  551. };
  552. juce::Array<BlockPingTime> blockPings;
  553. Block::UID getDeviceIDFromMessageIndex (BlocksProtocol::TopologyIndex index) noexcept
  554. {
  555. auto uid = getDeviceIDFromIndex (index);
  556. if (uid == Block::UID())
  557. {
  558. scheduleNewTopologyRequest(); // force a re-request of the topology when we
  559. // get an event from a block that we don't know about
  560. }
  561. else
  562. {
  563. auto now = juce::Time::getCurrentTime();
  564. for (auto& ping : blockPings)
  565. {
  566. if (ping.blockUID == uid)
  567. {
  568. ping.lastPing = now;
  569. return uid;
  570. }
  571. }
  572. blockPings.add ({ uid, now });
  573. }
  574. return uid;
  575. }
  576. juce::Array<BlockDeviceConnection> getArrayOfConnections (const juce::Array<BlocksProtocol::DeviceConnection>& connections)
  577. {
  578. juce::Array<BlockDeviceConnection> result;
  579. for (auto&& c : connections)
  580. {
  581. BlockDeviceConnection dc;
  582. dc.device1 = getDeviceIDFromIndex (c.device1);
  583. dc.device2 = getDeviceIDFromIndex (c.device2);
  584. dc.connectionPortOnDevice1 = convertConnectionPort (dc.device1, c.port1);
  585. dc.connectionPortOnDevice2 = convertConnectionPort (dc.device2, c.port2);
  586. result.add (dc);
  587. }
  588. return result;
  589. }
  590. Block::ConnectionPort convertConnectionPort (Block::UID uid, BlocksProtocol::ConnectorPort p) noexcept
  591. {
  592. if (auto* info = getDeviceInfoFromUID (uid))
  593. return BlocksProtocol::BlockDataSheet (info->serial).convertPortIndexToConnectorPort (p);
  594. jassertfalse;
  595. return { Block::ConnectionPort::DeviceEdge::north, 0 };
  596. }
  597. //==============================================================================
  598. void handleIncomingMessage (const void* data, size_t dataSize)
  599. {
  600. juce::MemoryBlock mb (data, dataSize);
  601. {
  602. const juce::ScopedLock sl (incomingPacketLock);
  603. incomingPackets.add (std::move (mb));
  604. }
  605. triggerAsyncUpdate();
  606. #if DUMP_BANDWIDTH_STATS
  607. registerBytesIn ((int) dataSize);
  608. #endif
  609. }
  610. void handleAsyncUpdate() override
  611. {
  612. juce::Array<juce::MemoryBlock> packets;
  613. packets.ensureStorageAllocated (32);
  614. {
  615. const juce::ScopedLock sl (incomingPacketLock);
  616. incomingPackets.swapWith (packets);
  617. }
  618. for (auto& packet : packets)
  619. {
  620. lastGlobalPingTime = juce::Time::getCurrentTime();
  621. auto data = static_cast<const uint8*> (packet.getData());
  622. BlocksProtocol::HostPacketDecoder<ConnectedDeviceGroup>
  623. ::processNextPacket (*this, *data, data + 1, (int) packet.getSize() - 1);
  624. }
  625. }
  626. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectedDeviceGroup)
  627. };
  628. //==============================================================================
  629. /** This is the main singleton object that keeps track of connected blocks */
  630. struct Detector : public juce::ReferenceCountedObject,
  631. private juce::Timer
  632. {
  633. Detector() : defaultDetector (new MIDIDeviceDetector()), deviceDetector (*defaultDetector)
  634. {
  635. startTimer (10);
  636. }
  637. Detector (DeviceDetector& dd) : deviceDetector (dd)
  638. {
  639. startTimer (10);
  640. }
  641. ~Detector()
  642. {
  643. jassert (activeTopologySources.isEmpty());
  644. jassert (activeControlButtons.isEmpty());
  645. }
  646. using Ptr = juce::ReferenceCountedObjectPtr<Detector>;
  647. static Detector::Ptr getDefaultDetector()
  648. {
  649. auto& d = getDefaultDetectorPointer();
  650. if (d == nullptr)
  651. d = new Detector();
  652. return d;
  653. }
  654. static Detector::Ptr& getDefaultDetectorPointer()
  655. {
  656. static Detector::Ptr defaultDetector;
  657. return defaultDetector;
  658. }
  659. void detach (PhysicalTopologySource* pts)
  660. {
  661. activeTopologySources.removeAllInstancesOf (pts);
  662. if (activeTopologySources.isEmpty())
  663. {
  664. for (auto& b : currentTopology.blocks)
  665. if (auto bi = BlockImplementation::getFrom (*b))
  666. bi->sendCommandMessage (BlocksProtocol::endAPIMode);
  667. currentTopology = {};
  668. auto& d = getDefaultDetectorPointer();
  669. if (d != nullptr && d->getReferenceCount() == 2)
  670. getDefaultDetectorPointer() = nullptr;
  671. }
  672. }
  673. bool isConnected (Block::UID deviceID) const noexcept
  674. {
  675. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  676. for (auto&& b : currentTopology.blocks)
  677. if (b->uid == deviceID)
  678. return true;
  679. return false;
  680. }
  681. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  682. {
  683. for (auto d : connectedDeviceGroups)
  684. if (auto status = d->getLastStatus (deviceID))
  685. return status;
  686. return nullptr;
  687. }
  688. void handleTopologyChange()
  689. {
  690. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  691. {
  692. juce::Array<DeviceInfo> newDeviceInfo;
  693. juce::Array<BlockDeviceConnection> newDeviceConnections;
  694. for (auto d : connectedDeviceGroups)
  695. {
  696. newDeviceInfo.addArray (d->currentDeviceInfo);
  697. newDeviceConnections.addArray (d->currentDeviceConnections);
  698. }
  699. for (int i = currentTopology.blocks.size(); --i >= 0;)
  700. {
  701. auto block = currentTopology.blocks.getUnchecked(i);
  702. if (! containsBlockWithUID (newDeviceInfo, block->uid))
  703. {
  704. if (auto bi = BlockImplementation::getFrom (*block))
  705. bi->invalidate();
  706. currentTopology.blocks.remove (i);
  707. }
  708. else if (versionNumberAddedToBlock (newDeviceInfo, block->uid, block->versionNumber))
  709. {
  710. setVersionNumberForBlock (newDeviceInfo, *block);
  711. }
  712. }
  713. for (auto& info : newDeviceInfo)
  714. if (info.serial.isValid())
  715. if (! containsBlockWithUID (currentTopology.blocks, getBlockUIDFromSerialNumber (info.serial)))
  716. currentTopology.blocks.add (new BlockImplementation (info.serial, *this, info.version, info.isMaster));
  717. currentTopology.connections.swapWith (newDeviceConnections);
  718. }
  719. for (auto d : activeTopologySources)
  720. d->listeners.call (&TopologySource::Listener::topologyChanged);
  721. #if DUMP_TOPOLOGY
  722. dumpTopology (currentTopology);
  723. #endif
  724. }
  725. void handleSharedDataACK (Block::UID deviceID, uint32 packetCounter) const
  726. {
  727. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  728. for (auto&& b : currentTopology.blocks)
  729. if (b->uid == deviceID)
  730. if (auto bi = BlockImplementation::getFrom (*b))
  731. bi->handleSharedDataACK (packetCounter);
  732. }
  733. void handleFirmwareUpdateACK (Block::UID deviceID, uint8 resultCode)
  734. {
  735. for (auto&& b : currentTopology.blocks)
  736. if (b->uid == deviceID)
  737. if (auto bi = BlockImplementation::getFrom (*b))
  738. bi->handleFirmwareUpdateACK (resultCode);
  739. }
  740. void handleConfigUpdateMessage (Block::UID deviceID, int32 item, int32 value, int32 min, int32 max)
  741. {
  742. for (auto&& b : currentTopology.blocks)
  743. if (b->uid == deviceID)
  744. if (auto bi = BlockImplementation::getFrom (*b))
  745. bi->handleConfigUpdateMessage (item, value, min, max);
  746. }
  747. void notifyBlockOfConfigChange (BlockImplementation& bi, uint32 item)
  748. {
  749. if (auto configChangedCallback = bi.configChangedCallback)
  750. {
  751. if (item >= bi.getMaxConfigIndex())
  752. configChangedCallback (bi, {}, item);
  753. else
  754. configChangedCallback (bi, bi.getLocalConfigMetaData (item), item);
  755. }
  756. }
  757. void handleConfigSetMessage (Block::UID deviceID, int32 item, int32 value)
  758. {
  759. for (auto&& b : currentTopology.blocks)
  760. {
  761. if (b->uid == deviceID)
  762. {
  763. if (auto bi = BlockImplementation::getFrom (*b))
  764. {
  765. bi->handleConfigSetMessage (item, value);
  766. notifyBlockOfConfigChange (*bi, uint32 (item));
  767. }
  768. }
  769. }
  770. }
  771. void handleConfigFactorySyncEndMessage (Block::UID deviceID)
  772. {
  773. for (auto&& b : currentTopology.blocks)
  774. if (b->uid == deviceID)
  775. if (auto bi = BlockImplementation::getFrom (*b))
  776. notifyBlockOfConfigChange (*bi, bi->getMaxConfigIndex());
  777. }
  778. void handleLogMessage (Block::UID deviceID, const String& message) const
  779. {
  780. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  781. for (auto&& b : currentTopology.blocks)
  782. if (b->uid == deviceID)
  783. if (auto bi = BlockImplementation::getFrom (*b))
  784. bi->handleLogMessage (message);
  785. }
  786. void handleButtonChange (Block::UID deviceID, Block::Timestamp timestamp, uint32 buttonIndex, bool isDown) const
  787. {
  788. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  789. for (auto b : activeControlButtons)
  790. {
  791. if (b->block.uid == deviceID)
  792. {
  793. if (auto bi = BlockImplementation::getFrom (b->block))
  794. {
  795. bi->pingFromDevice();
  796. if (buttonIndex < (uint32) bi->modelData.buttons.size())
  797. b->broadcastButtonChange (timestamp, bi->modelData.buttons[(int) buttonIndex].type, isDown);
  798. }
  799. }
  800. }
  801. }
  802. void handleTouchChange (Block::UID deviceID, const TouchSurface::Touch& touchEvent)
  803. {
  804. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  805. for (auto t : activeTouchSurfaces)
  806. {
  807. if (t->block.uid == deviceID)
  808. {
  809. TouchSurface::Touch scaledEvent (touchEvent);
  810. scaledEvent.x *= t->block.getWidth();
  811. scaledEvent.y *= t->block.getHeight();
  812. scaledEvent.startX *= t->block.getWidth();
  813. scaledEvent.startY *= t->block.getHeight();
  814. t->broadcastTouchChange (scaledEvent);
  815. }
  816. }
  817. }
  818. void cancelAllActiveTouches() noexcept
  819. {
  820. for (auto surface : activeTouchSurfaces)
  821. surface->cancelAllActiveTouches();
  822. }
  823. void handleCustomMessage (Block::UID deviceID, Block::Timestamp timestamp, const int32* data)
  824. {
  825. for (auto&& b : currentTopology.blocks)
  826. if (b->uid == deviceID)
  827. if (auto bi = BlockImplementation::getFrom (*b))
  828. bi->handleCustomMessage (timestamp, data);
  829. }
  830. //==============================================================================
  831. int getIndexFromDeviceID (Block::UID deviceID) const noexcept
  832. {
  833. for (auto* c : connectedDeviceGroups)
  834. {
  835. auto index = c->getIndexFromDeviceID (deviceID);
  836. if (index >= 0)
  837. return index;
  838. }
  839. return -1;
  840. }
  841. template <typename PacketBuilder>
  842. bool sendMessageToDevice (Block::UID deviceID, const PacketBuilder& builder) const
  843. {
  844. for (auto* c : connectedDeviceGroups)
  845. if (c->getIndexFromDeviceID (deviceID) >= 0)
  846. return c->sendMessageToDevice (builder);
  847. return false;
  848. }
  849. static Detector* getFrom (Block& b) noexcept
  850. {
  851. if (auto* bi = BlockImplementation::getFrom (b))
  852. return &(bi->detector);
  853. jassertfalse;
  854. return nullptr;
  855. }
  856. DeviceConnection* getDeviceConnectionFor (const Block& b)
  857. {
  858. for (const auto& d : connectedDeviceGroups)
  859. {
  860. for (const auto& info : d->currentDeviceInfo)
  861. {
  862. if (info.uid == b.uid)
  863. return d->getDeviceConnection();
  864. }
  865. }
  866. return nullptr;
  867. }
  868. std::unique_ptr<MIDIDeviceDetector> defaultDetector;
  869. DeviceDetector& deviceDetector;
  870. juce::Array<PhysicalTopologySource*> activeTopologySources;
  871. juce::Array<ControlButtonImplementation*> activeControlButtons;
  872. juce::Array<TouchSurfaceImplementation*> activeTouchSurfaces;
  873. BlockTopology currentTopology;
  874. private:
  875. void timerCallback() override
  876. {
  877. startTimer (1500);
  878. auto detectedDevices = deviceDetector.scanForDevices();
  879. handleDevicesRemoved (detectedDevices);
  880. handleDevicesAdded (detectedDevices);
  881. }
  882. void handleDevicesRemoved (const juce::StringArray& detectedDevices)
  883. {
  884. bool anyDevicesRemoved = false;
  885. for (int i = connectedDeviceGroups.size(); --i >= 0;)
  886. {
  887. if (! connectedDeviceGroups.getUnchecked(i)->isStillConnected (detectedDevices))
  888. {
  889. connectedDeviceGroups.remove (i);
  890. anyDevicesRemoved = true;
  891. }
  892. }
  893. if (anyDevicesRemoved)
  894. handleTopologyChange();
  895. }
  896. void handleDevicesAdded (const juce::StringArray& detectedDevices)
  897. {
  898. bool anyDevicesAdded = false;
  899. for (const auto& devName : detectedDevices)
  900. {
  901. if (! hasDeviceFor (devName))
  902. {
  903. if (auto d = deviceDetector.openDevice (detectedDevices.indexOf (devName)))
  904. {
  905. connectedDeviceGroups.add (new ConnectedDeviceGroup (*this, devName, d));
  906. anyDevicesAdded = true;
  907. }
  908. }
  909. }
  910. if (anyDevicesAdded)
  911. handleTopologyChange();
  912. }
  913. bool hasDeviceFor (const juce::String& devName) const
  914. {
  915. for (auto d : connectedDeviceGroups)
  916. if (d->deviceName == devName)
  917. return true;
  918. return false;
  919. }
  920. juce::OwnedArray<ConnectedDeviceGroup> connectedDeviceGroups;
  921. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Detector)
  922. };
  923. //==============================================================================
  924. struct BlockImplementation : public Block,
  925. private MIDIDeviceConnection::Listener,
  926. private Timer
  927. {
  928. BlockImplementation (const BlocksProtocol::BlockSerialNumber& serial, Detector& detectorToUse, BlocksProtocol::VersionNumber version, bool master)
  929. : Block (juce::String ((const char*) serial.serial, sizeof (serial.serial)),
  930. juce::String ((const char*) version.version, version.length)),
  931. modelData (serial),
  932. remoteHeap (modelData.programAndHeapSize),
  933. detector (detectorToUse),
  934. isMaster (master)
  935. {
  936. sendCommandMessage (BlocksProtocol::beginAPIMode);
  937. if (modelData.hasTouchSurface)
  938. touchSurface.reset (new TouchSurfaceImplementation (*this));
  939. int i = 0;
  940. for (auto&& b : modelData.buttons)
  941. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  942. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  943. ledGrid.reset (new LEDGridImplementation (*this));
  944. for (auto&& s : modelData.statusLEDs)
  945. statusLights.add (new StatusLightImplementation (*this, s));
  946. if (modelData.numLEDRowLEDs > 0)
  947. ledRow.reset (new LEDRowImplementation (*this));
  948. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this));
  949. if (listenerToMidiConnection != nullptr)
  950. listenerToMidiConnection->addListener (this);
  951. config.setDeviceComms (listenerToMidiConnection);
  952. }
  953. ~BlockImplementation()
  954. {
  955. if (listenerToMidiConnection != nullptr)
  956. listenerToMidiConnection->removeListener (this);
  957. }
  958. void invalidate()
  959. {
  960. isStillConnected = false;
  961. }
  962. Type getType() const override { return modelData.apiType; }
  963. juce::String getDeviceDescription() const override { return modelData.description; }
  964. int getWidth() const override { return modelData.widthUnits; }
  965. int getHeight() const override { return modelData.heightUnits; }
  966. float getMillimetersPerUnit() const override { return 47.0f; }
  967. bool isHardwareBlock() const override { return true; }
  968. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  969. bool isConnected() const override { return isStillConnected && detector.isConnected (uid); }
  970. bool isMasterBlock() const override { return isMaster; }
  971. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  972. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  973. LEDRow* getLEDRow() const override { return ledRow.get(); }
  974. juce::Array<ControlButton*> getButtons() const override
  975. {
  976. juce::Array<ControlButton*> result;
  977. result.addArray (controlButtons);
  978. return result;
  979. }
  980. juce::Array<StatusLight*> getStatusLights() const override
  981. {
  982. juce::Array<StatusLight*> result;
  983. result.addArray (statusLights);
  984. return result;
  985. }
  986. float getBatteryLevel() const override
  987. {
  988. if (auto status = detector.getLastStatus (uid))
  989. return status->batteryLevel.toUnipolarFloat();
  990. return 0.0f;
  991. }
  992. bool isBatteryCharging() const override
  993. {
  994. if (auto status = detector.getLastStatus (uid))
  995. return status->batteryCharging.get() != 0;
  996. return false;
  997. }
  998. bool supportsGraphics() const override
  999. {
  1000. return false;
  1001. }
  1002. int getDeviceIndex() const noexcept
  1003. {
  1004. return isConnected() ? detector.getIndexFromDeviceID (uid) : -1;
  1005. }
  1006. template <typename PacketBuilder>
  1007. bool sendMessageToDevice (const PacketBuilder& builder)
  1008. {
  1009. lastMessageSendTime = juce::Time::getCurrentTime();
  1010. return detector.sendMessageToDevice (uid, builder);
  1011. }
  1012. bool sendCommandMessage (uint32 commandID)
  1013. {
  1014. int index = getDeviceIndex();
  1015. if (index < 0)
  1016. return false;
  1017. BlocksProtocol::HostPacketBuilder<64> p;
  1018. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1019. p.deviceControlMessage (commandID);
  1020. p.writePacketSysexFooter();
  1021. return sendMessageToDevice (p);
  1022. }
  1023. void handleCustomMessage (Block::Timestamp, const int32* data)
  1024. {
  1025. ProgramEventMessage m;
  1026. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  1027. m.values[i] = data[i];
  1028. programEventListeners.call (&Block::ProgramEventListener::handleProgramEvent, *this, m);
  1029. }
  1030. static BlockImplementation* getFrom (Block& b) noexcept
  1031. {
  1032. if (auto bi = dynamic_cast<BlockImplementation*> (&b))
  1033. return bi;
  1034. jassertfalse;
  1035. return nullptr;
  1036. }
  1037. bool isControlBlock() const
  1038. {
  1039. auto type = getType();
  1040. return type == Block::Type::liveBlock
  1041. || type == Block::Type::loopBlock
  1042. || type == Block::Type::touchBlock
  1043. || type == Block::Type::developerControlBlock;
  1044. }
  1045. //==============================================================================
  1046. std::function<void(const String&)> logger;
  1047. void setLogger (std::function<void(const String&)> newLogger) override
  1048. {
  1049. logger = newLogger;
  1050. }
  1051. void handleLogMessage (const String& message) const
  1052. {
  1053. if (logger != nullptr)
  1054. logger (message);
  1055. }
  1056. //==============================================================================
  1057. juce::Result setProgram (Program* newProgram) override
  1058. {
  1059. if (newProgram == nullptr || program.get() != newProgram)
  1060. {
  1061. {
  1062. std::unique_ptr<Program> p (newProgram);
  1063. if (program != nullptr
  1064. && newProgram != nullptr
  1065. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  1066. return juce::Result::ok();
  1067. stopTimer();
  1068. std::swap (program, p);
  1069. }
  1070. stopTimer();
  1071. programSize = 0;
  1072. if (program != nullptr)
  1073. {
  1074. littlefoot::Compiler compiler;
  1075. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  1076. auto err = compiler.compile (program->getLittleFootProgram(), 512);
  1077. if (err.failed())
  1078. return err;
  1079. DBG ("Compiled littlefoot program, space needed: "
  1080. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  1081. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  1082. return Result::fail ("Program too large!");
  1083. auto size = (size_t) compiler.compiledObjectCode.size();
  1084. programSize = (uint32) size;
  1085. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  1086. remoteHeap.clear();
  1087. remoteHeap.sendChanges (*this, true);
  1088. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  1089. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  1090. remoteHeap.sendChanges (*this, true);
  1091. this->resetConfigListActiveStatus();
  1092. if (auto changeCallback = this->configChangedCallback)
  1093. changeCallback (*this, {}, this->getMaxConfigIndex());
  1094. }
  1095. else
  1096. {
  1097. remoteHeap.clear();
  1098. }
  1099. }
  1100. else
  1101. {
  1102. jassertfalse;
  1103. }
  1104. return juce::Result::ok();
  1105. }
  1106. Program* getProgram() const override { return program.get(); }
  1107. void sendProgramEvent (const ProgramEventMessage& message) override
  1108. {
  1109. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  1110. "Need to keep the internal and external messages structures the same");
  1111. if (remoteHeap.isProgramLoaded())
  1112. {
  1113. auto index = getDeviceIndex();
  1114. if (index >= 0)
  1115. {
  1116. BlocksProtocol::HostPacketBuilder<128> p;
  1117. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1118. if (p.addProgramEventMessage (message.values))
  1119. {
  1120. p.writePacketSysexFooter();
  1121. sendMessageToDevice (p);
  1122. }
  1123. }
  1124. else
  1125. {
  1126. jassertfalse;
  1127. }
  1128. }
  1129. }
  1130. void timerCallback() override
  1131. {
  1132. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  1133. {
  1134. stopTimer();
  1135. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  1136. }
  1137. else
  1138. {
  1139. startTimer (100);
  1140. }
  1141. }
  1142. void saveProgramAsDefault() override
  1143. {
  1144. startTimer (10);
  1145. }
  1146. uint32 getMemorySize() override
  1147. {
  1148. return modelData.programAndHeapSize;
  1149. }
  1150. void setDataByte (size_t offset, uint8 value) override
  1151. {
  1152. remoteHeap.setByte (programSize + offset, value);
  1153. }
  1154. void setDataBytes (size_t offset, const void* newData, size_t num) override
  1155. {
  1156. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  1157. }
  1158. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  1159. {
  1160. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  1161. }
  1162. uint8 getDataByte (size_t offset) override
  1163. {
  1164. return remoteHeap.getByte (programSize + offset);
  1165. }
  1166. void handleSharedDataACK (uint32 packetCounter) noexcept
  1167. {
  1168. pingFromDevice();
  1169. remoteHeap.handleACKFromDevice (*this, packetCounter);
  1170. }
  1171. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void (uint8)> callback) override
  1172. {
  1173. firmwarePacketAckCallback = {};
  1174. auto index = getDeviceIndex();
  1175. if (index >= 0)
  1176. {
  1177. BlocksProtocol::HostPacketBuilder<256> p;
  1178. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1179. if (p.addFirmwareUpdatePacket (data, size))
  1180. {
  1181. p.writePacketSysexFooter();
  1182. if (sendMessageToDevice (p))
  1183. {
  1184. firmwarePacketAckCallback = callback;
  1185. return true;
  1186. }
  1187. }
  1188. }
  1189. else
  1190. {
  1191. jassertfalse;
  1192. }
  1193. return false;
  1194. }
  1195. void handleFirmwareUpdateACK (uint8 resultCode)
  1196. {
  1197. if (firmwarePacketAckCallback != nullptr)
  1198. {
  1199. firmwarePacketAckCallback (resultCode);
  1200. firmwarePacketAckCallback = {};
  1201. }
  1202. }
  1203. void handleConfigUpdateMessage (int32 item, int32 value, int32 min, int32 max)
  1204. {
  1205. config.handleConfigUpdateMessage (item, value, min, max);
  1206. }
  1207. void handleConfigSetMessage(int32 item, int32 value)
  1208. {
  1209. config.handleConfigSetMessage (item, value);
  1210. }
  1211. void pingFromDevice()
  1212. {
  1213. lastMessageReceiveTime = juce::Time::getCurrentTime();
  1214. }
  1215. void addDataInputPortListener (DataInputPortListener* listener) override
  1216. {
  1217. Block::addDataInputPortListener (listener);
  1218. if (auto midiInput = getMidiInput())
  1219. midiInput->start();
  1220. }
  1221. void sendMessage (const void* message, size_t messageSize) override
  1222. {
  1223. if (auto midiOutput = getMidiOutput())
  1224. midiOutput->sendMessageNow ({ message, (int) messageSize });
  1225. }
  1226. void handleTimerTick()
  1227. {
  1228. if (++resetMessagesSent < 3)
  1229. {
  1230. if (resetMessagesSent == 1)
  1231. sendCommandMessage (BlocksProtocol::endAPIMode);
  1232. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1233. return;
  1234. }
  1235. if (ledGrid != nullptr)
  1236. if (auto renderer = ledGrid->getRenderer())
  1237. renderer->renderLEDGrid (*ledGrid);
  1238. remoteHeap.sendChanges (*this, false);
  1239. if (lastMessageSendTime < juce::Time::getCurrentTime() - juce::RelativeTime::milliseconds (pingIntervalMs))
  1240. sendCommandMessage (BlocksProtocol::ping);
  1241. }
  1242. //==============================================================================
  1243. int32 getLocalConfigValue (uint32 item) override
  1244. {
  1245. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1246. return config.getItemValue ((BlocksProtocol::ConfigItemId) item);
  1247. }
  1248. void setLocalConfigValue (uint32 item, int32 value) override
  1249. {
  1250. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1251. config.setItemValue ((BlocksProtocol::ConfigItemId) item, value);
  1252. }
  1253. void setLocalConfigRange (uint32 item, int32 min, int32 max) override
  1254. {
  1255. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1256. config.setItemMin ((BlocksProtocol::ConfigItemId) item, min);
  1257. config.setItemMax ((BlocksProtocol::ConfigItemId) item, max);
  1258. }
  1259. void setLocalConfigItemActive (uint32 item, bool isActive) override
  1260. {
  1261. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1262. config.setItemActive ((BlocksProtocol::ConfigItemId) item, isActive);
  1263. }
  1264. bool isLocalConfigItemActive (uint32 item) override
  1265. {
  1266. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1267. return config.getItemActive ((BlocksProtocol::ConfigItemId) item);
  1268. }
  1269. uint32 getMaxConfigIndex () override
  1270. {
  1271. return uint32 (BlocksProtocol::maxConfigIndex);
  1272. }
  1273. bool isValidUserConfigIndex (uint32 item) override
  1274. {
  1275. return item >= (uint32) BlocksProtocol::ConfigItemId::user0
  1276. && item < (uint32) (BlocksProtocol::ConfigItemId::user0 + numberOfUserConfigs);
  1277. }
  1278. ConfigMetaData getLocalConfigMetaData (uint32 item) override
  1279. {
  1280. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1281. return config.getMetaData ((BlocksProtocol::ConfigItemId) item);
  1282. }
  1283. void requestFactoryConfigSync() override
  1284. {
  1285. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1286. config.requestFactoryConfigSync();
  1287. }
  1288. void resetConfigListActiveStatus() override
  1289. {
  1290. config.resetConfigListActiveStatus();
  1291. }
  1292. void setConfigChangedCallback (std::function<void(Block&, const ConfigMetaData&, uint32)> configChanged) override
  1293. {
  1294. configChangedCallback = configChanged;
  1295. }
  1296. //==============================================================================
  1297. std::unique_ptr<TouchSurface> touchSurface;
  1298. juce::OwnedArray<ControlButton> controlButtons;
  1299. std::unique_ptr<LEDGridImplementation> ledGrid;
  1300. std::unique_ptr<LEDRowImplementation> ledRow;
  1301. juce::OwnedArray<StatusLight> statusLights;
  1302. BlocksProtocol::BlockDataSheet modelData;
  1303. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  1304. static constexpr int pingIntervalMs = 400;
  1305. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  1306. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  1307. static constexpr uint32 maxPacketSize = 200;
  1308. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  1309. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  1310. RemoteHeapType remoteHeap;
  1311. Detector& detector;
  1312. juce::Time lastMessageSendTime, lastMessageReceiveTime;
  1313. BlockConfigManager config;
  1314. std::function<void(Block&, const ConfigMetaData&, uint32)> configChangedCallback;
  1315. private:
  1316. std::unique_ptr<Program> program;
  1317. uint32 programSize = 0;
  1318. std::function<void(uint8)> firmwarePacketAckCallback;
  1319. uint32 resetMessagesSent = 0;
  1320. bool isStillConnected = true;
  1321. bool isMaster = false;
  1322. const juce::MidiInput* getMidiInput() const
  1323. {
  1324. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1325. return c->midiInput.get();
  1326. jassertfalse;
  1327. return nullptr;
  1328. }
  1329. juce::MidiInput* getMidiInput()
  1330. {
  1331. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  1332. }
  1333. const juce::MidiOutput* getMidiOutput() const
  1334. {
  1335. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1336. return c->midiOutput.get();
  1337. jassertfalse;
  1338. return nullptr;
  1339. }
  1340. juce::MidiOutput* getMidiOutput()
  1341. {
  1342. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  1343. }
  1344. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  1345. {
  1346. dataInputPortListeners.call (&Block::DataInputPortListener::handleIncomingDataPortMessage,
  1347. *this, message.getRawData(), (size_t) message.getRawDataSize());
  1348. }
  1349. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  1350. {
  1351. jassert (listenerToMidiConnection == &c);
  1352. juce::ignoreUnused (c);
  1353. listenerToMidiConnection->removeListener (this);
  1354. listenerToMidiConnection = nullptr;
  1355. }
  1356. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  1357. };
  1358. //==============================================================================
  1359. struct LEDRowImplementation : public LEDRow,
  1360. private Timer
  1361. {
  1362. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  1363. {
  1364. startTimer (300);
  1365. }
  1366. void setButtonColour (uint32 index, LEDColour colour)
  1367. {
  1368. if (index < 10)
  1369. {
  1370. colours[index] = colour;
  1371. flush();
  1372. }
  1373. }
  1374. int getNumLEDs() const override
  1375. {
  1376. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  1377. }
  1378. void setLEDColour (int index, LEDColour colour) override
  1379. {
  1380. if ((uint32) index < 15u)
  1381. {
  1382. colours[10 + index] = colour;
  1383. flush();
  1384. }
  1385. }
  1386. void setOverlayColour (LEDColour colour) override
  1387. {
  1388. colours[25] = colour;
  1389. flush();
  1390. }
  1391. void resetOverlayColour() override
  1392. {
  1393. setOverlayColour ({});
  1394. }
  1395. private:
  1396. LEDColour colours[26];
  1397. void timerCallback() override
  1398. {
  1399. stopTimer();
  1400. loadProgramOntoBlock();
  1401. flush();
  1402. }
  1403. void loadProgramOntoBlock()
  1404. {
  1405. if (block.getProgram() == nullptr)
  1406. {
  1407. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  1408. if (err.failed())
  1409. {
  1410. DBG (err.getErrorMessage());
  1411. jassertfalse;
  1412. }
  1413. }
  1414. }
  1415. void flush()
  1416. {
  1417. if (block.getProgram() != nullptr)
  1418. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  1419. write565Colour (16 * i, colours[i]);
  1420. }
  1421. void write565Colour (uint32 bitIndex, LEDColour colour)
  1422. {
  1423. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  1424. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  1425. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  1426. }
  1427. struct DefaultLEDGridProgram : public Block::Program
  1428. {
  1429. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  1430. juce::String getLittleFootProgram() override
  1431. {
  1432. /* Data format:
  1433. 0: 10 x 5-6-5 bits for button LED RGBs
  1434. 20: 15 x 5-6-5 bits for LED row colours
  1435. 50: 1 x 5-6-5 bits for LED row overlay colour
  1436. */
  1437. return R"littlefoot(
  1438. #heapsize: 128
  1439. int getColour (int bitIndex)
  1440. {
  1441. return makeARGB (255,
  1442. getHeapBits (bitIndex, 5) << 3,
  1443. getHeapBits (bitIndex + 5, 6) << 2,
  1444. getHeapBits (bitIndex + 11, 5) << 3);
  1445. }
  1446. int getButtonColour (int index)
  1447. {
  1448. return getColour (16 * index);
  1449. }
  1450. int getLEDColour (int index)
  1451. {
  1452. if (getHeapInt (50))
  1453. return getColour (50 * 8);
  1454. return getColour (20 * 8 + 16 * index);
  1455. }
  1456. void repaint()
  1457. {
  1458. for (int x = 0; x < 15; ++x)
  1459. fillPixel (getLEDColour (x), x, 0);
  1460. for (int i = 0; i < 10; ++i)
  1461. fillPixel (getButtonColour (i), i, 1);
  1462. }
  1463. void handleMessage (int p1, int p2) {}
  1464. )littlefoot";
  1465. }
  1466. };
  1467. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  1468. };
  1469. //==============================================================================
  1470. struct TouchSurfaceImplementation : public TouchSurface,
  1471. private juce::Timer
  1472. {
  1473. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  1474. {
  1475. if (auto det = Detector::getFrom (block))
  1476. det->activeTouchSurfaces.add (this);
  1477. startTimer (500);
  1478. }
  1479. ~TouchSurfaceImplementation()
  1480. {
  1481. if (auto det = Detector::getFrom (block))
  1482. det->activeTouchSurfaces.removeFirstMatchingValue (this);
  1483. }
  1484. int getNumberOfKeywaves() const noexcept override
  1485. {
  1486. return blockImpl.modelData.numKeywaves;
  1487. }
  1488. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  1489. {
  1490. auto& status = touches.getValue (touchEvent);
  1491. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  1492. if (touchEvent.isTouchStart && status.isActive)
  1493. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  1494. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  1495. if (! touchEvent.isTouchStart && ! status.isActive)
  1496. {
  1497. TouchSurface::Touch t (touchEvent);
  1498. t.isTouchStart = true;
  1499. t.isTouchEnd = false;
  1500. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  1501. if (t.zVelocity <= 0) t.zVelocity = t.z;
  1502. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  1503. listeners.call (&TouchSurface::Listener::touchChanged, *this, t);
  1504. }
  1505. // Normal handling:
  1506. status.lastEventTime = juce::Time::getMillisecondCounter();
  1507. status.isActive = ! touchEvent.isTouchEnd;
  1508. if (touchEvent.isTouchStart)
  1509. status.lastStrikePressure = touchEvent.zVelocity;
  1510. listeners.call (&TouchSurface::Listener::touchChanged, *this, touchEvent);
  1511. }
  1512. void timerCallback() override
  1513. {
  1514. // Find touches that seem to have become stuck, and fake a touch-end for them..
  1515. static const uint32 touchTimeOutMs = 40;
  1516. for (auto& t : touches)
  1517. {
  1518. auto& status = t.value;
  1519. auto now = juce::Time::getMillisecondCounter();
  1520. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  1521. killTouch (t.touch, status, now);
  1522. }
  1523. }
  1524. struct TouchStatus
  1525. {
  1526. uint32 lastEventTime = 0;
  1527. float lastStrikePressure = 0;
  1528. bool isActive = false;
  1529. };
  1530. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  1531. {
  1532. jassert (status.isActive);
  1533. TouchSurface::Touch killTouch (touch);
  1534. killTouch.z = 0;
  1535. killTouch.xVelocity = 0;
  1536. killTouch.yVelocity = 0;
  1537. killTouch.zVelocity = -1.0f;
  1538. killTouch.eventTimestamp = timeStamp;
  1539. killTouch.isTouchStart = false;
  1540. killTouch.isTouchEnd = true;
  1541. listeners.call (&TouchSurface::Listener::touchChanged, *this, killTouch);
  1542. status.isActive = false;
  1543. }
  1544. void cancelAllActiveTouches() noexcept override
  1545. {
  1546. const auto now = juce::Time::getMillisecondCounter();
  1547. for (auto& t : touches)
  1548. if (t.value.isActive)
  1549. killTouch (t.touch, t.value, now);
  1550. touches.clear();
  1551. }
  1552. BlockImplementation& blockImpl;
  1553. TouchList<TouchStatus> touches;
  1554. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  1555. };
  1556. //==============================================================================
  1557. struct ControlButtonImplementation : public ControlButton
  1558. {
  1559. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  1560. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  1561. {
  1562. if (auto det = Detector::getFrom (block))
  1563. det->activeControlButtons.add (this);
  1564. }
  1565. ~ControlButtonImplementation()
  1566. {
  1567. if (auto det = Detector::getFrom (block))
  1568. det->activeControlButtons.removeFirstMatchingValue (this);
  1569. }
  1570. ButtonFunction getType() const override { return buttonInfo.type; }
  1571. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  1572. float getPositionX() const override { return buttonInfo.x; }
  1573. float getPositionY() const override { return buttonInfo.y; }
  1574. bool hasLight() const override { return blockImpl.isControlBlock(); }
  1575. bool setLightColour (LEDColour colour) override
  1576. {
  1577. if (hasLight())
  1578. {
  1579. if (auto row = blockImpl.ledRow.get())
  1580. {
  1581. row->setButtonColour ((uint32) buttonIndex, colour);
  1582. return true;
  1583. }
  1584. }
  1585. return false;
  1586. }
  1587. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  1588. {
  1589. if (button == buttonInfo.type)
  1590. {
  1591. if (wasDown == isDown)
  1592. sendButtonChangeToListeners (timestamp, ! isDown);
  1593. sendButtonChangeToListeners (timestamp, isDown);
  1594. wasDown = isDown;
  1595. }
  1596. }
  1597. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  1598. {
  1599. if (isDown)
  1600. listeners.call (&ControlButton::Listener::buttonPressed, *this, timestamp);
  1601. else
  1602. listeners.call (&ControlButton::Listener::buttonReleased, *this, timestamp);
  1603. }
  1604. BlockImplementation& blockImpl;
  1605. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  1606. int buttonIndex;
  1607. bool wasDown = false;
  1608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  1609. };
  1610. //==============================================================================
  1611. struct StatusLightImplementation : public StatusLight
  1612. {
  1613. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  1614. {
  1615. }
  1616. juce::String getName() const override { return info.name; }
  1617. bool setColour (LEDColour newColour) override
  1618. {
  1619. // XXX TODO!
  1620. juce::ignoreUnused (newColour);
  1621. return false;
  1622. }
  1623. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  1624. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  1625. };
  1626. //==============================================================================
  1627. struct LEDGridImplementation : public LEDGrid
  1628. {
  1629. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  1630. {
  1631. }
  1632. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  1633. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  1634. BlockImplementation& blockImpl;
  1635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  1636. };
  1637. //==============================================================================
  1638. #if DUMP_TOPOLOGY
  1639. static juce::String idToSerialNum (const BlockTopology& topology, Block::UID uid)
  1640. {
  1641. for (auto* b : topology.blocks)
  1642. if (b->uid == uid)
  1643. return b->serialNumber;
  1644. return "???";
  1645. }
  1646. static juce::String portEdgeToString (Block::ConnectionPort port)
  1647. {
  1648. switch (port.edge)
  1649. {
  1650. case Block::ConnectionPort::DeviceEdge::north: return "north";
  1651. case Block::ConnectionPort::DeviceEdge::south: return "south";
  1652. case Block::ConnectionPort::DeviceEdge::east: return "east";
  1653. case Block::ConnectionPort::DeviceEdge::west: return "west";
  1654. }
  1655. return {};
  1656. }
  1657. static juce::String portToString (Block::ConnectionPort port)
  1658. {
  1659. return portEdgeToString (port) + "_" + juce::String (port.index);
  1660. }
  1661. static void dumpTopology (const BlockTopology& topology)
  1662. {
  1663. MemoryOutputStream m;
  1664. m << "=============================================================================" << newLine
  1665. << "Topology: " << topology.blocks.size() << " device(s)" << newLine
  1666. << newLine;
  1667. int index = 0;
  1668. for (auto block : topology.blocks)
  1669. {
  1670. m << "Device " << index++ << (block->isMasterBlock() ? ": (MASTER)" : ":") << newLine;
  1671. m << " Description: " << block->getDeviceDescription() << newLine
  1672. << " Serial: " << block->serialNumber << newLine;
  1673. if (auto bi = BlockImplementation::getFrom (*block))
  1674. m << " Short address: " << (int) bi->getDeviceIndex() << newLine;
  1675. m << " Battery level: " + juce::String (juce::roundToInt (100.0f * block->getBatteryLevel())) + "%" << newLine
  1676. << " Battery charging: " + juce::String (block->isBatteryCharging() ? "y" : "n") << newLine
  1677. << " Width: " << block->getWidth() << newLine
  1678. << " Height: " << block->getHeight() << newLine
  1679. << " Millimeters per unit: " << block->getMillimetersPerUnit() << newLine
  1680. << newLine;
  1681. }
  1682. for (auto& connection : topology.connections)
  1683. {
  1684. m << idToSerialNum (topology, connection.device1)
  1685. << ":" << portToString (connection.connectionPortOnDevice1)
  1686. << " <-> "
  1687. << idToSerialNum (topology, connection.device2)
  1688. << ":" << portToString (connection.connectionPortOnDevice2) << newLine;
  1689. }
  1690. m << "=============================================================================" << newLine;
  1691. Logger::outputDebugString (m.toString());
  1692. }
  1693. #endif
  1694. };
  1695. //==============================================================================
  1696. struct PhysicalTopologySource::DetectorHolder : private juce::Timer
  1697. {
  1698. DetectorHolder (PhysicalTopologySource& pts)
  1699. : topologySource (pts),
  1700. detector (Internal::Detector::getDefaultDetector())
  1701. {
  1702. startTimerHz (30);
  1703. }
  1704. DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
  1705. : topologySource (pts),
  1706. detector (new Internal::Detector (dd))
  1707. {
  1708. startTimerHz (30);
  1709. }
  1710. void timerCallback() override
  1711. {
  1712. if (! topologySource.hasOwnServiceTimer())
  1713. handleTimerTick();
  1714. }
  1715. void handleTimerTick()
  1716. {
  1717. for (auto& b : detector->currentTopology.blocks)
  1718. if (auto bi = Internal::BlockImplementation::getFrom (*b))
  1719. bi->handleTimerTick();
  1720. }
  1721. PhysicalTopologySource& topologySource;
  1722. Internal::Detector::Ptr detector;
  1723. };
  1724. //==============================================================================
  1725. PhysicalTopologySource::PhysicalTopologySource()
  1726. : detector (new DetectorHolder (*this))
  1727. {
  1728. detector->detector->activeTopologySources.add (this);
  1729. }
  1730. PhysicalTopologySource::PhysicalTopologySource (DeviceDetector& detectorToUse)
  1731. : detector (new DetectorHolder (*this, detectorToUse))
  1732. {
  1733. detector->detector->activeTopologySources.add (this);
  1734. }
  1735. PhysicalTopologySource::~PhysicalTopologySource()
  1736. {
  1737. detector->detector->detach (this);
  1738. detector = nullptr;
  1739. }
  1740. BlockTopology PhysicalTopologySource::getCurrentTopology() const
  1741. {
  1742. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  1743. return detector->detector->currentTopology;
  1744. }
  1745. void PhysicalTopologySource::cancelAllActiveTouches() noexcept
  1746. {
  1747. detector->detector->cancelAllActiveTouches();
  1748. }
  1749. bool PhysicalTopologySource::hasOwnServiceTimer() const { return false; }
  1750. void PhysicalTopologySource::handleTimerTick() { detector->handleTimerTick(); }
  1751. PhysicalTopologySource::DeviceConnection::DeviceConnection() {}
  1752. PhysicalTopologySource::DeviceConnection::~DeviceConnection() {}
  1753. PhysicalTopologySource::DeviceDetector::DeviceDetector() {}
  1754. PhysicalTopologySource::DeviceDetector::~DeviceDetector() {}
  1755. const char* const* PhysicalTopologySource::getStandardLittleFootFunctions() noexcept
  1756. {
  1757. return BlocksProtocol::ledProgramLittleFootFunctions;
  1758. }
  1759. static bool blocksMatch (const Block::Array& list1, const Block::Array& list2) noexcept
  1760. {
  1761. if (list1.size() != list2.size())
  1762. return false;
  1763. for (auto&& b : list1)
  1764. if (! list2.contains (b))
  1765. return false;
  1766. return true;
  1767. }
  1768. bool BlockTopology::operator== (const BlockTopology& other) const noexcept
  1769. {
  1770. return connections == other.connections && blocksMatch (blocks, other.blocks);
  1771. }
  1772. bool BlockTopology::operator!= (const BlockTopology& other) const noexcept
  1773. {
  1774. return ! operator== (other);
  1775. }
  1776. bool BlockDeviceConnection::operator== (const BlockDeviceConnection& other) const noexcept
  1777. {
  1778. return (device1 == other.device1 && device2 == other.device2
  1779. && connectionPortOnDevice1 == other.connectionPortOnDevice1
  1780. && connectionPortOnDevice2 == other.connectionPortOnDevice2)
  1781. || (device1 == other.device2 && device2 == other.device1
  1782. && connectionPortOnDevice1 == other.connectionPortOnDevice2
  1783. && connectionPortOnDevice2 == other.connectionPortOnDevice1);
  1784. }
  1785. bool BlockDeviceConnection::operator!= (const BlockDeviceConnection& other) const noexcept
  1786. {
  1787. return ! operator== (other);
  1788. }