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.

589 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: InAppPurchasesDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Showcases in-app purchases features. To run this demo you must enable the
  24. "In-App Purchases Capability" option in the Projucer exporter.
  25. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  26. juce_audio_processors, juce_audio_utils, juce_core,
  27. juce_cryptography, juce_data_structures, juce_events,
  28. juce_graphics, juce_gui_basics, juce_gui_extra,
  29. juce_product_unlocking
  30. exporters: xcode_mac, xcode_iphone, androidstudio
  31. type: Component
  32. mainClass: InAppPurchasesDemo
  33. useLocalCopy: 1
  34. END_JUCE_PIP_METADATA
  35. *******************************************************************************/
  36. #pragma once
  37. #include "../Assets/DemoUtilities.h"
  38. //==============================================================================
  39. class VoicePurchases : private InAppPurchases::Listener
  40. {
  41. public:
  42. //==============================================================================
  43. struct VoiceProduct
  44. {
  45. const char* identifier;
  46. const char* humanReadable;
  47. bool isPurchased, priceIsKnown, purchaseInProgress;
  48. String purchasePrice;
  49. };
  50. //==============================================================================
  51. VoicePurchases (AsyncUpdater& asyncUpdater)
  52. : guiUpdater (asyncUpdater)
  53. {
  54. voiceProducts = Array<VoiceProduct>(
  55. { VoiceProduct {"robot", "Robot", true, true, false, "Free" },
  56. VoiceProduct {"jules", "Jules", false, false, false, "Retrieving price..." },
  57. VoiceProduct {"fabian", "Fabian", false, false, false, "Retrieving price..." },
  58. VoiceProduct {"ed", "Ed", false, false, false, "Retrieving price..." },
  59. VoiceProduct {"lukasz", "Lukasz", false, false, false, "Retrieving price..." },
  60. VoiceProduct {"jb", "JB", false, false, false, "Retrieving price..." } });
  61. }
  62. ~VoicePurchases()
  63. {
  64. InAppPurchases::getInstance()->removeListener (this);
  65. }
  66. //==============================================================================
  67. VoiceProduct getPurchase (int voiceIndex)
  68. {
  69. if (! havePurchasesBeenRestored)
  70. {
  71. havePurchasesBeenRestored = true;
  72. InAppPurchases::getInstance()->addListener (this);
  73. InAppPurchases::getInstance()->restoreProductsBoughtList (true);
  74. }
  75. return voiceProducts[voiceIndex];
  76. }
  77. void purchaseVoice (int voiceIndex)
  78. {
  79. if (havePricesBeenFetched && isPositiveAndBelow (voiceIndex, voiceProducts.size()))
  80. {
  81. auto& product = voiceProducts.getReference (voiceIndex);
  82. if (! product.isPurchased)
  83. {
  84. purchaseInProgress = true;
  85. product.purchaseInProgress = true;
  86. InAppPurchases::getInstance()->purchaseProduct (product.identifier, false);
  87. guiUpdater.triggerAsyncUpdate();
  88. }
  89. }
  90. }
  91. StringArray getVoiceNames() const
  92. {
  93. StringArray names;
  94. for (auto& voiceProduct : voiceProducts)
  95. names.add (voiceProduct.humanReadable);
  96. return names;
  97. }
  98. bool isPurchaseInProgress() const noexcept { return purchaseInProgress; }
  99. private:
  100. //==============================================================================
  101. void productsInfoReturned (const Array<InAppPurchases::Product>& products) override
  102. {
  103. if (! InAppPurchases::getInstance()->isInAppPurchasesSupported())
  104. {
  105. for (auto idx = 1; idx < voiceProducts.size(); ++idx)
  106. {
  107. auto& voiceProduct = voiceProducts.getReference (idx);
  108. voiceProduct.isPurchased = false;
  109. voiceProduct.priceIsKnown = false;
  110. voiceProduct.purchasePrice = "In-App purchases unavailable";
  111. }
  112. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  113. "In-app purchase is unavailable!",
  114. "In-App purchases are not available. This either means you are trying "
  115. "to use IAP on a platform that does not support IAP or you haven't setup "
  116. "your app correctly to work with IAP.",
  117. "OK");
  118. }
  119. else
  120. {
  121. for (auto product : products)
  122. {
  123. auto idx = findVoiceIndexFromIdentifier (product.identifier);
  124. if (isPositiveAndBelow (idx, voiceProducts.size()))
  125. {
  126. auto& voiceProduct = voiceProducts.getReference (idx);
  127. voiceProduct.priceIsKnown = true;
  128. voiceProduct.purchasePrice = product.price;
  129. }
  130. }
  131. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  132. "Your credit card will be charged!",
  133. "You are running the sample code for JUCE In-App purchases. "
  134. "Although this is only sample code, it will still CHARGE YOUR CREDIT CARD!",
  135. "Understood!");
  136. }
  137. guiUpdater.triggerAsyncUpdate();
  138. }
  139. void productPurchaseFinished (const PurchaseInfo& info, bool success, const String&) override
  140. {
  141. purchaseInProgress = false;
  142. auto idx = findVoiceIndexFromIdentifier (info.purchase.productId);
  143. if (isPositiveAndBelow (idx, voiceProducts.size()))
  144. {
  145. auto& voiceProduct = voiceProducts.getReference (idx);
  146. voiceProduct.isPurchased = success;
  147. voiceProduct.purchaseInProgress = false;
  148. }
  149. else
  150. {
  151. // On failure Play Store will not tell us which purchase failed
  152. for (auto& voiceProduct : voiceProducts)
  153. voiceProduct.purchaseInProgress = false;
  154. }
  155. guiUpdater.triggerAsyncUpdate();
  156. }
  157. void purchasesListRestored (const Array<PurchaseInfo>& infos, bool success, const String&) override
  158. {
  159. if (success)
  160. {
  161. for (auto& info : infos)
  162. {
  163. auto idx = findVoiceIndexFromIdentifier (info.purchase.productId);
  164. if (isPositiveAndBelow (idx, voiceProducts.size()))
  165. {
  166. auto& voiceProduct = voiceProducts.getReference (idx);
  167. voiceProduct.isPurchased = true;
  168. }
  169. }
  170. guiUpdater.triggerAsyncUpdate();
  171. }
  172. if (! havePricesBeenFetched)
  173. {
  174. havePricesBeenFetched = true;
  175. StringArray identifiers;
  176. for (auto& voiceProduct : voiceProducts)
  177. identifiers.add (voiceProduct.identifier);
  178. InAppPurchases::getInstance()->getProductsInformation (identifiers);
  179. }
  180. }
  181. //==============================================================================
  182. int findVoiceIndexFromIdentifier (String identifier) const
  183. {
  184. identifier = identifier.toLowerCase();
  185. for (auto i = 0; i < voiceProducts.size(); ++i)
  186. if (String (voiceProducts.getReference (i).identifier) == identifier)
  187. return i;
  188. return -1;
  189. }
  190. //==============================================================================
  191. AsyncUpdater& guiUpdater;
  192. bool havePurchasesBeenRestored = false, havePricesBeenFetched = false, purchaseInProgress = false;
  193. Array<VoiceProduct> voiceProducts;
  194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VoicePurchases)
  195. };
  196. //==============================================================================
  197. class PhraseModel : public ListBoxModel
  198. {
  199. public:
  200. PhraseModel() {}
  201. int getNumRows() override { return phrases.size(); }
  202. void paintListBoxItem (int row, Graphics& g, int w, int h, bool isSelected) override
  203. {
  204. Rectangle<int> r (0, 0, w, h);
  205. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  206. g.setColour (lf.findColour (isSelected ? TextEditor::highlightColourId : ListBox::backgroundColourId));
  207. g.fillRect (r);
  208. g.setColour (lf.findColour (ListBox::textColourId));
  209. g.setFont (18);
  210. String phrase = (isPositiveAndBelow (row, phrases.size()) ? phrases[row] : String{});
  211. g.drawText (phrase, 10, 0, w, h, Justification::centredLeft);
  212. }
  213. private:
  214. StringArray phrases {"I love JUCE!", "The five dimensions of touch", "Make it fast!"};
  215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PhraseModel)
  216. };
  217. //==============================================================================
  218. class VoiceModel : public ListBoxModel
  219. {
  220. public:
  221. //==============================================================================
  222. class VoiceRow : public Component,
  223. private Timer
  224. {
  225. public:
  226. VoiceRow (VoicePurchases& voicePurchases) : purchases (voicePurchases)
  227. {
  228. addAndMakeVisible (nameLabel);
  229. addAndMakeVisible (purchaseButton);
  230. addAndMakeVisible (priceLabel);
  231. purchaseButton.onClick = [this] { clickPurchase(); };
  232. voices = purchases.getVoiceNames();
  233. setSize (600, 33);
  234. }
  235. void paint (Graphics& g) override
  236. {
  237. auto r = getLocalBounds().reduced (4);
  238. {
  239. auto voiceIconBounds = r.removeFromLeft (r.getHeight());
  240. g.setColour (Colours::black);
  241. g.drawRect (voiceIconBounds);
  242. voiceIconBounds.reduce (1, 1);
  243. g.setColour (hasBeenPurchased ? Colours::white : Colours::grey);
  244. g.fillRect (voiceIconBounds);
  245. g.drawImage (avatar, voiceIconBounds.toFloat());
  246. if (! hasBeenPurchased)
  247. {
  248. g.setColour (Colours::white.withAlpha (0.8f));
  249. g.fillRect (voiceIconBounds);
  250. if (purchaseInProgress)
  251. getLookAndFeel().drawSpinningWaitAnimation (g, Colours::darkgrey,
  252. voiceIconBounds.getX(),
  253. voiceIconBounds.getY(),
  254. voiceIconBounds.getWidth(),
  255. voiceIconBounds.getHeight());
  256. }
  257. }
  258. }
  259. void resized() override
  260. {
  261. auto r = getLocalBounds().reduced (4 + 8, 4);
  262. auto h = r.getHeight();
  263. auto w = static_cast<int> (h * 1.5);
  264. r.removeFromLeft (h);
  265. purchaseButton.setBounds (r.removeFromRight (w).withSizeKeepingCentre (w, h / 2));
  266. nameLabel.setBounds (r.removeFromTop (18));
  267. priceLabel.setBounds (r.removeFromTop (18));
  268. }
  269. void update (int rowNumber, bool rowIsSelected)
  270. {
  271. isSelected = rowIsSelected;
  272. rowSelected = rowNumber;
  273. if (isPositiveAndBelow (rowNumber, voices.size()))
  274. {
  275. auto imageResourceName = voices[rowNumber] + ".png";
  276. nameLabel.setText (voices[rowNumber], NotificationType::dontSendNotification);
  277. auto purchase = purchases.getPurchase (rowNumber);
  278. hasBeenPurchased = purchase.isPurchased;
  279. purchaseInProgress = purchase.purchaseInProgress;
  280. if (purchaseInProgress)
  281. startTimer (1000 / 50);
  282. else
  283. stopTimer();
  284. nameLabel.setFont (Font (16).withStyle (Font::bold | (hasBeenPurchased ? 0 : Font::italic)));
  285. nameLabel.setColour (Label::textColourId, hasBeenPurchased ? Colours::white : Colours::grey);
  286. priceLabel.setFont (Font (10).withStyle (purchase.priceIsKnown ? 0 : Font::italic));
  287. priceLabel.setColour (Label::textColourId, hasBeenPurchased ? Colours::white : Colours::grey);
  288. priceLabel.setText (purchase.purchasePrice, NotificationType::dontSendNotification);
  289. if (rowNumber == 0)
  290. {
  291. purchaseButton.setButtonText ("Internal");
  292. purchaseButton.setEnabled (false);
  293. }
  294. else
  295. {
  296. purchaseButton.setButtonText (hasBeenPurchased ? "Purchased" : "Purchase");
  297. purchaseButton.setEnabled (! hasBeenPurchased && purchase.priceIsKnown);
  298. }
  299. setInterceptsMouseClicks (! hasBeenPurchased, ! hasBeenPurchased);
  300. if (auto* assetStream = createAssetInputStream (String ("Purchases/" + String (imageResourceName)).toRawUTF8()))
  301. {
  302. std::unique_ptr<InputStream> fileStream (assetStream);
  303. avatar = PNGImageFormat().decodeImage (*fileStream);
  304. }
  305. }
  306. }
  307. private:
  308. //==============================================================================
  309. void clickPurchase()
  310. {
  311. if (rowSelected >= 0)
  312. {
  313. if (! hasBeenPurchased)
  314. {
  315. purchases.purchaseVoice (rowSelected);
  316. purchaseInProgress = true;
  317. startTimer (1000 / 50);
  318. }
  319. }
  320. }
  321. void timerCallback() override { repaint(); }
  322. //==============================================================================
  323. bool isSelected = false, hasBeenPurchased = false, purchaseInProgress = false;
  324. int rowSelected = -1;
  325. Image avatar;
  326. StringArray voices;
  327. VoicePurchases& purchases;
  328. Label nameLabel, priceLabel;
  329. TextButton purchaseButton {"Purchase"};
  330. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VoiceRow)
  331. };
  332. //==============================================================================
  333. VoiceModel (VoicePurchases& voicePurchases) : purchases (voicePurchases)
  334. {
  335. voiceProducts = purchases.getVoiceNames();
  336. }
  337. int getNumRows() override { return voiceProducts.size(); }
  338. Component* refreshComponentForRow (int row, bool selected, Component* existing) override
  339. {
  340. if (isPositiveAndBelow (row, voiceProducts.size()))
  341. {
  342. if (existing == nullptr)
  343. existing = new VoiceRow (purchases);
  344. if (auto* voiceRow = dynamic_cast<VoiceRow*> (existing))
  345. voiceRow->update (row, selected);
  346. return existing;
  347. }
  348. return nullptr;
  349. }
  350. void paintListBoxItem (int, Graphics& g, int w, int h, bool isSelected) override
  351. {
  352. auto r = Rectangle<int> (0, 0, w, h).reduced (4);
  353. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  354. g.setColour (lf.findColour (isSelected ? TextEditor::highlightColourId : ListBox::backgroundColourId));
  355. g.fillRect (r);
  356. }
  357. private:
  358. StringArray voiceProducts;
  359. VoicePurchases& purchases;
  360. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VoiceModel)
  361. };
  362. //==============================================================================
  363. class InAppPurchasesDemo : public Component,
  364. private AsyncUpdater
  365. {
  366. public:
  367. InAppPurchasesDemo()
  368. {
  369. Desktop::getInstance().getDefaultLookAndFeel().setUsingNativeAlertWindows (true);
  370. dm.addAudioCallback (&player);
  371. dm.initialiseWithDefaultDevices (0, 2);
  372. setOpaque (true);
  373. phraseListBox.setModel (phraseModel.get());
  374. voiceListBox .setModel (voiceModel.get());
  375. phraseListBox.setRowHeight (33);
  376. phraseListBox.selectRow (0);
  377. phraseListBox.updateContent();
  378. voiceListBox.setRowHeight (66);
  379. voiceListBox.selectRow (0);
  380. voiceListBox.updateContent();
  381. voiceListBox.getViewport()->setScrollOnDragEnabled (true);
  382. addAndMakeVisible (phraseLabel);
  383. addAndMakeVisible (phraseListBox);
  384. addAndMakeVisible (playStopButton);
  385. addAndMakeVisible (voiceLabel);
  386. addAndMakeVisible (voiceListBox);
  387. playStopButton.onClick = [this] { playStopPhrase(); };
  388. soundNames = purchases.getVoiceNames();
  389. #if JUCE_ANDROID || JUCE_IOS
  390. auto screenBounds = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  391. setSize (screenBounds.getWidth(), screenBounds.getHeight());
  392. #else
  393. setSize (800, 600);
  394. #endif
  395. }
  396. ~InAppPurchasesDemo()
  397. {
  398. dm.closeAudioDevice();
  399. dm.removeAudioCallback (&player);
  400. }
  401. private:
  402. //==============================================================================
  403. void handleAsyncUpdate() override
  404. {
  405. voiceListBox.updateContent();
  406. voiceListBox.setEnabled (! purchases.isPurchaseInProgress());
  407. voiceListBox.repaint();
  408. }
  409. //==============================================================================
  410. void resized() override
  411. {
  412. auto r = getLocalBounds().reduced (20);
  413. {
  414. auto phraseArea = r.removeFromTop (r.getHeight() / 2);
  415. phraseLabel .setBounds (phraseArea.removeFromTop (36).reduced (0, 10));
  416. playStopButton.setBounds (phraseArea.removeFromBottom (50).reduced (0, 10));
  417. phraseListBox .setBounds (phraseArea);
  418. }
  419. {
  420. auto voiceArea = r;
  421. voiceLabel .setBounds (voiceArea.removeFromTop (36).reduced (0, 10));
  422. voiceListBox.setBounds (voiceArea);
  423. }
  424. }
  425. void paint (Graphics& g) override
  426. {
  427. g.fillAll (Desktop::getInstance().getDefaultLookAndFeel()
  428. .findColour (ResizableWindow::backgroundColourId));
  429. }
  430. //==============================================================================
  431. void playStopPhrase()
  432. {
  433. auto idx = voiceListBox.getSelectedRow();
  434. if (isPositiveAndBelow (idx, soundNames.size()))
  435. {
  436. auto assetName = "Purchases/" + soundNames[idx] + String (phraseListBox.getSelectedRow()) + ".ogg";
  437. if (auto* assetStream = createAssetInputStream (assetName.toRawUTF8()))
  438. {
  439. std::unique_ptr<InputStream> fileStream (assetStream);
  440. currentPhraseData.reset();
  441. fileStream->readIntoMemoryBlock (currentPhraseData);
  442. player.play (currentPhraseData.getData(), currentPhraseData.getSize());
  443. }
  444. }
  445. }
  446. //==============================================================================
  447. StringArray soundNames;
  448. Label phraseLabel { "phraseLabel", NEEDS_TRANS ("Phrases:") };
  449. ListBox phraseListBox { "phraseListBox" };
  450. std::unique_ptr<ListBoxModel> phraseModel { new PhraseModel() };
  451. TextButton playStopButton { "Play" };
  452. SoundPlayer player;
  453. VoicePurchases purchases { *this };
  454. AudioDeviceManager dm;
  455. Label voiceLabel { "voiceLabel", NEEDS_TRANS ("Voices:") };
  456. ListBox voiceListBox { "voiceListBox" };
  457. std::unique_ptr<VoiceModel> voiceModel { new VoiceModel (purchases) };
  458. MemoryBlock currentPhraseData;
  459. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InAppPurchasesDemo)
  460. };