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.

2398 lines
84KB

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