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.

1858 lines
65KB

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