LanguageTool: don't crash if REST protocol isn't set
[LibreOffice.git] / starmath / inc / cursor.hxx
blobcd6128ba8e05dfcc10a81b0f61d59f4ab756ff5f
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #pragma once
12 #include "caret.hxx"
14 /** Factor to multiple the squared horizontal distance with
15 * Used for Up and Down movement.
17 #define HORIZONTICAL_DISTANCE_FACTOR 10
19 /** Enum of direction for movement */
20 enum SmMovementDirection
22 MoveUp,
23 MoveDown,
24 MoveLeft,
25 MoveRight
28 /** Enum of elements that can inserted into a formula */
29 enum SmFormulaElement
31 BlankElement,
32 FactorialElement,
33 PlusElement,
34 MinusElement,
35 CDotElement,
36 EqualElement,
37 LessThanElement,
38 GreaterThanElement,
39 PercentElement
42 /** Bracket types that can be inserted */
43 enum class SmBracketType
45 /** Round brackets, left command "(" */
46 Round,
47 /**Square brackets, left command "[" */
48 Square,
49 /** Curly brackets, left command "lbrace" */
50 Curly,
53 /** A list of nodes */
54 typedef std::list<SmNode*> SmNodeList;
56 typedef std::list<std::unique_ptr<SmNode>> SmClipboard;
58 class SmDocShell;
60 /** Formula cursor
62 * This class is used to represent a cursor in a formula, which can be used to manipulate
63 * a formula programmatically.
64 * @remarks This class is a very intimate friend of SmDocShell.
66 class SmCursor
68 public:
69 SmCursor(SmNode* tree, SmDocShell* pShell)
70 : mpAnchor(nullptr)
71 , mpPosition(nullptr)
72 , mpTree(tree)
73 , mpDocShell(pShell)
74 , mnEditSections(0)
75 , mbIsEnabledSetModifiedSmDocShell(false)
77 //Build graph
78 BuildGraph();
81 /** Get position */
82 const SmCaretPos& GetPosition() const { return mpPosition->CaretPos; }
84 /** True, if the cursor has a selection */
85 bool HasSelection() const { return mpAnchor != mpPosition; }
87 /** Move the position of this cursor */
88 void Move(OutputDevice* pDev, SmMovementDirection direction, bool bMoveAnchor = true);
90 /** Move to the caret position closest to a given point */
91 void MoveTo(OutputDevice* pDev, const Point& pos, bool bMoveAnchor);
93 /** Delete the current selection or do nothing */
94 void Delete();
96 /** Delete selection, previous element or merge lines
98 * This method implements the behaviour of backspace.
100 void DeletePrev(OutputDevice* pDev);
102 /** Insert text at the current position */
103 void InsertText(const OUString& aString);
105 /** Insert an element into the formula */
106 void InsertElement(SmFormulaElement element);
108 /** Insert command text translated into line entries at position
110 * Note: This method uses the parser to translate a command text into a
111 * tree, then it copies line entries from this tree into the current tree.
112 * Will not work for commands such as newline or ##, if position is in a matrix.
113 * This will work for stuff like "A intersection B". But stuff spanning multiple lines
114 * or dependent on the context which position is placed in will not work!
116 void InsertCommandText(const OUString& aCommandText);
118 /** Insert a special node created from aString
120 * Used for handling insert request from the "catalog" dialog.
121 * The provided string should be formatted as the desired command: %phi
122 * Note: this method ONLY supports commands defined in Math.xcu
124 * For more complex expressions use InsertCommandText, this method doesn't
125 * use SmParser, this means that it's faster, but not as strong.
127 void InsertSpecial(std::u16string_view aString);
129 /** Create sub-/super script
131 * If there's a selection, it will be move into the appropriate sub-/super scription
132 * of the node in front of it. If there's no node in front of position (or the selection),
133 * a sub-/super scription of a new SmPlaceNode will be made.
135 * If there's is an existing subscription of the node, the caret will be moved into it,
136 * and any selection will replace it.
138 void InsertSubSup(SmSubSup eSubSup);
140 /** Insert a new row or newline
142 * Inserts a new row if position is in a matrix or stack command.
143 * Otherwise a newline is inserted if we're in a toplevel line.
145 * @returns True, if a new row/line could be inserted.
147 * @remarks If the caret is placed in a subline of a command that doesn't support
148 * this operator the method returns FALSE, and doesn't do anything.
150 bool InsertRow();
152 /** Insert a fraction, use selection as numerator */
153 void InsertFraction();
155 /** Create brackets around current selection, or new SmPlaceNode */
156 void InsertBrackets(SmBracketType eBracketType);
158 /** Copy the current selection */
159 void Copy();
160 /** Cut the current selection */
161 void Cut()
163 Copy();
164 Delete();
166 /** Paste the clipboard */
167 void Paste();
169 /** Returns true if more than one node is selected
171 * This method is used for implementing backspace and delete.
172 * If one of these causes a complex selection, e.g. a node with
173 * subnodes or similar, this should not be deleted immediately.
175 bool HasComplexSelection();
177 /** Finds the topmost node in a visual line
179 * If MoveUpIfSelected is true, this will move up to the parent line
180 * if the parent of the current line is selected.
182 static SmNode* FindTopMostNodeInLine(SmNode* pSNode, bool MoveUpIfSelected = false);
184 /** Draw the caret */
185 void Draw(OutputDevice& pDev, Point Offset, bool isCaretVisible);
187 tools::Rectangle GetCaretRectangle(OutputDevice& rOutDev) const;
188 tools::Rectangle GetSelectionRectangle(OutputDevice& rOutDev) const;
190 bool IsAtTailOfBracket(SmBracketType eBracketType) const;
192 private:
193 friend class SmDocShell;
195 SmCaretPosGraphEntry *mpAnchor, *mpPosition;
196 /** Formula tree */
197 SmNode* mpTree;
198 /** Owner of the formula tree */
199 SmDocShell* mpDocShell;
200 /** Graph over caret position in the current tree */
201 std::unique_ptr<SmCaretPosGraph> mpGraph;
202 /** Clipboard holder */
203 SmClipboard maClipboard;
205 /** Returns a node that is selected, if any could be found */
206 SmNode* FindSelectedNode(SmNode* pNode);
208 /** Is this one of the nodes used to compose a line
210 * These are SmExpression, SmBinHorNode, SmUnHorNode etc.
212 static bool IsLineCompositionNode(SmNode const* pNode);
214 /** Count number of selected nodes, excluding line composition nodes
216 * Note this function doesn't count line composition nodes and it
217 * does count all subnodes as well as the owner nodes.
219 * Used by SmCursor::HasComplexSelection()
221 int CountSelectedNodes(SmNode* pNode);
223 /** Convert a visual line to a list
225 * Note this method will delete all the nodes that will no longer be needed.
226 * that includes pLine!
227 * This method also deletes SmErrorNode's as they're just meta info in the line.
229 static void LineToList(SmStructureNode* pLine, SmNodeList& rList);
231 /** Auxiliary function for calling LineToList on a node
233 * This method sets pNode = NULL and remove it from its parent.
234 * (Assuming it has a parent, and is a child of it).
236 static void NodeToList(SmNode*& rpNode, SmNodeList& rList)
238 //Remove from parent and NULL rpNode
239 SmNode* pNode = rpNode;
240 if (rpNode && rpNode->GetParent())
241 { //Don't remove this, correctness relies on it
242 int index = rpNode->GetParent()->IndexOfSubNode(rpNode);
243 assert(index >= 0);
244 rpNode->GetParent()->SetSubNode(index, nullptr);
246 rpNode = nullptr;
247 //Create line from node
248 if (pNode && IsLineCompositionNode(pNode))
250 LineToList(static_cast<SmStructureNode*>(pNode), rList);
251 return;
253 if (pNode)
254 rList.push_front(pNode);
257 /** Clone a visual line to a clipboard
259 * ... but the selected part only.
260 * Doesn't clone SmErrorNodes, which are ignored as they are context dependent metadata.
262 static void CloneLineToClipboard(SmStructureNode* pLine, SmClipboard* pClipboard);
264 /** Build pGraph over caret positions */
265 void BuildGraph();
267 /** Insert new nodes in the tree after position */
268 void InsertNodes(std::unique_ptr<SmNodeList> pNewNodes);
270 /** tries to set position to a specific SmCaretPos
272 * @returns false on failure to find the position in pGraph.
274 bool SetCaretPosition(SmCaretPos pos);
276 /** Set selected on nodes of the tree */
277 void AnnotateSelection() const;
279 /** Clone list of nodes in a clipboard (creates a deep clone) */
280 static std::unique_ptr<SmNodeList> CloneList(SmClipboard& rClipboard);
282 /** Find an iterator pointing to the node in pLineList following rCaretPos
284 * If rCaretPos.pSelectedNode cannot be found it is assumed that it's in front of pLineList,
285 * thus not an element in pLineList. In this case this method returns an iterator to the
286 * first element in pLineList.
288 * If the current position is inside an SmTextNode, this node will be split in two, for this
289 * reason you should beaware that iterators to elements in pLineList may be invalidated, and
290 * that you should call PatchLineList() with this iterator if no action is taken.
292 static SmNodeList::iterator FindPositionInLineList(SmNodeList* pLineList,
293 const SmCaretPos& rCaretPos);
295 /** Patch a line list after modification, merge SmTextNode, remove SmPlaceNode etc.
297 * @param pLineList The line list to patch
298 * @param aIter Iterator pointing to the element that needs to be patched with its previous.
300 * When the list is patched text nodes before and after aIter will be merged.
301 * If there's an, in the context, inappropriate SmPlaceNode before or after aIter it will also be
302 * removed.
304 * @returns A caret position equivalent to one selecting the node before aIter, the method returns
305 * an invalid SmCaretPos to indicate placement in front of the line.
307 static SmCaretPos PatchLineList(SmNodeList* pLineList, SmNodeList::iterator aIter);
309 /** Take selected nodes from a list
311 * Puts the selected nodes into pSelectedNodes, or if pSelectedNodes is NULL deletes
312 * the selected nodes.
313 * Note: If there's a selection inside an SmTextNode this node will be split, and it
314 * will not be merged when the selection have been taken. Use PatchLineList on the
315 * iterator returns to fix this.
317 * @returns An iterator pointing to the element following the selection taken.
319 static SmNodeList::iterator TakeSelectedNodesFromList(SmNodeList* pLineList,
320 SmNodeList* pSelectedNodes = nullptr);
322 /** Create an instance of SmMathSymbolNode usable for brackets */
323 static SmNode* CreateBracket(SmBracketType eBracketType, bool bIsLeft);
325 /** The number of times BeginEdit have been called
326 * Used to allow nesting of BeginEdit() and EndEdit() sections
328 int mnEditSections;
329 /** Holds data for BeginEdit() and EndEdit() */
330 bool mbIsEnabledSetModifiedSmDocShell;
331 /** Begin edit section where the tree will be modified */
332 void BeginEdit();
333 /** End edit section where the tree will be modified */
334 void EndEdit();
335 /** Finish editing
337 * Finishes editing by parsing pLineList and inserting back into pParent at nParentIndex.
338 * This method also rebuilds the graph, annotates the selection, sets caret position and
339 * Calls EndEdit.
341 * @remarks Please note that this method will delete pLineList, as the elements are taken.
343 * @param pLineList List the constitutes the edited line.
344 * @param pParent Parent to which the line should be inserted.
345 * @param nParentIndex Index in parent where the line should be inserted.
346 * @param PosAfterEdit Caret position to look for after rebuilding graph.
347 * @param pStartLine Line to take first position in, if PosAfterEdit cannot be found,
348 * leave it NULL for pLineList.
350 void FinishEdit(std::unique_ptr<SmNodeList> pLineList, SmStructureNode* pParent,
351 int nParentIndex, SmCaretPos PosAfterEdit, SmNode* pStartLine = nullptr);
352 /** Request the formula is repainted */
353 void RequestRepaint();
356 /** Minimalistic recursive decent SmNodeList parser
358 * This parser is used to take a list of nodes that constitutes a line
359 * and parse them to a tree of SmBinHorNode, SmUnHorNode and SmExpression.
361 * Please note, this will not handle all kinds of nodes, only nodes that
362 * constitutes and entry in a line.
364 * Below is an EBNF representation of the grammar used for this parser:
365 * \code
366 * Expression -> Relation*
367 * Relation -> Sum [(=|<|>|...) Sum]*
368 * Sum -> Product [(+|-) Product]*
369 * Product -> Factor [(*|/) Factor]*
370 * Factor -> [+|-|-+|...]* Factor | Postfix
371 * Postfix -> node [!]*
372 * \endcode
374 class SmNodeListParser
376 public:
377 /** Create an instance of SmNodeListParser */
378 SmNodeListParser() { pList = nullptr; }
379 /** Parse a list of nodes to an expression.
381 * Old error nodes will be deleted.
383 SmNode* Parse(SmNodeList* list);
384 /** True, if the token is an operator */
385 static bool IsOperator(const SmToken& token);
386 /** True, if the token is a relation operator */
387 static bool IsRelationOperator(const SmToken& token);
388 /** True, if the token is a sum operator */
389 static bool IsSumOperator(const SmToken& token);
390 /** True, if the token is a product operator */
391 static bool IsProductOperator(const SmToken& token);
392 /** True, if the token is a unary operator */
393 static bool IsUnaryOperator(const SmToken& token);
394 /** True, if the token is a postfix operator */
395 static bool IsPostfixOperator(const SmToken& token);
397 private:
398 SmNodeList* pList;
399 /** Get the current terminal */
400 SmNode* Terminal()
402 if (!pList->empty())
403 return pList->front();
404 return nullptr;
406 /** Move to next terminal */
407 SmNode* Next()
409 pList->pop_front();
410 return Terminal();
412 /** Take the current terminal */
413 SmNode* Take()
415 SmNode* pRetVal = Terminal();
416 Next();
417 return pRetVal;
419 SmNode* Expression();
420 SmNode* Relation();
421 SmNode* Sum();
422 SmNode* Product();
423 SmNode* Factor();
424 SmNode* Postfix();
425 static SmNode* Error();
428 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */