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.

605 lines
22KB

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