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.

769 lines
27KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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 "../Project/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. IntrojucerApp::getCommandManager().commandStatusChanged();
  45. cpp->getCodeDocument().addListener (this);
  46. IntrojucerApp::getApp().openDocumentManager.addListener (this);
  47. }
  48. JucerDocument::~JucerDocument()
  49. {
  50. IntrojucerApp::getApp().openDocumentManager.removeListener (this);
  51. cpp->getCodeDocument().removeListener (this);
  52. IntrojucerApp::getCommandManager().commandStatusChanged();
  53. }
  54. //==============================================================================
  55. void JucerDocument::changed()
  56. {
  57. sendChangeMessage();
  58. IntrojucerApp::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();
  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;
  133. parentClassLines.addTokens (classes, ",", String::empty);
  134. parentClassLines.trim();
  135. parentClassLines.removeEmptyStrings();
  136. parentClassLines.removeDuplicates (false);
  137. for (int i = parentClassLines.size(); --i >= 0;)
  138. {
  139. String s (parentClassLines[i]);
  140. String type;
  141. if (s.startsWith ("public ")
  142. || s.startsWith ("protected ")
  143. || s.startsWith ("private "))
  144. {
  145. type = s.upToFirstOccurrenceOf (" ", true, false);
  146. s = s.fromFirstOccurrenceOf (" ", false, false);
  147. if (s.trim().isEmpty())
  148. type = s = String::empty;
  149. }
  150. s = type + CodeHelpers::makeValidIdentifier (s.trim(), false, false, true);
  151. parentClassLines.set (i, s);
  152. }
  153. parentClasses = parentClassLines.joinIntoString (", ");
  154. changed();
  155. }
  156. }
  157. void JucerDocument::setConstructorParams (const String& newParams)
  158. {
  159. if (constructorParams != newParams)
  160. {
  161. constructorParams = newParams;
  162. changed();
  163. }
  164. }
  165. void JucerDocument::setVariableInitialisers (const String& newInitlialisers)
  166. {
  167. if (variableInitialisers != newInitlialisers)
  168. {
  169. variableInitialisers = newInitlialisers;
  170. changed();
  171. }
  172. }
  173. void JucerDocument::setFixedSize (const bool isFixed)
  174. {
  175. if (fixedSize != isFixed)
  176. {
  177. fixedSize = isFixed;
  178. changed();
  179. }
  180. }
  181. void JucerDocument::setInitialSize (int w, int h)
  182. {
  183. w = jmax (1, w);
  184. h = jmax (1, h);
  185. if (initialWidth != w || initialHeight != h)
  186. {
  187. initialWidth = w;
  188. initialHeight = h;
  189. changed();
  190. }
  191. }
  192. //==============================================================================
  193. bool JucerDocument::isSnapActive (const bool disableIfCtrlKeyDown) const noexcept
  194. {
  195. return snapActive != (disableIfCtrlKeyDown && ModifierKeys::getCurrentModifiers().isCtrlDown());
  196. }
  197. int JucerDocument::snapPosition (int pos) const noexcept
  198. {
  199. if (isSnapActive (true))
  200. {
  201. jassert (snapGridPixels > 0);
  202. pos = ((pos + snapGridPixels * 1024 + snapGridPixels / 2) / snapGridPixels - 1024) * snapGridPixels;
  203. }
  204. return pos;
  205. }
  206. void JucerDocument::setSnappingGrid (const int numPixels, const bool active, const bool shown)
  207. {
  208. if (numPixels != snapGridPixels
  209. || active != snapActive
  210. || shown != snapShown)
  211. {
  212. snapGridPixels = numPixels;
  213. snapActive = active;
  214. snapShown = shown;
  215. changed();
  216. }
  217. }
  218. void JucerDocument::setComponentOverlayOpacity (const float alpha)
  219. {
  220. if (alpha != componentOverlayOpacity)
  221. {
  222. componentOverlayOpacity = alpha;
  223. changed();
  224. }
  225. }
  226. //==============================================================================
  227. void JucerDocument::addMethod (const String& base, const String& returnVal, const String& method, const String& initialContent,
  228. StringArray& baseClasses, StringArray& returnValues, StringArray& methods, StringArray& initialContents)
  229. {
  230. baseClasses.add (base);
  231. returnValues.add (returnVal);
  232. methods.add (method);
  233. initialContents.add (initialContent);
  234. }
  235. void JucerDocument::getOptionalMethods (StringArray& baseClasses,
  236. StringArray& returnValues,
  237. StringArray& methods,
  238. StringArray& initialContents) const
  239. {
  240. addMethod ("Component", "void", "visibilityChanged()", "", baseClasses, returnValues, methods, initialContents);
  241. addMethod ("Component", "void", "moved()", "", baseClasses, returnValues, methods, initialContents);
  242. addMethod ("Component", "void", "parentHierarchyChanged()", "", baseClasses, returnValues, methods, initialContents);
  243. addMethod ("Component", "void", "parentSizeChanged()", "", baseClasses, returnValues, methods, initialContents);
  244. addMethod ("Component", "void", "lookAndFeelChanged()", "", baseClasses, returnValues, methods, initialContents);
  245. addMethod ("Component", "bool", "hitTest (int x, int y)", "return true;", baseClasses, returnValues, methods, initialContents);
  246. addMethod ("Component", "void", "broughtToFront()", "", baseClasses, returnValues, methods, initialContents);
  247. addMethod ("Component", "void", "filesDropped (const StringArray& filenames, int mouseX, int mouseY)", "", baseClasses, returnValues, methods, initialContents);
  248. addMethod ("Component", "void", "handleCommandMessage (int commandId)", "", baseClasses, returnValues, methods, initialContents);
  249. addMethod ("Component", "void", "childrenChanged()", "", baseClasses, returnValues, methods, initialContents);
  250. addMethod ("Component", "void", "enablementChanged()", "", baseClasses, returnValues, methods, initialContents);
  251. addMethod ("Component", "void", "mouseMove (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  252. addMethod ("Component", "void", "mouseEnter (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  253. addMethod ("Component", "void", "mouseExit (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  254. addMethod ("Component", "void", "mouseDown (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  255. addMethod ("Component", "void", "mouseDrag (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  256. addMethod ("Component", "void", "mouseUp (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  257. addMethod ("Component", "void", "mouseDoubleClick (const MouseEvent& e)", "", baseClasses, returnValues, methods, initialContents);
  258. addMethod ("Component", "void", "mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)", "", baseClasses, returnValues, methods, initialContents);
  259. 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);
  260. addMethod ("Component", "bool", "keyStateChanged (const 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);
  261. addMethod ("Component", "void", "modifierKeysChanged (const ModifierKeys& modifiers)", "", baseClasses, returnValues, methods, initialContents);
  262. addMethod ("Component", "void", "focusGained (FocusChangeType cause)", "", baseClasses, returnValues, methods, initialContents);
  263. addMethod ("Component", "void", "focusLost (FocusChangeType cause)", "", baseClasses, returnValues, methods, initialContents);
  264. addMethod ("Component", "void", "focusOfChildComponentChanged (FocusChangeType cause)", "", baseClasses, returnValues, methods, initialContents);
  265. addMethod ("Component", "void", "modifierKeysChanged (const ModifierKeys& modifiers)", "", baseClasses, returnValues, methods, initialContents);
  266. addMethod ("Component", "void", "inputAttemptWhenModal()", "", baseClasses, returnValues, methods, initialContents);
  267. }
  268. void JucerDocument::setOptionalMethodEnabled (const String& methodSignature, const bool enable)
  269. {
  270. if (enable)
  271. activeExtraMethods.addIfNotAlreadyThere (methodSignature);
  272. else
  273. activeExtraMethods.removeString (methodSignature);
  274. changed();
  275. }
  276. bool JucerDocument::isOptionalMethodEnabled (const String& sig) const noexcept
  277. {
  278. return activeExtraMethods.contains (sig);
  279. }
  280. void JucerDocument::addExtraClassProperties (PropertyPanel&)
  281. {
  282. }
  283. //==============================================================================
  284. const char* const JucerDocument::jucerCompXmlTag = "JUCER_COMPONENT";
  285. XmlElement* JucerDocument::createXml() const
  286. {
  287. XmlElement* doc = new XmlElement (jucerCompXmlTag);
  288. doc->setAttribute ("documentType", getTypeName());
  289. doc->setAttribute ("className", className);
  290. if (templateFile.trim().isNotEmpty())
  291. doc->setAttribute ("template", templateFile);
  292. doc->setAttribute ("componentName", componentName);
  293. doc->setAttribute ("parentClasses", parentClasses);
  294. doc->setAttribute ("constructorParams", constructorParams);
  295. doc->setAttribute ("variableInitialisers", variableInitialisers);
  296. doc->setAttribute ("snapPixels", snapGridPixels);
  297. doc->setAttribute ("snapActive", snapActive);
  298. doc->setAttribute ("snapShown", snapShown);
  299. doc->setAttribute ("overlayOpacity", String (componentOverlayOpacity, 3));
  300. doc->setAttribute ("fixedSize", fixedSize);
  301. doc->setAttribute ("initialWidth", initialWidth);
  302. doc->setAttribute ("initialHeight", initialHeight);
  303. if (activeExtraMethods.size() > 0)
  304. {
  305. XmlElement* extraMethods = new XmlElement ("METHODS");
  306. doc->addChildElement (extraMethods);
  307. for (int i = 0; i < activeExtraMethods.size(); ++i)
  308. {
  309. XmlElement* e = new XmlElement ("METHOD");
  310. extraMethods ->addChildElement (e);
  311. e->setAttribute ("name", activeExtraMethods[i]);
  312. }
  313. }
  314. return doc;
  315. }
  316. bool JucerDocument::loadFromXml (const XmlElement& xml)
  317. {
  318. if (xml.hasTagName (jucerCompXmlTag)
  319. && getTypeName().equalsIgnoreCase (xml.getStringAttribute ("documentType")))
  320. {
  321. className = xml.getStringAttribute ("className", defaultClassName);
  322. templateFile = xml.getStringAttribute ("template", String::empty);
  323. componentName = xml.getStringAttribute ("componentName", String::empty);
  324. parentClasses = xml.getStringAttribute ("parentClasses", defaultParentClasses);
  325. constructorParams = xml.getStringAttribute ("constructorParams", String::empty);
  326. variableInitialisers = xml.getStringAttribute ("variableInitialisers", String::empty);
  327. fixedSize = xml.getBoolAttribute ("fixedSize", false);
  328. initialWidth = xml.getIntAttribute ("initialWidth", 300);
  329. initialHeight = xml.getIntAttribute ("initialHeight", 200);
  330. snapGridPixels = xml.getIntAttribute ("snapPixels", snapGridPixels);
  331. snapActive = xml.getBoolAttribute ("snapActive", snapActive);
  332. snapShown = xml.getBoolAttribute ("snapShown", snapShown);
  333. componentOverlayOpacity = (float) xml.getDoubleAttribute ("overlayOpacity", 0.0);
  334. activeExtraMethods.clear();
  335. if (XmlElement* const methods = xml.getChildByName ("METHODS"))
  336. forEachXmlChildElementWithTagName (*methods, e, "METHOD")
  337. activeExtraMethods.addIfNotAlreadyThere (e->getStringAttribute ("name"));
  338. activeExtraMethods.trim();
  339. activeExtraMethods.removeEmptyStrings();
  340. changed();
  341. getUndoManager().clearUndoHistory();
  342. return true;
  343. }
  344. return false;
  345. }
  346. //==============================================================================
  347. void JucerDocument::fillInGeneratedCode (GeneratedCode& code) const
  348. {
  349. code.className = className;
  350. code.componentName = componentName;
  351. code.parentClasses = parentClasses;
  352. code.constructorParams = constructorParams;
  353. code.initialisers.addLines (variableInitialisers);
  354. if (! componentName.isEmpty())
  355. code.constructorCode << "setName (" + quotedString (componentName, false) + ");\n";
  356. // call these now, just to make sure they're the first two methods in the list.
  357. code.getCallbackCode (String::empty, "void", "paint (Graphics& g)", false)
  358. << "//[UserPrePaint] Add your own custom painting code here..\n//[/UserPrePaint]\n\n";
  359. code.getCallbackCode (String::empty, "void", "resized()", false);
  360. if (ComponentLayout* l = getComponentLayout())
  361. l->fillInGeneratedCode (code);
  362. fillInPaintCode (code);
  363. ScopedPointer<XmlElement> e (createXml());
  364. jassert (e != nullptr);
  365. code.jucerMetadata = e->createDocument ("", false, false);
  366. resources.fillInGeneratedCode (code);
  367. code.constructorCode
  368. << "\n//[UserPreSize]\n"
  369. "//[/UserPreSize]\n";
  370. if (initialWidth > 0 || initialHeight > 0)
  371. code.constructorCode << "\nsetSize (" << initialWidth << ", " << initialHeight << ");\n";
  372. code.getCallbackCode (String::empty, "void", "paint (Graphics& g)", false)
  373. << "//[UserPaint] Add your own custom painting code here..\n//[/UserPaint]";
  374. code.getCallbackCode (String::empty, "void", "resized()", false)
  375. << "//[UserResized] Add your own custom resize handling here..\n//[/UserResized]";
  376. // add optional methods
  377. StringArray baseClasses, returnValues, methods, initialContents;
  378. getOptionalMethods (baseClasses, returnValues, methods, initialContents);
  379. for (int i = 0; i < methods.size(); ++i)
  380. {
  381. if (isOptionalMethodEnabled (methods[i]))
  382. {
  383. String baseClassToAdd (baseClasses[i]);
  384. if (baseClassToAdd == "Component" || baseClassToAdd == "Button")
  385. baseClassToAdd.clear();
  386. String& s = code.getCallbackCode (baseClassToAdd, returnValues[i], methods[i], false);
  387. if (! s.contains ("//["))
  388. {
  389. String userCommentTag ("UserCode_");
  390. userCommentTag += methods[i].upToFirstOccurrenceOf ("(", false, false).trim();
  391. s << "\n//[" << userCommentTag << "] -- Add your code here...\n"
  392. << initialContents[i];
  393. if (initialContents[i].isNotEmpty() && ! initialContents[i].endsWithChar ('\n'))
  394. s << '\n';
  395. s << "//[/" << userCommentTag << "]\n";
  396. }
  397. }
  398. }
  399. }
  400. void JucerDocument::fillInPaintCode (GeneratedCode& code) const
  401. {
  402. for (int i = 0; i < getNumPaintRoutines(); ++i)
  403. getPaintRoutine (i)
  404. ->fillInGeneratedCode (code, code.getCallbackCode (String::empty, "void", "paint (Graphics& g)", false));
  405. }
  406. void JucerDocument::setTemplateFile (const String& newFile)
  407. {
  408. if (templateFile != newFile)
  409. {
  410. templateFile = newFile;
  411. changed();
  412. }
  413. }
  414. //==============================================================================
  415. bool JucerDocument::findTemplateFiles (String& headerContent, String& cppContent) const
  416. {
  417. if (templateFile.isNotEmpty())
  418. {
  419. const File f (getCppFile().getSiblingFile (templateFile));
  420. const File templateCpp (f.withFileExtension (".cpp"));
  421. const File templateH (f.withFileExtension (".h"));
  422. headerContent = templateH.loadFileAsString();
  423. cppContent = templateCpp.loadFileAsString();
  424. if (headerContent.isNotEmpty() && cppContent.isNotEmpty())
  425. return true;
  426. }
  427. headerContent = BinaryData::jucer_ComponentTemplate_h;
  428. cppContent = BinaryData::jucer_ComponentTemplate_cpp;
  429. return true;
  430. }
  431. static String fixLineEndings (const String& s)
  432. {
  433. StringArray lines;
  434. lines.addLines (s);
  435. for (int i = 0; i < lines.size(); ++i)
  436. lines.set (i, lines[i].trimEnd());
  437. while (lines.size() > 0 && lines [lines.size() - 1].trim().isEmpty())
  438. lines.remove (lines.size() - 1);
  439. lines.add (String::empty);
  440. return lines.joinIntoString ("\r\n");
  441. }
  442. bool JucerDocument::flushChangesToDocuments()
  443. {
  444. String headerTemplate, cppTemplate;
  445. if (! findTemplateFiles (headerTemplate, cppTemplate))
  446. return false;
  447. GeneratedCode generated (this);
  448. fillInGeneratedCode (generated);
  449. const File headerFile (getHeaderFile());
  450. generated.includeFilesCPP.insert (0, headerFile.getFileName());
  451. OpenDocumentManager& odm = IntrojucerApp::getApp().openDocumentManager;
  452. if (SourceCodeDocument* header = dynamic_cast <SourceCodeDocument*> (odm.openFile (nullptr, getHeaderFile())))
  453. {
  454. String existingHeader (header->getCodeDocument().getAllContent());
  455. String existingCpp (cpp->getCodeDocument().getAllContent());
  456. generated.applyToCode (headerTemplate, headerFile.getFileNameWithoutExtension(), false, existingHeader);
  457. generated.applyToCode (cppTemplate, headerFile.getFileNameWithoutExtension(), false, existingCpp);
  458. headerTemplate = fixLineEndings (headerTemplate);
  459. cppTemplate = fixLineEndings (cppTemplate);
  460. if (header->getCodeDocument().getAllContent() != headerTemplate)
  461. header->getCodeDocument().replaceAllContent (headerTemplate);
  462. if (cpp->getCodeDocument().getAllContent() != cppTemplate)
  463. cpp->getCodeDocument().replaceAllContent (cppTemplate);
  464. }
  465. userDocChangeTimer = nullptr;
  466. return true;
  467. }
  468. bool JucerDocument::reloadFromDocument()
  469. {
  470. const String cppContent (cpp->getCodeDocument().getAllContent());
  471. ScopedPointer<XmlElement> newXML (pullMetaDataFromCppFile (cppContent));
  472. if (newXML == nullptr || ! newXML->hasTagName (jucerCompXmlTag))
  473. return false;
  474. if (currentXML != nullptr && currentXML->isEquivalentTo (newXML, true))
  475. return true;
  476. currentXML = newXML;
  477. stopTimer();
  478. resources.loadFromCpp (getCppFile(), cppContent);
  479. return loadFromXml (*currentXML);
  480. }
  481. XmlElement* JucerDocument::pullMetaDataFromCppFile (const String& cpp)
  482. {
  483. StringArray lines;
  484. lines.addLines (cpp);
  485. const int startLine = indexOfLineStartingWith (lines, "BEGIN_JUCER_METADATA", 0);
  486. if (startLine > 0)
  487. {
  488. const int endLine = indexOfLineStartingWith (lines, "END_JUCER_METADATA", startLine);
  489. if (endLine > startLine)
  490. return XmlDocument::parse (lines.joinIntoString ("\n", startLine + 1,
  491. endLine - startLine - 1));
  492. }
  493. return nullptr;
  494. }
  495. bool JucerDocument::isValidJucerCppFile (const File& f)
  496. {
  497. if (f.hasFileExtension (".cpp"))
  498. {
  499. const ScopedPointer<XmlElement> xml (pullMetaDataFromCppFile (f.loadFileAsString()));
  500. return xml != nullptr && xml->hasTagName (jucerCompXmlTag);
  501. }
  502. return false;
  503. }
  504. static JucerDocument* createDocument (SourceCodeDocument* cpp)
  505. {
  506. CodeDocument& codeDoc = cpp->getCodeDocument();
  507. ScopedPointer<XmlElement> xml (JucerDocument::pullMetaDataFromCppFile (codeDoc.getAllContent()));
  508. if (xml == nullptr || ! xml->hasTagName (JucerDocument::jucerCompXmlTag))
  509. return nullptr;
  510. const String docType (xml->getStringAttribute ("documentType"));
  511. ScopedPointer<JucerDocument> newDoc;
  512. if (docType.equalsIgnoreCase ("Button"))
  513. newDoc = new ButtonDocument (cpp);
  514. if (docType.equalsIgnoreCase ("Component") || docType.isEmpty())
  515. newDoc = new ComponentDocument (cpp);
  516. if (newDoc != nullptr && newDoc->reloadFromDocument())
  517. return newDoc.release();
  518. return nullptr;
  519. }
  520. JucerDocument* JucerDocument::createForCppFile (Project* p, const File& file)
  521. {
  522. OpenDocumentManager& odm = IntrojucerApp::getApp().openDocumentManager;
  523. if (SourceCodeDocument* cpp = dynamic_cast<SourceCodeDocument*> (odm.openFile (p, file)))
  524. if (dynamic_cast<SourceCodeDocument*> (odm.openFile (p, file.withFileExtension (".h"))) != nullptr)
  525. return createDocument (cpp);
  526. return nullptr;
  527. }
  528. //==============================================================================
  529. class JucerComponentDocument : public SourceCodeDocument
  530. {
  531. public:
  532. JucerComponentDocument (Project* p, const File& f)
  533. : SourceCodeDocument (p, f)
  534. {
  535. }
  536. bool save() override
  537. {
  538. return SourceCodeDocument::save() && saveHeader();
  539. }
  540. bool saveHeader()
  541. {
  542. OpenDocumentManager& odm = IntrojucerApp::getApp().openDocumentManager;
  543. if (OpenDocumentManager::Document* header = odm.openFile (nullptr, getFile().withFileExtension (".h")))
  544. return header->save();
  545. return false;
  546. }
  547. Component* createEditor() override
  548. {
  549. ScopedPointer<JucerDocument> jucerDoc (JucerDocument::createForCppFile (getProject(), getFile()));
  550. if (jucerDoc != nullptr)
  551. return new JucerDocumentEditor (jucerDoc.release());
  552. return SourceCodeDocument::createEditor();
  553. }
  554. class Type : public OpenDocumentManager::DocumentType
  555. {
  556. public:
  557. Type() {}
  558. bool canOpenFile (const File& f) override { return JucerDocument::isValidJucerCppFile (f); }
  559. Document* openFile (Project* p, const File& f) override { return new JucerComponentDocument (p, f); }
  560. };
  561. };
  562. OpenDocumentManager::DocumentType* createGUIDocumentType()
  563. {
  564. return new JucerComponentDocument::Type();
  565. }
  566. //==============================================================================
  567. class JucerFileWizard : public NewFileWizard::Type
  568. {
  569. public:
  570. JucerFileWizard() {}
  571. String getName() { return "GUI Component"; }
  572. void createNewFile (Project::Item parent)
  573. {
  574. const File newFile (askUserToChooseNewFile (String (defaultClassName) + ".h", "*.h;*.cpp", parent));
  575. if (newFile != File::nonexistent)
  576. {
  577. const File headerFile (newFile.withFileExtension (".h"));
  578. const File cppFile (newFile.withFileExtension (".cpp"));
  579. headerFile.replaceWithText (String::empty);
  580. cppFile.replaceWithText (String::empty);
  581. OpenDocumentManager& odm = IntrojucerApp::getApp().openDocumentManager;
  582. if (SourceCodeDocument* cpp = dynamic_cast <SourceCodeDocument*> (odm.openFile (nullptr, cppFile)))
  583. {
  584. if (SourceCodeDocument* header = dynamic_cast <SourceCodeDocument*> (odm.openFile (nullptr, headerFile)))
  585. {
  586. ScopedPointer<JucerDocument> jucerDoc (new ComponentDocument (cpp));
  587. if (jucerDoc != nullptr)
  588. {
  589. jucerDoc->flushChangesToDocuments();
  590. jucerDoc = nullptr;
  591. cpp->save();
  592. header->save();
  593. odm.closeDocument (cpp, true);
  594. odm.closeDocument (header, true);
  595. parent.addFile (headerFile, 0, true);
  596. parent.addFile (cppFile, 0, true);
  597. }
  598. }
  599. }
  600. }
  601. }
  602. };
  603. NewFileWizard::Type* createGUIComponentWizard()
  604. {
  605. return new JucerFileWizard();
  606. }