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.

663 lines
21KB

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