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.

400 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. type: Component
  28. mainClass: XMLandJSONDemo
  29. useLocalCopy: 1
  30. END_JUCE_PIP_METADATA
  31. *******************************************************************************/
  32. #pragma once
  33. #include "../Assets/DemoUtilities.h"
  34. //==============================================================================
  35. class XmlTreeItem : public TreeViewItem
  36. {
  37. public:
  38. XmlTreeItem (XmlElement& x) : xml (x) {}
  39. String getUniqueName() const override
  40. {
  41. if (xml.getTagName().isEmpty())
  42. return "unknown";
  43. return xml.getTagName();
  44. }
  45. bool mightContainSubItems() override
  46. {
  47. return xml.getFirstChildElement() != nullptr;
  48. }
  49. void paintItem (Graphics& g, int width, int height) override
  50. {
  51. // if this item is selected, fill it with a background colour..
  52. if (isSelected())
  53. g.fillAll (Colours::blue.withAlpha (0.3f));
  54. // use a "colour" attribute in the xml tag for this node to set the text colour..
  55. g.setColour (Colour::fromString (xml.getStringAttribute ("colour", "ff000000")));
  56. g.setFont (height * 0.7f);
  57. // draw the xml element's tag name..
  58. g.drawText (xml.getTagName(),
  59. 4, 0, width - 4, height,
  60. Justification::centredLeft, true);
  61. }
  62. void itemOpennessChanged (bool isNowOpen) override
  63. {
  64. if (isNowOpen)
  65. {
  66. // if we've not already done so, we'll now add the tree's sub-items. You could
  67. // also choose to delete the existing ones and refresh them if that's more suitable
  68. // in your app.
  69. if (getNumSubItems() == 0)
  70. {
  71. // create and add sub-items to this node of the tree, corresponding to
  72. // each sub-element in the XML..
  73. forEachXmlChildElement (xml, child)
  74. {
  75. jassert (child != nullptr);
  76. addSubItem (new XmlTreeItem (*child));
  77. }
  78. }
  79. }
  80. else
  81. {
  82. // in this case, we'll leave any sub-items in the tree when the node gets closed,
  83. // though you could choose to delete them if that's more appropriate for
  84. // your application.
  85. }
  86. }
  87. private:
  88. XmlElement& xml;
  89. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlTreeItem)
  90. };
  91. //==============================================================================
  92. class JsonTreeItem : public TreeViewItem
  93. {
  94. public:
  95. JsonTreeItem (Identifier i, var value)
  96. : identifier (i),
  97. json (value)
  98. {}
  99. String getUniqueName() const override
  100. {
  101. return identifier.toString() + "_id";
  102. }
  103. bool mightContainSubItems() override
  104. {
  105. if (auto* obj = json.getDynamicObject())
  106. return obj->getProperties().size() > 0;
  107. return json.isArray();
  108. }
  109. void paintItem (Graphics& g, int width, int height) override
  110. {
  111. // if this item is selected, fill it with a background colour..
  112. if (isSelected())
  113. g.fillAll (Colours::blue.withAlpha (0.3f));
  114. g.setColour (Colours::black);
  115. g.setFont (height * 0.7f);
  116. // draw the element's tag name..
  117. g.drawText (getText(),
  118. 4, 0, width - 4, height,
  119. Justification::centredLeft, true);
  120. }
  121. void itemOpennessChanged (bool isNowOpen) override
  122. {
  123. if (isNowOpen)
  124. {
  125. // if we've not already done so, we'll now add the tree's sub-items. You could
  126. // also choose to delete the existing ones and refresh them if that's more suitable
  127. // in your app.
  128. if (getNumSubItems() == 0)
  129. {
  130. // create and add sub-items to this node of the tree, corresponding to
  131. // the type of object this var represents
  132. if (json.isArray())
  133. {
  134. for (int i = 0; i < json.size(); ++i)
  135. {
  136. auto& child = json[i];
  137. jassert (! child.isVoid());
  138. addSubItem (new JsonTreeItem ({}, child));
  139. }
  140. }
  141. else if (auto* obj = json.getDynamicObject())
  142. {
  143. auto& props = obj->getProperties();
  144. for (int i = 0; i < props.size(); ++i)
  145. {
  146. auto id = props.getName (i);
  147. auto child = props[id];
  148. jassert (! child.isVoid());
  149. addSubItem (new JsonTreeItem (id, child));
  150. }
  151. }
  152. }
  153. }
  154. else
  155. {
  156. // in this case, we'll leave any sub-items in the tree when the node gets closed,
  157. // though you could choose to delete them if that's more appropriate for
  158. // your application.
  159. }
  160. }
  161. private:
  162. Identifier identifier;
  163. var json;
  164. /** Returns the text to display in the tree.
  165. This is a little more complex for JSON than XML as nodes can be strings, objects or arrays.
  166. */
  167. String getText() const
  168. {
  169. String text;
  170. if (identifier.isValid())
  171. text << identifier.toString();
  172. if (! json.isVoid())
  173. {
  174. if (text.isNotEmpty() && (! json.isArray()))
  175. text << ": ";
  176. if (json.isObject() && (! identifier.isValid()))
  177. text << "[Array]";
  178. else if (! json.isArray())
  179. text << json.toString();
  180. }
  181. return text;
  182. }
  183. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JsonTreeItem)
  184. };
  185. //==============================================================================
  186. class XMLandJSONDemo : public Component,
  187. private CodeDocument::Listener
  188. {
  189. public:
  190. /** The type of database to parse. */
  191. enum Type
  192. {
  193. xml,
  194. json
  195. };
  196. XMLandJSONDemo()
  197. {
  198. setOpaque (true);
  199. addAndMakeVisible (typeBox);
  200. typeBox.addItem ("XML", 1);
  201. typeBox.addItem ("JSON", 2);
  202. typeBox.onChange = [this]
  203. {
  204. if (typeBox.getSelectedId() == 1)
  205. reset (xml);
  206. else
  207. reset (json);
  208. };
  209. comboBoxLabel.attachToComponent (&typeBox, true);
  210. addAndMakeVisible (codeDocumentComponent);
  211. codeDocument.addListener (this);
  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()
  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.get() != nullptr)
  253. openness.reset (rootItem->getOpennessState());
  254. createNewRootNode();
  255. if (openness.get() != nullptr && rootItem.get() != 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.get() != nullptr)
  272. errorMessage.clear();
  273. errorMessage.setVisible (! errorMessage.isEmpty());
  274. resultsTree.setRootItem (rootItem.get());
  275. }
  276. /** Parses the editors contects as XML. */
  277. TreeViewItem* rebuildXml()
  278. {
  279. parsedXml.reset();
  280. XmlDocument doc (codeDocument.getAllContent());
  281. parsedXml.reset (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 editors contects 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. };