cid#1640468 Dereference after null check
[LibreOffice.git] / odk / examples / python / Text / BookmarkInsertion.py
blobd65887cc21fe931ad47dad89da93357e2d7b9e0b
1 # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
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/.
10 import officehelper
11 import sys
12 import traceback
15 FIRST_PARAGRAPH = (
16 "He heard quiet steps behind him. That didn't bode well. Who could be following "
17 "him this late at night and in this deadbeat part of town? And at this "
18 "particular moment, just after he pulled off the big time and was making off "
19 "with the greenbacks. Was there another crook who'd had the same idea, and was "
20 "now watching him and waiting for a chance to grab the fruit of his labor?"
23 SECOND_PARAGRAPH = (
24 "Or did the steps behind him mean that one of many bloody officers in town was "
25 "on to him and just waiting to pounce and snap those cuffs on his wrists? He "
26 "nervously looked all around. Suddenly he saw the alley. Like lightning he "
27 "darted off to the left and disappeared between the two warehouses almost "
28 "falling over the trash can lying in the middle of the sidewalk. He tried to "
29 "nervously tap his way along in the inky darkness and suddenly stiffened: it was "
30 "a dead-end, he would have to go back the way he had come"
33 THIRD_PARAGRAPH = (
34 "The steps got louder and louder, he saw the black outline of a figure coming "
35 "around the corner. Is this the end of the line? he thought pressing himself "
36 "back against the wall trying to make himself invisible in the dark, was all "
37 "that planning and energy wasted? He was dripping with sweat now, cold and wet, "
38 "he could smell the brilliant fear coming off his clothes. Suddenly next to him, "
39 "with a barely noticeable squeak, a door swung quietly to and fro in the night's "
40 "breeze."
44 def create_example_text(component):
45 """Create example text
47 :param component: object which implements com.sun.star.text.XTextDocument interface.
48 """
49 try:
50 cursor = component.getText().createTextCursor()
51 cursor.setString(FIRST_PARAGRAPH)
52 cursor.collapseToEnd()
53 cursor.setString(SECOND_PARAGRAPH)
54 cursor.collapseToEnd()
55 cursor.setString(THIRD_PARAGRAPH)
56 cursor.gotoStart(False)
57 except Exception:
58 traceback.print_exc()
61 def find_first(document, search_str):
62 """Find the text
64 :param document: object which implements com.sun.star.text.XTextDocument interface.
65 :param str search_str: the search string.
66 :return: object representing the searched text, which implements com.sun.star.text.XTextRange interface.
67 :rtype: com.sun.star.uno.XInterface
68 """
69 try:
70 descriptor = document.createSearchDescriptor()
71 descriptor.setSearchString(search_str)
72 descriptor.setPropertyValue("SearchRegularExpression", True)
73 return document.findFirst(descriptor)
74 except Exception:
75 traceback.print_exc()
76 return None
79 def insert_bookmark(document, text_range, bookmark_name):
80 """Insert bookmark
82 :param document: object which implements om.sun.star.text.XTextDocument interface.
83 :param text_range: object representing the text range bookmark is inserted for.
84 This object should implement com.sun.star.text.XTextRange interface.
85 :param str bookmark_name: bookmark name.
86 """
87 try:
88 bookmark = document.createInstance("com.sun.star.text.Bookmark")
89 bookmark.setName(bookmark_name)
90 document.getText().insertTextContent(text_range, bookmark, True)
91 print("Insert bookmark:", bookmark_name)
92 except Exception:
93 traceback.print_exc()
96 def mark_list(component, mlist, prefix):
97 """Mark the matched text
99 :param component: object which implements com.sun.star.text.XTextDocument interface.
100 :param list[str] mlist: list of patterns to search text from document.
101 :param str prefix: prefix used to construct bookmark name.
103 try:
104 for i, search_str in enumerate(mlist):
105 search = find_first(component, search_str)
106 if not search:
107 continue
108 insert_bookmark(component, search, f"{prefix}{i}")
109 except Exception:
110 traceback.print_exc()
111 sys.exit(1)
114 def get_desktop():
115 desktop = None
116 try:
117 remote_context = officehelper.bootstrap()
118 srv_mgr = remote_context.getServiceManager()
119 if srv_mgr is None:
120 print("Can't create a desktop. No connection, no remote office servicemanager available!")
121 else:
122 desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
123 print("Connected to a running office ...")
124 except Exception:
125 traceback.print_exc()
126 sys.exit(1)
127 return desktop
130 def main():
131 desktop = get_desktop()
132 if desktop is None:
133 return
135 # Open an empty text document.
136 try:
137 doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple([]))
138 except Exception:
139 traceback.print_exc()
140 sys.exit(1)
142 create_example_text(doc)
144 mOffending = ["negro(e|es)?", "bor(ed|ing)?", "bloody?", "bleed(ing)?"]
145 mBad = ["possib(le|ilit(y|ies))", "real(ly)+", "brilliant"]
147 sOffendPrefix = "Offending"
148 sBadPrefix = "BadStyle"
150 mark_list(doc, mOffending, sOffendPrefix)
151 mark_list(doc, mBad, sBadPrefix)
153 print("Done")
156 if __name__ == "__main__":
157 main()
160 # vim: set shiftwidth=4 softtabstop=4 expandtab: