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.

402 lines
12KB

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