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.

669 lines
21KB

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