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.

451 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. class CodeDocumentLine;
  21. //==============================================================================
  22. /**
  23. A class for storing and manipulating a source code file.
  24. When using a CodeEditorComponent, it takes one of these as its source object.
  25. The CodeDocument stores its content as an array of lines, which makes it
  26. quick to insert and delete.
  27. @see CodeEditorComponent
  28. @tags{GUI}
  29. */
  30. class JUCE_API CodeDocument
  31. {
  32. public:
  33. /** Creates a new, empty document. */
  34. CodeDocument();
  35. /** Destructor. */
  36. ~CodeDocument();
  37. //==============================================================================
  38. /** A position in a code document.
  39. Using this class you can find a position in a code document and quickly get its
  40. character position, line, and index. By calling setPositionMaintained (true), the
  41. position is automatically updated when text is inserted or deleted in the document,
  42. so that it maintains its original place in the text.
  43. */
  44. class JUCE_API Position
  45. {
  46. public:
  47. /** Creates an uninitialised position.
  48. Don't attempt to call any methods on this until you've given it an owner document
  49. to refer to!
  50. */
  51. Position() noexcept;
  52. /** Creates a position based on a line and index in a document.
  53. Note that this index is NOT the column number, it's the number of characters from the
  54. start of the line. The "column" number isn't quite the same, because if the line
  55. contains any tab characters, the relationship of the index to its visual column depends on
  56. the number of spaces per tab being used!
  57. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  58. they will be adjusted to keep them within its limits.
  59. */
  60. Position (const CodeDocument& ownerDocument,
  61. int line, int indexInLine) noexcept;
  62. /** Creates a position based on a character index in a document.
  63. This position is placed at the specified number of characters from the start of the
  64. document. The line and column are auto-calculated.
  65. If the position is beyond the range of the document, it'll be adjusted to keep it
  66. inside.
  67. */
  68. Position (const CodeDocument& ownerDocument,
  69. int charactersFromStartOfDocument) noexcept;
  70. /** Creates a copy of another position.
  71. This will copy the position, but the new object will not be set to maintain its position,
  72. even if the source object was set to do so.
  73. */
  74. Position (const Position&) noexcept;
  75. /** Destructor. */
  76. ~Position();
  77. Position& operator= (const Position&);
  78. bool operator== (const Position&) const noexcept;
  79. bool operator!= (const Position&) const noexcept;
  80. /** Points this object at a new position within the document.
  81. If the position is beyond the range of the document, it'll be adjusted to keep it
  82. inside.
  83. @see getPosition, setLineAndIndex
  84. */
  85. void setPosition (int charactersFromStartOfDocument);
  86. /** Returns the position as the number of characters from the start of the document.
  87. @see setPosition, getLineNumber, getIndexInLine
  88. */
  89. int getPosition() const noexcept { return characterPos; }
  90. /** Moves the position to a new line and index within the line.
  91. Note that the index is NOT the column at which the position appears in an editor.
  92. If the line contains any tab characters, the relationship of the index to its
  93. visual position depends on the number of spaces per tab being used!
  94. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  95. they will be adjusted to keep them within its limits.
  96. */
  97. void setLineAndIndex (int newLineNumber, int newIndexInLine);
  98. /** Returns the line number of this position.
  99. The first line in the document is numbered zero, not one!
  100. */
  101. int getLineNumber() const noexcept { return line; }
  102. /** Returns the number of characters from the start of the line.
  103. Note that this value is NOT the column at which the position appears in an editor.
  104. If the line contains any tab characters, the relationship of the index to its
  105. visual position depends on the number of spaces per tab being used!
  106. */
  107. int getIndexInLine() const noexcept { return indexInLine; }
  108. /** Allows the position to be automatically updated when the document changes.
  109. If this is set to true, the position will register with its document so that
  110. when the document has text inserted or deleted, this position will be automatically
  111. moved to keep it at the same position in the text.
  112. */
  113. void setPositionMaintained (bool isMaintained);
  114. //==============================================================================
  115. /** Moves the position forwards or backwards by the specified number of characters.
  116. @see movedBy
  117. */
  118. void moveBy (int characterDelta);
  119. /** Returns a position which is the same as this one, moved by the specified number of
  120. characters.
  121. @see moveBy
  122. */
  123. Position movedBy (int characterDelta) const;
  124. /** Returns a position which is the same as this one, moved up or down by the specified
  125. number of lines.
  126. @see movedBy
  127. */
  128. Position movedByLines (int deltaLines) const;
  129. /** Returns the character in the document at this position.
  130. @see getLineText
  131. */
  132. juce_wchar getCharacter() const;
  133. /** Returns the line from the document that this position is within.
  134. @see getCharacter, getLineNumber
  135. */
  136. String getLineText() const;
  137. private:
  138. CodeDocument* owner = nullptr;
  139. int characterPos = 0, line = 0, indexInLine = 0;
  140. bool positionMaintained = false;
  141. friend class CodeDocument;
  142. };
  143. //==============================================================================
  144. /** Returns the full text of the document. */
  145. String getAllContent() const;
  146. /** Returns a section of the document's text. */
  147. String getTextBetween (const Position& start, const Position& end) const;
  148. /** Returns a line from the document. */
  149. String getLine (int lineIndex) const noexcept;
  150. /** Returns the number of characters in the document. */
  151. int getNumCharacters() const noexcept;
  152. /** Returns the number of lines in the document. */
  153. int getNumLines() const noexcept { return lines.size(); }
  154. /** Returns the number of characters in the longest line of the document. */
  155. int getMaximumLineLength() noexcept;
  156. /** Deletes a section of the text.
  157. This operation is undoable.
  158. */
  159. void deleteSection (const Position& startPosition, const Position& endPosition);
  160. /** Deletes a section of the text.
  161. This operation is undoable.
  162. */
  163. void deleteSection (int startIndex, int endIndex);
  164. /** Inserts some text into the document at a given position.
  165. This operation is undoable.
  166. */
  167. void insertText (const Position& position, const String& text);
  168. /** Inserts some text into the document at a given position.
  169. This operation is undoable.
  170. */
  171. void insertText (int insertIndex, const String& text);
  172. /** Replaces a section of the text with a new string.
  173. This operation is undoable.
  174. */
  175. void replaceSection (int startIndex, int endIndex, const String& newText);
  176. /** Clears the document and replaces it with some new text.
  177. This operation is undoable - if you're trying to completely reset the document, you
  178. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  179. */
  180. void replaceAllContent (const String& newContent);
  181. /** Analyses the changes between the current content and some new text, and applies
  182. those changes.
  183. */
  184. void applyChanges (const String& newContent);
  185. /** Replaces the editor's contents with the contents of a stream.
  186. This will also reset the undo history and save point marker.
  187. */
  188. bool loadFromStream (InputStream& stream);
  189. /** Writes the editor's current contents to a stream. */
  190. bool writeToStream (OutputStream& stream);
  191. //==============================================================================
  192. /** Returns the preferred new-line characters for the document.
  193. This will be either "\\n", "\\r\\n", or (rarely) "\\r".
  194. @see setNewLineCharacters
  195. */
  196. String getNewLineCharacters() const noexcept { return newLineChars; }
  197. /** Sets the new-line characters that the document should use.
  198. The string must be either "\\n", "\\r\\n", or (rarely) "\\r".
  199. @see getNewLineCharacters
  200. */
  201. void setNewLineCharacters (const String& newLineCharacters) noexcept;
  202. //==============================================================================
  203. /** Begins a new undo transaction.
  204. The document itself will not call this internally, so relies on whatever is using the
  205. document to periodically call this to break up the undo sequence into sensible chunks.
  206. @see UndoManager::beginNewTransaction
  207. */
  208. void newTransaction();
  209. /** Undo the last operation.
  210. @see UndoManager::undo
  211. */
  212. void undo();
  213. /** Redo the last operation.
  214. @see UndoManager::redo
  215. */
  216. void redo();
  217. /** Clears the undo history.
  218. @see UndoManager::clearUndoHistory
  219. */
  220. void clearUndoHistory();
  221. /** Returns the document's UndoManager */
  222. UndoManager& getUndoManager() noexcept { return undoManager; }
  223. //==============================================================================
  224. /** Makes a note that the document's current state matches the one that is saved.
  225. After this has been called, hasChangedSinceSavePoint() will return false until
  226. the document has been altered, and then it'll start returning true. If the document is
  227. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  228. will again return false.
  229. @see hasChangedSinceSavePoint
  230. */
  231. void setSavePoint() noexcept;
  232. /** Returns true if the state of the document differs from the state it was in when
  233. setSavePoint() was last called.
  234. @see setSavePoint
  235. */
  236. bool hasChangedSinceSavePoint() const noexcept;
  237. //==============================================================================
  238. /** Searches for a word-break. */
  239. Position findWordBreakAfter (const Position& position) const noexcept;
  240. /** Searches for a word-break. */
  241. Position findWordBreakBefore (const Position& position) const noexcept;
  242. /** Finds the token that contains the given position. */
  243. void findTokenContaining (const Position& pos, Position& start, Position& end) const noexcept;
  244. /** Finds the line that contains the given position. */
  245. void findLineContaining (const Position& pos, Position& start, Position& end) const noexcept;
  246. //==============================================================================
  247. /** An object that receives callbacks from the CodeDocument when its text changes.
  248. @see CodeDocument::addListener, CodeDocument::removeListener
  249. */
  250. class JUCE_API Listener
  251. {
  252. public:
  253. Listener() = default;
  254. virtual ~Listener() = default;
  255. /** Called by a CodeDocument when text is added. */
  256. virtual void codeDocumentTextInserted (const String& newText, int insertIndex) = 0;
  257. /** Called by a CodeDocument when text is deleted. */
  258. virtual void codeDocumentTextDeleted (int startIndex, int endIndex) = 0;
  259. };
  260. /** Registers a listener object to receive callbacks when the document changes.
  261. If the listener is already registered, this method has no effect.
  262. @see removeListener
  263. */
  264. void addListener (Listener* listener);
  265. /** Deregisters a listener.
  266. @see addListener
  267. */
  268. void removeListener (Listener* listener);
  269. //==============================================================================
  270. /** Iterates the text in a CodeDocument.
  271. This class lets you read characters from a CodeDocument. It's designed to be used
  272. by a CodeTokeniser object.
  273. @see CodeDocument
  274. */
  275. class JUCE_API Iterator
  276. {
  277. public:
  278. /** Creates an uninitialised iterator.
  279. Don't attempt to call any methods on this until you've given it an
  280. owner document to refer to!
  281. */
  282. Iterator() noexcept;
  283. Iterator (const CodeDocument& document) noexcept;
  284. Iterator (CodeDocument::Position) noexcept;
  285. ~Iterator() noexcept;
  286. Iterator (const Iterator&) = default;
  287. Iterator& operator= (const Iterator&) = default;
  288. /** Reads the next character and returns it. Returns 0 if you try to
  289. read past the document's end.
  290. @see peekNextChar, previousChar
  291. */
  292. juce_wchar nextChar() noexcept;
  293. /** Reads the next character without moving the current position. */
  294. juce_wchar peekNextChar() const noexcept;
  295. /** Reads the previous character and returns it. Returns 0 if you try to
  296. read past the document's start.
  297. @see isSOF, peekPreviousChar, nextChar
  298. */
  299. juce_wchar previousChar() noexcept;
  300. /** Reads the next character without moving the current position. */
  301. juce_wchar peekPreviousChar() const noexcept;
  302. /** Advances the position by one character. */
  303. void skip() noexcept;
  304. /** Returns the position as the number of characters from the start of the document. */
  305. int getPosition() const noexcept { return position; }
  306. /** Skips over any whitespace characters until the next character is non-whitespace. */
  307. void skipWhitespace() noexcept;
  308. /** Skips forward until the next character will be the first character on the next line */
  309. void skipToEndOfLine() noexcept;
  310. /** Skips backward until the next character will be the first character on this line */
  311. void skipToStartOfLine() noexcept;
  312. /** Returns the line number of the next character. */
  313. int getLine() const noexcept { return line; }
  314. /** Returns true if the iterator has reached the end of the document. */
  315. bool isEOF() const noexcept;
  316. /** Returns true if the iterator is at the start of the document. */
  317. bool isSOF() const noexcept;
  318. /** Convert this iterator to a CodeDocument::Position. */
  319. CodeDocument::Position toPosition() const;
  320. private:
  321. bool reinitialiseCharPtr() const;
  322. const CodeDocument* document;
  323. mutable String::CharPointerType charPointer { nullptr };
  324. int line = 0, position = 0;
  325. };
  326. private:
  327. //==============================================================================
  328. struct InsertAction;
  329. struct DeleteAction;
  330. friend class Iterator;
  331. friend class Position;
  332. OwnedArray<CodeDocumentLine> lines;
  333. Array<Position*> positionsToMaintain;
  334. UndoManager undoManager;
  335. int currentActionIndex = 0, indexOfSavedState = -1;
  336. int maximumLineLength = -1;
  337. ListenerList<Listener> listeners;
  338. String newLineChars { "\r\n" };
  339. void insert (const String& text, int insertPos, bool undoable);
  340. void remove (int startPos, int endPos, bool undoable);
  341. void checkLastLineStatus();
  342. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument)
  343. };
  344. } // namespace juce