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.

599 lines
22KB

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