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.

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