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.

2628 lines
92KB

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