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.

2671 lines
94KB

  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. updateMidiConnectionListener();
  1178. }
  1179. ~BlockImplementation()
  1180. {
  1181. if (listenerToMidiConnection != nullptr)
  1182. {
  1183. config.setDeviceComms (nullptr);
  1184. listenerToMidiConnection->removeListener (this);
  1185. }
  1186. }
  1187. void invalidate()
  1188. {
  1189. isStillConnected = false;
  1190. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  1191. surface->disableTouchSurface();
  1192. for (auto* b : controlButtons)
  1193. if (auto controlButton = dynamic_cast<ControlButtonImplementation*> (b))
  1194. controlButton->disableControlButton();
  1195. }
  1196. void revalidate (BlocksProtocol::VersionNumber newVersion, BlocksProtocol::BlockName newName, bool master)
  1197. {
  1198. versionNumber = getVersionString (newVersion);
  1199. name = getNameString (newName);
  1200. isMaster = master;
  1201. isStillConnected = true;
  1202. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  1203. surface->activateTouchSurface();
  1204. for (auto* b : controlButtons)
  1205. if (auto controlButton = dynamic_cast<ControlButtonImplementation*> (b))
  1206. controlButton->activateControlButton();
  1207. updateMidiConnectionListener();
  1208. }
  1209. void setToMaster (bool shouldBeMaster)
  1210. {
  1211. isMaster = shouldBeMaster;
  1212. }
  1213. void updateMidiConnectionListener()
  1214. {
  1215. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this));
  1216. if (listenerToMidiConnection != nullptr)
  1217. listenerToMidiConnection->addListener (this);
  1218. config.setDeviceComms (listenerToMidiConnection);
  1219. }
  1220. Type getType() const override { return modelData.apiType; }
  1221. juce::String getDeviceDescription() const override { return modelData.description; }
  1222. int getWidth() const override { return modelData.widthUnits; }
  1223. int getHeight() const override { return modelData.heightUnits; }
  1224. float getMillimetersPerUnit() const override { return 47.0f; }
  1225. bool isHardwareBlock() const override { return true; }
  1226. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  1227. bool isConnected() const override { return isStillConnected && detector.isConnected (uid); }
  1228. bool isMasterBlock() const override { return isMaster; }
  1229. Block::UID getConnectedMasterUID() const override { return masterUID; }
  1230. int getRotation() const override { return rotation; }
  1231. Rectangle<int> getBlockAreaWithinLayout() const override
  1232. {
  1233. if (rotation % 2 == 0)
  1234. return { position.getX(), position.getY(), modelData.widthUnits, modelData.heightUnits };
  1235. return { position.getX(), position.getY(), modelData.heightUnits, modelData.widthUnits };
  1236. }
  1237. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  1238. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  1239. LEDRow* getLEDRow() const override { return ledRow.get(); }
  1240. juce::Array<ControlButton*> getButtons() const override
  1241. {
  1242. juce::Array<ControlButton*> result;
  1243. result.addArray (controlButtons);
  1244. return result;
  1245. }
  1246. juce::Array<StatusLight*> getStatusLights() const override
  1247. {
  1248. juce::Array<StatusLight*> result;
  1249. result.addArray (statusLights);
  1250. return result;
  1251. }
  1252. float getBatteryLevel() const override
  1253. {
  1254. if (auto status = detector.getLastStatus (uid))
  1255. return status->batteryLevel.toUnipolarFloat();
  1256. return 0.0f;
  1257. }
  1258. bool isBatteryCharging() const override
  1259. {
  1260. if (auto status = detector.getLastStatus (uid))
  1261. return status->batteryCharging.get() != 0;
  1262. return false;
  1263. }
  1264. bool supportsGraphics() const override
  1265. {
  1266. return false;
  1267. }
  1268. int getDeviceIndex() const noexcept
  1269. {
  1270. return isConnected() ? detector.getIndexFromDeviceID (uid) : -1;
  1271. }
  1272. template <typename PacketBuilder>
  1273. bool sendMessageToDevice (const PacketBuilder& builder)
  1274. {
  1275. lastMessageSendTime = juce::Time::getCurrentTime();
  1276. return detector.sendMessageToDevice (uid, builder);
  1277. }
  1278. bool sendCommandMessage (uint32 commandID)
  1279. {
  1280. int index = getDeviceIndex();
  1281. if (index < 0)
  1282. return false;
  1283. BlocksProtocol::HostPacketBuilder<64> p;
  1284. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1285. p.deviceControlMessage (commandID);
  1286. p.writePacketSysexFooter();
  1287. return sendMessageToDevice (p);
  1288. }
  1289. void handleCustomMessage (Block::Timestamp, const int32* data)
  1290. {
  1291. ProgramEventMessage m;
  1292. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  1293. m.values[i] = data[i];
  1294. programEventListeners.call ([&] (ProgramEventListener& l) { l.handleProgramEvent (*this, m); });
  1295. }
  1296. static BlockImplementation* getFrom (Block& b) noexcept
  1297. {
  1298. if (auto bi = dynamic_cast<BlockImplementation*> (&b))
  1299. return bi;
  1300. jassertfalse;
  1301. return nullptr;
  1302. }
  1303. bool isControlBlock() const
  1304. {
  1305. auto type = getType();
  1306. return type == Block::Type::liveBlock
  1307. || type == Block::Type::loopBlock
  1308. || type == Block::Type::touchBlock
  1309. || type == Block::Type::developerControlBlock;
  1310. }
  1311. //==============================================================================
  1312. std::function<void(const String&)> logger;
  1313. void setLogger (std::function<void(const String&)> newLogger) override
  1314. {
  1315. logger = newLogger;
  1316. }
  1317. void handleLogMessage (const String& message) const
  1318. {
  1319. if (logger != nullptr)
  1320. logger (message);
  1321. }
  1322. //==============================================================================
  1323. juce::Result setProgram (Program* newProgram) override
  1324. {
  1325. if (newProgram == nullptr || program.get() != newProgram)
  1326. {
  1327. {
  1328. std::unique_ptr<Program> p (newProgram);
  1329. if (program != nullptr
  1330. && newProgram != nullptr
  1331. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  1332. return juce::Result::ok();
  1333. stopTimer();
  1334. std::swap (program, p);
  1335. }
  1336. stopTimer();
  1337. programSize = 0;
  1338. if (program != nullptr)
  1339. {
  1340. littlefoot::Compiler compiler;
  1341. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  1342. auto err = compiler.compile (program->getLittleFootProgram(), 512);
  1343. if (err.failed())
  1344. return err;
  1345. DBG ("Compiled littlefoot program, space needed: "
  1346. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  1347. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  1348. return Result::fail ("Program too large!");
  1349. auto size = (size_t) compiler.compiledObjectCode.size();
  1350. programSize = (uint32) size;
  1351. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  1352. remoteHeap.clear();
  1353. remoteHeap.sendChanges (*this, true);
  1354. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  1355. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  1356. remoteHeap.sendChanges (*this, true);
  1357. this->resetConfigListActiveStatus();
  1358. if (auto changeCallback = this->configChangedCallback)
  1359. changeCallback (*this, {}, this->getMaxConfigIndex());
  1360. }
  1361. else
  1362. {
  1363. remoteHeap.clear();
  1364. }
  1365. }
  1366. else
  1367. {
  1368. jassertfalse;
  1369. }
  1370. return juce::Result::ok();
  1371. }
  1372. Program* getProgram() const override { return program.get(); }
  1373. void sendProgramEvent (const ProgramEventMessage& message) override
  1374. {
  1375. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  1376. "Need to keep the internal and external messages structures the same");
  1377. if (remoteHeap.isProgramLoaded())
  1378. {
  1379. auto index = getDeviceIndex();
  1380. if (index >= 0)
  1381. {
  1382. BlocksProtocol::HostPacketBuilder<128> p;
  1383. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1384. if (p.addProgramEventMessage (message.values))
  1385. {
  1386. p.writePacketSysexFooter();
  1387. sendMessageToDevice (p);
  1388. }
  1389. }
  1390. else
  1391. {
  1392. jassertfalse;
  1393. }
  1394. }
  1395. }
  1396. void timerCallback() override
  1397. {
  1398. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  1399. {
  1400. stopTimer();
  1401. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  1402. }
  1403. else
  1404. {
  1405. startTimer (100);
  1406. }
  1407. }
  1408. void saveProgramAsDefault() override
  1409. {
  1410. startTimer (10);
  1411. }
  1412. uint32 getMemorySize() override
  1413. {
  1414. return modelData.programAndHeapSize;
  1415. }
  1416. uint32 getHeapMemorySize() override
  1417. {
  1418. jassert (isPositiveAndNotGreaterThan (programSize, modelData.programAndHeapSize));
  1419. return modelData.programAndHeapSize - programSize;
  1420. }
  1421. void setDataByte (size_t offset, uint8 value) override
  1422. {
  1423. remoteHeap.setByte (programSize + offset, value);
  1424. }
  1425. void setDataBytes (size_t offset, const void* newData, size_t num) override
  1426. {
  1427. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  1428. }
  1429. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  1430. {
  1431. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  1432. }
  1433. uint8 getDataByte (size_t offset) override
  1434. {
  1435. return remoteHeap.getByte (programSize + offset);
  1436. }
  1437. void handleSharedDataACK (uint32 packetCounter) noexcept
  1438. {
  1439. pingFromDevice();
  1440. remoteHeap.handleACKFromDevice (*this, packetCounter);
  1441. }
  1442. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void (uint8, uint32)> callback) override
  1443. {
  1444. firmwarePacketAckCallback = {};
  1445. auto index = getDeviceIndex();
  1446. if (index >= 0)
  1447. {
  1448. BlocksProtocol::HostPacketBuilder<256> p;
  1449. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1450. if (p.addFirmwareUpdatePacket (data, size))
  1451. {
  1452. p.writePacketSysexFooter();
  1453. if (sendMessageToDevice (p))
  1454. {
  1455. firmwarePacketAckCallback = callback;
  1456. return true;
  1457. }
  1458. }
  1459. }
  1460. else
  1461. {
  1462. jassertfalse;
  1463. }
  1464. return false;
  1465. }
  1466. void handleFirmwareUpdateACK (uint8 resultCode, uint32 resultDetail)
  1467. {
  1468. if (firmwarePacketAckCallback != nullptr)
  1469. {
  1470. firmwarePacketAckCallback (resultCode, resultDetail);
  1471. firmwarePacketAckCallback = {};
  1472. }
  1473. }
  1474. void handleConfigUpdateMessage (int32 item, int32 value, int32 min, int32 max)
  1475. {
  1476. config.handleConfigUpdateMessage (item, value, min, max);
  1477. }
  1478. void handleConfigSetMessage(int32 item, int32 value)
  1479. {
  1480. config.handleConfigSetMessage (item, value);
  1481. }
  1482. void pingFromDevice()
  1483. {
  1484. lastMessageReceiveTime = juce::Time::getCurrentTime();
  1485. }
  1486. void addDataInputPortListener (DataInputPortListener* listener) override
  1487. {
  1488. Block::addDataInputPortListener (listener);
  1489. if (auto midiInput = getMidiInput())
  1490. midiInput->start();
  1491. }
  1492. void sendMessage (const void* message, size_t messageSize) override
  1493. {
  1494. if (auto midiOutput = getMidiOutput())
  1495. midiOutput->sendMessageNow ({ message, (int) messageSize });
  1496. }
  1497. void handleTimerTick()
  1498. {
  1499. if (++resetMessagesSent < 3)
  1500. {
  1501. if (resetMessagesSent == 1)
  1502. sendCommandMessage (BlocksProtocol::endAPIMode);
  1503. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1504. return;
  1505. }
  1506. if (ledGrid != nullptr)
  1507. if (auto renderer = ledGrid->getRenderer())
  1508. renderer->renderLEDGrid (*ledGrid);
  1509. remoteHeap.sendChanges (*this, false);
  1510. if (lastMessageSendTime < juce::Time::getCurrentTime() - juce::RelativeTime::milliseconds (pingIntervalMs))
  1511. sendCommandMessage (BlocksProtocol::ping);
  1512. }
  1513. //==============================================================================
  1514. int32 getLocalConfigValue (uint32 item) override
  1515. {
  1516. initialiseDeviceIndexAndConnection();
  1517. return config.getItemValue ((BlocksProtocol::ConfigItemId) item);
  1518. }
  1519. void setLocalConfigValue (uint32 item, int32 value) override
  1520. {
  1521. initialiseDeviceIndexAndConnection();
  1522. config.setItemValue ((BlocksProtocol::ConfigItemId) item, value);
  1523. }
  1524. void setLocalConfigRange (uint32 item, int32 min, int32 max) override
  1525. {
  1526. initialiseDeviceIndexAndConnection();
  1527. config.setItemMin ((BlocksProtocol::ConfigItemId) item, min);
  1528. config.setItemMax ((BlocksProtocol::ConfigItemId) item, max);
  1529. }
  1530. void setLocalConfigItemActive (uint32 item, bool isActive) override
  1531. {
  1532. initialiseDeviceIndexAndConnection();
  1533. config.setItemActive ((BlocksProtocol::ConfigItemId) item, isActive);
  1534. }
  1535. bool isLocalConfigItemActive (uint32 item) override
  1536. {
  1537. initialiseDeviceIndexAndConnection();
  1538. return config.getItemActive ((BlocksProtocol::ConfigItemId) item);
  1539. }
  1540. uint32 getMaxConfigIndex() override
  1541. {
  1542. return uint32 (BlocksProtocol::maxConfigIndex);
  1543. }
  1544. bool isValidUserConfigIndex (uint32 item) override
  1545. {
  1546. return item >= (uint32) BlocksProtocol::ConfigItemId::user0
  1547. && item < (uint32) (BlocksProtocol::ConfigItemId::user0 + numberOfUserConfigs);
  1548. }
  1549. ConfigMetaData getLocalConfigMetaData (uint32 item) override
  1550. {
  1551. initialiseDeviceIndexAndConnection();
  1552. return config.getMetaData ((BlocksProtocol::ConfigItemId) item);
  1553. }
  1554. void requestFactoryConfigSync() override
  1555. {
  1556. initialiseDeviceIndexAndConnection();
  1557. config.requestFactoryConfigSync();
  1558. }
  1559. void resetConfigListActiveStatus() override
  1560. {
  1561. config.resetConfigListActiveStatus();
  1562. }
  1563. void setConfigChangedCallback (std::function<void(Block&, const ConfigMetaData&, uint32)> configChanged) override
  1564. {
  1565. configChangedCallback = configChanged;
  1566. }
  1567. void factoryReset() override
  1568. {
  1569. auto index = getDeviceIndex();
  1570. if (index >= 0)
  1571. {
  1572. BlocksProtocol::HostPacketBuilder<32> p;
  1573. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1574. p.addFactoryReset();
  1575. p.writePacketSysexFooter();
  1576. sendMessageToDevice (p);
  1577. }
  1578. else
  1579. {
  1580. jassertfalse;
  1581. }
  1582. }
  1583. void blockReset() override
  1584. {
  1585. auto index = getDeviceIndex();
  1586. if (index >= 0)
  1587. {
  1588. BlocksProtocol::HostPacketBuilder<32> p;
  1589. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1590. p.addBlockReset();
  1591. p.writePacketSysexFooter();
  1592. sendMessageToDevice (p);
  1593. }
  1594. else
  1595. {
  1596. jassertfalse;
  1597. }
  1598. }
  1599. bool setName (const juce::String& newName) override
  1600. {
  1601. auto index = getDeviceIndex();
  1602. if (index >= 0)
  1603. {
  1604. BlocksProtocol::HostPacketBuilder<128> p;
  1605. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1606. if (p.addSetBlockName (newName))
  1607. {
  1608. p.writePacketSysexFooter();
  1609. if (sendMessageToDevice (p))
  1610. return true;
  1611. }
  1612. }
  1613. else
  1614. {
  1615. jassertfalse;
  1616. }
  1617. return false;
  1618. }
  1619. //==============================================================================
  1620. std::unique_ptr<TouchSurface> touchSurface;
  1621. juce::OwnedArray<ControlButton> controlButtons;
  1622. std::unique_ptr<LEDGridImplementation> ledGrid;
  1623. std::unique_ptr<LEDRowImplementation> ledRow;
  1624. juce::OwnedArray<StatusLight> statusLights;
  1625. BlocksProtocol::BlockDataSheet modelData;
  1626. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  1627. static constexpr int pingIntervalMs = 400;
  1628. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  1629. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  1630. static constexpr uint32 maxPacketSize = 200;
  1631. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  1632. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  1633. RemoteHeapType remoteHeap;
  1634. Detector& detector;
  1635. juce::Time lastMessageSendTime, lastMessageReceiveTime;
  1636. BlockConfigManager config;
  1637. std::function<void(Block&, const ConfigMetaData&, uint32)> configChangedCallback;
  1638. private:
  1639. std::unique_ptr<Program> program;
  1640. uint32 programSize = 0;
  1641. std::function<void(uint8, uint32)> firmwarePacketAckCallback;
  1642. uint32 resetMessagesSent = 0;
  1643. bool isStillConnected = true;
  1644. bool isMaster = false;
  1645. Block::UID masterUID = {};
  1646. Point<int> position;
  1647. int rotation = 0;
  1648. friend BlocksTraverser;
  1649. void initialiseDeviceIndexAndConnection()
  1650. {
  1651. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1652. config.setDeviceComms (listenerToMidiConnection);
  1653. }
  1654. const juce::MidiInput* getMidiInput() const
  1655. {
  1656. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1657. return c->midiInput.get();
  1658. jassertfalse;
  1659. return nullptr;
  1660. }
  1661. juce::MidiInput* getMidiInput()
  1662. {
  1663. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  1664. }
  1665. const juce::MidiOutput* getMidiOutput() const
  1666. {
  1667. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1668. return c->midiOutput.get();
  1669. jassertfalse;
  1670. return nullptr;
  1671. }
  1672. juce::MidiOutput* getMidiOutput()
  1673. {
  1674. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  1675. }
  1676. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  1677. {
  1678. dataInputPortListeners.call ([&] (DataInputPortListener& l) { l.handleIncomingDataPortMessage (*this, message.getRawData(),
  1679. (size_t) message.getRawDataSize()); });
  1680. }
  1681. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  1682. {
  1683. jassert (listenerToMidiConnection == &c);
  1684. juce::ignoreUnused (c);
  1685. listenerToMidiConnection->removeListener (this);
  1686. listenerToMidiConnection = nullptr;
  1687. config.setDeviceComms (nullptr);
  1688. }
  1689. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  1690. };
  1691. //==============================================================================
  1692. struct LEDRowImplementation : public LEDRow,
  1693. private Timer
  1694. {
  1695. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  1696. {
  1697. startTimer (300);
  1698. }
  1699. void setButtonColour (uint32 index, LEDColour colour)
  1700. {
  1701. if (index < 10)
  1702. {
  1703. colours[index] = colour;
  1704. flush();
  1705. }
  1706. }
  1707. int getNumLEDs() const override
  1708. {
  1709. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  1710. }
  1711. void setLEDColour (int index, LEDColour colour) override
  1712. {
  1713. if ((uint32) index < 15u)
  1714. {
  1715. colours[10 + index] = colour;
  1716. flush();
  1717. }
  1718. }
  1719. void setOverlayColour (LEDColour colour) override
  1720. {
  1721. colours[25] = colour;
  1722. flush();
  1723. }
  1724. void resetOverlayColour() override
  1725. {
  1726. setOverlayColour ({});
  1727. }
  1728. private:
  1729. LEDColour colours[26];
  1730. void timerCallback() override
  1731. {
  1732. stopTimer();
  1733. loadProgramOntoBlock();
  1734. flush();
  1735. }
  1736. void loadProgramOntoBlock()
  1737. {
  1738. if (block.getProgram() == nullptr)
  1739. {
  1740. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  1741. if (err.failed())
  1742. {
  1743. DBG (err.getErrorMessage());
  1744. jassertfalse;
  1745. }
  1746. }
  1747. }
  1748. void flush()
  1749. {
  1750. if (block.getProgram() != nullptr)
  1751. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  1752. write565Colour (16 * i, colours[i]);
  1753. }
  1754. void write565Colour (uint32 bitIndex, LEDColour colour)
  1755. {
  1756. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  1757. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  1758. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  1759. }
  1760. struct DefaultLEDGridProgram : public Block::Program
  1761. {
  1762. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  1763. juce::String getLittleFootProgram() override
  1764. {
  1765. /* Data format:
  1766. 0: 10 x 5-6-5 bits for button LED RGBs
  1767. 20: 15 x 5-6-5 bits for LED row colours
  1768. 50: 1 x 5-6-5 bits for LED row overlay colour
  1769. */
  1770. return R"littlefoot(
  1771. #heapsize: 128
  1772. int getColour (int bitIndex)
  1773. {
  1774. return makeARGB (255,
  1775. getHeapBits (bitIndex, 5) << 3,
  1776. getHeapBits (bitIndex + 5, 6) << 2,
  1777. getHeapBits (bitIndex + 11, 5) << 3);
  1778. }
  1779. int getButtonColour (int index)
  1780. {
  1781. return getColour (16 * index);
  1782. }
  1783. int getLEDColour (int index)
  1784. {
  1785. if (getHeapInt (50))
  1786. return getColour (50 * 8);
  1787. return getColour (20 * 8 + 16 * index);
  1788. }
  1789. void repaint()
  1790. {
  1791. for (int x = 0; x < 15; ++x)
  1792. fillPixel (getLEDColour (x), x, 0);
  1793. for (int i = 0; i < 10; ++i)
  1794. fillPixel (getButtonColour (i), i, 1);
  1795. }
  1796. void handleMessage (int p1, int p2) {}
  1797. )littlefoot";
  1798. }
  1799. };
  1800. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  1801. };
  1802. //==============================================================================
  1803. struct TouchSurfaceImplementation : public TouchSurface,
  1804. private juce::Timer
  1805. {
  1806. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  1807. {
  1808. activateTouchSurface();
  1809. }
  1810. ~TouchSurfaceImplementation()
  1811. {
  1812. disableTouchSurface();
  1813. }
  1814. void activateTouchSurface()
  1815. {
  1816. if (auto det = Detector::getFrom (block))
  1817. det->activeTouchSurfaces.add (this);
  1818. startTimer (500);
  1819. }
  1820. void disableTouchSurface()
  1821. {
  1822. stopTimer();
  1823. if (auto det = Detector::getFrom (block))
  1824. det->activeTouchSurfaces.removeFirstMatchingValue (this);
  1825. }
  1826. int getNumberOfKeywaves() const noexcept override
  1827. {
  1828. return blockImpl.modelData.numKeywaves;
  1829. }
  1830. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  1831. {
  1832. auto& status = touches.getValue (touchEvent);
  1833. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  1834. if (touchEvent.isTouchStart && status.isActive)
  1835. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  1836. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  1837. if (! touchEvent.isTouchStart && ! status.isActive)
  1838. {
  1839. TouchSurface::Touch t (touchEvent);
  1840. t.isTouchStart = true;
  1841. t.isTouchEnd = false;
  1842. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  1843. if (t.zVelocity <= 0) t.zVelocity = t.z;
  1844. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  1845. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, t); });
  1846. }
  1847. // Normal handling:
  1848. status.lastEventTime = juce::Time::getMillisecondCounter();
  1849. status.isActive = ! touchEvent.isTouchEnd;
  1850. if (touchEvent.isTouchStart)
  1851. status.lastStrikePressure = touchEvent.zVelocity;
  1852. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, touchEvent); });
  1853. }
  1854. void timerCallback() override
  1855. {
  1856. // Find touches that seem to have become stuck, and fake a touch-end for them..
  1857. static const uint32 touchTimeOutMs = 500;
  1858. for (auto& t : touches)
  1859. {
  1860. auto& status = t.value;
  1861. auto now = juce::Time::getMillisecondCounter();
  1862. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  1863. killTouch (t.touch, status, now);
  1864. }
  1865. }
  1866. struct TouchStatus
  1867. {
  1868. uint32 lastEventTime = 0;
  1869. float lastStrikePressure = 0;
  1870. bool isActive = false;
  1871. };
  1872. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  1873. {
  1874. jassert (status.isActive);
  1875. TouchSurface::Touch killTouch (touch);
  1876. killTouch.z = 0;
  1877. killTouch.xVelocity = 0;
  1878. killTouch.yVelocity = 0;
  1879. killTouch.zVelocity = -1.0f;
  1880. killTouch.eventTimestamp = timeStamp;
  1881. killTouch.isTouchStart = false;
  1882. killTouch.isTouchEnd = true;
  1883. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, killTouch); });
  1884. status.isActive = false;
  1885. }
  1886. void cancelAllActiveTouches() noexcept override
  1887. {
  1888. const auto now = juce::Time::getMillisecondCounter();
  1889. for (auto& t : touches)
  1890. if (t.value.isActive)
  1891. killTouch (t.touch, t.value, now);
  1892. touches.clear();
  1893. }
  1894. BlockImplementation& blockImpl;
  1895. TouchList<TouchStatus> touches;
  1896. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  1897. };
  1898. //==============================================================================
  1899. struct ControlButtonImplementation : public ControlButton
  1900. {
  1901. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  1902. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  1903. {
  1904. activateControlButton();
  1905. }
  1906. ~ControlButtonImplementation()
  1907. {
  1908. disableControlButton();
  1909. }
  1910. void activateControlButton()
  1911. {
  1912. if (auto det = Detector::getFrom (block))
  1913. det->activeControlButtons.add (this);
  1914. }
  1915. void disableControlButton()
  1916. {
  1917. if (auto det = Detector::getFrom (block))
  1918. det->activeControlButtons.removeFirstMatchingValue (this);
  1919. }
  1920. ButtonFunction getType() const override { return buttonInfo.type; }
  1921. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  1922. float getPositionX() const override { return buttonInfo.x; }
  1923. float getPositionY() const override { return buttonInfo.y; }
  1924. bool hasLight() const override { return blockImpl.isControlBlock(); }
  1925. bool setLightColour (LEDColour colour) override
  1926. {
  1927. if (hasLight())
  1928. {
  1929. if (auto row = blockImpl.ledRow.get())
  1930. {
  1931. row->setButtonColour ((uint32) buttonIndex, colour);
  1932. return true;
  1933. }
  1934. }
  1935. return false;
  1936. }
  1937. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  1938. {
  1939. if (button == buttonInfo.type)
  1940. {
  1941. if (wasDown == isDown)
  1942. sendButtonChangeToListeners (timestamp, ! isDown);
  1943. sendButtonChangeToListeners (timestamp, isDown);
  1944. wasDown = isDown;
  1945. }
  1946. }
  1947. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  1948. {
  1949. if (isDown)
  1950. listeners.call ([&] (ControlButton::Listener& l) { l.buttonPressed (*this, timestamp); });
  1951. else
  1952. listeners.call ([&] (ControlButton::Listener& l) { l.buttonReleased (*this, timestamp); });
  1953. }
  1954. BlockImplementation& blockImpl;
  1955. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  1956. int buttonIndex;
  1957. bool wasDown = false;
  1958. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  1959. };
  1960. //==============================================================================
  1961. struct StatusLightImplementation : public StatusLight
  1962. {
  1963. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  1964. {
  1965. }
  1966. juce::String getName() const override { return info.name; }
  1967. bool setColour (LEDColour newColour) override
  1968. {
  1969. // XXX TODO!
  1970. juce::ignoreUnused (newColour);
  1971. return false;
  1972. }
  1973. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  1974. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  1975. };
  1976. //==============================================================================
  1977. struct LEDGridImplementation : public LEDGrid
  1978. {
  1979. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  1980. {
  1981. }
  1982. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  1983. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  1984. BlockImplementation& blockImpl;
  1985. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  1986. };
  1987. //==============================================================================
  1988. #if DUMP_TOPOLOGY
  1989. static juce::String idToSerialNum (const BlockTopology& topology, Block::UID uid)
  1990. {
  1991. for (auto* b : topology.blocks)
  1992. if (b->uid == uid)
  1993. return b->serialNumber;
  1994. return "???";
  1995. }
  1996. static juce::String portEdgeToString (Block::ConnectionPort port)
  1997. {
  1998. switch (port.edge)
  1999. {
  2000. case Block::ConnectionPort::DeviceEdge::north: return "north";
  2001. case Block::ConnectionPort::DeviceEdge::south: return "south";
  2002. case Block::ConnectionPort::DeviceEdge::east: return "east";
  2003. case Block::ConnectionPort::DeviceEdge::west: return "west";
  2004. }
  2005. return {};
  2006. }
  2007. static juce::String portToString (Block::ConnectionPort port)
  2008. {
  2009. return portEdgeToString (port) + "_" + juce::String (port.index);
  2010. }
  2011. static void dumpTopology (const BlockTopology& topology)
  2012. {
  2013. MemoryOutputStream m;
  2014. m << "=============================================================================" << newLine
  2015. << "Topology: " << topology.blocks.size() << " device(s)" << newLine
  2016. << newLine;
  2017. int index = 0;
  2018. for (auto block : topology.blocks)
  2019. {
  2020. m << "Device " << index++ << (block->isMasterBlock() ? ": (MASTER)" : ":") << newLine;
  2021. m << " Description: " << block->getDeviceDescription() << newLine
  2022. << " Serial: " << block->serialNumber << newLine;
  2023. if (auto bi = BlockImplementation::getFrom (*block))
  2024. m << " Short address: " << (int) bi->getDeviceIndex() << newLine;
  2025. m << " Battery level: " + juce::String (juce::roundToInt (100.0f * block->getBatteryLevel())) + "%" << newLine
  2026. << " Battery charging: " + juce::String (block->isBatteryCharging() ? "y" : "n") << newLine
  2027. << " Width: " << block->getWidth() << newLine
  2028. << " Height: " << block->getHeight() << newLine
  2029. << " Millimeters per unit: " << block->getMillimetersPerUnit() << newLine
  2030. << newLine;
  2031. }
  2032. for (auto& connection : topology.connections)
  2033. {
  2034. m << idToSerialNum (topology, connection.device1)
  2035. << ":" << portToString (connection.connectionPortOnDevice1)
  2036. << " <-> "
  2037. << idToSerialNum (topology, connection.device2)
  2038. << ":" << portToString (connection.connectionPortOnDevice2) << newLine;
  2039. }
  2040. m << "=============================================================================" << newLine;
  2041. Logger::outputDebugString (m.toString());
  2042. }
  2043. #endif
  2044. };
  2045. //==============================================================================
  2046. struct PhysicalTopologySource::DetectorHolder : private juce::Timer
  2047. {
  2048. DetectorHolder (PhysicalTopologySource& pts)
  2049. : topologySource (pts),
  2050. detector (Internal::Detector::getDefaultDetector())
  2051. {
  2052. startTimerHz (30);
  2053. }
  2054. DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
  2055. : topologySource (pts),
  2056. detector (new Internal::Detector (dd))
  2057. {
  2058. startTimerHz (30);
  2059. }
  2060. void timerCallback() override
  2061. {
  2062. if (! topologySource.hasOwnServiceTimer())
  2063. handleTimerTick();
  2064. }
  2065. void handleTimerTick()
  2066. {
  2067. for (auto& b : detector->currentTopology.blocks)
  2068. if (auto bi = Internal::BlockImplementation::getFrom (*b))
  2069. bi->handleTimerTick();
  2070. }
  2071. PhysicalTopologySource& topologySource;
  2072. Internal::Detector::Ptr detector;
  2073. };
  2074. //==============================================================================
  2075. PhysicalTopologySource::PhysicalTopologySource()
  2076. : detector (new DetectorHolder (*this))
  2077. {
  2078. detector->detector->activeTopologySources.add (this);
  2079. }
  2080. PhysicalTopologySource::PhysicalTopologySource (DeviceDetector& detectorToUse)
  2081. : detector (new DetectorHolder (*this, detectorToUse))
  2082. {
  2083. detector->detector->activeTopologySources.add (this);
  2084. }
  2085. PhysicalTopologySource::~PhysicalTopologySource()
  2086. {
  2087. detector->detector->detach (this);
  2088. detector = nullptr;
  2089. }
  2090. BlockTopology PhysicalTopologySource::getCurrentTopology() const
  2091. {
  2092. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  2093. return detector->detector->currentTopology;
  2094. }
  2095. void PhysicalTopologySource::cancelAllActiveTouches() noexcept
  2096. {
  2097. detector->detector->cancelAllActiveTouches();
  2098. }
  2099. bool PhysicalTopologySource::hasOwnServiceTimer() const { return false; }
  2100. void PhysicalTopologySource::handleTimerTick() { detector->handleTimerTick(); }
  2101. PhysicalTopologySource::DeviceConnection::DeviceConnection() {}
  2102. PhysicalTopologySource::DeviceConnection::~DeviceConnection() {}
  2103. PhysicalTopologySource::DeviceDetector::DeviceDetector() {}
  2104. PhysicalTopologySource::DeviceDetector::~DeviceDetector() {}
  2105. const char* const* PhysicalTopologySource::getStandardLittleFootFunctions() noexcept
  2106. {
  2107. return BlocksProtocol::ledProgramLittleFootFunctions;
  2108. }
  2109. template <typename ListType>
  2110. static bool collectionsMatch (const ListType& list1, const ListType& list2) noexcept
  2111. {
  2112. if (list1.size() != list2.size())
  2113. return false;
  2114. for (auto&& b : list1)
  2115. if (! list2.contains (b))
  2116. return false;
  2117. return true;
  2118. }
  2119. bool BlockTopology::operator== (const BlockTopology& other) const noexcept
  2120. {
  2121. return collectionsMatch (connections, other.connections) && collectionsMatch (blocks, other.blocks);
  2122. }
  2123. bool BlockTopology::operator!= (const BlockTopology& other) const noexcept
  2124. {
  2125. return ! operator== (other);
  2126. }
  2127. bool BlockDeviceConnection::operator== (const BlockDeviceConnection& other) const noexcept
  2128. {
  2129. return (device1 == other.device1 && device2 == other.device2
  2130. && connectionPortOnDevice1 == other.connectionPortOnDevice1
  2131. && connectionPortOnDevice2 == other.connectionPortOnDevice2)
  2132. || (device1 == other.device2 && device2 == other.device1
  2133. && connectionPortOnDevice1 == other.connectionPortOnDevice2
  2134. && connectionPortOnDevice2 == other.connectionPortOnDevice1);
  2135. }
  2136. bool BlockDeviceConnection::operator!= (const BlockDeviceConnection& other) const noexcept
  2137. {
  2138. return ! operator== (other);
  2139. }
  2140. } // namespace juce