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.

652 lines
20KB

  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. auto 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 (auto* 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. auto 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 ({ 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. auto 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. {
  279. public:
  280. FindPanel()
  281. {
  282. editor.setColour (CaretComponent::caretColourId, Colours::black);
  283. addAndMakeVisible (editor);
  284. label.setColour (Label::textColourId, Colours::white);
  285. label.attachToComponent (&editor, false);
  286. addAndMakeVisible (caseButton);
  287. caseButton.setColour (ToggleButton::textColourId, Colours::white);
  288. caseButton.setToggleState (isCaseSensitiveSearch(), dontSendNotification);
  289. caseButton.onClick = [this] { setCaseSensitiveSearch (caseButton.getToggleState()); };
  290. findPrev.setConnectedEdges (Button::ConnectedOnRight);
  291. findNext.setConnectedEdges (Button::ConnectedOnLeft);
  292. addAndMakeVisible (findPrev);
  293. addAndMakeVisible (findNext);
  294. setWantsKeyboardFocus (false);
  295. setFocusContainer (true);
  296. findPrev.setWantsKeyboardFocus (false);
  297. findNext.setWantsKeyboardFocus (false);
  298. editor.setText (getSearchString());
  299. editor.onTextChange = [this] { changeSearchString(); };
  300. editor.onReturnKey = [] { ProjucerApplication::getCommandManager().invokeDirectly (CommandIDs::findNext, true); };
  301. editor.onEscapeKey = [this]
  302. {
  303. if (auto* ed = getOwner())
  304. ed->hideFindPanel();
  305. };
  306. }
  307. void setCommandManager (ApplicationCommandManager* cm)
  308. {
  309. findPrev.setCommandToTrigger (cm, CommandIDs::findPrevious, true);
  310. findNext.setCommandToTrigger (cm, CommandIDs::findNext, true);
  311. }
  312. void paint (Graphics& g) override
  313. {
  314. Path outline;
  315. outline.addRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 8.0f);
  316. g.setColour (Colours::black.withAlpha (0.6f));
  317. g.fillPath (outline);
  318. g.setColour (Colours::white.withAlpha (0.8f));
  319. g.strokePath (outline, PathStrokeType (1.0f));
  320. }
  321. void resized() override
  322. {
  323. int y = 30;
  324. editor.setBounds (10, y, getWidth() - 20, 24);
  325. y += 30;
  326. caseButton.setBounds (10, y, getWidth() / 2 - 10, 22);
  327. findNext.setBounds (getWidth() - 40, y, 30, 22);
  328. findPrev.setBounds (getWidth() - 70, y, 30, 22);
  329. }
  330. void changeSearchString()
  331. {
  332. setSearchString (editor.getText());
  333. if (auto* ed = getOwner())
  334. ed->findNext (true, false);
  335. }
  336. GenericCodeEditorComponent* getOwner() const
  337. {
  338. return findParentComponentOfClass <GenericCodeEditorComponent>();
  339. }
  340. TextEditor editor;
  341. Label label { {}, "Find:" };
  342. ToggleButton caseButton { "Case-sensitive" };
  343. TextButton findPrev { "<" },
  344. findNext { ">" };
  345. };
  346. void GenericCodeEditorComponent::resized()
  347. {
  348. CodeEditorComponent::resized();
  349. if (findPanel != nullptr)
  350. {
  351. findPanel->setSize (jmin (260, getWidth() - 32), 100);
  352. findPanel->setTopRightPosition (getWidth() - 16, 8);
  353. }
  354. }
  355. void GenericCodeEditorComponent::showFindPanel()
  356. {
  357. if (findPanel == nullptr)
  358. {
  359. findPanel.reset (new FindPanel());
  360. findPanel->setCommandManager (&ProjucerApplication::getCommandManager());
  361. addAndMakeVisible (findPanel.get());
  362. resized();
  363. }
  364. if (findPanel != nullptr)
  365. {
  366. findPanel->editor.grabKeyboardFocus();
  367. findPanel->editor.selectAll();
  368. }
  369. }
  370. void GenericCodeEditorComponent::hideFindPanel()
  371. {
  372. findPanel.reset();
  373. }
  374. void GenericCodeEditorComponent::findSelection()
  375. {
  376. auto selected = getTextInRange (getHighlightedRegion());
  377. if (selected.isNotEmpty())
  378. {
  379. setSearchString (selected);
  380. findNext (true, true);
  381. }
  382. }
  383. void GenericCodeEditorComponent::findNext (bool forwards, bool skipCurrentSelection)
  384. {
  385. auto highlight = getHighlightedRegion();
  386. const CodeDocument::Position startPos (getDocument(), skipCurrentSelection ? highlight.getEnd()
  387. : highlight.getStart());
  388. auto lineNum = startPos.getLineNumber();
  389. auto linePos = startPos.getIndexInLine();
  390. auto totalLines = getDocument().getNumLines();
  391. auto searchText = getSearchString();
  392. auto caseSensitive = isCaseSensitiveSearch();
  393. for (auto linesToSearch = totalLines; --linesToSearch >= 0;)
  394. {
  395. auto line = getDocument().getLine (lineNum);
  396. int index;
  397. if (forwards)
  398. {
  399. index = caseSensitive ? line.indexOf (linePos, searchText)
  400. : line.indexOfIgnoreCase (linePos, searchText);
  401. }
  402. else
  403. {
  404. if (linePos >= 0)
  405. line = line.substring (0, linePos);
  406. index = caseSensitive ? line.lastIndexOf (searchText)
  407. : line.lastIndexOfIgnoreCase (searchText);
  408. }
  409. if (index >= 0)
  410. {
  411. const CodeDocument::Position p (getDocument(), lineNum, index);
  412. selectRegion (p, p.movedBy (searchText.length()));
  413. break;
  414. }
  415. if (forwards)
  416. {
  417. linePos = 0;
  418. lineNum = (lineNum + 1) % totalLines;
  419. }
  420. else
  421. {
  422. if (--lineNum < 0)
  423. lineNum = totalLines - 1;
  424. linePos = -1;
  425. }
  426. }
  427. }
  428. void GenericCodeEditorComponent::handleEscapeKey()
  429. {
  430. CodeEditorComponent::handleEscapeKey();
  431. hideFindPanel();
  432. }
  433. void GenericCodeEditorComponent::editorViewportPositionChanged()
  434. {
  435. CodeEditorComponent::editorViewportPositionChanged();
  436. listeners.call ([this] (Listener& l) { l.codeEditorViewportMoved (*this); });
  437. }
  438. //==============================================================================
  439. static CPlusPlusCodeTokeniser cppTokeniser;
  440. CppCodeEditorComponent::CppCodeEditorComponent (const File& f, CodeDocument& doc)
  441. : GenericCodeEditorComponent (f, doc, &cppTokeniser)
  442. {
  443. }
  444. CppCodeEditorComponent::~CppCodeEditorComponent() {}
  445. void CppCodeEditorComponent::handleReturnKey()
  446. {
  447. GenericCodeEditorComponent::handleReturnKey();
  448. auto pos = getCaretPos();
  449. String blockIndent, lastLineIndent;
  450. CodeHelpers::getIndentForCurrentBlock (pos, getTabString (getTabSize()), blockIndent, lastLineIndent);
  451. auto remainderOfBrokenLine = pos.getLineText();
  452. auto numLeadingWSChars = CodeHelpers::getLeadingWhitespace (remainderOfBrokenLine).length();
  453. if (numLeadingWSChars > 0)
  454. getDocument().deleteSection (pos, pos.movedBy (numLeadingWSChars));
  455. if (remainderOfBrokenLine.trimStart().startsWithChar ('}'))
  456. insertTextAtCaret (blockIndent);
  457. else
  458. insertTextAtCaret (lastLineIndent);
  459. auto previousLine = pos.movedByLines (-1).getLineText();
  460. auto trimmedPreviousLine = previousLine.trim();
  461. if ((trimmedPreviousLine.startsWith ("if ")
  462. || trimmedPreviousLine.startsWith ("if(")
  463. || trimmedPreviousLine.startsWith ("for ")
  464. || trimmedPreviousLine.startsWith ("for(")
  465. || trimmedPreviousLine.startsWith ("while(")
  466. || trimmedPreviousLine.startsWith ("while "))
  467. && trimmedPreviousLine.endsWithChar (')'))
  468. {
  469. insertTabAtCaret();
  470. }
  471. }
  472. void CppCodeEditorComponent::insertTextAtCaret (const String& newText)
  473. {
  474. if (getHighlightedRegion().isEmpty())
  475. {
  476. auto pos = getCaretPos();
  477. if ((newText == "{" || newText == "}")
  478. && pos.getLineNumber() > 0
  479. && pos.getLineText().trim().isEmpty())
  480. {
  481. moveCaretToStartOfLine (true);
  482. String blockIndent, lastLineIndent;
  483. if (CodeHelpers::getIndentForCurrentBlock (pos, getTabString (getTabSize()), blockIndent, lastLineIndent))
  484. {
  485. GenericCodeEditorComponent::insertTextAtCaret (blockIndent);
  486. if (newText == "{")
  487. insertTabAtCaret();
  488. }
  489. }
  490. }
  491. GenericCodeEditorComponent::insertTextAtCaret (newText);
  492. }
  493. void CppCodeEditorComponent::addPopupMenuItems (PopupMenu& menu, const MouseEvent* e)
  494. {
  495. GenericCodeEditorComponent::addPopupMenuItems (menu, e);
  496. menu.addSeparator();
  497. menu.addItem (insertComponentID, TRANS("Insert code for a new Component class..."));
  498. }
  499. void CppCodeEditorComponent::performPopupMenuAction (int menuItemID)
  500. {
  501. if (menuItemID == insertComponentID)
  502. insertComponentClass();
  503. GenericCodeEditorComponent::performPopupMenuAction (menuItemID);
  504. }
  505. void CppCodeEditorComponent::insertComponentClass()
  506. {
  507. AlertWindow aw (TRANS ("Insert a new Component class"),
  508. TRANS ("Please enter a name for the new class"),
  509. AlertWindow::NoIcon, nullptr);
  510. const char* classNameField = "Class Name";
  511. aw.addTextEditor (classNameField, String(), String(), false);
  512. aw.addButton (TRANS ("Insert Code"), 1, KeyPress (KeyPress::returnKey));
  513. aw.addButton (TRANS ("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  514. while (aw.runModalLoop() != 0)
  515. {
  516. auto className = aw.getTextEditorContents (classNameField).trim();
  517. if (className == CodeHelpers::makeValidIdentifier (className, false, true, false))
  518. {
  519. String code (BinaryData::jucer_InlineComponentTemplate_h);
  520. code = code.replace ("%%component_class%%", className);
  521. insertTextAtCaret (code);
  522. break;
  523. }
  524. }
  525. }