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.

795 lines
28KB

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