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.

1038 lines
34KB

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