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.

770 lines
27KB

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