comphelper, msicreator, odk: fix issues found by Ruff linter

Change-Id: I5ef65baeb0100b9d70b5c59c1d5f6f43ab951a22
Reviewed-on: https://gerrit.libreoffice.org/c/core/+/171092
Reviewed-by: Ilmari Lauhakangas <ilmari.lauhakangas@libreoffice.org>
Tested-by: Jenkins
Tested-by: Ilmari Lauhakangas <ilmari.lauhakangas@libreoffice.org>
This commit is contained in:
Ilmari Lauhakangas 2024-07-27 14:54:40 +03:00
parent 5ed1415d1c
commit 558b20d1ac
16 changed files with 94 additions and 90 deletions

View file

@ -30,7 +30,7 @@ class TestSequenceOutputStream(unittest.TestCase):
self.data = uno.ByteSequence(b"some data") self.data = uno.ByteSequence(b"some data")
try: try:
self.service_manager = self._uno.getContext().getServiceManager() self.service_manager = self._uno.getContext().getServiceManager()
except: except Exception:
raise RuntimeError("Cannot create service factory!") raise RuntimeError("Cannot create service factory!")
if self.service_manager is None: if self.service_manager is None:
raise RuntimeError("Cannot create service factory!") raise RuntimeError("Cannot create service factory!")

View file

@ -1,4 +1,5 @@
import os, sys import os
import sys
from shutil import copytree, copy2, move, rmtree from shutil import copytree, copy2, move, rmtree
import json import json
import createmsi import createmsi

View file

@ -14,7 +14,11 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import sys, os, subprocess, shutil, uuid, json, re import sys
import os
import subprocess
import uuid
import json
from glob import glob from glob import glob
import platform import platform
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET

View file

@ -37,7 +37,7 @@ class HelloTextTableShape:
self.remote_context = officehelper.bootstrap() self.remote_context = officehelper.bootstrap()
print("Connected to a running office ...") print("Connected to a running office ...")
return self.remote_context.ServiceManager return self.remote_context.ServiceManager
except Exception as e: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)

View file

@ -50,7 +50,7 @@ def convert(src_file, dest_file, to_type):
PropertyValue(Name="FilterName", Value=to_type), PropertyValue(Name="FilterName", Value=to_type),
) )
try: try:
doc.storeAsURL(dest_url, opts); doc.storeAsURL(dest_url, opts)
finally: finally:
doc.dispose() doc.dispose()

View file

@ -7,14 +7,15 @@
# file, You can obtain one at https://mozilla.org/MPL/2.0/. # file, You can obtain one at https://mozilla.org/MPL/2.0/.
# #
import uno, unohelper; import uno
from com.sun.star.awt import XKeyHandler; import unohelper
from com.sun.star.awt import XKeyListener; from com.sun.star.awt import XKeyHandler
from com.sun.star.awt import XMouseClickHandler; from com.sun.star.awt import XKeyListener
from com.sun.star.awt import XMouseMotionHandler; from com.sun.star.awt import XMouseClickHandler
from com.sun.star.awt import XMouseListener; from com.sun.star.awt import XMouseMotionHandler
from com.sun.star.awt import XMouseMotionListener; from com.sun.star.awt import XMouseListener
from com.sun.star.accessibility import AccessibleRole; from com.sun.star.awt import XMouseMotionListener
from com.sun.star.accessibility import AccessibleRole
""" """
@ -34,36 +35,36 @@ SOFFICE_CONNECTION_URI = "uno:socket,host=localhost,port=2083;urp;StarOffice.Com
def demo(): def demo():
# Connect to LibreOffice process # Connect to LibreOffice process
localComponentContext = uno.getComponentContext(); localComponentContext = uno.getComponentContext()
localServiceManager = localComponentContext.getServiceManager(); localServiceManager = localComponentContext.getServiceManager()
resolver = localServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localComponentContext); resolver = localServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localComponentContext)
remoteComponentContext = resolver.resolve(SOFFICE_CONNECTION_URI); remoteComponentContext = resolver.resolve(SOFFICE_CONNECTION_URI)
# Get the currently opened view context. # Get the currently opened view context.
remoteServiceManager = remoteComponentContext.getServiceManager(); remoteServiceManager = remoteComponentContext.getServiceManager()
desktop = remoteServiceManager.createInstance("com.sun.star.frame.Desktop"); desktop = remoteServiceManager.createInstance("com.sun.star.frame.Desktop")
xComponent = desktop.getCurrentComponent(); # e.g. SwXTextDocument, ScModelObj, SdXImpressDocument xComponent = desktop.getCurrentComponent() # e.g. SwXTextDocument, ScModelObj, SdXImpressDocument
if "com.sun.star.document.OfficeDocument" not in xComponent.getSupportedServiceNames(): if "com.sun.star.document.OfficeDocument" not in xComponent.getSupportedServiceNames():
print("No OfficeDocument opened."); print("No OfficeDocument opened.")
exit(1); exit(1)
else: else:
handler = MyXKeyMouseClickMotionHandler("handler"); handler = MyXKeyMouseClickMotionHandler("handler")
# Events in the document view area. Not in the surrounding UI. # Events in the document view area. Not in the surrounding UI.
xController = xComponent.getCurrentController(); # xModel.getCurrentController() xController = xComponent.getCurrentController() # xModel.getCurrentController()
xController.addKeyHandler(handler); # XUserInputInterception.addKeyHandler() xController.addKeyHandler(handler) # XUserInputInterception.addKeyHandler()
xController.addMouseClickHandler(handler); # XUserInputInterception.addMouseClickHandler() xController.addMouseClickHandler(handler) # XUserInputInterception.addMouseClickHandler()
listener = MyXKeyMouseClickMotionHandler("listener"); listener = MyXKeyMouseClickMotionHandler("listener")
# TODO: Register to e.value.Source of Handler events. # TODO: Register to e.value.Source of Handler events.
# That's the correct source. # That's the correct source.
xWindow = xController.ComponentWindow; xWindow = xController.ComponentWindow
# In writer we're usually looking for: # In writer we're usually looking for:
# xWindow.Windows[0].Windows[0] # xWindow.Windows[0].Windows[0]
recursive_windows("", xWindow, lambda subXWindow: ( recursive_windows("", xWindow, lambda subXWindow: (
subXWindow.addKeyListener(listener), subXWindow.addKeyListener(listener),
subXWindow.addMouseListener(listener), subXWindow.addMouseListener(listener),
#subXWindow.addMouseMotionListener(listener), # very much events #subXWindow.addMouseMotionListener(listener), # very much events
)); ))
# Maybe the event handlers can also be registered via one of the objects # Maybe the event handlers can also be registered via one of the objects
# this function iterates through. But currently this function just # this function iterates through. But currently this function just
@ -71,72 +72,72 @@ def demo():
#recursive_acc_ctx("", xWindow.AccessibleContext.AccessibleParent); #recursive_acc_ctx("", xWindow.AccessibleContext.AccessibleParent);
#recursive_acc_ctx("", xWindow); #recursive_acc_ctx("", xWindow);
input("Waiting for events. Press Enter to quit...\n"); input("Waiting for events. Press Enter to quit...\n")
def recursive_acc_ctx(path, obj): def recursive_acc_ctx(path, obj):
print("recursive_acc_ctx: " + path + find_accessible_role(obj.getAccessibleContext().getAccessibleRole())) print("recursive_acc_ctx: " + path + find_accessible_role(obj.getAccessibleContext().getAccessibleRole()))
for i in range(obj.getAccessibleContext().AccessibleChildCount): for i in range(obj.getAccessibleContext().AccessibleChildCount):
recursive_acc_ctx(path+str(i)+": ", obj.getAccessibleContext().getAccessibleChild(i)); recursive_acc_ctx(path+str(i)+": ", obj.getAccessibleContext().getAccessibleChild(i))
def recursive_windows(path, xWindow, func): def recursive_windows(path, xWindow, func):
print("recursive_windows: " + path + find_accessible_role(xWindow.getAccessibleContext().getAccessibleRole())) print("recursive_windows: " + path + find_accessible_role(xWindow.getAccessibleContext().getAccessibleRole()))
func(xWindow); func(xWindow)
try: try:
windows = xWindow.getWindows(); # XVclContainer.getWindows() windows = xWindow.getWindows() # XVclContainer.getWindows()
except: except Exception:
return; return
for i in range(len(windows)): for i in range(len(windows)):
subXWindow = windows[i]; subXWindow = windows[i]
recursive_windows(path+str(i)+": ", subXWindow, func); recursive_windows(path+str(i)+": ", subXWindow, func)
def find_accessible_role(role_int): def find_accessible_role(role_int):
for role_name in dir(AccessibleRole): for role_name in dir(AccessibleRole):
if role_int == eval("AccessibleRole." + role_name): if role_int == eval("AccessibleRole." + role_name):
return role_name; return role_name
class MyXKeyMouseClickMotionHandler(unohelper.Base, XKeyHandler, XKeyListener, XMouseClickHandler, XMouseMotionHandler, XMouseListener, XMouseMotionListener): class MyXKeyMouseClickMotionHandler(unohelper.Base, XKeyHandler, XKeyListener, XMouseClickHandler, XMouseMotionHandler, XMouseListener, XMouseMotionListener):
def __init__(self, name): # XKeyHandler, XKeyListener def __init__(self, name): # XKeyHandler, XKeyListener
self.name = name; self.name = name
def keyPressed(self, e): # XKeyHandler, XKeyListener def keyPressed(self, e): # XKeyHandler, XKeyListener
self.key_evt(e, "pressed"); self.key_evt(e, "pressed")
return False; # False: don't consume (run other event handlers) return False # False: don't consume (run other event handlers)
def keyReleased(self, e): def keyReleased(self, e):
self.key_evt(e, "released"); self.key_evt(e, "released")
return False; return False
def mousePressed(self, e): # XMouseClickHandler, XMouseListener def mousePressed(self, e): # XMouseClickHandler, XMouseListener
self.mouse_evt(e, "pressed"); self.mouse_evt(e, "pressed")
return False; return False
def mouseReleased(self, e): # XMouseClickHandler, XMouseListener def mouseReleased(self, e): # XMouseClickHandler, XMouseListener
self.mouse_evt(e, "released"); self.mouse_evt(e, "released")
return False; return False
def mouseEntered(self, e): # XMouseListener def mouseEntered(self, e): # XMouseListener
self.mouse_evt(e, "entered"); self.mouse_evt(e, "entered")
return False; return False
def mouseExited(self, e): # XMouseListener def mouseExited(self, e): # XMouseListener
self.mouse_evt(e, "exited"); self.mouse_evt(e, "exited")
return False; return False
def mouseDragged(self, e): # XMouseMotionHandler, XMouseMotionListener def mouseDragged(self, e): # XMouseMotionHandler, XMouseMotionListener
self.mouse_evt(e, "dragged"); self.mouse_evt(e, "dragged")
return False; return False
def mouseMoved(self, e): # XMouseMotionHandler, XMouseMotionListener def mouseMoved(self, e): # XMouseMotionHandler, XMouseMotionListener
self.mouse_evt(e, "moved"); self.mouse_evt(e, "moved")
return False; return False
def disposing(self, s): def disposing(self, s):
print(self.name + "# disposing"); print(self.name + "# disposing")
def key_evt(self, e, action): def key_evt(self, e, action):
#print(self.name + "# key "+action+": " + str(e)); # very much output #print(self.name + "# key "+action+": " + str(e)); # very much output
print(self.name + "# key "+action+" (code: " + str(e.value.KeyCode.real) + "): " + e.value.KeyChar.value); print(self.name + "# key "+action+" (code: " + str(e.value.KeyCode.real) + "): " + e.value.KeyChar.value)
def mouse_evt(self, e, action): def mouse_evt(self, e, action):
#print(self.name + "# mouse "+action+": " + str(e)); # very much output #print(self.name + "# mouse "+action+": " + str(e)); # very much output
print(self.name + "# mouse "+action+": Modifiers: "+str(e.value.Modifiers)+"; Buttons: "+str(e.value.Buttons)+"; X: "+str(e.value.X)+"; Y: "+str(e.value.Y)+"; ClickCount: "+str(e.value.ClickCount)+"; PopupTrigger: "+str(e.value.PopupTrigger)); print(self.name + "# mouse "+action+": Modifiers: "+str(e.value.Modifiers)+"; Buttons: "+str(e.value.Buttons)+"; X: "+str(e.value.X)+"; Y: "+str(e.value.Y)+"; ClickCount: "+str(e.value.ClickCount)+"; PopupTrigger: "+str(e.value.PopupTrigger))
demo(); demo()
# vim: set shiftwidth=4 softtabstop=4 expandtab: # vim: set shiftwidth=4 softtabstop=4 expandtab:

View file

@ -54,7 +54,7 @@ def create_example_text(component):
cursor.collapseToEnd() cursor.collapseToEnd()
cursor.setString(THIRD_PARAGRAPH) cursor.setString(THIRD_PARAGRAPH)
cursor.gotoStart(False) cursor.gotoStart(False)
except: except Exception:
traceback.print_exc() traceback.print_exc()
@ -71,7 +71,7 @@ def find_first(document, search_str):
descriptor.setSearchString(search_str) descriptor.setSearchString(search_str)
descriptor.setPropertyValue("SearchRegularExpression", True) descriptor.setPropertyValue("SearchRegularExpression", True)
return document.findFirst(descriptor) return document.findFirst(descriptor)
except: except Exception:
traceback.print_exc() traceback.print_exc()
return None return None
@ -89,7 +89,7 @@ def insert_bookmark(document, text_range, bookmark_name):
bookmark.setName(bookmark_name) bookmark.setName(bookmark_name)
document.getText().insertTextContent(text_range, bookmark, True) document.getText().insertTextContent(text_range, bookmark, True)
print("Insert bookmark:", bookmark_name) print("Insert bookmark:", bookmark_name)
except: except Exception:
traceback.print_exc() traceback.print_exc()
@ -106,7 +106,7 @@ def mark_list(component, mlist, prefix):
if not search: if not search:
continue continue
insert_bookmark(component, search, f"{prefix}{i}") insert_bookmark(component, search, f"{prefix}{i}")
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
@ -121,7 +121,7 @@ def get_desktop():
else: else:
desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context) desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
print("Connected to a running office ...") print("Connected to a running office ...")
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
return desktop return desktop
@ -135,7 +135,7 @@ def main():
# Open an empty text document. # Open an empty text document.
try: try:
doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple([])) doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple([]))
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)

View file

@ -34,14 +34,14 @@ def insert_graphic(filename):
try: try:
graphic = doc.createInstance("com.sun.star.text.TextGraphicObject") graphic = doc.createInstance("com.sun.star.text.TextGraphicObject")
except: except Exception:
traceback.print_exc(file=log_file) traceback.print_exc(file=log_file)
return return
log_file.write("inserting graphic\n") log_file.write("inserting graphic\n")
try: try:
text.insertTextContent(cursor, graphic, True) text.insertTextContent(cursor, graphic, True)
except: except Exception:
print("Could not insert Content") print("Could not insert Content")
traceback.print_exc() traceback.print_exc()
return return
@ -70,7 +70,7 @@ def insert_graphic(filename):
graphic.setPropertyValue("Width", 4400) graphic.setPropertyValue("Width", 4400)
# Setting the height # Setting the height
graphic.setPropertyValue("Height", 4000) graphic.setPropertyValue("Height", 4000)
except: except Exception:
print("Couldn't set property 'GraphicURL'") print("Couldn't set property 'GraphicURL'")
traceback.print_exc(file=log_file) traceback.print_exc(file=log_file)
@ -89,7 +89,7 @@ def main():
args = parser.parse_args() args = parser.parse_args()
try: try:
insert_graphic(args.image) insert_graphic(args.image)
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)

View file

@ -27,7 +27,7 @@ def get_desktop():
print("Can't create a desktop. No connection, no remote office servicemanager available!") print("Can't create a desktop. No connection, no remote office servicemanager available!")
else: else:
desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context) desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
return desktop return desktop
@ -85,7 +85,7 @@ def main():
text_range.setPropertyToDefault("CharWeight") text_range.setPropertyToDefault("CharWeight")
# Then, check again # Then, check again
check_property_state(text_range, text_range.getPropertyState("CharWeight")) check_property_state(text_range, text_range.getPropertyState("CharWeight"))
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)

View file

@ -32,8 +32,8 @@ def main():
print("Opening an empty Writer document") print("Opening an empty Writer document")
doc_url = "private:factory/swriter" doc_url = "private:factory/swriter"
doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple()) doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple())
except Exception as e: except Exception:
print(f"d", file=sys.stderr) print("d", file=sys.stderr)
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
@ -55,7 +55,7 @@ def generate(doc):
try: try:
cursor.setPropertyValue("CharColor", 255) cursor.setPropertyValue("CharColor", 255)
cursor.setPropertyValue("CharShadowed", True) cursor.setPropertyValue("CharShadowed", True)
except: except Exception:
print("Couldn't change the color", file=sys.stderr) print("Couldn't change the color", file=sys.stderr)
traceback.print_exc() traceback.print_exc()

View file

@ -66,7 +66,7 @@ def get_desktop():
print("Can't create a desktop. No connection, no remote office servicemanager available!") print("Can't create a desktop. No connection, no remote office servicemanager available!")
else: else:
desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context) desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
return desktop return desktop
@ -81,7 +81,7 @@ def main():
doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple()) doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple())
create_style(doc) create_style(doc)
apply_style(doc) apply_style(doc)
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)

View file

@ -23,7 +23,7 @@ def get_desktop():
print("Can't create a desktop. No connection, no remote office servicemanager available!") print("Can't create a desktop. No connection, no remote office servicemanager available!")
else: else:
desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context) desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
return desktop return desktop
@ -43,13 +43,13 @@ def main():
try: try:
cursor.setPropertyValue("CharFontName", "Arial") cursor.setPropertyValue("CharFontName", "Arial")
except: except Exception:
pass pass
text.insertString(cursor, "Headline", False) text.insertString(cursor, "Headline", False)
try: try:
cursor.setPropertyValue("CharFontName", "Liberation Sans") cursor.setPropertyValue("CharFontName", "Liberation Sans")
except: except Exception:
pass pass
text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False) text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
text.insertString(cursor, "A very short paragraph for illustration only", False) text.insertString(cursor, "A very short paragraph for illustration only", False)
@ -72,7 +72,6 @@ def main():
paragraph_enumeration = text.createEnumeration() paragraph_enumeration = text.createEnumeration()
while paragraph_enumeration.hasMoreElements(): while paragraph_enumeration.hasMoreElements():
paragraph = paragraph_enumeration.nextElement() paragraph = paragraph_enumeration.nextElement()
paragraph_text = paragraph.getAnchor().getString()
# Create a cursor from this paragraph # Create a cursor from this paragraph
paragraph_cursor = paragraph.getAnchor().getText().createTextCursor() paragraph_cursor = paragraph.getAnchor().getText().createTextCursor()
@ -96,7 +95,7 @@ def main():
text_range.setPropertyValue("ParaStyleName", style_name) text_range.setPropertyValue("ParaStyleName", style_name)
print("Apply the paragraph style:", style_name) print("Apply the paragraph style:", style_name)
break break
except: except Exception:
traceback.print_exc() traceback.print_exc()
print("Done") print("Done")

View file

@ -28,7 +28,7 @@ def main():
text = doc.getText() text = doc.getText()
create_example_data(text) create_example_data(text)
display_structure(text) display_structure(text)
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
@ -44,7 +44,7 @@ def create_example_data(text):
cursor.gotoEndOfWord(True) cursor.gotoEndOfWord(True)
cursor.setPropertyValue("CharWeight", BOLD) cursor.setPropertyValue("CharWeight", BOLD)
print("create example data") print("create example data")
except: except Exception:
traceback.print_exc() traceback.print_exc()

View file

@ -23,7 +23,7 @@ def get_desktop():
print("Can't create a desktop. No connection, no remote office servicemanager available!") print("Can't create a desktop. No connection, no remote office servicemanager available!")
else: else:
desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context) desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
return desktop return desktop
@ -38,7 +38,7 @@ def main():
try: try:
doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple()) doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple())
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)
@ -57,7 +57,7 @@ def main():
replaced_cnt = doc.replaceAll(replace_descriptor) replaced_cnt = doc.replaceAll(replace_descriptor)
if replaced_cnt > 0: if replaced_cnt > 0:
print("Replaced", british_word, "with", us_word) print("Replaced", british_word, "with", us_word)
except: except Exception:
traceback.print_exc() traceback.print_exc()
print("Done") print("Done")
@ -94,7 +94,7 @@ def create_example_data(doc):
) )
text.insertString(cursor, content, False) text.insertString(cursor, content, False)
cursor.gotoStart(False) cursor.gotoStart(False)
except: except Exception:
traceback.print_exc() traceback.print_exc()

View file

@ -54,9 +54,9 @@ def main():
# XComponent.dispose. # XComponent.dispose.
try: try:
doc.close(False) doc.close(False)
except: except Exception:
doc.dispose() doc.dispose()
except: except Exception:
traceback.print_exc() traceback.print_exc()
sys.exit(1) sys.exit(1)

View file

@ -9,7 +9,6 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
# #
import xml.etree.ElementTree as ET
import os import os
from prompt_toolkit import prompt from prompt_toolkit import prompt
import xml.dom.minidom import xml.dom.minidom