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.

2399 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. topologyBroadcastThrottle.lastTopology = {};
  708. auto& d = getDefaultDetectorPointer();
  709. if (d != nullptr && d->getReferenceCount() == 2)
  710. getDefaultDetectorPointer() = nullptr;
  711. }
  712. }
  713. bool isConnected (Block::UID deviceID) const noexcept
  714. {
  715. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  716. for (auto&& b : currentTopology.blocks)
  717. if (b->uid == deviceID)
  718. return true;
  719. return false;
  720. }
  721. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  722. {
  723. for (auto d : connectedDeviceGroups)
  724. if (auto status = d->getLastStatus (deviceID))
  725. return status;
  726. return nullptr;
  727. }
  728. void handleTopologyChange()
  729. {
  730. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  731. {
  732. juce::Array<DeviceInfo> newDeviceInfo;
  733. juce::Array<BlockDeviceConnection> newDeviceConnections;
  734. for (auto d : connectedDeviceGroups)
  735. {
  736. newDeviceInfo.addArray (d->currentDeviceInfo);
  737. newDeviceConnections.addArray (d->currentDeviceConnections);
  738. }
  739. for (int i = currentTopology.blocks.size(); --i >= 0;)
  740. {
  741. auto block = currentTopology.blocks.getUnchecked (i);
  742. if (! containsBlockWithUID (newDeviceInfo, block->uid))
  743. {
  744. if (auto bi = BlockImplementation::getFrom (*block))
  745. bi->invalidate();
  746. currentTopology.blocks.remove (i);
  747. }
  748. else
  749. {
  750. if (versionNumberAddedToBlock (newDeviceInfo, block->uid, block->versionNumber))
  751. setVersionNumberForBlock (newDeviceInfo, *block);
  752. if (nameAddedToBlock (newDeviceInfo, block->uid))
  753. setNameForBlock (newDeviceInfo, *block);
  754. }
  755. }
  756. for (auto& info : newDeviceInfo)
  757. if (info.serial.isValid())
  758. if (! containsBlockWithUID (currentTopology.blocks, getBlockUIDFromSerialNumber (info.serial)))
  759. currentTopology.blocks.add (new BlockImplementation (info.serial, *this, info.version, info.name, info.isMaster));
  760. currentTopology.connections.swapWith (newDeviceConnections);
  761. }
  762. topologyBroadcastThrottle.scheduleTopologyChangeCallback();
  763. }
  764. void handleSharedDataACK (Block::UID deviceID, uint32 packetCounter) const
  765. {
  766. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  767. for (auto&& b : currentTopology.blocks)
  768. if (b->uid == deviceID)
  769. if (auto bi = BlockImplementation::getFrom (*b))
  770. bi->handleSharedDataACK (packetCounter);
  771. }
  772. void handleFirmwareUpdateACK (Block::UID deviceID, uint8 resultCode, uint32 resultDetail)
  773. {
  774. for (auto&& b : currentTopology.blocks)
  775. if (b->uid == deviceID)
  776. if (auto bi = BlockImplementation::getFrom (*b))
  777. bi->handleFirmwareUpdateACK (resultCode, resultDetail);
  778. }
  779. void handleConfigUpdateMessage (Block::UID deviceID, int32 item, int32 value, int32 min, int32 max)
  780. {
  781. for (auto&& b : currentTopology.blocks)
  782. if (b->uid == deviceID)
  783. if (auto bi = BlockImplementation::getFrom (*b))
  784. bi->handleConfigUpdateMessage (item, value, min, max);
  785. }
  786. void notifyBlockOfConfigChange (BlockImplementation& bi, uint32 item)
  787. {
  788. if (auto configChangedCallback = bi.configChangedCallback)
  789. {
  790. if (item >= bi.getMaxConfigIndex())
  791. configChangedCallback (bi, {}, item);
  792. else
  793. configChangedCallback (bi, bi.getLocalConfigMetaData (item), item);
  794. }
  795. }
  796. void handleConfigSetMessage (Block::UID deviceID, int32 item, int32 value)
  797. {
  798. for (auto&& b : currentTopology.blocks)
  799. {
  800. if (b->uid == deviceID)
  801. {
  802. if (auto bi = BlockImplementation::getFrom (*b))
  803. {
  804. bi->handleConfigSetMessage (item, value);
  805. notifyBlockOfConfigChange (*bi, uint32 (item));
  806. }
  807. }
  808. }
  809. }
  810. void handleConfigFactorySyncEndMessage (Block::UID deviceID)
  811. {
  812. for (auto&& b : currentTopology.blocks)
  813. if (b->uid == deviceID)
  814. if (auto bi = BlockImplementation::getFrom (*b))
  815. notifyBlockOfConfigChange (*bi, bi->getMaxConfigIndex());
  816. }
  817. void handleLogMessage (Block::UID deviceID, const String& message) const
  818. {
  819. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  820. for (auto&& b : currentTopology.blocks)
  821. if (b->uid == deviceID)
  822. if (auto bi = BlockImplementation::getFrom (*b))
  823. bi->handleLogMessage (message);
  824. }
  825. void handleButtonChange (Block::UID deviceID, Block::Timestamp timestamp, uint32 buttonIndex, bool isDown) const
  826. {
  827. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  828. for (auto b : activeControlButtons)
  829. {
  830. if (b->block.uid == deviceID)
  831. {
  832. if (auto bi = BlockImplementation::getFrom (b->block))
  833. {
  834. bi->pingFromDevice();
  835. if (buttonIndex < (uint32) bi->modelData.buttons.size())
  836. b->broadcastButtonChange (timestamp, bi->modelData.buttons[(int) buttonIndex].type, isDown);
  837. }
  838. }
  839. }
  840. }
  841. void handleTouchChange (Block::UID deviceID, const TouchSurface::Touch& touchEvent)
  842. {
  843. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  844. for (auto t : activeTouchSurfaces)
  845. {
  846. if (t->block.uid == deviceID)
  847. {
  848. TouchSurface::Touch scaledEvent (touchEvent);
  849. scaledEvent.x *= t->block.getWidth();
  850. scaledEvent.y *= t->block.getHeight();
  851. scaledEvent.startX *= t->block.getWidth();
  852. scaledEvent.startY *= t->block.getHeight();
  853. t->broadcastTouchChange (scaledEvent);
  854. }
  855. }
  856. }
  857. void cancelAllActiveTouches() noexcept
  858. {
  859. for (auto surface : activeTouchSurfaces)
  860. surface->cancelAllActiveTouches();
  861. }
  862. void handleCustomMessage (Block::UID deviceID, Block::Timestamp timestamp, const int32* data)
  863. {
  864. for (auto&& b : currentTopology.blocks)
  865. if (b->uid == deviceID)
  866. if (auto bi = BlockImplementation::getFrom (*b))
  867. bi->handleCustomMessage (timestamp, data);
  868. }
  869. //==============================================================================
  870. int getIndexFromDeviceID (Block::UID deviceID) const noexcept
  871. {
  872. for (auto* c : connectedDeviceGroups)
  873. {
  874. auto index = c->getIndexFromDeviceID (deviceID);
  875. if (index >= 0)
  876. return index;
  877. }
  878. return -1;
  879. }
  880. template <typename PacketBuilder>
  881. bool sendMessageToDevice (Block::UID deviceID, const PacketBuilder& builder) const
  882. {
  883. for (auto* c : connectedDeviceGroups)
  884. if (c->getIndexFromDeviceID (deviceID) >= 0)
  885. return c->sendMessageToDevice (builder);
  886. return false;
  887. }
  888. static Detector* getFrom (Block& b) noexcept
  889. {
  890. if (auto* bi = BlockImplementation::getFrom (b))
  891. return &(bi->detector);
  892. jassertfalse;
  893. return nullptr;
  894. }
  895. DeviceConnection* getDeviceConnectionFor (const Block& b)
  896. {
  897. for (const auto& d : connectedDeviceGroups)
  898. {
  899. for (const auto& info : d->currentDeviceInfo)
  900. {
  901. if (info.uid == b.uid)
  902. return d->getDeviceConnection();
  903. }
  904. }
  905. return nullptr;
  906. }
  907. std::unique_ptr<MIDIDeviceDetector> defaultDetector;
  908. DeviceDetector& deviceDetector;
  909. juce::Array<PhysicalTopologySource*> activeTopologySources;
  910. juce::Array<ControlButtonImplementation*> activeControlButtons;
  911. juce::Array<TouchSurfaceImplementation*> activeTouchSurfaces;
  912. BlockTopology currentTopology;
  913. private:
  914. void timerCallback() override
  915. {
  916. startTimer (1500);
  917. auto detectedDevices = deviceDetector.scanForDevices();
  918. handleDevicesRemoved (detectedDevices);
  919. handleDevicesAdded (detectedDevices);
  920. }
  921. void handleDevicesRemoved (const juce::StringArray& detectedDevices)
  922. {
  923. bool anyDevicesRemoved = false;
  924. for (int i = connectedDeviceGroups.size(); --i >= 0;)
  925. {
  926. if (! connectedDeviceGroups.getUnchecked(i)->isStillConnected (detectedDevices))
  927. {
  928. connectedDeviceGroups.remove (i);
  929. anyDevicesRemoved = true;
  930. }
  931. }
  932. if (anyDevicesRemoved)
  933. handleTopologyChange();
  934. }
  935. void handleDevicesAdded (const juce::StringArray& detectedDevices)
  936. {
  937. bool anyDevicesAdded = false;
  938. for (const auto& devName : detectedDevices)
  939. {
  940. if (! hasDeviceFor (devName))
  941. {
  942. if (auto d = deviceDetector.openDevice (detectedDevices.indexOf (devName)))
  943. {
  944. connectedDeviceGroups.add (new ConnectedDeviceGroup (*this, devName, d));
  945. anyDevicesAdded = true;
  946. }
  947. }
  948. }
  949. if (anyDevicesAdded)
  950. handleTopologyChange();
  951. }
  952. bool hasDeviceFor (const juce::String& devName) const
  953. {
  954. for (auto d : connectedDeviceGroups)
  955. if (d->deviceName == devName)
  956. return true;
  957. return false;
  958. }
  959. juce::OwnedArray<ConnectedDeviceGroup> connectedDeviceGroups;
  960. //==============================================================================
  961. /** Flurries of topology messages sometimes arrive due to loose connections.
  962. Avoid informing listeners until they've stabilised.
  963. */
  964. struct TopologyBroadcastThrottle : private juce::Timer
  965. {
  966. TopologyBroadcastThrottle() = default;
  967. void scheduleTopologyChangeCallback()
  968. {
  969. #ifdef JUCE_BLOCKS_TOPOLOGY_BROADCAST_THROTTLE_TIME
  970. startTimer (JUCE_BLOCKS_TOPOLOGY_BROADCAST_THROTTLE_TIME);
  971. #else
  972. startTimer (750);
  973. #endif
  974. }
  975. void timerCallback() override
  976. {
  977. if (detector->currentTopology != lastTopology)
  978. {
  979. lastTopology = detector->currentTopology;
  980. for (auto* d : detector->activeTopologySources)
  981. d->listeners.call ([] (TopologySource::Listener& l) { l.topologyChanged(); });
  982. #if DUMP_TOPOLOGY
  983. dumpTopology (lastTopology);
  984. #endif
  985. }
  986. stopTimer();
  987. }
  988. Detector* detector = nullptr;
  989. BlockTopology lastTopology;
  990. };
  991. TopologyBroadcastThrottle topologyBroadcastThrottle;
  992. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Detector)
  993. };
  994. //==============================================================================
  995. struct BlockImplementation : public Block,
  996. private MIDIDeviceConnection::Listener,
  997. private Timer
  998. {
  999. BlockImplementation (const BlocksProtocol::BlockSerialNumber& serial, Detector& detectorToUse, BlocksProtocol::VersionNumber version, BlocksProtocol::BlockName name, bool master)
  1000. : Block (juce::String ((const char*) serial.serial, sizeof (serial.serial)),
  1001. juce::String ((const char*) version.version, version.length),
  1002. juce::String ((const char*) name.name, name.length)),
  1003. modelData (serial),
  1004. remoteHeap (modelData.programAndHeapSize),
  1005. detector (detectorToUse),
  1006. isMaster (master)
  1007. {
  1008. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1009. if (modelData.hasTouchSurface)
  1010. touchSurface.reset (new TouchSurfaceImplementation (*this));
  1011. int i = 0;
  1012. for (auto&& b : modelData.buttons)
  1013. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  1014. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  1015. ledGrid.reset (new LEDGridImplementation (*this));
  1016. for (auto&& s : modelData.statusLEDs)
  1017. statusLights.add (new StatusLightImplementation (*this, s));
  1018. if (modelData.numLEDRowLEDs > 0)
  1019. ledRow.reset (new LEDRowImplementation (*this));
  1020. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this));
  1021. if (listenerToMidiConnection != nullptr)
  1022. listenerToMidiConnection->addListener (this);
  1023. config.setDeviceComms (listenerToMidiConnection);
  1024. }
  1025. ~BlockImplementation()
  1026. {
  1027. if (listenerToMidiConnection != nullptr)
  1028. {
  1029. config.setDeviceComms (nullptr);
  1030. listenerToMidiConnection->removeListener (this);
  1031. }
  1032. }
  1033. void invalidate()
  1034. {
  1035. isStillConnected = false;
  1036. }
  1037. Type getType() const override { return modelData.apiType; }
  1038. juce::String getDeviceDescription() const override { return modelData.description; }
  1039. int getWidth() const override { return modelData.widthUnits; }
  1040. int getHeight() const override { return modelData.heightUnits; }
  1041. float getMillimetersPerUnit() const override { return 47.0f; }
  1042. bool isHardwareBlock() const override { return true; }
  1043. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  1044. bool isConnected() const override { return isStillConnected && detector.isConnected (uid); }
  1045. bool isMasterBlock() const override { return isMaster; }
  1046. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  1047. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  1048. LEDRow* getLEDRow() const override { return ledRow.get(); }
  1049. juce::Array<ControlButton*> getButtons() const override
  1050. {
  1051. juce::Array<ControlButton*> result;
  1052. result.addArray (controlButtons);
  1053. return result;
  1054. }
  1055. juce::Array<StatusLight*> getStatusLights() const override
  1056. {
  1057. juce::Array<StatusLight*> result;
  1058. result.addArray (statusLights);
  1059. return result;
  1060. }
  1061. float getBatteryLevel() const override
  1062. {
  1063. if (auto status = detector.getLastStatus (uid))
  1064. return status->batteryLevel.toUnipolarFloat();
  1065. return 0.0f;
  1066. }
  1067. bool isBatteryCharging() const override
  1068. {
  1069. if (auto status = detector.getLastStatus (uid))
  1070. return status->batteryCharging.get() != 0;
  1071. return false;
  1072. }
  1073. bool supportsGraphics() const override
  1074. {
  1075. return false;
  1076. }
  1077. int getDeviceIndex() const noexcept
  1078. {
  1079. return isConnected() ? detector.getIndexFromDeviceID (uid) : -1;
  1080. }
  1081. template <typename PacketBuilder>
  1082. bool sendMessageToDevice (const PacketBuilder& builder)
  1083. {
  1084. lastMessageSendTime = juce::Time::getCurrentTime();
  1085. return detector.sendMessageToDevice (uid, builder);
  1086. }
  1087. bool sendCommandMessage (uint32 commandID)
  1088. {
  1089. int index = getDeviceIndex();
  1090. if (index < 0)
  1091. return false;
  1092. BlocksProtocol::HostPacketBuilder<64> p;
  1093. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1094. p.deviceControlMessage (commandID);
  1095. p.writePacketSysexFooter();
  1096. return sendMessageToDevice (p);
  1097. }
  1098. void handleCustomMessage (Block::Timestamp, const int32* data)
  1099. {
  1100. ProgramEventMessage m;
  1101. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  1102. m.values[i] = data[i];
  1103. programEventListeners.call ([&] (ProgramEventListener& l) { l.handleProgramEvent (*this, m); });
  1104. }
  1105. static BlockImplementation* getFrom (Block& b) noexcept
  1106. {
  1107. if (auto bi = dynamic_cast<BlockImplementation*> (&b))
  1108. return bi;
  1109. jassertfalse;
  1110. return nullptr;
  1111. }
  1112. bool isControlBlock() const
  1113. {
  1114. auto type = getType();
  1115. return type == Block::Type::liveBlock
  1116. || type == Block::Type::loopBlock
  1117. || type == Block::Type::touchBlock
  1118. || type == Block::Type::developerControlBlock;
  1119. }
  1120. //==============================================================================
  1121. std::function<void(const String&)> logger;
  1122. void setLogger (std::function<void(const String&)> newLogger) override
  1123. {
  1124. logger = newLogger;
  1125. }
  1126. void handleLogMessage (const String& message) const
  1127. {
  1128. if (logger != nullptr)
  1129. logger (message);
  1130. }
  1131. //==============================================================================
  1132. juce::Result setProgram (Program* newProgram) override
  1133. {
  1134. if (newProgram == nullptr || program.get() != newProgram)
  1135. {
  1136. {
  1137. std::unique_ptr<Program> p (newProgram);
  1138. if (program != nullptr
  1139. && newProgram != nullptr
  1140. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  1141. return juce::Result::ok();
  1142. stopTimer();
  1143. std::swap (program, p);
  1144. }
  1145. stopTimer();
  1146. programSize = 0;
  1147. if (program != nullptr)
  1148. {
  1149. littlefoot::Compiler compiler;
  1150. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  1151. auto err = compiler.compile (program->getLittleFootProgram(), 512);
  1152. if (err.failed())
  1153. return err;
  1154. DBG ("Compiled littlefoot program, space needed: "
  1155. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  1156. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  1157. return Result::fail ("Program too large!");
  1158. auto size = (size_t) compiler.compiledObjectCode.size();
  1159. programSize = (uint32) size;
  1160. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  1161. remoteHeap.clear();
  1162. remoteHeap.sendChanges (*this, true);
  1163. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  1164. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  1165. remoteHeap.sendChanges (*this, true);
  1166. this->resetConfigListActiveStatus();
  1167. if (auto changeCallback = this->configChangedCallback)
  1168. changeCallback (*this, {}, this->getMaxConfigIndex());
  1169. }
  1170. else
  1171. {
  1172. remoteHeap.clear();
  1173. }
  1174. }
  1175. else
  1176. {
  1177. jassertfalse;
  1178. }
  1179. return juce::Result::ok();
  1180. }
  1181. Program* getProgram() const override { return program.get(); }
  1182. void sendProgramEvent (const ProgramEventMessage& message) override
  1183. {
  1184. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  1185. "Need to keep the internal and external messages structures the same");
  1186. if (remoteHeap.isProgramLoaded())
  1187. {
  1188. auto index = getDeviceIndex();
  1189. if (index >= 0)
  1190. {
  1191. BlocksProtocol::HostPacketBuilder<128> p;
  1192. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1193. if (p.addProgramEventMessage (message.values))
  1194. {
  1195. p.writePacketSysexFooter();
  1196. sendMessageToDevice (p);
  1197. }
  1198. }
  1199. else
  1200. {
  1201. jassertfalse;
  1202. }
  1203. }
  1204. }
  1205. void timerCallback() override
  1206. {
  1207. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  1208. {
  1209. stopTimer();
  1210. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  1211. }
  1212. else
  1213. {
  1214. startTimer (100);
  1215. }
  1216. }
  1217. void saveProgramAsDefault() override
  1218. {
  1219. startTimer (10);
  1220. }
  1221. uint32 getMemorySize() override
  1222. {
  1223. return modelData.programAndHeapSize;
  1224. }
  1225. void setDataByte (size_t offset, uint8 value) override
  1226. {
  1227. remoteHeap.setByte (programSize + offset, value);
  1228. }
  1229. void setDataBytes (size_t offset, const void* newData, size_t num) override
  1230. {
  1231. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  1232. }
  1233. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  1234. {
  1235. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  1236. }
  1237. uint8 getDataByte (size_t offset) override
  1238. {
  1239. return remoteHeap.getByte (programSize + offset);
  1240. }
  1241. void handleSharedDataACK (uint32 packetCounter) noexcept
  1242. {
  1243. pingFromDevice();
  1244. remoteHeap.handleACKFromDevice (*this, packetCounter);
  1245. }
  1246. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void (uint8, uint32)> callback) override
  1247. {
  1248. firmwarePacketAckCallback = {};
  1249. auto index = getDeviceIndex();
  1250. if (index >= 0)
  1251. {
  1252. BlocksProtocol::HostPacketBuilder<256> p;
  1253. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1254. if (p.addFirmwareUpdatePacket (data, size))
  1255. {
  1256. p.writePacketSysexFooter();
  1257. if (sendMessageToDevice (p))
  1258. {
  1259. firmwarePacketAckCallback = callback;
  1260. return true;
  1261. }
  1262. }
  1263. }
  1264. else
  1265. {
  1266. jassertfalse;
  1267. }
  1268. return false;
  1269. }
  1270. void handleFirmwareUpdateACK (uint8 resultCode, uint32 resultDetail)
  1271. {
  1272. if (firmwarePacketAckCallback != nullptr)
  1273. {
  1274. firmwarePacketAckCallback (resultCode, resultDetail);
  1275. firmwarePacketAckCallback = {};
  1276. }
  1277. }
  1278. void handleConfigUpdateMessage (int32 item, int32 value, int32 min, int32 max)
  1279. {
  1280. config.handleConfigUpdateMessage (item, value, min, max);
  1281. }
  1282. void handleConfigSetMessage(int32 item, int32 value)
  1283. {
  1284. config.handleConfigSetMessage (item, value);
  1285. }
  1286. void pingFromDevice()
  1287. {
  1288. lastMessageReceiveTime = juce::Time::getCurrentTime();
  1289. }
  1290. void addDataInputPortListener (DataInputPortListener* listener) override
  1291. {
  1292. Block::addDataInputPortListener (listener);
  1293. if (auto midiInput = getMidiInput())
  1294. midiInput->start();
  1295. }
  1296. void sendMessage (const void* message, size_t messageSize) override
  1297. {
  1298. if (auto midiOutput = getMidiOutput())
  1299. midiOutput->sendMessageNow ({ message, (int) messageSize });
  1300. }
  1301. void handleTimerTick()
  1302. {
  1303. if (++resetMessagesSent < 3)
  1304. {
  1305. if (resetMessagesSent == 1)
  1306. sendCommandMessage (BlocksProtocol::endAPIMode);
  1307. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1308. return;
  1309. }
  1310. if (ledGrid != nullptr)
  1311. if (auto renderer = ledGrid->getRenderer())
  1312. renderer->renderLEDGrid (*ledGrid);
  1313. remoteHeap.sendChanges (*this, false);
  1314. if (lastMessageSendTime < juce::Time::getCurrentTime() - juce::RelativeTime::milliseconds (pingIntervalMs))
  1315. sendCommandMessage (BlocksProtocol::ping);
  1316. }
  1317. //==============================================================================
  1318. int32 getLocalConfigValue (uint32 item) override
  1319. {
  1320. initialiseDeviceIndexAndConnection();
  1321. return config.getItemValue ((BlocksProtocol::ConfigItemId) item);
  1322. }
  1323. void setLocalConfigValue (uint32 item, int32 value) override
  1324. {
  1325. initialiseDeviceIndexAndConnection();
  1326. config.setItemValue ((BlocksProtocol::ConfigItemId) item, value);
  1327. }
  1328. void setLocalConfigRange (uint32 item, int32 min, int32 max) override
  1329. {
  1330. initialiseDeviceIndexAndConnection();
  1331. config.setItemMin ((BlocksProtocol::ConfigItemId) item, min);
  1332. config.setItemMax ((BlocksProtocol::ConfigItemId) item, max);
  1333. }
  1334. void setLocalConfigItemActive (uint32 item, bool isActive) override
  1335. {
  1336. initialiseDeviceIndexAndConnection();
  1337. config.setItemActive ((BlocksProtocol::ConfigItemId) item, isActive);
  1338. }
  1339. bool isLocalConfigItemActive (uint32 item) override
  1340. {
  1341. initialiseDeviceIndexAndConnection();
  1342. return config.getItemActive ((BlocksProtocol::ConfigItemId) item);
  1343. }
  1344. uint32 getMaxConfigIndex() override
  1345. {
  1346. return uint32 (BlocksProtocol::maxConfigIndex);
  1347. }
  1348. bool isValidUserConfigIndex (uint32 item) override
  1349. {
  1350. return item >= (uint32) BlocksProtocol::ConfigItemId::user0
  1351. && item < (uint32) (BlocksProtocol::ConfigItemId::user0 + numberOfUserConfigs);
  1352. }
  1353. ConfigMetaData getLocalConfigMetaData (uint32 item) override
  1354. {
  1355. initialiseDeviceIndexAndConnection();
  1356. return config.getMetaData ((BlocksProtocol::ConfigItemId) item);
  1357. }
  1358. void requestFactoryConfigSync() override
  1359. {
  1360. initialiseDeviceIndexAndConnection();
  1361. config.requestFactoryConfigSync();
  1362. }
  1363. void resetConfigListActiveStatus() override
  1364. {
  1365. config.resetConfigListActiveStatus();
  1366. }
  1367. void setConfigChangedCallback (std::function<void(Block&, const ConfigMetaData&, uint32)> configChanged) override
  1368. {
  1369. configChangedCallback = configChanged;
  1370. }
  1371. void factoryReset() override
  1372. {
  1373. auto index = getDeviceIndex();
  1374. if (index >= 0)
  1375. {
  1376. BlocksProtocol::HostPacketBuilder<32> p;
  1377. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1378. p.addFactoryReset();
  1379. p.writePacketSysexFooter();
  1380. sendMessageToDevice (p);
  1381. }
  1382. else
  1383. {
  1384. jassertfalse;
  1385. }
  1386. }
  1387. void blockReset() override
  1388. {
  1389. auto index = getDeviceIndex();
  1390. if (index >= 0)
  1391. {
  1392. BlocksProtocol::HostPacketBuilder<32> p;
  1393. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1394. p.addBlockReset();
  1395. p.writePacketSysexFooter();
  1396. sendMessageToDevice (p);
  1397. }
  1398. else
  1399. {
  1400. jassertfalse;
  1401. }
  1402. }
  1403. bool setName (const juce::String& newName) override
  1404. {
  1405. auto index = getDeviceIndex();
  1406. if (index >= 0)
  1407. {
  1408. BlocksProtocol::HostPacketBuilder<128> p;
  1409. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1410. if (p.addSetBlockName (newName))
  1411. {
  1412. p.writePacketSysexFooter();
  1413. if (sendMessageToDevice (p))
  1414. return true;
  1415. }
  1416. }
  1417. else
  1418. {
  1419. jassertfalse;
  1420. }
  1421. return false;
  1422. }
  1423. //==============================================================================
  1424. std::unique_ptr<TouchSurface> touchSurface;
  1425. juce::OwnedArray<ControlButton> controlButtons;
  1426. std::unique_ptr<LEDGridImplementation> ledGrid;
  1427. std::unique_ptr<LEDRowImplementation> ledRow;
  1428. juce::OwnedArray<StatusLight> statusLights;
  1429. BlocksProtocol::BlockDataSheet modelData;
  1430. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  1431. static constexpr int pingIntervalMs = 400;
  1432. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  1433. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  1434. static constexpr uint32 maxPacketSize = 200;
  1435. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  1436. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  1437. RemoteHeapType remoteHeap;
  1438. Detector& detector;
  1439. juce::Time lastMessageSendTime, lastMessageReceiveTime;
  1440. BlockConfigManager config;
  1441. std::function<void(Block&, const ConfigMetaData&, uint32)> configChangedCallback;
  1442. private:
  1443. std::unique_ptr<Program> program;
  1444. uint32 programSize = 0;
  1445. std::function<void(uint8, uint32)> firmwarePacketAckCallback;
  1446. uint32 resetMessagesSent = 0;
  1447. bool isStillConnected = true;
  1448. bool isMaster = false;
  1449. void initialiseDeviceIndexAndConnection()
  1450. {
  1451. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1452. config.setDeviceComms (listenerToMidiConnection);
  1453. }
  1454. const juce::MidiInput* getMidiInput() const
  1455. {
  1456. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1457. return c->midiInput.get();
  1458. jassertfalse;
  1459. return nullptr;
  1460. }
  1461. juce::MidiInput* getMidiInput()
  1462. {
  1463. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  1464. }
  1465. const juce::MidiOutput* getMidiOutput() const
  1466. {
  1467. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1468. return c->midiOutput.get();
  1469. jassertfalse;
  1470. return nullptr;
  1471. }
  1472. juce::MidiOutput* getMidiOutput()
  1473. {
  1474. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  1475. }
  1476. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  1477. {
  1478. dataInputPortListeners.call ([&] (DataInputPortListener& l) { l.handleIncomingDataPortMessage (*this, message.getRawData(),
  1479. (size_t) message.getRawDataSize()); });
  1480. }
  1481. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  1482. {
  1483. jassert (listenerToMidiConnection == &c);
  1484. juce::ignoreUnused (c);
  1485. listenerToMidiConnection->removeListener (this);
  1486. listenerToMidiConnection = nullptr;
  1487. config.setDeviceComms (nullptr);
  1488. }
  1489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  1490. };
  1491. //==============================================================================
  1492. struct LEDRowImplementation : public LEDRow,
  1493. private Timer
  1494. {
  1495. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  1496. {
  1497. startTimer (300);
  1498. }
  1499. void setButtonColour (uint32 index, LEDColour colour)
  1500. {
  1501. if (index < 10)
  1502. {
  1503. colours[index] = colour;
  1504. flush();
  1505. }
  1506. }
  1507. int getNumLEDs() const override
  1508. {
  1509. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  1510. }
  1511. void setLEDColour (int index, LEDColour colour) override
  1512. {
  1513. if ((uint32) index < 15u)
  1514. {
  1515. colours[10 + index] = colour;
  1516. flush();
  1517. }
  1518. }
  1519. void setOverlayColour (LEDColour colour) override
  1520. {
  1521. colours[25] = colour;
  1522. flush();
  1523. }
  1524. void resetOverlayColour() override
  1525. {
  1526. setOverlayColour ({});
  1527. }
  1528. private:
  1529. LEDColour colours[26];
  1530. void timerCallback() override
  1531. {
  1532. stopTimer();
  1533. loadProgramOntoBlock();
  1534. flush();
  1535. }
  1536. void loadProgramOntoBlock()
  1537. {
  1538. if (block.getProgram() == nullptr)
  1539. {
  1540. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  1541. if (err.failed())
  1542. {
  1543. DBG (err.getErrorMessage());
  1544. jassertfalse;
  1545. }
  1546. }
  1547. }
  1548. void flush()
  1549. {
  1550. if (block.getProgram() != nullptr)
  1551. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  1552. write565Colour (16 * i, colours[i]);
  1553. }
  1554. void write565Colour (uint32 bitIndex, LEDColour colour)
  1555. {
  1556. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  1557. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  1558. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  1559. }
  1560. struct DefaultLEDGridProgram : public Block::Program
  1561. {
  1562. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  1563. juce::String getLittleFootProgram() override
  1564. {
  1565. /* Data format:
  1566. 0: 10 x 5-6-5 bits for button LED RGBs
  1567. 20: 15 x 5-6-5 bits for LED row colours
  1568. 50: 1 x 5-6-5 bits for LED row overlay colour
  1569. */
  1570. return R"littlefoot(
  1571. #heapsize: 128
  1572. int getColour (int bitIndex)
  1573. {
  1574. return makeARGB (255,
  1575. getHeapBits (bitIndex, 5) << 3,
  1576. getHeapBits (bitIndex + 5, 6) << 2,
  1577. getHeapBits (bitIndex + 11, 5) << 3);
  1578. }
  1579. int getButtonColour (int index)
  1580. {
  1581. return getColour (16 * index);
  1582. }
  1583. int getLEDColour (int index)
  1584. {
  1585. if (getHeapInt (50))
  1586. return getColour (50 * 8);
  1587. return getColour (20 * 8 + 16 * index);
  1588. }
  1589. void repaint()
  1590. {
  1591. for (int x = 0; x < 15; ++x)
  1592. fillPixel (getLEDColour (x), x, 0);
  1593. for (int i = 0; i < 10; ++i)
  1594. fillPixel (getButtonColour (i), i, 1);
  1595. }
  1596. void handleMessage (int p1, int p2) {}
  1597. )littlefoot";
  1598. }
  1599. };
  1600. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  1601. };
  1602. //==============================================================================
  1603. struct TouchSurfaceImplementation : public TouchSurface,
  1604. private juce::Timer
  1605. {
  1606. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  1607. {
  1608. if (auto det = Detector::getFrom (block))
  1609. det->activeTouchSurfaces.add (this);
  1610. startTimer (500);
  1611. }
  1612. ~TouchSurfaceImplementation()
  1613. {
  1614. if (auto det = Detector::getFrom (block))
  1615. det->activeTouchSurfaces.removeFirstMatchingValue (this);
  1616. }
  1617. int getNumberOfKeywaves() const noexcept override
  1618. {
  1619. return blockImpl.modelData.numKeywaves;
  1620. }
  1621. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  1622. {
  1623. auto& status = touches.getValue (touchEvent);
  1624. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  1625. if (touchEvent.isTouchStart && status.isActive)
  1626. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  1627. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  1628. if (! touchEvent.isTouchStart && ! status.isActive)
  1629. {
  1630. TouchSurface::Touch t (touchEvent);
  1631. t.isTouchStart = true;
  1632. t.isTouchEnd = false;
  1633. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  1634. if (t.zVelocity <= 0) t.zVelocity = t.z;
  1635. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  1636. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, t); });
  1637. }
  1638. // Normal handling:
  1639. status.lastEventTime = juce::Time::getMillisecondCounter();
  1640. status.isActive = ! touchEvent.isTouchEnd;
  1641. if (touchEvent.isTouchStart)
  1642. status.lastStrikePressure = touchEvent.zVelocity;
  1643. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, touchEvent); });
  1644. }
  1645. void timerCallback() override
  1646. {
  1647. // Find touches that seem to have become stuck, and fake a touch-end for them..
  1648. static const uint32 touchTimeOutMs = 500;
  1649. for (auto& t : touches)
  1650. {
  1651. auto& status = t.value;
  1652. auto now = juce::Time::getMillisecondCounter();
  1653. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  1654. killTouch (t.touch, status, now);
  1655. }
  1656. }
  1657. struct TouchStatus
  1658. {
  1659. uint32 lastEventTime = 0;
  1660. float lastStrikePressure = 0;
  1661. bool isActive = false;
  1662. };
  1663. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  1664. {
  1665. jassert (status.isActive);
  1666. TouchSurface::Touch killTouch (touch);
  1667. killTouch.z = 0;
  1668. killTouch.xVelocity = 0;
  1669. killTouch.yVelocity = 0;
  1670. killTouch.zVelocity = -1.0f;
  1671. killTouch.eventTimestamp = timeStamp;
  1672. killTouch.isTouchStart = false;
  1673. killTouch.isTouchEnd = true;
  1674. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, killTouch); });
  1675. status.isActive = false;
  1676. }
  1677. void cancelAllActiveTouches() noexcept override
  1678. {
  1679. const auto now = juce::Time::getMillisecondCounter();
  1680. for (auto& t : touches)
  1681. if (t.value.isActive)
  1682. killTouch (t.touch, t.value, now);
  1683. touches.clear();
  1684. }
  1685. BlockImplementation& blockImpl;
  1686. TouchList<TouchStatus> touches;
  1687. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  1688. };
  1689. //==============================================================================
  1690. struct ControlButtonImplementation : public ControlButton
  1691. {
  1692. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  1693. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  1694. {
  1695. if (auto det = Detector::getFrom (block))
  1696. det->activeControlButtons.add (this);
  1697. }
  1698. ~ControlButtonImplementation()
  1699. {
  1700. if (auto det = Detector::getFrom (block))
  1701. det->activeControlButtons.removeFirstMatchingValue (this);
  1702. }
  1703. ButtonFunction getType() const override { return buttonInfo.type; }
  1704. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  1705. float getPositionX() const override { return buttonInfo.x; }
  1706. float getPositionY() const override { return buttonInfo.y; }
  1707. bool hasLight() const override { return blockImpl.isControlBlock(); }
  1708. bool setLightColour (LEDColour colour) override
  1709. {
  1710. if (hasLight())
  1711. {
  1712. if (auto row = blockImpl.ledRow.get())
  1713. {
  1714. row->setButtonColour ((uint32) buttonIndex, colour);
  1715. return true;
  1716. }
  1717. }
  1718. return false;
  1719. }
  1720. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  1721. {
  1722. if (button == buttonInfo.type)
  1723. {
  1724. if (wasDown == isDown)
  1725. sendButtonChangeToListeners (timestamp, ! isDown);
  1726. sendButtonChangeToListeners (timestamp, isDown);
  1727. wasDown = isDown;
  1728. }
  1729. }
  1730. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  1731. {
  1732. if (isDown)
  1733. listeners.call ([&] (ControlButton::Listener& l) { l.buttonPressed (*this, timestamp); });
  1734. else
  1735. listeners.call ([&] (ControlButton::Listener& l) { l.buttonReleased (*this, timestamp); });
  1736. }
  1737. BlockImplementation& blockImpl;
  1738. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  1739. int buttonIndex;
  1740. bool wasDown = false;
  1741. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  1742. };
  1743. //==============================================================================
  1744. struct StatusLightImplementation : public StatusLight
  1745. {
  1746. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  1747. {
  1748. }
  1749. juce::String getName() const override { return info.name; }
  1750. bool setColour (LEDColour newColour) override
  1751. {
  1752. // XXX TODO!
  1753. juce::ignoreUnused (newColour);
  1754. return false;
  1755. }
  1756. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  1757. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  1758. };
  1759. //==============================================================================
  1760. struct LEDGridImplementation : public LEDGrid
  1761. {
  1762. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  1763. {
  1764. }
  1765. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  1766. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  1767. BlockImplementation& blockImpl;
  1768. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  1769. };
  1770. //==============================================================================
  1771. #if DUMP_TOPOLOGY
  1772. static juce::String idToSerialNum (const BlockTopology& topology, Block::UID uid)
  1773. {
  1774. for (auto* b : topology.blocks)
  1775. if (b->uid == uid)
  1776. return b->serialNumber;
  1777. return "???";
  1778. }
  1779. static juce::String portEdgeToString (Block::ConnectionPort port)
  1780. {
  1781. switch (port.edge)
  1782. {
  1783. case Block::ConnectionPort::DeviceEdge::north: return "north";
  1784. case Block::ConnectionPort::DeviceEdge::south: return "south";
  1785. case Block::ConnectionPort::DeviceEdge::east: return "east";
  1786. case Block::ConnectionPort::DeviceEdge::west: return "west";
  1787. }
  1788. return {};
  1789. }
  1790. static juce::String portToString (Block::ConnectionPort port)
  1791. {
  1792. return portEdgeToString (port) + "_" + juce::String (port.index);
  1793. }
  1794. static void dumpTopology (const BlockTopology& topology)
  1795. {
  1796. MemoryOutputStream m;
  1797. m << "=============================================================================" << newLine
  1798. << "Topology: " << topology.blocks.size() << " device(s)" << newLine
  1799. << newLine;
  1800. int index = 0;
  1801. for (auto block : topology.blocks)
  1802. {
  1803. m << "Device " << index++ << (block->isMasterBlock() ? ": (MASTER)" : ":") << newLine;
  1804. m << " Description: " << block->getDeviceDescription() << newLine
  1805. << " Serial: " << block->serialNumber << newLine;
  1806. if (auto bi = BlockImplementation::getFrom (*block))
  1807. m << " Short address: " << (int) bi->getDeviceIndex() << newLine;
  1808. m << " Battery level: " + juce::String (juce::roundToInt (100.0f * block->getBatteryLevel())) + "%" << newLine
  1809. << " Battery charging: " + juce::String (block->isBatteryCharging() ? "y" : "n") << newLine
  1810. << " Width: " << block->getWidth() << newLine
  1811. << " Height: " << block->getHeight() << newLine
  1812. << " Millimeters per unit: " << block->getMillimetersPerUnit() << newLine
  1813. << newLine;
  1814. }
  1815. for (auto& connection : topology.connections)
  1816. {
  1817. m << idToSerialNum (topology, connection.device1)
  1818. << ":" << portToString (connection.connectionPortOnDevice1)
  1819. << " <-> "
  1820. << idToSerialNum (topology, connection.device2)
  1821. << ":" << portToString (connection.connectionPortOnDevice2) << newLine;
  1822. }
  1823. m << "=============================================================================" << newLine;
  1824. Logger::outputDebugString (m.toString());
  1825. }
  1826. #endif
  1827. };
  1828. //==============================================================================
  1829. struct PhysicalTopologySource::DetectorHolder : private juce::Timer
  1830. {
  1831. DetectorHolder (PhysicalTopologySource& pts)
  1832. : topologySource (pts),
  1833. detector (Internal::Detector::getDefaultDetector())
  1834. {
  1835. startTimerHz (30);
  1836. }
  1837. DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
  1838. : topologySource (pts),
  1839. detector (new Internal::Detector (dd))
  1840. {
  1841. startTimerHz (30);
  1842. }
  1843. void timerCallback() override
  1844. {
  1845. if (! topologySource.hasOwnServiceTimer())
  1846. handleTimerTick();
  1847. }
  1848. void handleTimerTick()
  1849. {
  1850. for (auto& b : detector->currentTopology.blocks)
  1851. if (auto bi = Internal::BlockImplementation::getFrom (*b))
  1852. bi->handleTimerTick();
  1853. }
  1854. PhysicalTopologySource& topologySource;
  1855. Internal::Detector::Ptr detector;
  1856. };
  1857. //==============================================================================
  1858. PhysicalTopologySource::PhysicalTopologySource()
  1859. : detector (new DetectorHolder (*this))
  1860. {
  1861. detector->detector->activeTopologySources.add (this);
  1862. }
  1863. PhysicalTopologySource::PhysicalTopologySource (DeviceDetector& detectorToUse)
  1864. : detector (new DetectorHolder (*this, detectorToUse))
  1865. {
  1866. detector->detector->activeTopologySources.add (this);
  1867. }
  1868. PhysicalTopologySource::~PhysicalTopologySource()
  1869. {
  1870. detector->detector->detach (this);
  1871. detector = nullptr;
  1872. }
  1873. BlockTopology PhysicalTopologySource::getCurrentTopology() const
  1874. {
  1875. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  1876. return detector->detector->currentTopology;
  1877. }
  1878. void PhysicalTopologySource::cancelAllActiveTouches() noexcept
  1879. {
  1880. detector->detector->cancelAllActiveTouches();
  1881. }
  1882. bool PhysicalTopologySource::hasOwnServiceTimer() const { return false; }
  1883. void PhysicalTopologySource::handleTimerTick() { detector->handleTimerTick(); }
  1884. PhysicalTopologySource::DeviceConnection::DeviceConnection() {}
  1885. PhysicalTopologySource::DeviceConnection::~DeviceConnection() {}
  1886. PhysicalTopologySource::DeviceDetector::DeviceDetector() {}
  1887. PhysicalTopologySource::DeviceDetector::~DeviceDetector() {}
  1888. const char* const* PhysicalTopologySource::getStandardLittleFootFunctions() noexcept
  1889. {
  1890. return BlocksProtocol::ledProgramLittleFootFunctions;
  1891. }
  1892. static bool blocksMatch (const Block::Array& list1, const Block::Array& list2) noexcept
  1893. {
  1894. if (list1.size() != list2.size())
  1895. return false;
  1896. for (auto&& b : list1)
  1897. if (! list2.contains (b))
  1898. return false;
  1899. return true;
  1900. }
  1901. bool BlockTopology::operator== (const BlockTopology& other) const noexcept
  1902. {
  1903. return connections == other.connections && blocksMatch (blocks, other.blocks);
  1904. }
  1905. bool BlockTopology::operator!= (const BlockTopology& other) const noexcept
  1906. {
  1907. return ! operator== (other);
  1908. }
  1909. bool BlockDeviceConnection::operator== (const BlockDeviceConnection& other) const noexcept
  1910. {
  1911. return (device1 == other.device1 && device2 == other.device2
  1912. && connectionPortOnDevice1 == other.connectionPortOnDevice1
  1913. && connectionPortOnDevice2 == other.connectionPortOnDevice2)
  1914. || (device1 == other.device2 && device2 == other.device1
  1915. && connectionPortOnDevice1 == other.connectionPortOnDevice2
  1916. && connectionPortOnDevice2 == other.connectionPortOnDevice1);
  1917. }
  1918. bool BlockDeviceConnection::operator!= (const BlockDeviceConnection& other) const noexcept
  1919. {
  1920. return ! operator== (other);
  1921. }
  1922. } // namespace juce