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.

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