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.

1120 lines
36KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. template <typename Detector>
  20. struct BlockImplementation : public Block,
  21. private MIDIDeviceConnection::Listener,
  22. private Timer
  23. {
  24. public:
  25. struct ControlButtonImplementation;
  26. struct TouchSurfaceImsplementation;
  27. struct LEDGridImplementation;
  28. struct LEDRowImplementation;
  29. BlockImplementation (Detector& detectorToUse, const DeviceInfo& deviceInfo)
  30. : Block (deviceInfo.serial.asString(),
  31. deviceInfo.version.asString(),
  32. deviceInfo.name.asString()),
  33. modelData (deviceInfo.serial),
  34. remoteHeap (modelData.programAndHeapSize),
  35. detector (&detectorToUse)
  36. {
  37. markReconnected (deviceInfo);
  38. if (modelData.hasTouchSurface)
  39. touchSurface.reset (new TouchSurfaceImplementation (*this));
  40. int i = 0;
  41. for (auto&& b : modelData.buttons)
  42. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  43. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  44. ledGrid.reset (new LEDGridImplementation (*this));
  45. for (auto&& s : modelData.statusLEDs)
  46. statusLights.add (new StatusLightImplementation (*this, s));
  47. updateMidiConnectionListener();
  48. }
  49. ~BlockImplementation() override
  50. {
  51. markDisconnected();
  52. }
  53. void markDisconnected()
  54. {
  55. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  56. surface->disableTouchSurface();
  57. disconnectMidiConnectionListener();
  58. connectionTime = Time();
  59. }
  60. void markReconnected (const DeviceInfo& deviceInfo)
  61. {
  62. if (wasPowerCycled())
  63. resetPowerCycleFlag();
  64. if (connectionTime == Time())
  65. connectionTime = Time::getCurrentTime();
  66. updateDeviceInfo (deviceInfo);
  67. setProgram (nullptr);
  68. remoteHeap.resetDeviceStateToUnknown();
  69. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  70. surface->activateTouchSurface();
  71. updateMidiConnectionListener();
  72. }
  73. void updateDeviceInfo (const DeviceInfo& deviceInfo)
  74. {
  75. versionNumber = deviceInfo.version.asString();
  76. name = deviceInfo.name.asString();
  77. isMaster = deviceInfo.isMaster;
  78. masterUID = deviceInfo.masterUid;
  79. batteryCharging = deviceInfo.batteryCharging;
  80. batteryLevel = deviceInfo.batteryLevel;
  81. topologyIndex = deviceInfo.index;
  82. }
  83. void setToMaster (bool shouldBeMaster)
  84. {
  85. isMaster = shouldBeMaster;
  86. }
  87. void updateMidiConnectionListener()
  88. {
  89. if (detector == nullptr)
  90. return;
  91. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector->getDeviceConnectionFor (*this));
  92. if (listenerToMidiConnection != nullptr)
  93. listenerToMidiConnection->addListener (this);
  94. config.setDeviceComms (listenerToMidiConnection);
  95. }
  96. void disconnectMidiConnectionListener()
  97. {
  98. if (listenerToMidiConnection != nullptr)
  99. {
  100. config.setDeviceComms (nullptr);
  101. listenerToMidiConnection->removeListener (this);
  102. listenerToMidiConnection = nullptr;
  103. }
  104. }
  105. bool isConnected() const override
  106. {
  107. if (detector != nullptr)
  108. return detector->isConnected (uid);
  109. return false;
  110. }
  111. bool isConnectedViaBluetooth() const override
  112. {
  113. if (detector != nullptr)
  114. return detector->isConnectedViaBluetooth (*this);
  115. return false;
  116. }
  117. Type getType() const override { return modelData.apiType; }
  118. String getDeviceDescription() const override { return modelData.description; }
  119. int getWidth() const override { return modelData.widthUnits; }
  120. int getHeight() const override { return modelData.heightUnits; }
  121. float getMillimetersPerUnit() const override { return 47.0f; }
  122. bool isHardwareBlock() const override { return true; }
  123. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  124. Time getConnectionTime() const override { return connectionTime; }
  125. bool isMasterBlock() const override { return isMaster; }
  126. Block::UID getConnectedMasterUID() const override { return masterUID; }
  127. int getRotation() const override { return rotation; }
  128. BlockArea getBlockAreaWithinLayout() const override
  129. {
  130. if (rotation % 2 == 0)
  131. return { position.first, position.second, modelData.widthUnits, modelData.heightUnits };
  132. return { position.first, position.second, modelData.heightUnits, modelData.widthUnits };
  133. }
  134. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  135. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  136. LEDRow* getLEDRow() override
  137. {
  138. if (ledRow == nullptr && modelData.numLEDRowLEDs > 0)
  139. ledRow.reset (new LEDRowImplementation (*this));
  140. return ledRow.get();
  141. }
  142. juce::Array<ControlButton*> getButtons() const override
  143. {
  144. juce::Array<ControlButton*> result;
  145. result.addArray (controlButtons);
  146. return result;
  147. }
  148. juce::Array<StatusLight*> getStatusLights() const override
  149. {
  150. juce::Array<StatusLight*> result;
  151. result.addArray (statusLights);
  152. return result;
  153. }
  154. float getBatteryLevel() const override
  155. {
  156. return batteryLevel.toUnipolarFloat();
  157. }
  158. bool isBatteryCharging() const override
  159. {
  160. return batteryCharging.get() > 0;
  161. }
  162. bool supportsGraphics() const override
  163. {
  164. return false;
  165. }
  166. int getDeviceIndex() const noexcept
  167. {
  168. return isConnected() ? topologyIndex : -1;
  169. }
  170. template <typename PacketBuilder>
  171. bool sendMessageToDevice (const PacketBuilder& builder)
  172. {
  173. if (detector != nullptr)
  174. {
  175. lastMessageSendTime = Time::getCurrentTime();
  176. return detector->sendMessageToDevice (uid, builder);
  177. }
  178. return false;
  179. }
  180. bool sendCommandMessage (uint32 commandID)
  181. {
  182. return buildAndSendPacket<64> ([commandID] (BlocksProtocol::HostPacketBuilder<64>& p)
  183. { return p.deviceControlMessage (commandID); });
  184. }
  185. void handleCustomMessage (Block::Timestamp, const int32* data)
  186. {
  187. ProgramEventMessage m;
  188. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  189. m.values[i] = data[i];
  190. programEventListeners.call ([&] (ProgramEventListener& l) { l.handleProgramEvent (*this, m); });
  191. }
  192. static BlockImplementation* getFrom (Block* b) noexcept
  193. {
  194. jassert (dynamic_cast<BlockImplementation*> (b) != nullptr);
  195. return dynamic_cast<BlockImplementation*> (b);
  196. }
  197. static BlockImplementation* getFrom (Block& b) noexcept
  198. {
  199. return getFrom (&b);
  200. }
  201. //==============================================================================
  202. std::function<void(const Block& block, const String&)> logger;
  203. void setLogger (std::function<void(const Block& block, const String&)> newLogger) override
  204. {
  205. logger = std::move (newLogger);
  206. }
  207. void handleLogMessage (const String& message) const
  208. {
  209. if (logger != nullptr)
  210. logger (*this, message);
  211. }
  212. //==============================================================================
  213. Result setProgram (Program* newProgram) override
  214. {
  215. if (newProgram != nullptr && program.get() == newProgram)
  216. {
  217. jassertfalse;
  218. return Result::ok();
  219. }
  220. {
  221. std::unique_ptr<Program> p (newProgram);
  222. if (program != nullptr
  223. && newProgram != nullptr
  224. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  225. return Result::ok();
  226. std::swap (program, p);
  227. }
  228. stopTimer();
  229. programSize = 0;
  230. isProgramLoaded = shouldSaveProgramAsDefault = false;
  231. if (program == nullptr)
  232. {
  233. remoteHeap.clear();
  234. return Result::ok();
  235. }
  236. littlefoot::Compiler compiler;
  237. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  238. const auto err = compiler.compile (program->getLittleFootProgram(), 512, program->getSearchPaths());
  239. if (err.failed())
  240. return err;
  241. DBG ("Compiled littlefoot program, space needed: "
  242. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  243. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  244. return Result::fail ("Program too large!");
  245. const auto size = (size_t) compiler.compiledObjectCode.size();
  246. programSize = (uint32) size;
  247. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  248. remoteHeap.clear();
  249. remoteHeap.sendChanges (*this, true);
  250. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  251. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  252. remoteHeap.sendChanges (*this, true);
  253. this->resetConfigListActiveStatus();
  254. if (auto changeCallback = this->configChangedCallback)
  255. changeCallback (*this, {}, this->getMaxConfigIndex());
  256. startTimer (20);
  257. return Result::ok();
  258. }
  259. Program* getProgram() const override { return program.get(); }
  260. void sendProgramEvent (const ProgramEventMessage& message) override
  261. {
  262. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  263. "Need to keep the internal and external messages structures the same");
  264. if (remoteHeap.isProgramLoaded())
  265. {
  266. buildAndSendPacket<128> ([&message] (BlocksProtocol::HostPacketBuilder<128>& p)
  267. { return p.addProgramEventMessage (message.values); });
  268. }
  269. }
  270. void timerCallback() override
  271. {
  272. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  273. {
  274. isProgramLoaded = true;
  275. stopTimer();
  276. if (shouldSaveProgramAsDefault)
  277. doSaveProgramAsDefault();
  278. if (programLoadedCallback != nullptr)
  279. programLoadedCallback (*this);
  280. }
  281. else
  282. {
  283. startTimer (100);
  284. }
  285. }
  286. void saveProgramAsDefault() override
  287. {
  288. shouldSaveProgramAsDefault = true;
  289. if (! isTimerRunning() && isProgramLoaded)
  290. doSaveProgramAsDefault();
  291. }
  292. void resetProgramToDefault() override
  293. {
  294. if (! shouldSaveProgramAsDefault)
  295. setProgram (nullptr);
  296. sendCommandMessage (BlocksProtocol::endAPIMode);
  297. sendCommandMessage (BlocksProtocol::beginAPIMode);
  298. }
  299. uint32 getMemorySize() override
  300. {
  301. return modelData.programAndHeapSize;
  302. }
  303. uint32 getHeapMemorySize() override
  304. {
  305. jassert (isPositiveAndNotGreaterThan (programSize, modelData.programAndHeapSize));
  306. return modelData.programAndHeapSize - programSize;
  307. }
  308. void setDataByte (size_t offset, uint8 value) override
  309. {
  310. remoteHeap.setByte (programSize + offset, value);
  311. }
  312. void setDataBytes (size_t offset, const void* newData, size_t num) override
  313. {
  314. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  315. }
  316. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  317. {
  318. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  319. }
  320. uint8 getDataByte (size_t offset) override
  321. {
  322. return remoteHeap.getByte (programSize + offset);
  323. }
  324. void handleSharedDataACK (uint32 packetCounter) noexcept
  325. {
  326. pingFromDevice();
  327. remoteHeap.handleACKFromDevice (*this, packetCounter);
  328. }
  329. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void(uint8, uint32)> callback) override
  330. {
  331. firmwarePacketAckCallback = nullptr;
  332. if (buildAndSendPacket<256> ([data, size] (BlocksProtocol::HostPacketBuilder<256>& p)
  333. { return p.addFirmwareUpdatePacket (data, size); }))
  334. {
  335. firmwarePacketAckCallback = callback;
  336. return true;
  337. }
  338. return false;
  339. }
  340. void handleFirmwareUpdateACK (uint8 resultCode, uint32 resultDetail)
  341. {
  342. if (firmwarePacketAckCallback != nullptr)
  343. {
  344. firmwarePacketAckCallback (resultCode, resultDetail);
  345. firmwarePacketAckCallback = nullptr;
  346. }
  347. }
  348. void handleConfigUpdateMessage (int32 item, int32 value, int32 min, int32 max)
  349. {
  350. config.handleConfigUpdateMessage (item, value, min, max);
  351. }
  352. void handleConfigSetMessage(int32 item, int32 value)
  353. {
  354. config.handleConfigSetMessage (item, value);
  355. }
  356. void pingFromDevice()
  357. {
  358. lastMessageReceiveTime = Time::getCurrentTime();
  359. }
  360. MIDIDeviceConnection* getDeviceConnection()
  361. {
  362. return dynamic_cast<MIDIDeviceConnection*> (detector->getDeviceConnectionFor (*this));
  363. }
  364. void addDataInputPortListener (DataInputPortListener* listener) override
  365. {
  366. if (auto deviceConnection = getDeviceConnection())
  367. {
  368. {
  369. ScopedLock scopedLock (deviceConnection->criticalSecton);
  370. Block::addDataInputPortListener (listener);
  371. }
  372. deviceConnection->midiInput->start();
  373. }
  374. else
  375. {
  376. Block::addDataInputPortListener (listener);
  377. }
  378. }
  379. void removeDataInputPortListener (DataInputPortListener* listener) override
  380. {
  381. if (auto deviceConnection = getDeviceConnection())
  382. {
  383. {
  384. ScopedLock scopedLock (deviceConnection->criticalSecton);
  385. Block::removeDataInputPortListener (listener);
  386. }
  387. }
  388. else
  389. {
  390. Block::removeDataInputPortListener (listener);
  391. }
  392. }
  393. void sendMessage (const void* message, size_t messageSize) override
  394. {
  395. if (auto midiOutput = getMidiOutput())
  396. midiOutput->sendMessageNow ({ message, (int) messageSize });
  397. }
  398. void handleTimerTick()
  399. {
  400. if (ledGrid != nullptr)
  401. if (auto renderer = ledGrid->getRenderer())
  402. renderer->renderLEDGrid (*ledGrid);
  403. remoteHeap.sendChanges (*this, false);
  404. if (lastMessageSendTime < Time::getCurrentTime() - getPingInterval())
  405. sendCommandMessage (BlocksProtocol::ping);
  406. }
  407. RelativeTime getPingInterval()
  408. {
  409. return RelativeTime::milliseconds (isMaster ? masterPingIntervalMs : dnaPingIntervalMs);
  410. }
  411. //==============================================================================
  412. int32 getLocalConfigValue (uint32 item) override
  413. {
  414. initialiseDeviceIndexAndConnection();
  415. return config.getItemValue ((BlocksProtocol::ConfigItemId) item);
  416. }
  417. void setLocalConfigValue (uint32 item, int32 value) override
  418. {
  419. initialiseDeviceIndexAndConnection();
  420. config.setItemValue ((BlocksProtocol::ConfigItemId) item, value);
  421. }
  422. void setLocalConfigRange (uint32 item, int32 min, int32 max) override
  423. {
  424. initialiseDeviceIndexAndConnection();
  425. config.setItemMin ((BlocksProtocol::ConfigItemId) item, min);
  426. config.setItemMax ((BlocksProtocol::ConfigItemId) item, max);
  427. }
  428. void setLocalConfigItemActive (uint32 item, bool isActive) override
  429. {
  430. initialiseDeviceIndexAndConnection();
  431. config.setItemActive ((BlocksProtocol::ConfigItemId) item, isActive);
  432. }
  433. bool isLocalConfigItemActive (uint32 item) override
  434. {
  435. initialiseDeviceIndexAndConnection();
  436. return config.getItemActive ((BlocksProtocol::ConfigItemId) item);
  437. }
  438. uint32 getMaxConfigIndex() override
  439. {
  440. return uint32 (BlocksProtocol::maxConfigIndex);
  441. }
  442. bool isValidUserConfigIndex (uint32 item) override
  443. {
  444. return item >= (uint32) BlocksProtocol::ConfigItemId::user0
  445. && item < (uint32) (BlocksProtocol::ConfigItemId::user0 + numberOfUserConfigs);
  446. }
  447. ConfigMetaData getLocalConfigMetaData (uint32 item) override
  448. {
  449. initialiseDeviceIndexAndConnection();
  450. return config.getMetaData ((BlocksProtocol::ConfigItemId) item);
  451. }
  452. void requestFactoryConfigSync() override
  453. {
  454. initialiseDeviceIndexAndConnection();
  455. config.requestFactoryConfigSync();
  456. }
  457. void resetConfigListActiveStatus() override
  458. {
  459. config.resetConfigListActiveStatus();
  460. }
  461. void setConfigChangedCallback (std::function<void(Block&, const ConfigMetaData&, uint32)> configChanged) override
  462. {
  463. configChangedCallback = std::move (configChanged);
  464. }
  465. void setProgramLoadedCallback (std::function<void(Block&)> programLoaded) override
  466. {
  467. programLoadedCallback = std::move (programLoaded);
  468. }
  469. bool setName (const String& newName) override
  470. {
  471. return buildAndSendPacket<128> ([&newName] (BlocksProtocol::HostPacketBuilder<128>& p)
  472. { return p.addSetBlockName (newName); });
  473. }
  474. void factoryReset() override
  475. {
  476. buildAndSendPacket<32> ([] (BlocksProtocol::HostPacketBuilder<32>& p)
  477. { return p.addFactoryReset(); });
  478. }
  479. void blockReset() override
  480. {
  481. bool messageSent = false;
  482. if (isMasterBlock())
  483. {
  484. sendMessage (BlocksProtocol::SpecialMessageFromHost::resetMaster,
  485. sizeof (BlocksProtocol::SpecialMessageFromHost::resetMaster));
  486. messageSent = true;
  487. }
  488. else
  489. {
  490. messageSent = buildAndSendPacket<32> ([] (BlocksProtocol::HostPacketBuilder<32>& p)
  491. { return p.addBlockReset(); });
  492. }
  493. if (messageSent)
  494. {
  495. hasBeenPowerCycled = true;
  496. if (detector != nullptr)
  497. detector->notifyBlockIsRestarting (uid);
  498. }
  499. }
  500. bool wasPowerCycled() const { return hasBeenPowerCycled; }
  501. void resetPowerCycleFlag() { hasBeenPowerCycled = false; }
  502. //==============================================================================
  503. std::unique_ptr<TouchSurface> touchSurface;
  504. OwnedArray<ControlButton> controlButtons;
  505. std::unique_ptr<LEDGridImplementation> ledGrid;
  506. std::unique_ptr<LEDRowImplementation> ledRow;
  507. OwnedArray<StatusLight> statusLights;
  508. BlocksProtocol::BlockDataSheet modelData;
  509. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  510. static constexpr int masterPingIntervalMs = 400;
  511. static constexpr int dnaPingIntervalMs = 1666;
  512. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  513. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  514. static constexpr uint32 maxPacketSize = 200;
  515. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  516. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  517. RemoteHeapType remoteHeap;
  518. WeakReference<Detector> detector;
  519. Time lastMessageSendTime, lastMessageReceiveTime;
  520. BlockConfigManager config;
  521. std::function<void(Block&, const ConfigMetaData&, uint32)> configChangedCallback;
  522. std::function<void(Block&)> programLoadedCallback;
  523. private:
  524. std::unique_ptr<Program> program;
  525. uint32 programSize = 0;
  526. std::function<void(uint8, uint32)> firmwarePacketAckCallback;
  527. bool isMaster = false;
  528. Block::UID masterUID = {};
  529. BlocksProtocol::BatteryLevel batteryLevel {};
  530. BlocksProtocol::BatteryCharging batteryCharging {};
  531. BlocksProtocol::TopologyIndex topologyIndex {};
  532. Time connectionTime {};
  533. std::pair<int, int> position;
  534. int rotation = 0;
  535. friend Detector;
  536. bool isProgramLoaded = false;
  537. bool shouldSaveProgramAsDefault = false;
  538. bool hasBeenPowerCycled = false;
  539. void initialiseDeviceIndexAndConnection()
  540. {
  541. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  542. config.setDeviceComms (listenerToMidiConnection);
  543. }
  544. const MidiInput* getMidiInput() const
  545. {
  546. if (detector != nullptr)
  547. if (auto c = dynamic_cast<const MIDIDeviceConnection*> (detector->getDeviceConnectionFor (*this)))
  548. return c->midiInput.get();
  549. jassertfalse;
  550. return nullptr;
  551. }
  552. MidiInput* getMidiInput()
  553. {
  554. return const_cast<MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  555. }
  556. const MidiOutput* getMidiOutput() const
  557. {
  558. if (detector != nullptr)
  559. if (auto c = dynamic_cast<const MIDIDeviceConnection*> (detector->getDeviceConnectionFor (*this)))
  560. return c->midiOutput.get();
  561. jassertfalse;
  562. return nullptr;
  563. }
  564. MidiOutput* getMidiOutput()
  565. {
  566. return const_cast<MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  567. }
  568. void handleIncomingMidiMessage (const MidiMessage& message) override
  569. {
  570. dataInputPortListeners.call ([&] (DataInputPortListener& l) { l.handleIncomingDataPortMessage (*this, message.getRawData(),
  571. (size_t) message.getRawDataSize()); });
  572. }
  573. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  574. {
  575. jassert (listenerToMidiConnection == &c);
  576. ignoreUnused (c);
  577. disconnectMidiConnectionListener();
  578. }
  579. void doSaveProgramAsDefault()
  580. {
  581. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  582. }
  583. template<int packetBytes, typename PacketBuilderFn>
  584. bool buildAndSendPacket (PacketBuilderFn buildFn)
  585. {
  586. auto index = getDeviceIndex();
  587. if (index < 0)
  588. {
  589. jassertfalse;
  590. return false;
  591. }
  592. BlocksProtocol::HostPacketBuilder<packetBytes> p;
  593. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  594. if (! buildFn (p))
  595. return false;
  596. p.writePacketSysexFooter();
  597. return sendMessageToDevice (p);
  598. }
  599. public:
  600. //==============================================================================
  601. struct TouchSurfaceImplementation : public TouchSurface,
  602. private Timer
  603. {
  604. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  605. {
  606. activateTouchSurface();
  607. }
  608. ~TouchSurfaceImplementation() override
  609. {
  610. disableTouchSurface();
  611. }
  612. void activateTouchSurface()
  613. {
  614. startTimer (500);
  615. }
  616. void disableTouchSurface()
  617. {
  618. stopTimer();
  619. }
  620. int getNumberOfKeywaves() const noexcept override
  621. {
  622. return blockImpl.modelData.numKeywaves;
  623. }
  624. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  625. {
  626. auto& status = touches.getValue (touchEvent);
  627. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  628. if (touchEvent.isTouchStart && status.isActive)
  629. killTouch (touchEvent, status, Time::getMillisecondCounter());
  630. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  631. if (! touchEvent.isTouchStart && ! status.isActive)
  632. {
  633. TouchSurface::Touch t (touchEvent);
  634. t.isTouchStart = true;
  635. t.isTouchEnd = false;
  636. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  637. if (t.zVelocity <= 0) t.zVelocity = t.z;
  638. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  639. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, t); });
  640. }
  641. // Normal handling:
  642. status.lastEventTime = Time::getMillisecondCounter();
  643. status.isActive = ! touchEvent.isTouchEnd;
  644. if (touchEvent.isTouchStart)
  645. status.lastStrikePressure = touchEvent.zVelocity;
  646. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, touchEvent); });
  647. }
  648. void timerCallback() override
  649. {
  650. // Find touches that seem to have become stuck, and fake a touch-end for them..
  651. static const uint32 touchTimeOutMs = 500;
  652. for (auto& t : touches)
  653. {
  654. auto& status = t.value;
  655. auto now = Time::getMillisecondCounter();
  656. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  657. killTouch (t.touch, status, now);
  658. }
  659. }
  660. struct TouchStatus
  661. {
  662. uint32 lastEventTime = 0;
  663. float lastStrikePressure = 0;
  664. bool isActive = false;
  665. };
  666. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  667. {
  668. jassert (status.isActive);
  669. TouchSurface::Touch killTouch (touch);
  670. killTouch.z = 0;
  671. killTouch.xVelocity = 0;
  672. killTouch.yVelocity = 0;
  673. killTouch.zVelocity = -1.0f;
  674. killTouch.eventTimestamp = timeStamp;
  675. killTouch.isTouchStart = false;
  676. killTouch.isTouchEnd = true;
  677. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, killTouch); });
  678. status.isActive = false;
  679. }
  680. void cancelAllActiveTouches() noexcept override
  681. {
  682. const auto now = Time::getMillisecondCounter();
  683. for (auto& t : touches)
  684. if (t.value.isActive)
  685. killTouch (t.touch, t.value, now);
  686. touches.clear();
  687. }
  688. BlockImplementation& blockImpl;
  689. TouchList<TouchStatus> touches;
  690. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  691. };
  692. //==============================================================================
  693. struct ControlButtonImplementation : public ControlButton
  694. {
  695. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  696. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  697. {
  698. }
  699. ~ControlButtonImplementation() override
  700. {
  701. }
  702. ButtonFunction getType() const override { return buttonInfo.type; }
  703. String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  704. float getPositionX() const override { return buttonInfo.x; }
  705. float getPositionY() const override { return buttonInfo.y; }
  706. bool hasLight() const override { return blockImpl.isControlBlock(); }
  707. bool setLightColour (LEDColour colour) override
  708. {
  709. if (hasLight())
  710. {
  711. if (auto row = blockImpl.ledRow.get())
  712. {
  713. row->setButtonColour ((uint32) buttonIndex, colour);
  714. return true;
  715. }
  716. }
  717. return false;
  718. }
  719. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  720. {
  721. if (button == buttonInfo.type)
  722. {
  723. if (wasDown == isDown)
  724. sendButtonChangeToListeners (timestamp, ! isDown);
  725. sendButtonChangeToListeners (timestamp, isDown);
  726. wasDown = isDown;
  727. }
  728. }
  729. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  730. {
  731. if (isDown)
  732. listeners.call ([&] (ControlButton::Listener& l) { l.buttonPressed (*this, timestamp); });
  733. else
  734. listeners.call ([&] (ControlButton::Listener& l) { l.buttonReleased (*this, timestamp); });
  735. }
  736. BlockImplementation& blockImpl;
  737. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  738. int buttonIndex;
  739. bool wasDown = false;
  740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  741. };
  742. //==============================================================================
  743. struct StatusLightImplementation : public StatusLight
  744. {
  745. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  746. {
  747. }
  748. String getName() const override { return info.name; }
  749. bool setColour (LEDColour newColour) override
  750. {
  751. // XXX TODO!
  752. ignoreUnused (newColour);
  753. return false;
  754. }
  755. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  756. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  757. };
  758. //==============================================================================
  759. struct LEDGridImplementation : public LEDGrid
  760. {
  761. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  762. {
  763. }
  764. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  765. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  766. BlockImplementation& blockImpl;
  767. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  768. };
  769. //==============================================================================
  770. struct LEDRowImplementation : public LEDRow,
  771. private Timer
  772. {
  773. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  774. {
  775. startTimer (300);
  776. }
  777. void setButtonColour (uint32 index, LEDColour colour)
  778. {
  779. if (index < 10)
  780. {
  781. colours[index] = colour;
  782. flush();
  783. }
  784. }
  785. int getNumLEDs() const override
  786. {
  787. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  788. }
  789. void setLEDColour (int index, LEDColour colour) override
  790. {
  791. if ((uint32) index < 15u)
  792. {
  793. colours[10 + index] = colour;
  794. flush();
  795. }
  796. }
  797. void setOverlayColour (LEDColour colour) override
  798. {
  799. colours[25] = colour;
  800. flush();
  801. }
  802. void resetOverlayColour() override
  803. {
  804. setOverlayColour ({});
  805. }
  806. private:
  807. LEDColour colours[26];
  808. void timerCallback() override
  809. {
  810. stopTimer();
  811. loadProgramOntoBlock();
  812. flush();
  813. }
  814. void loadProgramOntoBlock()
  815. {
  816. if (block.getProgram() == nullptr)
  817. {
  818. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  819. if (err.failed())
  820. {
  821. DBG (err.getErrorMessage());
  822. jassertfalse;
  823. }
  824. }
  825. }
  826. void flush()
  827. {
  828. if (block.getProgram() != nullptr)
  829. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  830. write565Colour (16 * i, colours[i]);
  831. }
  832. void write565Colour (uint32 bitIndex, LEDColour colour)
  833. {
  834. block.setDataBits (bitIndex, 5, (uint32) (colour.getRed() >> 3));
  835. block.setDataBits (bitIndex + 5, 6, (uint32) (colour.getGreen() >> 2));
  836. block.setDataBits (bitIndex + 11, 5, (uint32) (colour.getBlue() >> 3));
  837. }
  838. struct DefaultLEDGridProgram : public Block::Program
  839. {
  840. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  841. String getLittleFootProgram() override
  842. {
  843. /* Data format:
  844. 0: 10 x 5-6-5 bits for button LED RGBs
  845. 20: 15 x 5-6-5 bits for LED row colours
  846. 50: 1 x 5-6-5 bits for LED row overlay colour
  847. */
  848. return R"littlefoot(
  849. #heapsize: 128
  850. int getColour (int bitIndex)
  851. {
  852. return makeARGB (255,
  853. getHeapBits (bitIndex, 5) << 3,
  854. getHeapBits (bitIndex + 5, 6) << 2,
  855. getHeapBits (bitIndex + 11, 5) << 3);
  856. }
  857. int getButtonColour (int index)
  858. {
  859. return getColour (16 * index);
  860. }
  861. int getLEDColour (int index)
  862. {
  863. if (getHeapInt (50))
  864. return getColour (50 * 8);
  865. return getColour (20 * 8 + 16 * index);
  866. }
  867. void repaint()
  868. {
  869. for (int x = 0; x < 15; ++x)
  870. fillPixel (getLEDColour (x), x, 0);
  871. for (int i = 0; i < 10; ++i)
  872. fillPixel (getButtonColour (i), i, 1);
  873. }
  874. void handleMessage (int p1, int p2) {}
  875. )littlefoot";
  876. }
  877. };
  878. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  879. };
  880. private:
  881. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  882. };
  883. } // namespace juce