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.

1109 lines
35KB

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