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.

186 lines
6.1KB

  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: JavaScriptDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Showcases JavaScript features.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics, juce_gui_extra
  26. exporters: xcode_mac, vs2022, linux_make, androidstudio, xcode_iphone
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Component
  29. mainClass: JavaScriptDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. //==============================================================================
  36. class JavaScriptDemo final : public Component,
  37. private CodeDocument::Listener,
  38. private Timer
  39. {
  40. public:
  41. JavaScriptDemo()
  42. {
  43. setOpaque (true);
  44. editor.reset (new CodeEditorComponent (codeDocument, nullptr));
  45. addAndMakeVisible (editor.get());
  46. editor->setFont ({ Font::getDefaultMonospacedFontName(), 14.0f, Font::plain });
  47. editor->setTabSize (4, true);
  48. outputDisplay.setMultiLine (true);
  49. outputDisplay.setReadOnly (true);
  50. outputDisplay.setCaretVisible (false);
  51. outputDisplay.setFont ({ Font::getDefaultMonospacedFontName(), 14.0f, Font::plain });
  52. addAndMakeVisible (outputDisplay);
  53. codeDocument.addListener (this);
  54. editor->loadContent (
  55. "/*\n"
  56. " Javascript! In this simple demo, the native\n"
  57. " code provides an object called \'Demo\' which\n"
  58. " has a method \'print\' that writes to the\n"
  59. " console below...\n"
  60. "*/\n"
  61. "\n"
  62. "Demo.print (\"Hello World in JUCE + Javascript!\");\n"
  63. "Demo.print (\"\");\n"
  64. "\n"
  65. "function factorial (n)\n"
  66. "{\n"
  67. " var total = 1;\n"
  68. " while (n > 0)\n"
  69. " total = total * n--;\n"
  70. " return total;\n"
  71. "}\n"
  72. "\n"
  73. "for (var i = 1; i < 10; ++i)\n"
  74. " Demo.print (\"Factorial of \" + i \n"
  75. " + \" = \" + factorial (i));\n");
  76. setSize (600, 750);
  77. }
  78. void runScript()
  79. {
  80. outputDisplay.clear();
  81. JavascriptEngine engine;
  82. engine.maximumExecutionTime = RelativeTime::seconds (5);
  83. engine.registerNativeObject ("Demo", new DemoClass (*this));
  84. auto startTime = Time::getMillisecondCounterHiRes();
  85. auto result = engine.execute (codeDocument.getAllContent());
  86. auto elapsedMs = Time::getMillisecondCounterHiRes() - startTime;
  87. if (result.failed())
  88. outputDisplay.setText (result.getErrorMessage());
  89. else
  90. outputDisplay.insertTextAtCaret ("\n(Execution time: " + String (elapsedMs, 2) + " milliseconds)");
  91. }
  92. void consoleOutput (const String& message)
  93. {
  94. outputDisplay.moveCaretToEnd();
  95. outputDisplay.insertTextAtCaret (message + newLine);
  96. }
  97. //==============================================================================
  98. // This class is used by the script, and provides methods that the JS can call.
  99. struct DemoClass final : public DynamicObject
  100. {
  101. DemoClass (JavaScriptDemo& demo) : owner (demo)
  102. {
  103. setMethod ("print", print);
  104. }
  105. static Identifier getClassName() { return "Demo"; }
  106. static var print (const var::NativeFunctionArgs& args)
  107. {
  108. if (args.numArguments > 0)
  109. if (auto* thisObject = dynamic_cast<DemoClass*> (args.thisObject.getObject()))
  110. thisObject->owner.consoleOutput (args.arguments[0].toString());
  111. return var::undefined();
  112. }
  113. JavaScriptDemo& owner;
  114. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoClass)
  115. };
  116. void paint (Graphics& g) override
  117. {
  118. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  119. }
  120. private:
  121. CodeDocument codeDocument;
  122. std::unique_ptr<CodeEditorComponent> editor;
  123. TextEditor outputDisplay;
  124. void codeDocumentTextInserted (const String&, int) override { startTimer (300); }
  125. void codeDocumentTextDeleted (int, int) override { startTimer (300); }
  126. void timerCallback() override
  127. {
  128. stopTimer();
  129. runScript();
  130. }
  131. void resized() override
  132. {
  133. auto r = getLocalBounds().reduced (8);
  134. editor->setBounds (r.removeFromTop (proportionOfHeight (0.6f)));
  135. outputDisplay.setBounds (r.withTrimmedTop (8));
  136. }
  137. void lookAndFeelChanged() override
  138. {
  139. outputDisplay.applyFontToAllText (outputDisplay.getFont());
  140. }
  141. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JavaScriptDemo)
  142. };