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.

614 lines
23KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2022 - 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 final : 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. auto options = MessageBoxOptions::makeOptionsOk (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. messageBox = AlertWindow::showScopedAsync (options, nullptr);
  132. }
  133. else
  134. {
  135. for (auto product : products)
  136. {
  137. auto idx = findVoiceIndexFromIdentifier (product.identifier);
  138. if (isPositiveAndBelow (idx, voiceProducts.size()))
  139. {
  140. auto& voiceProduct = voiceProducts.getReference (idx);
  141. voiceProduct.priceIsKnown = true;
  142. voiceProduct.purchasePrice = product.price;
  143. }
  144. }
  145. auto options = MessageBoxOptions::makeOptionsOk (MessageBoxIconType::WarningIcon,
  146. "Your credit card will be charged!",
  147. "You are running the sample code for JUCE In-App purchases. "
  148. "Although this is only sample code, it will still CHARGE YOUR CREDIT CARD!",
  149. "Understood!");
  150. messageBox = AlertWindow::showScopedAsync (options, nullptr);
  151. }
  152. guiUpdater.triggerAsyncUpdate();
  153. }
  154. void productPurchaseFinished (const PurchaseInfo& info, bool success, const String& error) override
  155. {
  156. purchaseInProgress = false;
  157. for (const auto& productId : info.purchase.productIds)
  158. {
  159. auto idx = findVoiceIndexFromIdentifier (productId);
  160. if (isPositiveAndBelow (idx, voiceProducts.size()))
  161. {
  162. auto& voiceProduct = voiceProducts.getReference (idx);
  163. voiceProduct.isPurchased = success;
  164. voiceProduct.purchaseInProgress = false;
  165. }
  166. else
  167. {
  168. // On failure Play Store will not tell us which purchase failed
  169. for (auto& voiceProduct : voiceProducts)
  170. voiceProduct.purchaseInProgress = false;
  171. }
  172. }
  173. if (! success)
  174. {
  175. auto options = MessageBoxOptions::makeOptionsOk (MessageBoxIconType::WarningIcon, "Purchase failed", error);
  176. messageBox = AlertWindow::showScopedAsync (options, nullptr);
  177. }
  178. guiUpdater.triggerAsyncUpdate();
  179. }
  180. void purchasesListRestored (const Array<PurchaseInfo>& infos, bool success, const String&) override
  181. {
  182. if (success)
  183. {
  184. for (const auto& info : infos)
  185. {
  186. for (const auto& productId : info.purchase.productIds)
  187. {
  188. auto idx = findVoiceIndexFromIdentifier (productId);
  189. if (isPositiveAndBelow (idx, voiceProducts.size()))
  190. {
  191. auto& voiceProduct = voiceProducts.getReference (idx);
  192. voiceProduct.isPurchased = true;
  193. }
  194. }
  195. }
  196. guiUpdater.triggerAsyncUpdate();
  197. }
  198. if (! havePricesBeenFetched)
  199. {
  200. havePricesBeenFetched = true;
  201. StringArray identifiers;
  202. for (const auto& voiceProduct : voiceProducts)
  203. identifiers.add (voiceProduct.identifier);
  204. InAppPurchases::getInstance()->getProductsInformation (identifiers);
  205. }
  206. }
  207. //==============================================================================
  208. int findVoiceIndexFromIdentifier (String identifier) const
  209. {
  210. identifier = identifier.toLowerCase();
  211. for (auto i = 0; i < voiceProducts.size(); ++i)
  212. if (String (voiceProducts.getReference (i).identifier) == identifier)
  213. return i;
  214. return -1;
  215. }
  216. //==============================================================================
  217. AsyncUpdater& guiUpdater;
  218. bool havePurchasesBeenRestored = false, havePricesBeenFetched = false, purchaseInProgress = false;
  219. Array<VoiceProduct> voiceProducts;
  220. ScopedMessageBox messageBox;
  221. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VoicePurchases)
  222. };
  223. //==============================================================================
  224. class PhraseModel final : public ListBoxModel
  225. {
  226. public:
  227. PhraseModel() {}
  228. int getNumRows() override { return phrases.size(); }
  229. void paintListBoxItem (int row, Graphics& g, int w, int h, bool isSelected) override
  230. {
  231. Rectangle<int> r (0, 0, w, h);
  232. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  233. g.setColour (lf.findColour (isSelected ? (int) TextEditor::highlightColourId : (int) ListBox::backgroundColourId));
  234. g.fillRect (r);
  235. g.setColour (lf.findColour (ListBox::textColourId));
  236. g.setFont (18);
  237. String phrase = (isPositiveAndBelow (row, phrases.size()) ? phrases[row] : String{});
  238. g.drawText (phrase, 10, 0, w, h, Justification::centredLeft);
  239. }
  240. private:
  241. StringArray phrases {"I love JUCE!", "The five dimensions of touch", "Make it fast!"};
  242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PhraseModel)
  243. };
  244. //==============================================================================
  245. class VoiceModel final : public ListBoxModel
  246. {
  247. public:
  248. //==============================================================================
  249. class VoiceRow final : public Component,
  250. private Timer
  251. {
  252. public:
  253. VoiceRow (VoicePurchases& voicePurchases) : purchases (voicePurchases)
  254. {
  255. addAndMakeVisible (nameLabel);
  256. addAndMakeVisible (purchaseButton);
  257. addAndMakeVisible (priceLabel);
  258. purchaseButton.onClick = [this] { clickPurchase(); };
  259. voices = purchases.getVoiceNames();
  260. setSize (600, 33);
  261. }
  262. void paint (Graphics& g) override
  263. {
  264. auto r = getLocalBounds().reduced (4);
  265. {
  266. auto voiceIconBounds = r.removeFromLeft (r.getHeight());
  267. g.setColour (Colours::black);
  268. g.drawRect (voiceIconBounds);
  269. voiceIconBounds.reduce (1, 1);
  270. g.setColour (hasBeenPurchased ? Colours::white : Colours::grey);
  271. g.fillRect (voiceIconBounds);
  272. g.drawImage (avatar, voiceIconBounds.toFloat());
  273. if (! hasBeenPurchased)
  274. {
  275. g.setColour (Colours::white.withAlpha (0.8f));
  276. g.fillRect (voiceIconBounds);
  277. if (purchaseInProgress)
  278. getLookAndFeel().drawSpinningWaitAnimation (g, Colours::darkgrey,
  279. voiceIconBounds.getX(),
  280. voiceIconBounds.getY(),
  281. voiceIconBounds.getWidth(),
  282. voiceIconBounds.getHeight());
  283. }
  284. }
  285. }
  286. void resized() override
  287. {
  288. auto r = getLocalBounds().reduced (4 + 8, 4);
  289. auto h = r.getHeight();
  290. auto w = static_cast<int> (h * 1.5);
  291. r.removeFromLeft (h);
  292. purchaseButton.setBounds (r.removeFromRight (w).withSizeKeepingCentre (w, h / 2));
  293. nameLabel.setBounds (r.removeFromTop (18));
  294. priceLabel.setBounds (r.removeFromTop (18));
  295. }
  296. void update (int rowNumber, bool rowIsSelected)
  297. {
  298. isSelected = rowIsSelected;
  299. rowSelected = rowNumber;
  300. if (isPositiveAndBelow (rowNumber, voices.size()))
  301. {
  302. auto imageResourceName = voices[rowNumber] + ".png";
  303. nameLabel.setText (voices[rowNumber], NotificationType::dontSendNotification);
  304. auto purchase = purchases.getPurchase (rowNumber);
  305. hasBeenPurchased = purchase.isPurchased;
  306. purchaseInProgress = purchase.purchaseInProgress;
  307. if (purchaseInProgress)
  308. startTimer (1000 / 50);
  309. else
  310. stopTimer();
  311. nameLabel.setFont (Font (16).withStyle (Font::bold | (hasBeenPurchased ? 0 : Font::italic)));
  312. nameLabel.setColour (Label::textColourId, hasBeenPurchased ? Colours::white : Colours::grey);
  313. priceLabel.setFont (Font (10).withStyle (purchase.priceIsKnown ? 0 : Font::italic));
  314. priceLabel.setColour (Label::textColourId, hasBeenPurchased ? Colours::white : Colours::grey);
  315. priceLabel.setText (purchase.purchasePrice, NotificationType::dontSendNotification);
  316. if (rowNumber == 0)
  317. {
  318. purchaseButton.setButtonText ("Internal");
  319. purchaseButton.setEnabled (false);
  320. }
  321. else
  322. {
  323. purchaseButton.setButtonText (hasBeenPurchased ? "Purchased" : "Purchase");
  324. purchaseButton.setEnabled (! hasBeenPurchased && purchase.priceIsKnown);
  325. }
  326. setInterceptsMouseClicks (! hasBeenPurchased, ! hasBeenPurchased);
  327. if (auto fileStream = createAssetInputStream (String ("Purchases/" + String (imageResourceName)).toRawUTF8()))
  328. avatar = PNGImageFormat().decodeImage (*fileStream);
  329. }
  330. }
  331. private:
  332. //==============================================================================
  333. void clickPurchase()
  334. {
  335. if (rowSelected >= 0)
  336. {
  337. if (! hasBeenPurchased)
  338. {
  339. purchases.purchaseVoice (rowSelected);
  340. purchaseInProgress = true;
  341. startTimer (1000 / 50);
  342. }
  343. }
  344. }
  345. void timerCallback() override { repaint(); }
  346. //==============================================================================
  347. bool isSelected = false, hasBeenPurchased = false, purchaseInProgress = false;
  348. int rowSelected = -1;
  349. Image avatar;
  350. StringArray voices;
  351. VoicePurchases& purchases;
  352. Label nameLabel, priceLabel;
  353. TextButton purchaseButton {"Purchase"};
  354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VoiceRow)
  355. };
  356. //==============================================================================
  357. VoiceModel (VoicePurchases& voicePurchases) : purchases (voicePurchases)
  358. {
  359. voiceProducts = purchases.getVoiceNames();
  360. }
  361. int getNumRows() override { return voiceProducts.size(); }
  362. Component* refreshComponentForRow (int row, bool selected, Component* existing) override
  363. {
  364. auto safePtr = rawToUniquePtr (existing);
  365. if (isPositiveAndBelow (row, voiceProducts.size()))
  366. {
  367. if (safePtr == nullptr)
  368. safePtr = std::make_unique<VoiceRow> (purchases);
  369. if (auto* voiceRow = dynamic_cast<VoiceRow*> (safePtr.get()))
  370. voiceRow->update (row, selected);
  371. return safePtr.release();
  372. }
  373. return nullptr;
  374. }
  375. void paintListBoxItem (int, Graphics& g, int w, int h, bool isSelected) override
  376. {
  377. auto r = Rectangle<int> (0, 0, w, h).reduced (4);
  378. auto& lf = Desktop::getInstance().getDefaultLookAndFeel();
  379. g.setColour (lf.findColour (isSelected ? (int) TextEditor::highlightColourId : (int) ListBox::backgroundColourId));
  380. g.fillRect (r);
  381. }
  382. private:
  383. StringArray voiceProducts;
  384. VoicePurchases& purchases;
  385. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VoiceModel)
  386. };
  387. //==============================================================================
  388. class InAppPurchasesDemo final : public Component,
  389. private AsyncUpdater
  390. {
  391. public:
  392. InAppPurchasesDemo()
  393. {
  394. manager.registerBasicFormats();
  395. Desktop::getInstance().getDefaultLookAndFeel().setUsingNativeAlertWindows (true);
  396. dm.addAudioCallback (&player);
  397. dm.initialiseWithDefaultDevices (0, 2);
  398. setOpaque (true);
  399. phraseListBox.setModel (phraseModel.get());
  400. voiceListBox .setModel (voiceModel.get());
  401. phraseListBox.setRowHeight (33);
  402. phraseListBox.selectRow (0);
  403. phraseListBox.updateContent();
  404. voiceListBox.setRowHeight (66);
  405. voiceListBox.selectRow (0);
  406. voiceListBox.updateContent();
  407. addAndMakeVisible (phraseLabel);
  408. addAndMakeVisible (phraseListBox);
  409. addAndMakeVisible (playStopButton);
  410. addAndMakeVisible (voiceLabel);
  411. addAndMakeVisible (voiceListBox);
  412. playStopButton.onClick = [this] { playStopPhrase(); };
  413. soundNames = purchases.getVoiceNames();
  414. #if JUCE_ANDROID || JUCE_IOS
  415. auto screenBounds = Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  416. setSize (screenBounds.getWidth(), screenBounds.getHeight());
  417. #else
  418. setSize (800, 600);
  419. #endif
  420. }
  421. ~InAppPurchasesDemo() override
  422. {
  423. dm.closeAudioDevice();
  424. dm.removeAudioCallback (&player);
  425. }
  426. private:
  427. //==============================================================================
  428. void handleAsyncUpdate() override
  429. {
  430. voiceListBox.updateContent();
  431. voiceListBox.setEnabled (! purchases.isPurchaseInProgress());
  432. voiceListBox.repaint();
  433. }
  434. //==============================================================================
  435. void resized() override
  436. {
  437. auto r = getLocalBounds().reduced (20);
  438. {
  439. auto phraseArea = r.removeFromTop (r.getHeight() / 2);
  440. phraseLabel .setBounds (phraseArea.removeFromTop (36).reduced (0, 10));
  441. playStopButton.setBounds (phraseArea.removeFromBottom (50).reduced (0, 10));
  442. phraseListBox .setBounds (phraseArea);
  443. }
  444. {
  445. auto voiceArea = r;
  446. voiceLabel .setBounds (voiceArea.removeFromTop (36).reduced (0, 10));
  447. voiceListBox.setBounds (voiceArea);
  448. }
  449. }
  450. void paint (Graphics& g) override
  451. {
  452. g.fillAll (Desktop::getInstance().getDefaultLookAndFeel()
  453. .findColour (ResizableWindow::backgroundColourId));
  454. }
  455. //==============================================================================
  456. void playStopPhrase()
  457. {
  458. auto idx = voiceListBox.getSelectedRow();
  459. if (isPositiveAndBelow (idx, soundNames.size()))
  460. {
  461. auto assetName = "Purchases/" + soundNames[idx] + String (phraseListBox.getSelectedRow()) + ".ogg";
  462. if (auto fileStream = createAssetInputStream (assetName.toRawUTF8()))
  463. if (auto* reader = manager.createReaderFor (std::move (fileStream)))
  464. player.play (reader, true);
  465. }
  466. }
  467. //==============================================================================
  468. StringArray soundNames;
  469. Label phraseLabel { "phraseLabel", NEEDS_TRANS ("Phrases:") };
  470. ListBox phraseListBox { "phraseListBox" };
  471. std::unique_ptr<ListBoxModel> phraseModel { new PhraseModel() };
  472. TextButton playStopButton { "Play" };
  473. SoundPlayer player;
  474. VoicePurchases purchases { *this };
  475. AudioDeviceManager dm;
  476. Label voiceLabel { "voiceLabel", NEEDS_TRANS ("Voices:") };
  477. ListBox voiceListBox { "voiceListBox" };
  478. std::unique_ptr<VoiceModel> voiceModel { new VoiceModel (purchases) };
  479. AudioFormatManager manager;
  480. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InAppPurchasesDemo)
  481. };