Hossein b9a36edc6d Add a minimal Python extension
This is a minimal Python extension. It is possible to run main.py from:

1. Inside a LibreOffice extension
2. Inside LibreOffice, and also via APSO
3. Outside LibreOffice, as an external process, and also in a Python IDE

The provided Python script is very useful for debugging extensions as an
example. That is because it is possible to debug it in an IDE before
packaging it as a LibreOffice extension.

Python file is checked with:

$ flake8 --ignore E501 main.py

Change-Id: I24d9aefdfda29264bf6b5f9403a40fae35e610f6
Reviewed-on: https://gerrit.libreoffice.org/c/core/+/159938
Tested-by: Jenkins
Reviewed-by: Hossein <hossein@libreoffice.org>
2024-01-16 10:54:20 +01:00

69 lines
2.2 KiB
Python

# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
import sys
import unohelper
import officehelper
from com.sun.star.task import XJobExecutor
# The MainJob is a UNO component derived from unohelper.Base class
# and also the XJobExecutor, the implemented interface
class MainJob(unohelper.Base, XJobExecutor):
def __init__(self, ctx):
self.ctx = ctx
# handling different situations (inside LibreOffice or other process)
try:
self.sm = ctx.getServiceManager()
self.desktop = XSCRIPTCONTEXT.getDesktop()
except NameError:
self.sm = ctx.ServiceManager
self.desktop = self.ctx.getServiceManager().createInstanceWithContext(
"com.sun.star.frame.Desktop", self.ctx)
def trigger(self, args):
desktop = self.ctx.ServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", self.ctx)
model = desktop.getCurrentComponent()
if not hasattr(model, "Text"):
model = self.desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, ())
text = model.Text
cursor = text.createTextCursor()
text.insertString(cursor, "Hello Extension argument -> " + args + "\n", 0)
# Starting from Python IDE
def main():
try:
ctx = XSCRIPTCONTEXT
except NameError:
ctx = officehelper.bootstrap()
if ctx is None:
print("ERROR: Could not bootstrap default Office.")
sys.exit(1)
job = MainJob(ctx)
job.trigger("hello")
# Starting from command line
if __name__ == "__main__":
main()
# pythonloader loads a static g_ImplementationHelper variable
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
MainJob, # UNO object class
"org.extension.sample.do", # implementation name (customize for yourself)
("com.sun.star.task.Job",), ) # implemented services (only 1)
# vim: set shiftwidth=4 softtabstop=4 expandtab: