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.

1031 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 (const BlocksProtocol::BlockSerialNumber& serial,
  30. Detector& detectorToUse,
  31. BlocksProtocol::VersionNumber version,
  32. BlocksProtocol::BlockName blockName,
  33. bool isMasterBlock)
  34. : Block (juce::String ((const char*) serial.serial, sizeof (serial.serial)),
  35. juce::String ((const char*) version.data, version.length),
  36. juce::String ((const char*) blockName.data, blockName.length)),
  37. modelData (serial),
  38. remoteHeap (modelData.programAndHeapSize),
  39. detector (&detectorToUse),
  40. isMaster (isMasterBlock)
  41. {
  42. if (modelData.hasTouchSurface)
  43. touchSurface.reset (new TouchSurfaceImplementation (*this));
  44. int i = 0;
  45. for (auto&& b : modelData.buttons)
  46. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  47. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  48. ledGrid.reset (new LEDGridImplementation (*this));
  49. for (auto&& s : modelData.statusLEDs)
  50. statusLights.add (new StatusLightImplementation (*this, s));
  51. updateMidiConnectionListener();
  52. }
  53. ~BlockImplementation()
  54. {
  55. if (listenerToMidiConnection != nullptr)
  56. {
  57. config.setDeviceComms (nullptr);
  58. listenerToMidiConnection->removeListener (this);
  59. }
  60. }
  61. void markDisconnected()
  62. {
  63. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  64. surface->disableTouchSurface();
  65. }
  66. void markReconnected (const DeviceInfo& deviceInfo)
  67. {
  68. versionNumber = asString (deviceInfo.version);
  69. name = asString (deviceInfo.name);
  70. isMaster = deviceInfo.isMaster;
  71. setProgram (nullptr);
  72. remoteHeap.resetDeviceStateToUnknown();
  73. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  74. surface->activateTouchSurface();
  75. updateMidiConnectionListener();
  76. }
  77. void setToMaster (bool shouldBeMaster)
  78. {
  79. isMaster = shouldBeMaster;
  80. }
  81. void updateMidiConnectionListener()
  82. {
  83. if (detector == nullptr)
  84. return;
  85. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector->getDeviceConnectionFor (*this));
  86. if (listenerToMidiConnection != nullptr)
  87. listenerToMidiConnection->addListener (this);
  88. config.setDeviceComms (listenerToMidiConnection);
  89. }
  90. Type getType() const override { return modelData.apiType; }
  91. juce::String getDeviceDescription() const override { return modelData.description; }
  92. int getWidth() const override { return modelData.widthUnits; }
  93. int getHeight() const override { return modelData.heightUnits; }
  94. float getMillimetersPerUnit() const override { return 47.0f; }
  95. bool isHardwareBlock() const override { return true; }
  96. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  97. bool isConnected() const override { return detector && detector->isConnected (uid); }
  98. bool isMasterBlock() const override { return isMaster; }
  99. Block::UID getConnectedMasterUID() const override { return masterUID; }
  100. int getRotation() const override { return rotation; }
  101. Rectangle<int> getBlockAreaWithinLayout() const override
  102. {
  103. if (rotation % 2 == 0)
  104. return { position.getX(), position.getY(), modelData.widthUnits, modelData.heightUnits };
  105. return { position.getX(), position.getY(), modelData.heightUnits, modelData.widthUnits };
  106. }
  107. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  108. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  109. LEDRow* getLEDRow() override
  110. {
  111. if (ledRow == nullptr && modelData.numLEDRowLEDs > 0)
  112. ledRow.reset (new LEDRowImplementation (*this));
  113. return ledRow.get();
  114. }
  115. juce::Array<ControlButton*> getButtons() const override
  116. {
  117. juce::Array<ControlButton*> result;
  118. result.addArray (controlButtons);
  119. return result;
  120. }
  121. juce::Array<StatusLight*> getStatusLights() const override
  122. {
  123. juce::Array<StatusLight*> result;
  124. result.addArray (statusLights);
  125. return result;
  126. }
  127. float getBatteryLevel() const override
  128. {
  129. if (detector == nullptr)
  130. return 0.0f;
  131. if (auto status = detector->getLastStatus (uid))
  132. return status->batteryLevel.toUnipolarFloat();
  133. return 0.0f;
  134. }
  135. bool isBatteryCharging() const override
  136. {
  137. if (detector == nullptr)
  138. return false;
  139. if (auto status = detector->getLastStatus (uid))
  140. return status->batteryCharging.get() != 0;
  141. return false;
  142. }
  143. bool supportsGraphics() const override
  144. {
  145. return false;
  146. }
  147. int getDeviceIndex() const noexcept
  148. {
  149. if (detector == nullptr)
  150. return -1;
  151. return isConnected() ? detector->getIndexFromDeviceID (uid) : -1;
  152. }
  153. template <typename PacketBuilder>
  154. bool sendMessageToDevice (const PacketBuilder& builder)
  155. {
  156. if (detector != nullptr)
  157. {
  158. lastMessageSendTime = juce::Time::getCurrentTime();
  159. return detector->sendMessageToDevice (uid, builder);
  160. }
  161. return false;
  162. }
  163. bool sendCommandMessage (uint32 commandID)
  164. {
  165. return buildAndSendPacket<64> ([commandID] (BlocksProtocol::HostPacketBuilder<64>& p)
  166. { return p.deviceControlMessage (commandID); });
  167. }
  168. void handleCustomMessage (Block::Timestamp, const int32* data)
  169. {
  170. ProgramEventMessage m;
  171. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  172. m.values[i] = data[i];
  173. programEventListeners.call ([&] (ProgramEventListener& l) { l.handleProgramEvent (*this, m); });
  174. }
  175. static BlockImplementation* getFrom (Block& b) noexcept
  176. {
  177. jassert (dynamic_cast<BlockImplementation*> (&b) != nullptr);
  178. return dynamic_cast<BlockImplementation*> (&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. Point<int> position;
  459. int rotation = 0;
  460. friend Detector;
  461. bool isProgramLoaded = false;
  462. bool shouldSaveProgramAsDefault = false;
  463. bool hasBeenPowerCycled = false;
  464. void initialiseDeviceIndexAndConnection()
  465. {
  466. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  467. config.setDeviceComms (listenerToMidiConnection);
  468. }
  469. const juce::MidiInput* getMidiInput() const
  470. {
  471. if (detector != nullptr)
  472. if (auto c = dynamic_cast<const MIDIDeviceConnection*> (detector->getDeviceConnectionFor (*this)))
  473. return c->midiInput.get();
  474. jassertfalse;
  475. return nullptr;
  476. }
  477. juce::MidiInput* getMidiInput()
  478. {
  479. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  480. }
  481. const juce::MidiOutput* getMidiOutput() const
  482. {
  483. if (detector != nullptr)
  484. if (auto c = dynamic_cast<const MIDIDeviceConnection*> (detector->getDeviceConnectionFor (*this)))
  485. return c->midiOutput.get();
  486. jassertfalse;
  487. return nullptr;
  488. }
  489. juce::MidiOutput* getMidiOutput()
  490. {
  491. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  492. }
  493. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  494. {
  495. dataInputPortListeners.call ([&] (DataInputPortListener& l) { l.handleIncomingDataPortMessage (*this, message.getRawData(),
  496. (size_t) message.getRawDataSize()); });
  497. }
  498. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  499. {
  500. jassert (listenerToMidiConnection == &c);
  501. juce::ignoreUnused (c);
  502. listenerToMidiConnection->removeListener (this);
  503. listenerToMidiConnection = nullptr;
  504. config.setDeviceComms (nullptr);
  505. }
  506. void doSaveProgramAsDefault()
  507. {
  508. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  509. }
  510. template<int packetBytes, typename PacketBuilderFn>
  511. bool buildAndSendPacket (PacketBuilderFn buildFn)
  512. {
  513. auto index = getDeviceIndex();
  514. if (index < 0)
  515. {
  516. jassertfalse;
  517. return false;
  518. }
  519. BlocksProtocol::HostPacketBuilder<packetBytes> p;
  520. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  521. if (! buildFn (p))
  522. return false;
  523. p.writePacketSysexFooter();
  524. return sendMessageToDevice (p);
  525. }
  526. public:
  527. //==============================================================================
  528. struct TouchSurfaceImplementation : public TouchSurface,
  529. private juce::Timer
  530. {
  531. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  532. {
  533. activateTouchSurface();
  534. }
  535. ~TouchSurfaceImplementation()
  536. {
  537. disableTouchSurface();
  538. }
  539. void activateTouchSurface()
  540. {
  541. startTimer (500);
  542. }
  543. void disableTouchSurface()
  544. {
  545. stopTimer();
  546. }
  547. int getNumberOfKeywaves() const noexcept override
  548. {
  549. return blockImpl.modelData.numKeywaves;
  550. }
  551. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  552. {
  553. auto& status = touches.getValue (touchEvent);
  554. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  555. if (touchEvent.isTouchStart && status.isActive)
  556. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  557. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  558. if (! touchEvent.isTouchStart && ! status.isActive)
  559. {
  560. TouchSurface::Touch t (touchEvent);
  561. t.isTouchStart = true;
  562. t.isTouchEnd = false;
  563. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  564. if (t.zVelocity <= 0) t.zVelocity = t.z;
  565. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  566. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, t); });
  567. }
  568. // Normal handling:
  569. status.lastEventTime = juce::Time::getMillisecondCounter();
  570. status.isActive = ! touchEvent.isTouchEnd;
  571. if (touchEvent.isTouchStart)
  572. status.lastStrikePressure = touchEvent.zVelocity;
  573. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, touchEvent); });
  574. }
  575. void timerCallback() override
  576. {
  577. // Find touches that seem to have become stuck, and fake a touch-end for them..
  578. static const uint32 touchTimeOutMs = 500;
  579. for (auto& t : touches)
  580. {
  581. auto& status = t.value;
  582. auto now = juce::Time::getMillisecondCounter();
  583. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  584. killTouch (t.touch, status, now);
  585. }
  586. }
  587. struct TouchStatus
  588. {
  589. uint32 lastEventTime = 0;
  590. float lastStrikePressure = 0;
  591. bool isActive = false;
  592. };
  593. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  594. {
  595. jassert (status.isActive);
  596. TouchSurface::Touch killTouch (touch);
  597. killTouch.z = 0;
  598. killTouch.xVelocity = 0;
  599. killTouch.yVelocity = 0;
  600. killTouch.zVelocity = -1.0f;
  601. killTouch.eventTimestamp = timeStamp;
  602. killTouch.isTouchStart = false;
  603. killTouch.isTouchEnd = true;
  604. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, killTouch); });
  605. status.isActive = false;
  606. }
  607. void cancelAllActiveTouches() noexcept override
  608. {
  609. const auto now = juce::Time::getMillisecondCounter();
  610. for (auto& t : touches)
  611. if (t.value.isActive)
  612. killTouch (t.touch, t.value, now);
  613. touches.clear();
  614. }
  615. BlockImplementation& blockImpl;
  616. TouchList<TouchStatus> touches;
  617. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  618. };
  619. //==============================================================================
  620. struct ControlButtonImplementation : public ControlButton
  621. {
  622. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  623. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  624. {
  625. }
  626. ~ControlButtonImplementation()
  627. {
  628. }
  629. ButtonFunction getType() const override { return buttonInfo.type; }
  630. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  631. float getPositionX() const override { return buttonInfo.x; }
  632. float getPositionY() const override { return buttonInfo.y; }
  633. bool hasLight() const override { return blockImpl.isControlBlock(); }
  634. bool setLightColour (LEDColour colour) override
  635. {
  636. if (hasLight())
  637. {
  638. if (auto row = blockImpl.ledRow.get())
  639. {
  640. row->setButtonColour ((uint32) buttonIndex, colour);
  641. return true;
  642. }
  643. }
  644. return false;
  645. }
  646. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  647. {
  648. if (button == buttonInfo.type)
  649. {
  650. if (wasDown == isDown)
  651. sendButtonChangeToListeners (timestamp, ! isDown);
  652. sendButtonChangeToListeners (timestamp, isDown);
  653. wasDown = isDown;
  654. }
  655. }
  656. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  657. {
  658. if (isDown)
  659. listeners.call ([&] (ControlButton::Listener& l) { l.buttonPressed (*this, timestamp); });
  660. else
  661. listeners.call ([&] (ControlButton::Listener& l) { l.buttonReleased (*this, timestamp); });
  662. }
  663. BlockImplementation& blockImpl;
  664. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  665. int buttonIndex;
  666. bool wasDown = false;
  667. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  668. };
  669. //==============================================================================
  670. struct StatusLightImplementation : public StatusLight
  671. {
  672. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  673. {
  674. }
  675. juce::String getName() const override { return info.name; }
  676. bool setColour (LEDColour newColour) override
  677. {
  678. // XXX TODO!
  679. juce::ignoreUnused (newColour);
  680. return false;
  681. }
  682. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  683. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  684. };
  685. //==============================================================================
  686. struct LEDGridImplementation : public LEDGrid
  687. {
  688. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  689. {
  690. }
  691. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  692. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  693. BlockImplementation& blockImpl;
  694. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  695. };
  696. //==============================================================================
  697. struct LEDRowImplementation : public LEDRow,
  698. private Timer
  699. {
  700. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  701. {
  702. startTimer (300);
  703. }
  704. void setButtonColour (uint32 index, LEDColour colour)
  705. {
  706. if (index < 10)
  707. {
  708. colours[index] = colour;
  709. flush();
  710. }
  711. }
  712. int getNumLEDs() const override
  713. {
  714. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  715. }
  716. void setLEDColour (int index, LEDColour colour) override
  717. {
  718. if ((uint32) index < 15u)
  719. {
  720. colours[10 + index] = colour;
  721. flush();
  722. }
  723. }
  724. void setOverlayColour (LEDColour colour) override
  725. {
  726. colours[25] = colour;
  727. flush();
  728. }
  729. void resetOverlayColour() override
  730. {
  731. setOverlayColour ({});
  732. }
  733. private:
  734. LEDColour colours[26];
  735. void timerCallback() override
  736. {
  737. stopTimer();
  738. loadProgramOntoBlock();
  739. flush();
  740. }
  741. void loadProgramOntoBlock()
  742. {
  743. if (block.getProgram() == nullptr)
  744. {
  745. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  746. if (err.failed())
  747. {
  748. DBG (err.getErrorMessage());
  749. jassertfalse;
  750. }
  751. }
  752. }
  753. void flush()
  754. {
  755. if (block.getProgram() != nullptr)
  756. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  757. write565Colour (16 * i, colours[i]);
  758. }
  759. void write565Colour (uint32 bitIndex, LEDColour colour)
  760. {
  761. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  762. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  763. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  764. }
  765. struct DefaultLEDGridProgram : public Block::Program
  766. {
  767. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  768. juce::String getLittleFootProgram() override
  769. {
  770. /* Data format:
  771. 0: 10 x 5-6-5 bits for button LED RGBs
  772. 20: 15 x 5-6-5 bits for LED row colours
  773. 50: 1 x 5-6-5 bits for LED row overlay colour
  774. */
  775. return R"littlefoot(
  776. #heapsize: 128
  777. int getColour (int bitIndex)
  778. {
  779. return makeARGB (255,
  780. getHeapBits (bitIndex, 5) << 3,
  781. getHeapBits (bitIndex + 5, 6) << 2,
  782. getHeapBits (bitIndex + 11, 5) << 3);
  783. }
  784. int getButtonColour (int index)
  785. {
  786. return getColour (16 * index);
  787. }
  788. int getLEDColour (int index)
  789. {
  790. if (getHeapInt (50))
  791. return getColour (50 * 8);
  792. return getColour (20 * 8 + 16 * index);
  793. }
  794. void repaint()
  795. {
  796. for (int x = 0; x < 15; ++x)
  797. fillPixel (getLEDColour (x), x, 0);
  798. for (int i = 0; i < 10; ++i)
  799. fillPixel (getButtonColour (i), i, 1);
  800. }
  801. void handleMessage (int p1, int p2) {}
  802. )littlefoot";
  803. }
  804. };
  805. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  806. };
  807. private:
  808. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  809. };
  810. } // namespace juce