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.

643 lines
20KB

  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_SourceCodeEditor.h"
  18. #include "../Application/jucer_Application.h"
  19. #include "../Application/jucer_OpenDocumentManager.h"
  20. //==============================================================================
  21. SourceCodeDocument::SourceCodeDocument (Project* p, const File& f)
  22. : modDetector (f), project (p)
  23. {
  24. }
  25. CodeDocument& SourceCodeDocument::getCodeDocument()
  26. {
  27. if (codeDoc == nullptr)
  28. {
  29. codeDoc = new CodeDocument();
  30. reloadInternal();
  31. codeDoc->clearUndoHistory();
  32. }
  33. return *codeDoc;
  34. }
  35. Component* SourceCodeDocument::createEditor()
  36. {
  37. SourceCodeEditor* e = new SourceCodeEditor (this, getCodeDocument());
  38. applyLastState (*(e->editor));
  39. return e;
  40. }
  41. void SourceCodeDocument::reloadFromFile()
  42. {
  43. getCodeDocument();
  44. reloadInternal();
  45. }
  46. void SourceCodeDocument::reloadInternal()
  47. {
  48. jassert (codeDoc != nullptr);
  49. modDetector.updateHash();
  50. codeDoc->applyChanges (getFile().loadFileAsString());
  51. codeDoc->setSavePoint();
  52. }
  53. static bool writeCodeDocToFile (const File& file, CodeDocument& doc)
  54. {
  55. TemporaryFile temp (file);
  56. {
  57. FileOutputStream fo (temp.getFile());
  58. if (! (fo.openedOk() && doc.writeToStream (fo)))
  59. return false;
  60. }
  61. return temp.overwriteTargetFileWithTemporary();
  62. }
  63. bool SourceCodeDocument::save()
  64. {
  65. if (writeCodeDocToFile (getFile(), getCodeDocument()))
  66. {
  67. getCodeDocument().setSavePoint();
  68. modDetector.updateHash();
  69. return true;
  70. }
  71. return false;
  72. }
  73. bool SourceCodeDocument::saveAs()
  74. {
  75. FileChooser fc (TRANS("Save As..."), getFile(), "*");
  76. if (! fc.browseForFileToSave (true))
  77. return true;
  78. return writeCodeDocToFile (fc.getResult(), getCodeDocument());
  79. }
  80. void SourceCodeDocument::updateLastState (CodeEditorComponent& editor)
  81. {
  82. lastState = new CodeEditorComponent::State (editor);
  83. }
  84. void SourceCodeDocument::applyLastState (CodeEditorComponent& editor) const
  85. {
  86. if (lastState != nullptr)
  87. lastState->restoreState (editor);
  88. }
  89. //==============================================================================
  90. SourceCodeEditor::SourceCodeEditor (OpenDocumentManager::Document* doc, CodeDocument& codeDocument)
  91. : DocumentEditorComponent (doc)
  92. {
  93. GenericCodeEditorComponent* ed = nullptr;
  94. const File file (document->getFile());
  95. if (file.hasFileExtension (sourceOrHeaderFileExtensions))
  96. {
  97. ed = new CppCodeEditorComponent (file, codeDocument);
  98. }
  99. else
  100. {
  101. CodeTokeniser* tokeniser = nullptr;
  102. if (file.hasFileExtension ("xml;svg"))
  103. {
  104. static XmlTokeniser xmlTokeniser;
  105. tokeniser = &xmlTokeniser;
  106. }
  107. if (file.hasFileExtension ("lua"))
  108. {
  109. static LuaTokeniser luaTokeniser;
  110. tokeniser = &luaTokeniser;
  111. }
  112. ed = new GenericCodeEditorComponent (file, codeDocument, tokeniser);
  113. }
  114. setEditor (ed);
  115. }
  116. SourceCodeEditor::SourceCodeEditor (OpenDocumentManager::Document* doc, CodeEditorComponent* ed)
  117. : DocumentEditorComponent (doc)
  118. {
  119. setEditor (ed);
  120. }
  121. SourceCodeEditor::~SourceCodeEditor()
  122. {
  123. if (editor != nullptr)
  124. editor->getDocument().removeListener (this);
  125. getAppSettings().appearance.settings.removeListener (this);
  126. if (SourceCodeDocument* doc = dynamic_cast <SourceCodeDocument*> (getDocument()))
  127. doc->updateLastState (*editor);
  128. }
  129. void SourceCodeEditor::setEditor (CodeEditorComponent* newEditor)
  130. {
  131. if (editor != nullptr)
  132. editor->getDocument().removeListener (this);
  133. addAndMakeVisible (editor = newEditor);
  134. editor->setFont (AppearanceSettings::getDefaultCodeFont());
  135. editor->setTabSize (4, true);
  136. updateColourScheme();
  137. getAppSettings().appearance.settings.addListener (this);
  138. editor->getDocument().addListener (this);
  139. }
  140. void SourceCodeEditor::scrollToKeepRangeOnScreen (Range<int> range)
  141. {
  142. const int space = jmin (10, editor->getNumLinesOnScreen() / 3);
  143. const CodeDocument::Position start (editor->getDocument(), range.getStart());
  144. const CodeDocument::Position end (editor->getDocument(), range.getEnd());
  145. editor->scrollToKeepLinesOnScreen (Range<int> (start.getLineNumber() - space, end.getLineNumber() + space));
  146. }
  147. void SourceCodeEditor::highlight (Range<int> range, bool cursorAtStart)
  148. {
  149. scrollToKeepRangeOnScreen (range);
  150. if (cursorAtStart)
  151. {
  152. editor->moveCaretTo (CodeDocument::Position (editor->getDocument(), range.getEnd()), false);
  153. editor->moveCaretTo (CodeDocument::Position (editor->getDocument(), range.getStart()), true);
  154. }
  155. else
  156. {
  157. editor->setHighlightedRegion (range);
  158. }
  159. }
  160. void SourceCodeEditor::resized()
  161. {
  162. editor->setBounds (getLocalBounds());
  163. }
  164. void SourceCodeEditor::updateColourScheme() { getAppSettings().appearance.applyToCodeEditor (*editor); }
  165. void SourceCodeEditor::checkSaveState()
  166. {
  167. setEditedState (getDocument()->needsSaving());
  168. }
  169. void SourceCodeEditor::valueTreePropertyChanged (ValueTree&, const Identifier&) { updateColourScheme(); }
  170. void SourceCodeEditor::valueTreeChildAdded (ValueTree&, ValueTree&) { updateColourScheme(); }
  171. void SourceCodeEditor::valueTreeChildRemoved (ValueTree&, ValueTree&) { updateColourScheme(); }
  172. void SourceCodeEditor::valueTreeChildOrderChanged (ValueTree&) { updateColourScheme(); }
  173. void SourceCodeEditor::valueTreeParentChanged (ValueTree&) { updateColourScheme(); }
  174. void SourceCodeEditor::valueTreeRedirected (ValueTree&) { updateColourScheme(); }
  175. void SourceCodeEditor::codeDocumentTextInserted (const String&, int) { checkSaveState(); }
  176. void SourceCodeEditor::codeDocumentTextDeleted (int, int) { checkSaveState(); }
  177. //==============================================================================
  178. GenericCodeEditorComponent::GenericCodeEditorComponent (const File& f, CodeDocument& codeDocument,
  179. CodeTokeniser* tokeniser)
  180. : CodeEditorComponent (codeDocument, tokeniser), file (f)
  181. {
  182. setCommandManager (&IntrojucerApp::getCommandManager());
  183. }
  184. GenericCodeEditorComponent::~GenericCodeEditorComponent() {}
  185. enum
  186. {
  187. showInFinderID = 0x2fe821e3,
  188. insertComponentID = 0x2fe821e4
  189. };
  190. void GenericCodeEditorComponent::addPopupMenuItems (PopupMenu& menu, const MouseEvent* e)
  191. {
  192. menu.addItem (showInFinderID,
  193. #if JUCE_MAC
  194. "Reveal " + file.getFileName() + " in Finder");
  195. #else
  196. "Reveal " + file.getFileName() + " in Explorer");
  197. #endif
  198. menu.addSeparator();
  199. CodeEditorComponent::addPopupMenuItems (menu, e);
  200. }
  201. void GenericCodeEditorComponent::performPopupMenuAction (int menuItemID)
  202. {
  203. if (menuItemID == showInFinderID)
  204. file.revealToUser();
  205. else
  206. CodeEditorComponent::performPopupMenuAction (menuItemID);
  207. }
  208. void GenericCodeEditorComponent::getAllCommands (Array <CommandID>& commands)
  209. {
  210. CodeEditorComponent::getAllCommands (commands);
  211. const CommandID ids[] = { CommandIDs::showFindPanel,
  212. CommandIDs::findSelection,
  213. CommandIDs::findNext,
  214. CommandIDs::findPrevious };
  215. commands.addArray (ids, numElementsInArray (ids));
  216. }
  217. void GenericCodeEditorComponent::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  218. {
  219. const bool anythingSelected = isHighlightActive();
  220. switch (commandID)
  221. {
  222. case CommandIDs::showFindPanel:
  223. result.setInfo (TRANS ("Find"), TRANS ("Searches for text in the current document."), "Editing", 0);
  224. result.defaultKeypresses.add (KeyPress ('f', ModifierKeys::commandModifier, 0));
  225. break;
  226. case CommandIDs::findSelection:
  227. result.setInfo (TRANS ("Find Selection"), TRANS ("Searches for the currently selected text."), "Editing", 0);
  228. result.setActive (anythingSelected);
  229. result.defaultKeypresses.add (KeyPress ('l', ModifierKeys::commandModifier, 0));
  230. break;
  231. case CommandIDs::findNext:
  232. result.setInfo (TRANS ("Find Next"), TRANS ("Searches for the next occurrence of the current search-term."), "Editing", 0);
  233. result.defaultKeypresses.add (KeyPress ('g', ModifierKeys::commandModifier, 0));
  234. break;
  235. case CommandIDs::findPrevious:
  236. result.setInfo (TRANS ("Find Previous"), TRANS ("Searches for the previous occurrence of the current search-term."), "Editing", 0);
  237. result.defaultKeypresses.add (KeyPress ('g', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0));
  238. result.defaultKeypresses.add (KeyPress ('d', ModifierKeys::commandModifier, 0));
  239. break;
  240. default:
  241. CodeEditorComponent::getCommandInfo (commandID, result);
  242. break;
  243. }
  244. }
  245. bool GenericCodeEditorComponent::perform (const InvocationInfo& info)
  246. {
  247. switch (info.commandID)
  248. {
  249. case CommandIDs::showFindPanel: showFindPanel(); return true;
  250. case CommandIDs::findSelection: findSelection(); return true;
  251. case CommandIDs::findNext: findNext (true, true); return true;
  252. case CommandIDs::findPrevious: findNext (false, false); return true;
  253. default: break;
  254. }
  255. return CodeEditorComponent::perform (info);
  256. }
  257. //==============================================================================
  258. class GenericCodeEditorComponent::FindPanel : public Component,
  259. private TextEditor::Listener,
  260. private ButtonListener
  261. {
  262. public:
  263. FindPanel()
  264. : caseButton ("Case-sensitive"),
  265. findPrev ("<"),
  266. findNext (">")
  267. {
  268. editor.setColour (CaretComponent::caretColourId, Colours::black);
  269. addAndMakeVisible (editor);
  270. label.setText ("Find:", dontSendNotification);
  271. label.setColour (Label::textColourId, Colours::white);
  272. label.attachToComponent (&editor, false);
  273. addAndMakeVisible (caseButton);
  274. caseButton.setColour (ToggleButton::textColourId, Colours::white);
  275. caseButton.setToggleState (isCaseSensitiveSearch(), dontSendNotification);
  276. caseButton.addListener (this);
  277. findPrev.setConnectedEdges (Button::ConnectedOnRight);
  278. findNext.setConnectedEdges (Button::ConnectedOnLeft);
  279. addAndMakeVisible (findPrev);
  280. addAndMakeVisible (findNext);
  281. setWantsKeyboardFocus (false);
  282. setFocusContainer (true);
  283. findPrev.setWantsKeyboardFocus (false);
  284. findNext.setWantsKeyboardFocus (false);
  285. editor.setText (getSearchString());
  286. editor.addListener (this);
  287. }
  288. void setCommandManager (ApplicationCommandManager* cm)
  289. {
  290. findPrev.setCommandToTrigger (cm, CommandIDs::findPrevious, true);
  291. findNext.setCommandToTrigger (cm, CommandIDs::findNext, true);
  292. }
  293. void paint (Graphics& g) override
  294. {
  295. Path outline;
  296. outline.addRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 8.0f);
  297. g.setColour (Colours::black.withAlpha (0.6f));
  298. g.fillPath (outline);
  299. g.setColour (Colours::white.withAlpha (0.8f));
  300. g.strokePath (outline, PathStrokeType (1.0f));
  301. }
  302. void resized() override
  303. {
  304. int y = 30;
  305. editor.setBounds (10, y, getWidth() - 20, 24);
  306. y += 30;
  307. caseButton.setBounds (10, y, getWidth() / 2 - 10, 22);
  308. findNext.setBounds (getWidth() - 40, y, 30, 22);
  309. findPrev.setBounds (getWidth() - 70, y, 30, 22);
  310. }
  311. void buttonClicked (Button*) override
  312. {
  313. setCaseSensitiveSearch (caseButton.getToggleState());
  314. }
  315. void textEditorTextChanged (TextEditor&) override
  316. {
  317. setSearchString (editor.getText());
  318. if (GenericCodeEditorComponent* ed = getOwner())
  319. ed->findNext (true, false);
  320. }
  321. void textEditorFocusLost (TextEditor&) override {}
  322. void textEditorReturnKeyPressed (TextEditor&) override
  323. {
  324. IntrojucerApp::getCommandManager().invokeDirectly (CommandIDs::findNext, true);
  325. }
  326. void textEditorEscapeKeyPressed (TextEditor&) override
  327. {
  328. if (GenericCodeEditorComponent* ed = getOwner())
  329. ed->hideFindPanel();
  330. }
  331. GenericCodeEditorComponent* getOwner() const
  332. {
  333. return findParentComponentOfClass <GenericCodeEditorComponent>();
  334. }
  335. TextEditor editor;
  336. Label label;
  337. ToggleButton caseButton;
  338. TextButton findPrev, findNext;
  339. };
  340. void GenericCodeEditorComponent::resized()
  341. {
  342. CodeEditorComponent::resized();
  343. if (findPanel != nullptr)
  344. {
  345. findPanel->setSize (jmin (260, getWidth() - 32), 100);
  346. findPanel->setTopRightPosition (getWidth() - 16, 8);
  347. }
  348. }
  349. void GenericCodeEditorComponent::showFindPanel()
  350. {
  351. if (findPanel == nullptr)
  352. {
  353. findPanel = new FindPanel();
  354. findPanel->setCommandManager (&IntrojucerApp::getCommandManager());
  355. addAndMakeVisible (findPanel);
  356. resized();
  357. }
  358. if (findPanel != nullptr)
  359. {
  360. findPanel->editor.grabKeyboardFocus();
  361. findPanel->editor.selectAll();
  362. }
  363. }
  364. void GenericCodeEditorComponent::hideFindPanel()
  365. {
  366. findPanel = nullptr;
  367. }
  368. void GenericCodeEditorComponent::findSelection()
  369. {
  370. const String selected (getTextInRange (getHighlightedRegion()));
  371. if (selected.isNotEmpty())
  372. {
  373. setSearchString (selected);
  374. findNext (true, true);
  375. }
  376. }
  377. void GenericCodeEditorComponent::findNext (bool forwards, bool skipCurrentSelection)
  378. {
  379. const Range<int> highlight (getHighlightedRegion());
  380. const CodeDocument::Position startPos (getDocument(), skipCurrentSelection ? highlight.getEnd()
  381. : highlight.getStart());
  382. int lineNum = startPos.getLineNumber();
  383. int linePos = startPos.getIndexInLine();
  384. const int totalLines = getDocument().getNumLines();
  385. const String searchText (getSearchString());
  386. const bool caseSensitive = isCaseSensitiveSearch();
  387. for (int linesToSearch = totalLines; --linesToSearch >= 0;)
  388. {
  389. String line (getDocument().getLine (lineNum));
  390. int index;
  391. if (forwards)
  392. {
  393. index = caseSensitive ? line.indexOf (linePos, searchText)
  394. : line.indexOfIgnoreCase (linePos, searchText);
  395. }
  396. else
  397. {
  398. if (linePos >= 0)
  399. line = line.substring (0, linePos);
  400. index = caseSensitive ? line.lastIndexOf (searchText)
  401. : line.lastIndexOfIgnoreCase (searchText);
  402. }
  403. if (index >= 0)
  404. {
  405. const CodeDocument::Position p (getDocument(), lineNum, index);
  406. selectRegion (p, p.movedBy (searchText.length()));
  407. break;
  408. }
  409. if (forwards)
  410. {
  411. linePos = 0;
  412. lineNum = (lineNum + 1) % totalLines;
  413. }
  414. else
  415. {
  416. if (--lineNum < 0)
  417. lineNum = totalLines - 1;
  418. linePos = -1;
  419. }
  420. }
  421. }
  422. void GenericCodeEditorComponent::handleEscapeKey()
  423. {
  424. CodeEditorComponent::handleEscapeKey();
  425. hideFindPanel();
  426. }
  427. //==============================================================================
  428. static CPlusPlusCodeTokeniser cppTokeniser;
  429. CppCodeEditorComponent::CppCodeEditorComponent (const File& f, CodeDocument& doc)
  430. : GenericCodeEditorComponent (f, doc, &cppTokeniser)
  431. {
  432. }
  433. CppCodeEditorComponent::~CppCodeEditorComponent() {}
  434. void CppCodeEditorComponent::handleReturnKey()
  435. {
  436. GenericCodeEditorComponent::handleReturnKey();
  437. CodeDocument::Position pos (getCaretPos());
  438. String blockIndent, lastLineIndent;
  439. CodeHelpers::getIndentForCurrentBlock (pos, getTabString (getTabSize()), blockIndent, lastLineIndent);
  440. const String remainderOfBrokenLine (pos.getLineText());
  441. const int numLeadingWSChars = CodeHelpers::getLeadingWhitespace (remainderOfBrokenLine).length();
  442. if (numLeadingWSChars > 0)
  443. getDocument().deleteSection (pos, pos.movedBy (numLeadingWSChars));
  444. if (remainderOfBrokenLine.trimStart().startsWithChar ('}'))
  445. insertTextAtCaret (blockIndent);
  446. else
  447. insertTextAtCaret (lastLineIndent);
  448. const String previousLine (pos.movedByLines (-1).getLineText());
  449. const String trimmedPreviousLine (previousLine.trim());
  450. if ((trimmedPreviousLine.startsWith ("if ")
  451. || trimmedPreviousLine.startsWith ("if(")
  452. || trimmedPreviousLine.startsWith ("for ")
  453. || trimmedPreviousLine.startsWith ("for(")
  454. || trimmedPreviousLine.startsWith ("while(")
  455. || trimmedPreviousLine.startsWith ("while "))
  456. && trimmedPreviousLine.endsWithChar (')'))
  457. {
  458. insertTabAtCaret();
  459. }
  460. }
  461. void CppCodeEditorComponent::insertTextAtCaret (const String& newText)
  462. {
  463. if (getHighlightedRegion().isEmpty())
  464. {
  465. const CodeDocument::Position pos (getCaretPos());
  466. if ((newText == "{" || newText == "}")
  467. && pos.getLineNumber() > 0
  468. && pos.getLineText().trim().isEmpty())
  469. {
  470. moveCaretToStartOfLine (true);
  471. String blockIndent, lastLineIndent;
  472. if (CodeHelpers::getIndentForCurrentBlock (pos, getTabString (getTabSize()), blockIndent, lastLineIndent))
  473. {
  474. GenericCodeEditorComponent::insertTextAtCaret (blockIndent);
  475. if (newText == "{")
  476. insertTabAtCaret();
  477. }
  478. }
  479. }
  480. GenericCodeEditorComponent::insertTextAtCaret (newText);
  481. }
  482. void CppCodeEditorComponent::addPopupMenuItems (PopupMenu& menu, const MouseEvent* e)
  483. {
  484. GenericCodeEditorComponent::addPopupMenuItems (menu, e);
  485. menu.addSeparator();
  486. menu.addItem (insertComponentID, TRANS("Insert code for a new Component class..."));
  487. }
  488. void CppCodeEditorComponent::performPopupMenuAction (int menuItemID)
  489. {
  490. if (menuItemID == insertComponentID)
  491. insertComponentClass();
  492. GenericCodeEditorComponent::performPopupMenuAction (menuItemID);
  493. }
  494. void CppCodeEditorComponent::insertComponentClass()
  495. {
  496. AlertWindow aw (TRANS ("Insert a new Component class"),
  497. TRANS ("Please enter a name for the new class"),
  498. AlertWindow::NoIcon, nullptr);
  499. const char* classNameField = "Class Name";
  500. aw.addTextEditor (classNameField, String::empty, String::empty, false);
  501. aw.addButton (TRANS ("Insert Code"), 1, KeyPress (KeyPress::returnKey));
  502. aw.addButton (TRANS ("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  503. while (aw.runModalLoop() != 0)
  504. {
  505. const String className (aw.getTextEditorContents (classNameField).trim());
  506. if (className == CodeHelpers::makeValidIdentifier (className, false, true, false))
  507. {
  508. String code (BinaryData::jucer_InlineComponentTemplate_h);
  509. code = code.replace ("COMPONENTCLASS", className);
  510. insertTextAtCaret (code);
  511. break;
  512. }
  513. }
  514. }