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.

401 lines
12KB

  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: XMLandJSONDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Reads XML and JSON files.
  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: XMLandJSONDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. //==============================================================================
  36. class XmlTreeItem final : public TreeViewItem
  37. {
  38. public:
  39. XmlTreeItem (XmlElement& x) : xml (x) {}
  40. String getUniqueName() const override
  41. {
  42. if (xml.getTagName().isEmpty())
  43. return "unknown";
  44. return xml.getTagName();
  45. }
  46. bool mightContainSubItems() override
  47. {
  48. return xml.getFirstChildElement() != nullptr;
  49. }
  50. void paintItem (Graphics& g, int width, int height) override
  51. {
  52. // if this item is selected, fill it with a background colour..
  53. if (isSelected())
  54. g.fillAll (Colours::blue.withAlpha (0.3f));
  55. // use a "colour" attribute in the xml tag for this node to set the text colour..
  56. g.setColour (Colour::fromString (xml.getStringAttribute ("colour", "ff000000")));
  57. g.setFont ((float) height * 0.7f);
  58. // draw the xml element's tag name..
  59. g.drawText (xml.getTagName(),
  60. 4, 0, width - 4, height,
  61. Justification::centredLeft, true);
  62. }
  63. void itemOpennessChanged (bool isNowOpen) override
  64. {
  65. if (isNowOpen)
  66. {
  67. // if we've not already done so, we'll now add the tree's sub-items. You could
  68. // also choose to delete the existing ones and refresh them if that's more suitable
  69. // in your app.
  70. if (getNumSubItems() == 0)
  71. {
  72. // create and add sub-items to this node of the tree, corresponding to
  73. // each sub-element in the XML..
  74. for (auto* child : xml.getChildIterator())
  75. if (child != nullptr)
  76. addSubItem (new XmlTreeItem (*child));
  77. }
  78. }
  79. else
  80. {
  81. // in this case, we'll leave any sub-items in the tree when the node gets closed,
  82. // though you could choose to delete them if that's more appropriate for
  83. // your application.
  84. }
  85. }
  86. private:
  87. XmlElement& xml;
  88. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlTreeItem)
  89. };
  90. //==============================================================================
  91. class JsonTreeItem final : public TreeViewItem
  92. {
  93. public:
  94. JsonTreeItem (Identifier i, var value)
  95. : identifier (i),
  96. json (value)
  97. {}
  98. String getUniqueName() const override
  99. {
  100. return identifier.toString() + "_id";
  101. }
  102. bool mightContainSubItems() override
  103. {
  104. if (auto* obj = json.getDynamicObject())
  105. return obj->getProperties().size() > 0;
  106. return json.isArray();
  107. }
  108. void paintItem (Graphics& g, int width, int height) override
  109. {
  110. // if this item is selected, fill it with a background colour..
  111. if (isSelected())
  112. g.fillAll (Colours::blue.withAlpha (0.3f));
  113. g.setColour (Colours::black);
  114. g.setFont ((float) height * 0.7f);
  115. // draw the element's tag name..
  116. g.drawText (getText(),
  117. 4, 0, width - 4, height,
  118. Justification::centredLeft, true);
  119. }
  120. void itemOpennessChanged (bool isNowOpen) override
  121. {
  122. if (isNowOpen)
  123. {
  124. // if we've not already done so, we'll now add the tree's sub-items. You could
  125. // also choose to delete the existing ones and refresh them if that's more suitable
  126. // in your app.
  127. if (getNumSubItems() == 0)
  128. {
  129. // create and add sub-items to this node of the tree, corresponding to
  130. // the type of object this var represents
  131. if (json.isArray())
  132. {
  133. for (int i = 0; i < json.size(); ++i)
  134. {
  135. auto& child = json[i];
  136. jassert (! child.isVoid());
  137. addSubItem (new JsonTreeItem ({}, child));
  138. }
  139. }
  140. else if (auto* obj = json.getDynamicObject())
  141. {
  142. auto& props = obj->getProperties();
  143. for (int i = 0; i < props.size(); ++i)
  144. {
  145. auto id = props.getName (i);
  146. auto child = props[id];
  147. jassert (! child.isVoid());
  148. addSubItem (new JsonTreeItem (id, child));
  149. }
  150. }
  151. }
  152. }
  153. else
  154. {
  155. // in this case, we'll leave any sub-items in the tree when the node gets closed,
  156. // though you could choose to delete them if that's more appropriate for
  157. // your application.
  158. }
  159. }
  160. private:
  161. Identifier identifier;
  162. var json;
  163. /** Returns the text to display in the tree.
  164. This is a little more complex for JSON than XML as nodes can be strings, objects or arrays.
  165. */
  166. String getText() const
  167. {
  168. String text;
  169. if (identifier.isValid())
  170. text << identifier.toString();
  171. if (! json.isVoid())
  172. {
  173. if (text.isNotEmpty() && (! json.isArray()))
  174. text << ": ";
  175. if (json.isObject() && (! identifier.isValid()))
  176. text << "[Array]";
  177. else if (! json.isArray())
  178. text << json.toString();
  179. }
  180. return text;
  181. }
  182. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JsonTreeItem)
  183. };
  184. //==============================================================================
  185. class XMLandJSONDemo final : public Component,
  186. private CodeDocument::Listener
  187. {
  188. public:
  189. /** The type of database to parse. */
  190. enum Type
  191. {
  192. xml,
  193. json
  194. };
  195. XMLandJSONDemo()
  196. {
  197. setOpaque (true);
  198. addAndMakeVisible (typeBox);
  199. typeBox.addItem ("XML", 1);
  200. typeBox.addItem ("JSON", 2);
  201. typeBox.onChange = [this]
  202. {
  203. if (typeBox.getSelectedId() == 1)
  204. reset (xml);
  205. else
  206. reset (json);
  207. };
  208. comboBoxLabel.attachToComponent (&typeBox, true);
  209. addAndMakeVisible (codeDocumentComponent);
  210. codeDocument.addListener (this);
  211. resultsTree.setTitle ("Results");
  212. addAndMakeVisible (resultsTree);
  213. resultsTree.setColour (TreeView::backgroundColourId, Colours::white);
  214. resultsTree.setDefaultOpenness (true);
  215. addAndMakeVisible (errorMessage);
  216. errorMessage.setReadOnly (true);
  217. errorMessage.setMultiLine (true);
  218. errorMessage.setCaretVisible (false);
  219. errorMessage.setColour (TextEditor::outlineColourId, Colours::transparentWhite);
  220. errorMessage.setColour (TextEditor::shadowColourId, Colours::transparentWhite);
  221. typeBox.setSelectedId (1);
  222. setSize (500, 500);
  223. }
  224. ~XMLandJSONDemo() override
  225. {
  226. resultsTree.setRootItem (nullptr);
  227. }
  228. void paint (Graphics& g) override
  229. {
  230. g.fillAll (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground));
  231. }
  232. void resized() override
  233. {
  234. auto area = getLocalBounds();
  235. typeBox.setBounds (area.removeFromTop (36).removeFromRight (150).reduced (8));
  236. codeDocumentComponent.setBounds (area.removeFromTop (area.getHeight() / 2).reduced (8));
  237. resultsTree .setBounds (area.reduced (8));
  238. errorMessage .setBounds (resultsTree.getBounds());
  239. }
  240. private:
  241. ComboBox typeBox;
  242. Label comboBoxLabel { {}, "Database Type:" };
  243. CodeDocument codeDocument;
  244. CodeEditorComponent codeDocumentComponent { codeDocument, nullptr };
  245. TreeView resultsTree;
  246. std::unique_ptr<TreeViewItem> rootItem;
  247. std::unique_ptr<XmlElement> parsedXml;
  248. TextEditor errorMessage;
  249. void rebuildTree()
  250. {
  251. std::unique_ptr<XmlElement> openness;
  252. if (rootItem != nullptr)
  253. openness = rootItem->getOpennessState();
  254. createNewRootNode();
  255. if (openness != nullptr && rootItem != nullptr)
  256. rootItem->restoreOpennessState (*openness);
  257. }
  258. void createNewRootNode()
  259. {
  260. // clear the current tree
  261. resultsTree.setRootItem (nullptr);
  262. rootItem.reset();
  263. // try and parse the editor's contents
  264. switch (typeBox.getSelectedItemIndex())
  265. {
  266. case xml: rootItem.reset (rebuildXml()); break;
  267. case json: rootItem.reset (rebuildJson()); break;
  268. default: rootItem.reset(); break;
  269. }
  270. // if we have a valid TreeViewItem hide any old error messages and set our TreeView to use it
  271. if (rootItem != nullptr)
  272. errorMessage.clear();
  273. errorMessage.setVisible (! errorMessage.isEmpty());
  274. resultsTree.setRootItem (rootItem.get());
  275. }
  276. /** Parses the editor's contents as XML. */
  277. TreeViewItem* rebuildXml()
  278. {
  279. parsedXml.reset();
  280. XmlDocument doc (codeDocument.getAllContent());
  281. parsedXml = doc.getDocumentElement();
  282. if (parsedXml.get() == nullptr)
  283. {
  284. auto error = doc.getLastParseError();
  285. if (error.isEmpty())
  286. error = "Unknown error";
  287. errorMessage.setText ("Error parsing XML: " + error, dontSendNotification);
  288. return nullptr;
  289. }
  290. return new XmlTreeItem (*parsedXml);
  291. }
  292. /** Parses the editor's contents as JSON. */
  293. TreeViewItem* rebuildJson()
  294. {
  295. var parsedJson;
  296. auto result = JSON::parse (codeDocument.getAllContent(), parsedJson);
  297. if (! result.wasOk())
  298. {
  299. errorMessage.setText ("Error parsing JSON: " + result.getErrorMessage());
  300. return nullptr;
  301. }
  302. return new JsonTreeItem (Identifier(), parsedJson);
  303. }
  304. /** Clears the editor and loads some default text. */
  305. void reset (Type type)
  306. {
  307. switch (type)
  308. {
  309. case xml: codeDocument.replaceAllContent (loadEntireAssetIntoString ("treedemo.xml")); break;
  310. case json: codeDocument.replaceAllContent (loadEntireAssetIntoString ("juce_module_info")); break;
  311. default: codeDocument.replaceAllContent ({}); break;
  312. }
  313. }
  314. void codeDocumentTextInserted (const String&, int) override { rebuildTree(); }
  315. void codeDocumentTextDeleted (int, int) override { rebuildTree(); }
  316. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XMLandJSONDemo)
  317. };