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.

184 lines
6.1KB

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