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.

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