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.

786 lines
28KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. #include "../Application/jucer_Headers.h"
  14. #include "../Application/jucer_Application.h"
  15. #include "../Wizards/jucer_NewFileWizard.h"
  16. #include "jucer_JucerDocument.h"
  17. #include "jucer_ObjectTypes.h"
  18. #include "UI/jucer_JucerDocumentEditor.h"
  19. #include "UI/jucer_TestComponent.h"
  20. #include "jucer_UtilityFunctions.h"
  21. #include "Documents/jucer_ComponentDocument.h"
  22. #include "Documents/jucer_ButtonDocument.h"
  23. const char* const defaultClassName = "NewComponent";
  24. const char* const defaultParentClasses = "public Component";
  25. //==============================================================================
  26. JucerDocument::JucerDocument (SourceCodeDocument* c)
  27. : cpp (c),
  28. className (defaultClassName),
  29. parentClasses (defaultParentClasses)
  30. {
  31. jassert (cpp != nullptr);
  32. resources.setDocument (this);
  33. ProjucerApplication::getCommandManager().commandStatusChanged();
  34. cpp->getCodeDocument().addListener (this);
  35. }
  36. JucerDocument::~JucerDocument()
  37. {
  38. cpp->getCodeDocument().removeListener (this);
  39. ProjucerApplication::getCommandManager().commandStatusChanged();
  40. }
  41. //==============================================================================
  42. void JucerDocument::changed()
  43. {
  44. sendChangeMessage();
  45. ProjucerApplication::getCommandManager().commandStatusChanged();
  46. startTimer (800);
  47. }
  48. struct UserDocChangeTimer : public Timer
  49. {
  50. UserDocChangeTimer (JucerDocument& d) : doc (d) {}
  51. void timerCallback() override { doc.reloadFromDocument(); }
  52. JucerDocument& doc;
  53. };
  54. void JucerDocument::userEditedCpp()
  55. {
  56. if (userDocChangeTimer == nullptr)
  57. userDocChangeTimer.reset (new UserDocChangeTimer (*this));
  58. userDocChangeTimer->startTimer (500);
  59. }
  60. void JucerDocument::beginTransaction()
  61. {
  62. getUndoManager().beginNewTransaction();
  63. }
  64. void JucerDocument::beginTransaction (const String& name)
  65. {
  66. getUndoManager().beginNewTransaction (name);
  67. }
  68. void JucerDocument::timerCallback()
  69. {
  70. if (! Component::isMouseButtonDownAnywhere())
  71. {
  72. stopTimer();
  73. beginTransaction();
  74. flushChangesToDocuments (nullptr, false);
  75. }
  76. }
  77. void JucerDocument::codeDocumentTextInserted (const String&, int) { userEditedCpp(); }
  78. void JucerDocument::codeDocumentTextDeleted (int, int) { userEditedCpp(); }
  79. bool JucerDocument::perform (UndoableAction* const action, const String& actionName)
  80. {
  81. return undoManager.perform (action, actionName);
  82. }
  83. void JucerDocument::refreshAllPropertyComps()
  84. {
  85. if (ComponentLayout* l = getComponentLayout())
  86. l->getSelectedSet().changed();
  87. for (int i = getNumPaintRoutines(); --i >= 0;)
  88. {
  89. getPaintRoutine (i)->getSelectedElements().changed();
  90. getPaintRoutine (i)->getSelectedPoints().changed();
  91. }
  92. }
  93. //==============================================================================
  94. void JucerDocument::setClassName (const String& newName)
  95. {
  96. if (newName != className
  97. && build_tools::makeValidIdentifier (newName, false, false, true).isNotEmpty())
  98. {
  99. className = build_tools::makeValidIdentifier (newName, false, false, true);
  100. changed();
  101. }
  102. }
  103. void JucerDocument::setComponentName (const String& newName)
  104. {
  105. if (newName != componentName)
  106. {
  107. componentName = newName;
  108. changed();
  109. }
  110. }
  111. void JucerDocument::setParentClasses (const String& classes)
  112. {
  113. if (classes != parentClasses)
  114. {
  115. StringArray parentClassLines (getCleanedStringArray (StringArray::fromTokens (classes, ",", StringRef())));
  116. for (int i = parentClassLines.size(); --i >= 0;)
  117. {
  118. String s (parentClassLines[i]);
  119. String type;
  120. if (s.startsWith ("public ")
  121. || s.startsWith ("protected ")
  122. || s.startsWith ("private "))
  123. {
  124. type = s.upToFirstOccurrenceOf (" ", true, false);
  125. s = s.fromFirstOccurrenceOf (" ", false, false);
  126. if (s.trim().isEmpty())
  127. type = s = String();
  128. }
  129. s = type + build_tools::makeValidIdentifier (s.trim(), false, false, true, true);
  130. parentClassLines.set (i, s);
  131. }
  132. parentClasses = parentClassLines.joinIntoString (", ");
  133. changed();
  134. }
  135. }
  136. void JucerDocument::setConstructorParams (const String& newParams)
  137. {
  138. if (constructorParams != newParams)
  139. {
  140. constructorParams = newParams;
  141. changed();
  142. }
  143. }
  144. void JucerDocument::setVariableInitialisers (const String& newInitlialisers)
  145. {
  146. if (variableInitialisers != newInitlialisers)
  147. {
  148. variableInitialisers = newInitlialisers;
  149. changed();
  150. }
  151. }
  152. void JucerDocument::setFixedSize (const bool isFixed)
  153. {
  154. if (fixedSize != isFixed)
  155. {
  156. fixedSize = isFixed;
  157. changed();
  158. }
  159. }
  160. void JucerDocument::setInitialSize (int w, int h)
  161. {
  162. w = jmax (1, w);
  163. h = jmax (1, h);
  164. if (initialWidth != w || initialHeight != h)
  165. {
  166. initialWidth = w;
  167. initialHeight = h;
  168. changed();
  169. }
  170. }
  171. //==============================================================================
  172. bool JucerDocument::isSnapActive (const bool disableIfCtrlKeyDown) const noexcept
  173. {
  174. return snapActive != (disableIfCtrlKeyDown && ModifierKeys::currentModifiers.isCtrlDown());
  175. }
  176. int JucerDocument::snapPosition (int pos) const noexcept
  177. {
  178. if (isSnapActive (true))
  179. {
  180. jassert (snapGridPixels > 0);
  181. pos = ((pos + snapGridPixels * 1024 + snapGridPixels / 2) / snapGridPixels - 1024) * snapGridPixels;
  182. }
  183. return pos;
  184. }
  185. void JucerDocument::setSnappingGrid (const int numPixels, const bool active, const bool shown)
  186. {
  187. if (numPixels != snapGridPixels
  188. || active != snapActive
  189. || shown != snapShown)
  190. {
  191. snapGridPixels = numPixels;
  192. snapActive = active;
  193. snapShown = shown;
  194. changed();
  195. }
  196. }
  197. void JucerDocument::setComponentOverlayOpacity (const float alpha)
  198. {
  199. if (alpha != componentOverlayOpacity)
  200. {
  201. componentOverlayOpacity = alpha;
  202. changed();
  203. }
  204. }
  205. //==============================================================================
  206. void JucerDocument::addMethod (const String& base, const String& returnVal, const String& method, const String& initialContent,
  207. StringArray& baseClasses, StringArray& returnValues, StringArray& methods, StringArray& initialContents)
  208. {
  209. baseClasses.add (base);
  210. returnValues.add (returnVal);
  211. methods.add (method);
  212. initialContents.add (initialContent);
  213. }
  214. void JucerDocument::getOptionalMethods (StringArray& baseClasses,
  215. StringArray& returnValues,
  216. StringArray& methods,
  217. StringArray& initialContents) const
  218. {
  219. addMethod ("Component", "void", "visibilityChanged()", "", baseClasses, returnValues, methods, initialContents);
  220. addMethod ("Component", "void", "moved()", "", baseClasses, returnValues, methods, initialContents);
  221. addMethod ("Component", "void", "parentHierarchyChanged()", "", baseClasses, returnValues, methods, initialContents);
  222. addMethod ("Component", "void", "parentSizeChanged()", "", baseClasses, returnValues, methods, initialContents);
  223. addMethod ("Component", "void", "lookAndFeelChanged()", "", baseClasses, returnValues, methods, initialContents);
  224. addMethod ("Component", "bool", "hitTest (int x, int y)", "return true;", baseClasses, returnValues, methods, initialContents);
  225. addMethod ("Component", "void", "broughtToFront()", "", baseClasses, returnValues, methods, initialContents);
  226. addMethod ("Component", "void", "filesDropped (const StringArray& filenames, int mouseX, int mouseY)", "", baseClasses, returnValues, methods, initialContents);
  227. addMethod ("Component", "void", "handleCommandMessage (int commandId)", "", baseClasses, returnValues, methods, initialContents);
  228. addMethod ("Component", "void", "childrenChanged()", "", baseClasses, returnValues, methods, initialContents);
  229. addMethod ("Component", "void", "enablementChanged()", "", baseClasses, returnValues, methods, initialContents);
  230. addMethod ("Component", "void", "mouseMove (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  231. addMethod ("Component", "void", "mouseEnter (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  232. addMethod ("Component", "void", "mouseExit (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  233. addMethod ("Component", "void", "mouseDown (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  234. addMethod ("Component", "void", "mouseDrag (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  235. addMethod ("Component", "void", "mouseUp (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  236. addMethod ("Component", "void", "mouseDoubleClick (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  237. addMethod ("Component", "void", "mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)", "", baseClasses, returnValues, methods, initialContents);
  238. addMethod ("Component", "bool", "keyPressed (const KeyPress& key)", "return false; // Return true if your handler uses this key event, or false to allow it to be passed-on.", baseClasses, returnValues, methods, initialContents);
  239. addMethod ("Component", "bool", "keyStateChanged (bool isKeyDown)", "return false; // Return true if your handler uses this key event, or false to allow it to be passed-on.", baseClasses, returnValues, methods, initialContents);
  240. addMethod ("Component", "void", "modifierKeysChanged (const ModifierKeys& modifiers)", "", baseClasses, returnValues, methods, initialContents);
  241. addMethod ("Component", "void", "focusGained (FocusChangeType cause)", "", baseClasses, returnValues, methods, initialContents);
  242. addMethod ("Component", "void", "focusLost (FocusChangeType cause)", "", baseClasses, returnValues, methods, initialContents);
  243. addMethod ("Component", "void", "focusOfChildComponentChanged (FocusChangeType cause)", "", baseClasses, returnValues, methods, initialContents);
  244. addMethod ("Component", "void", "modifierKeysChanged (const ModifierKeys& modifiers)", "", baseClasses, returnValues, methods, initialContents);
  245. addMethod ("Component", "void", "inputAttemptWhenModal()", "", baseClasses, returnValues, methods, initialContents);
  246. }
  247. void JucerDocument::setOptionalMethodEnabled (const String& methodSignature, const bool enable)
  248. {
  249. if (enable)
  250. activeExtraMethods.addIfNotAlreadyThere (methodSignature);
  251. else
  252. activeExtraMethods.removeString (methodSignature);
  253. changed();
  254. }
  255. bool JucerDocument::isOptionalMethodEnabled (const String& sig) const noexcept
  256. {
  257. return activeExtraMethods.contains (sig);
  258. }
  259. void JucerDocument::addExtraClassProperties (PropertyPanel&)
  260. {
  261. }
  262. //==============================================================================
  263. const char* const JucerDocument::jucerCompXmlTag = "JUCER_COMPONENT";
  264. std::unique_ptr<XmlElement> JucerDocument::createXml() const
  265. {
  266. auto doc = std::make_unique<XmlElement> (jucerCompXmlTag);
  267. doc->setAttribute ("documentType", getTypeName());
  268. doc->setAttribute ("className", className);
  269. if (templateFile.trim().isNotEmpty())
  270. doc->setAttribute ("template", templateFile);
  271. doc->setAttribute ("componentName", componentName);
  272. doc->setAttribute ("parentClasses", parentClasses);
  273. doc->setAttribute ("constructorParams", constructorParams);
  274. doc->setAttribute ("variableInitialisers", variableInitialisers);
  275. doc->setAttribute ("snapPixels", snapGridPixels);
  276. doc->setAttribute ("snapActive", snapActive);
  277. doc->setAttribute ("snapShown", snapShown);
  278. doc->setAttribute ("overlayOpacity", String (componentOverlayOpacity, 3));
  279. doc->setAttribute ("fixedSize", fixedSize);
  280. doc->setAttribute ("initialWidth", initialWidth);
  281. doc->setAttribute ("initialHeight", initialHeight);
  282. if (activeExtraMethods.size() > 0)
  283. {
  284. XmlElement* extraMethods = new XmlElement ("METHODS");
  285. doc->addChildElement (extraMethods);
  286. for (int i = 0; i < activeExtraMethods.size(); ++i)
  287. {
  288. XmlElement* e = new XmlElement ("METHOD");
  289. extraMethods ->addChildElement (e);
  290. e->setAttribute ("name", activeExtraMethods[i]);
  291. }
  292. }
  293. return doc;
  294. }
  295. bool JucerDocument::loadFromXml (const XmlElement& xml)
  296. {
  297. if (xml.hasTagName (jucerCompXmlTag)
  298. && getTypeName().equalsIgnoreCase (xml.getStringAttribute ("documentType")))
  299. {
  300. className = xml.getStringAttribute ("className", defaultClassName);
  301. templateFile = xml.getStringAttribute ("template", String());
  302. componentName = xml.getStringAttribute ("componentName", String());
  303. parentClasses = xml.getStringAttribute ("parentClasses", defaultParentClasses);
  304. constructorParams = xml.getStringAttribute ("constructorParams", String());
  305. variableInitialisers = xml.getStringAttribute ("variableInitialisers", String());
  306. fixedSize = xml.getBoolAttribute ("fixedSize", false);
  307. initialWidth = xml.getIntAttribute ("initialWidth", 300);
  308. initialHeight = xml.getIntAttribute ("initialHeight", 200);
  309. snapGridPixels = xml.getIntAttribute ("snapPixels", snapGridPixels);
  310. snapActive = xml.getBoolAttribute ("snapActive", snapActive);
  311. snapShown = xml.getBoolAttribute ("snapShown", snapShown);
  312. componentOverlayOpacity = (float) xml.getDoubleAttribute ("overlayOpacity", 0.0);
  313. activeExtraMethods.clear();
  314. if (XmlElement* const methods = xml.getChildByName ("METHODS"))
  315. forEachXmlChildElementWithTagName (*methods, e, "METHOD")
  316. activeExtraMethods.addIfNotAlreadyThere (e->getStringAttribute ("name"));
  317. activeExtraMethods.trim();
  318. activeExtraMethods.removeEmptyStrings();
  319. changed();
  320. getUndoManager().clearUndoHistory();
  321. return true;
  322. }
  323. return false;
  324. }
  325. //==============================================================================
  326. void JucerDocument::fillInGeneratedCode (GeneratedCode& code) const
  327. {
  328. code.className = className;
  329. code.componentName = componentName;
  330. code.parentClasses = parentClasses;
  331. code.constructorParams = constructorParams;
  332. code.initialisers.addLines (variableInitialisers);
  333. if (! componentName.isEmpty())
  334. code.constructorCode << "setName (" + quotedString (componentName, false) + ");\n";
  335. // call these now, just to make sure they're the first two methods in the list.
  336. code.getCallbackCode (String(), "void", "paint (Graphics& g)", false)
  337. << "//[UserPrePaint] Add your own custom painting code here..\n//[/UserPrePaint]\n\n";
  338. code.getCallbackCode (String(), "void", "resized()", false)
  339. << "//[UserPreResize] Add your own custom resize code here..\n//[/UserPreResize]\n\n";
  340. if (ComponentLayout* l = getComponentLayout())
  341. l->fillInGeneratedCode (code);
  342. fillInPaintCode (code);
  343. std::unique_ptr<XmlElement> e (createXml());
  344. jassert (e != nullptr);
  345. code.jucerMetadata = e->toString (XmlElement::TextFormat().withoutHeader());
  346. resources.fillInGeneratedCode (code);
  347. code.constructorCode
  348. << "\n//[UserPreSize]\n"
  349. "//[/UserPreSize]\n";
  350. if (initialWidth > 0 || initialHeight > 0)
  351. code.constructorCode << "\nsetSize (" << initialWidth << ", " << initialHeight << ");\n";
  352. code.getCallbackCode (String(), "void", "paint (Graphics& g)", false)
  353. << "//[UserPaint] Add your own custom painting code here..\n//[/UserPaint]";
  354. code.getCallbackCode (String(), "void", "resized()", false)
  355. << "//[UserResized] Add your own custom resize handling here..\n//[/UserResized]";
  356. // add optional methods
  357. StringArray baseClasses, returnValues, methods, initialContents;
  358. getOptionalMethods (baseClasses, returnValues, methods, initialContents);
  359. for (int i = 0; i < methods.size(); ++i)
  360. {
  361. if (isOptionalMethodEnabled (methods[i]))
  362. {
  363. String baseClassToAdd (baseClasses[i]);
  364. if (baseClassToAdd == "Component" || baseClassToAdd == "Button")
  365. baseClassToAdd.clear();
  366. String& s = code.getCallbackCode (baseClassToAdd, returnValues[i], methods[i], false);
  367. if (! s.contains ("//["))
  368. {
  369. String userCommentTag ("UserCode_");
  370. userCommentTag += methods[i].upToFirstOccurrenceOf ("(", false, false).trim();
  371. s << "\n//[" << userCommentTag << "] -- Add your code here...\n"
  372. << initialContents[i];
  373. if (initialContents[i].isNotEmpty() && ! initialContents[i].endsWithChar ('\n'))
  374. s << '\n';
  375. s << "//[/" << userCommentTag << "]\n";
  376. }
  377. }
  378. }
  379. }
  380. void JucerDocument::fillInPaintCode (GeneratedCode& code) const
  381. {
  382. for (int i = 0; i < getNumPaintRoutines(); ++i)
  383. getPaintRoutine (i)
  384. ->fillInGeneratedCode (code, code.getCallbackCode (String(), "void", "paint (Graphics& g)", false));
  385. }
  386. void JucerDocument::setTemplateFile (const String& newFile)
  387. {
  388. if (templateFile != newFile)
  389. {
  390. templateFile = newFile;
  391. changed();
  392. }
  393. }
  394. //==============================================================================
  395. bool JucerDocument::findTemplateFiles (String& headerContent, String& cppContent) const
  396. {
  397. if (templateFile.isNotEmpty())
  398. {
  399. const File f (getCppFile().getSiblingFile (templateFile));
  400. const File templateCpp (f.withFileExtension (".cpp"));
  401. const File templateH (f.withFileExtension (".h"));
  402. headerContent = templateH.loadFileAsString();
  403. cppContent = templateCpp.loadFileAsString();
  404. if (headerContent.isNotEmpty() && cppContent.isNotEmpty())
  405. return true;
  406. }
  407. headerContent = BinaryData::jucer_ComponentTemplate_h;
  408. cppContent = BinaryData::jucer_ComponentTemplate_cpp;
  409. return true;
  410. }
  411. bool JucerDocument::flushChangesToDocuments (Project* project, bool isInitial)
  412. {
  413. String headerTemplate, cppTemplate;
  414. if (! findTemplateFiles (headerTemplate, cppTemplate))
  415. return false;
  416. GeneratedCode generated (this);
  417. fillInGeneratedCode (generated);
  418. const File headerFile (getHeaderFile());
  419. generated.includeFilesCPP.insert (0, headerFile);
  420. OpenDocumentManager& odm = ProjucerApplication::getApp().openDocumentManager;
  421. if (SourceCodeDocument* header = dynamic_cast<SourceCodeDocument*> (odm.openFile (nullptr, headerFile)))
  422. {
  423. String existingHeader (header->getCodeDocument().getAllContent());
  424. String existingCpp (cpp->getCodeDocument().getAllContent());
  425. generated.applyToCode (headerTemplate, headerFile, existingHeader);
  426. generated.applyToCode (cppTemplate, headerFile.withFileExtension (".cpp"), existingCpp);
  427. if (isInitial)
  428. {
  429. jassert (project != nullptr);
  430. auto lineFeed = project->getProjectLineFeed();
  431. headerTemplate = replaceLineFeeds (headerTemplate, lineFeed);
  432. cppTemplate = replaceLineFeeds (cppTemplate, lineFeed);
  433. }
  434. else
  435. {
  436. headerTemplate = replaceLineFeeds (headerTemplate, getLineFeedForFile (existingHeader));
  437. cppTemplate = replaceLineFeeds (cppTemplate, getLineFeedForFile (existingCpp));
  438. }
  439. if (header->getCodeDocument().getAllContent() != headerTemplate)
  440. header->getCodeDocument().replaceAllContent (headerTemplate);
  441. if (cpp->getCodeDocument().getAllContent() != cppTemplate)
  442. cpp->getCodeDocument().replaceAllContent (cppTemplate);
  443. }
  444. userDocChangeTimer.reset();
  445. return true;
  446. }
  447. bool JucerDocument::reloadFromDocument()
  448. {
  449. const String cppContent (cpp->getCodeDocument().getAllContent());
  450. std::unique_ptr<XmlElement> newXML (pullMetaDataFromCppFile (cppContent));
  451. if (newXML == nullptr || ! newXML->hasTagName (jucerCompXmlTag))
  452. return false;
  453. if (currentXML != nullptr && currentXML->isEquivalentTo (newXML.get(), true))
  454. return true;
  455. currentXML.reset (newXML.release());
  456. stopTimer();
  457. resources.loadFromCpp (getCppFile(), cppContent);
  458. bool result = loadFromXml (*currentXML);
  459. extractCustomPaintSnippetsFromCppFile (cppContent);
  460. return result;
  461. }
  462. void JucerDocument::refreshCustomCodeFromDocument()
  463. {
  464. const String cppContent (cpp->getCodeDocument().getAllContent());
  465. extractCustomPaintSnippetsFromCppFile (cppContent);
  466. }
  467. void JucerDocument::extractCustomPaintSnippetsFromCppFile (const String& cppContent)
  468. {
  469. StringArray customPaintSnippets;
  470. auto lines = StringArray::fromLines (cppContent);
  471. int last = 0;
  472. while (last >= 0)
  473. {
  474. const int start = indexOfLineStartingWith (lines, "//[UserPaintCustomArguments]", last);
  475. if (start < 0)
  476. break;
  477. const int end = indexOfLineStartingWith (lines, "//[/UserPaintCustomArguments]", start);
  478. if (end < 0)
  479. break;
  480. last = end + 1;
  481. String result;
  482. for (int i = start + 1; i < end; ++i)
  483. result << lines [i] << newLine;
  484. customPaintSnippets.add (CodeHelpers::unindent (result, 4));
  485. }
  486. applyCustomPaintSnippets (customPaintSnippets);
  487. }
  488. std::unique_ptr<XmlElement> JucerDocument::pullMetaDataFromCppFile (const String& cpp)
  489. {
  490. auto lines = StringArray::fromLines (cpp);
  491. auto startLine = indexOfLineStartingWith (lines, "BEGIN_JUCER_METADATA", 0);
  492. if (startLine > 0)
  493. {
  494. auto endLine = indexOfLineStartingWith (lines, "END_JUCER_METADATA", startLine);
  495. if (endLine > startLine)
  496. return parseXML (lines.joinIntoString ("\n", startLine + 1, endLine - startLine - 1));
  497. }
  498. return nullptr;
  499. }
  500. bool JucerDocument::isValidJucerCppFile (const File& f)
  501. {
  502. if (f.hasFileExtension (cppFileExtensions))
  503. {
  504. std::unique_ptr<XmlElement> xml (pullMetaDataFromCppFile (f.loadFileAsString()));
  505. if (xml != nullptr)
  506. return xml->hasTagName (jucerCompXmlTag);
  507. }
  508. return false;
  509. }
  510. static JucerDocument* createDocument (SourceCodeDocument* cpp)
  511. {
  512. auto& codeDoc = cpp->getCodeDocument();
  513. std::unique_ptr<XmlElement> xml (JucerDocument::pullMetaDataFromCppFile (codeDoc.getAllContent()));
  514. if (xml == nullptr || ! xml->hasTagName (JucerDocument::jucerCompXmlTag))
  515. return nullptr;
  516. const String docType (xml->getStringAttribute ("documentType"));
  517. std::unique_ptr<JucerDocument> newDoc;
  518. if (docType.equalsIgnoreCase ("Button"))
  519. newDoc.reset (new ButtonDocument (cpp));
  520. if (docType.equalsIgnoreCase ("Component") || docType.isEmpty())
  521. newDoc.reset (new ComponentDocument (cpp));
  522. if (newDoc != nullptr && newDoc->reloadFromDocument())
  523. return newDoc.release();
  524. return nullptr;
  525. }
  526. JucerDocument* JucerDocument::createForCppFile (Project* p, const File& file)
  527. {
  528. OpenDocumentManager& odm = ProjucerApplication::getApp().openDocumentManager;
  529. if (SourceCodeDocument* cpp = dynamic_cast<SourceCodeDocument*> (odm.openFile (p, file)))
  530. if (dynamic_cast<SourceCodeDocument*> (odm.openFile (p, file.withFileExtension (".h"))) != nullptr)
  531. return createDocument (cpp);
  532. return nullptr;
  533. }
  534. //==============================================================================
  535. class JucerComponentDocument : public SourceCodeDocument
  536. {
  537. public:
  538. JucerComponentDocument (Project* p, const File& f)
  539. : SourceCodeDocument (p, f)
  540. {
  541. }
  542. bool save() override
  543. {
  544. return SourceCodeDocument::save() && saveHeader();
  545. }
  546. bool saveHeader()
  547. {
  548. auto& odm = ProjucerApplication::getApp().openDocumentManager;
  549. if (auto* header = odm.openFile (nullptr, getFile().withFileExtension (".h")))
  550. {
  551. if (header->save())
  552. {
  553. odm.closeFile (getFile().withFileExtension(".h"), false);
  554. return true;
  555. }
  556. }
  557. return false;
  558. }
  559. Component* createEditor() override
  560. {
  561. std::unique_ptr<JucerDocument> jucerDoc (JucerDocument::createForCppFile (getProject(), getFile()));
  562. if (jucerDoc != nullptr)
  563. return new JucerDocumentEditor (jucerDoc.release());
  564. return SourceCodeDocument::createEditor();
  565. }
  566. struct Type : public OpenDocumentManager::DocumentType
  567. {
  568. Type() {}
  569. bool canOpenFile (const File& f) override { return JucerDocument::isValidJucerCppFile (f); }
  570. Document* openFile (Project* p, const File& f) override { return new JucerComponentDocument (p, f); }
  571. };
  572. };
  573. OpenDocumentManager::DocumentType* createGUIDocumentType();
  574. OpenDocumentManager::DocumentType* createGUIDocumentType()
  575. {
  576. return new JucerComponentDocument::Type();
  577. }
  578. //==============================================================================
  579. struct NewGUIComponentWizard : public NewFileWizard::Type
  580. {
  581. NewGUIComponentWizard() {}
  582. String getName() override { return "GUI Component"; }
  583. void createNewFile (Project& project, Project::Item parent) override
  584. {
  585. auto newFile = askUserToChooseNewFile (String (defaultClassName) + ".h", "*.h;*.cpp", parent);
  586. if (newFile != File())
  587. {
  588. auto headerFile = newFile.withFileExtension (".h");
  589. auto cppFile = newFile.withFileExtension (".cpp");
  590. headerFile.replaceWithText (String());
  591. cppFile.replaceWithText (String());
  592. auto& odm = ProjucerApplication::getApp().openDocumentManager;
  593. if (auto* cpp = dynamic_cast<SourceCodeDocument*> (odm.openFile (&project, cppFile)))
  594. {
  595. if (auto* header = dynamic_cast<SourceCodeDocument*> (odm.openFile (&project, headerFile)))
  596. {
  597. std::unique_ptr<JucerDocument> jucerDoc (new ComponentDocument (cpp));
  598. if (jucerDoc != nullptr)
  599. {
  600. jucerDoc->setClassName (newFile.getFileNameWithoutExtension());
  601. jucerDoc->flushChangesToDocuments (&project, true);
  602. jucerDoc.reset();
  603. cpp->save();
  604. header->save();
  605. odm.closeDocument (cpp, true);
  606. odm.closeDocument (header, true);
  607. parent.addFileRetainingSortOrder (headerFile, true);
  608. parent.addFileRetainingSortOrder (cppFile, true);
  609. }
  610. }
  611. }
  612. }
  613. }
  614. };
  615. NewFileWizard::Type* createGUIComponentWizard();
  616. NewFileWizard::Type* createGUIComponentWizard()
  617. {
  618. return new NewGUIComponentWizard();
  619. }