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.

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