def testInterface(self): clazz = uno.getClass("com.sun.star.lang.XComponent") self.failUnless( "com.sun.star.lang.XComponent" == clazz.__pyunointerface__) self.failUnless( issubclass(clazz, uno.getClass("com.sun.star.uno.XInterface"))) self.tobj.Interface = None
def testErrors( self ): wasHere = 0 try: self.tobj.a = 5 self.fail("attribute a shouldn't exist") except AttributeError: wasHere = 1 except IllegalArgumentException: wasHere = 1 self.failUnless( wasHere, "wrong attribute test" ) IllegalArgumentException = uno.getClass("com.sun.star.lang.IllegalArgumentException" ) RuntimeException = uno.getClass("com.sun.star.uno.RuntimeException" ) # TODO: Remove this once it is done # wrong number of arguments bug !? self.failUnlessRaises( IllegalArgumentException, self.tobj.transportAny, 42, 43 ) self.failUnlessRaises( IllegalArgumentException, self.tobj.transportAny ) self.failUnlessRaises( RuntimeException, uno.getClass, "a.b" ) self.failUnlessRaises( RuntimeException, uno.getClass, "com.sun.star.uno.TypeClass" ) self.failUnlessRaises( RuntimeException, uno.Enum, "a" , "b" ) self.failUnlessRaises( RuntimeException, uno.Enum, "com.sun.star.uno.TypeClass" , "b" ) self.failUnlessRaises( RuntimeException, uno.Enum, "com.sun.star.uno.XInterface" , "b" ) tcInterface =uno.Enum( "com.sun.star.uno.TypeClass" , "INTERFACE" ) self.failUnlessRaises( RuntimeException, uno.Type, "a", tcInterface ) self.failUnlessRaises( RuntimeException, uno.Type, "com.sun.star.uno.Exception", tcInterface ) self.failUnlessRaises( (RuntimeException,exceptions.RuntimeError), uno.getTypeByName, "a" ) self.failUnlessRaises( (RuntimeException), uno.getConstantByName, "a" ) self.failUnlessRaises( (RuntimeException), uno.getConstantByName, "com.sun.star.uno.XInterface" )
def testExceptions( self ): unoExc = uno.getClass( "com.sun.star.uno.Exception" ) ioExc = uno.getClass( "com.sun.star.io.IOException" ) dispExc = uno.getClass( "com.sun.star.lang.DisposedException" ) wasHere = 0 try: raise ioExc( "huhuh" , self.tobj ) except unoExc , instance: wasHere = 1 self.failUnless( wasHere , "exceptiont test 1" )
def save(self, path, filetype=None): IOException = uno.getClass('com.sun.star.io.IOException') # UNO requires absolute paths url = uno.systemPathToFileUrl(os.path.abspath(path)) # Filters used when saving document. # https://github.com/LibreOffice/core/tree/330df37c7e2af0564bcd2de1f171bed4befcc074/filter/source/config/fragments/filters filetypes = dict( jpg='calc_jpg_Export', pdf='calc_pdf_Export', png='calc_png_Export', svg='calc_svg_Export', xls='Calc MS Excel 2007 XML', xlsx='Calc MS Excel 2007 XML Template', ) if filetype: filter = uno.createUnoStruct('com.sun.star.beans.PropertyValue') filter.Name = 'FilterName' filter.Value = filetypes[filetype] filters = (filter, ) else: filters = () try: self.document.storeToURL(url, filters) except IOException as e: raise IOError(e.Message)
def __init__(self): libreoffice = LibreOffice() self.desktop = libreoffice.get_desktop() PropertyValue = uno.getClass('com.sun.star.beans.PropertyValue') inProps = PropertyValue("Hidden", 0, True, 0), # https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XComponentLoader.html self.document = self.desktop.loadComponentFromURL( "private:factory/scalc", "_blank", 0, inProps)
def startOffice(host="localhost", port="2002"): NoConnectionException = uno.getClass("com.sun.star.connection.NoConnectException") ooffice = 'soffice --norestore "-accept=socket,host={},port={};urp;"'.format(host, port) if os.fork(): return retcode = subprocess.call(ooffice, shell=True) if retcode != 0: print("OOo returned {}".format(retcode))#, file=sys.stderr)
def testExceptions( self ): unoExc = uno.getClass( "com.sun.star.uno.Exception" ) ioExc = uno.getClass( "com.sun.star.io.IOException" ) dispExc = uno.getClass( "com.sun.star.lang.DisposedException" ) wasHere = 0 try: raise ioExc( "huhuh" , self.tobj ) except unoExc as instance: wasHere = 1 self.failUnless( wasHere , "exceptiont test 1" ) wasHere = 0 try: raise ioExc except ioExc: wasHere = 1 else: self.failUnless( wasHere, "exception test 2" ) wasHere = 0 try: raise dispExc except ioExc: pass except unoExc: wasHere = 1 self.failUnless(wasHere, "exception test 3") illegalArg = uno.getClass( "com.sun.star.lang.IllegalArgumentException" ) wasHere = 0 try: self.tobj.raiseException( 1 , "foo" , self.tobj ) self.failUnless( 0 , "exception test 5a" ) except ioExc: self.failUnless( 0 , "exception test 5b" ) except illegalArg as i: self.failUnless( 1 == i.ArgumentPosition , "exception member test" ) self.failUnless( "foo" == i.Message , "exception member test 2 " ) wasHere = 1 else: self.failUnless( 0, "except test 5c" ) self.failUnless( wasHere, "illegal argument exception test failed" )
def getmembers_uno( object, predicate=lambda obj: not isinstance(obj, uno.ByteSequence)): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if isclass(object): mro = (object, ) + getmro(object) else: mro = () results = [] processed = set() names = dir(object) # :dd any DynamicClassAttributes to the list of names if object is a class; # this may result in duplicate entries if, for example, a virtual # attribute with the same name as a DynamicClassAttribute exists try: for base in object.__bases__: for k, v in base.__dict__.items(): if isinstance(v, types.DynamicClassAttribute): names.append(k) except AttributeError: pass for key in names: # First try to get the value via getattr. Some descriptors don't # like calling their __get__ (see bug #1785), so fall back to # looking in the __dict__. try: value = getattr(object, key) # handle the duplicate key if key in processed: raise AttributeError except AttributeError: for base in mro: if key in base.__dict__: value = base.__dict__[key] break else: # could be a (currently) missing slot member, or a buggy # __dir__; discard and move on continue except uno.getClass("com.sun.star.uno.RuntimeException"): continue # ignore: inspect.RuntimeException: Getting from this property is not supported except Exception: continue # ignore: everything, we don't care if not predicate or predicate(value): results.append((key, value)) processed.add(key) results.sort(key=lambda pair: pair[0]) return results
import time import atexit import socket import uno import argparse print("Executing LibreOffice python script using LibreOffice python") OPENOFFICE_PORT = 8100 # 2002 if 'Linux' in platform.system(): OPENOFFICE_BIN = "soffice" else: OPENOFFICE_PATH = os.environ["LIBREOFFICE_PROGRAM"] OPENOFFICE_BIN = os.path.join(OPENOFFICE_PATH, 'soffice') NoConnectException = uno.getClass("com.sun.star.connection.NoConnectException") PropertyValue = uno.getClass("com.sun.star.beans.PropertyValue") # Adapted from: https://www.linuxjournal.com/content/starting-stopping-and-connecting-openoffice-python class OORunner: """ Start, stop, and connect to OpenOffice. """ def __init__(self, port=OPENOFFICE_PORT): """ Create OORunner that connects on the specified port. """ self.port = port def connect(self, no_startup=False): """ Connect to OpenOffice.
""" A simple API to cite references in OpenOffice.org Based on code from Bibus <http://bibus-biblio.sourceforge.net/>. """ import uno from gettext import gettext as _ from Pyblio.Cite.WP import CommunicationError, OperationError from Pyblio.Store import Key DIRECT_VALUE = uno.getConstantByName("com.sun.star.beans.PropertyState.DIRECT_VALUE") PARAGRAPH_BREAK = uno.getConstantByName("com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK") PropertyValue = uno.getClass("com.sun.star.beans.PropertyValue") NoSuchElementException = uno.getClass("com.sun.star.container.NoSuchElementException") NoConnectException = uno.getClass("com.sun.star.connection.NoConnectException") ITALIC = (uno.getConstantByName("com.sun.star.awt.FontSlant.ITALIC"), uno.getConstantByName("com.sun.star.awt.FontSlant.NONE")) OO_BIBLIOGRAPHIC_FIELDS = {} for f in ('Custom1', 'Custom2', 'Identifier'): OO_BIBLIOGRAPHIC_FIELDS[f] = \ uno.getConstantByName("com.sun.star.text.BibliographyDataField." + f.upper()) from Pyblio.Format.OpenOffice import Generator, ITALIC import re
def testInterface(self): clazz = uno.getClass( "com.sun.star.lang.XComponent" ) self.failUnless( "com.sun.star.lang.XComponent" == clazz.__pyunointerface__ ) self.failUnless( issubclass( clazz, uno.getClass( "com.sun.star.uno.XInterface" ) ) ) self.tobj.Interface = None
import time import atexit import logging try: import uno import unohelper except ImportError: print >> sys.stderr, 'Unable to find pyUno -- aborting!', # Note on com.sun.star.* imports -- using the uno.getClass() and # uno.getContantByName() methods is necessary for compatibility with # cx_freeze -- not too sure if I care about this or not... # Exceptions UnoException = uno.getClass('com.sun.star.uno.Exception') NoConnectException = uno.getClass('com.sun.star.connection.NoConnectException') RuntimeException = uno.getClass('com.sun.star.uno.RuntimeException') IllegalArgumentException = uno.getClass( 'com.sun.star.lang.IllegalArgumentException') DisposedException = uno.getClass('com.sun.star.lang.DisposedException') IOException = uno.getClass('com.sun.star.io.IOException') NoSuchElementException = uno.getClass( 'com.sun.star.container.NoSuchElementException') # Control Characters PARAGRAPH_BREAK = uno.getConstantByName( 'com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK') LINE_BREAK = uno.getConstantByName( 'com.sun.star.text.ControlCharacter.LINE_BREAK') HARD_HYPHEN = uno.getConstantByName(
try: sys.path.append(path) import uno os.environ["PATH"] = "%s:" % path + os.environ["PATH"] break except ImportError: sys.path.remove(path) continue else: print >>sys.stderr, "PyODConverter: Cannot find the pyuno.so library in sys.path and known paths." sys.exit(1) from com.sun.star.beans import PropertyValue NoConnectException = uno.getClass("com.sun.star.connection.NoConnectException") IllegalArgumentException = uno.getClass("com.sun.star.lang.IllegalArgumentException") RuntimeException = uno.getClass("com.sun.star.uno.RuntimeException") IOException = uno.getClass("com.sun.star.io.IOException") url_original = uno.systemPathToFileUrl(sys.argv[1]) url_save = uno.systemPathToFileUrl(sys.argv[2]) try: ### Get Service Manager context = uno.getComponentContext() resolver = context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", context) ctx = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager ### Load document
class TestCase( unittest.TestCase): def __init__(self,method,ctx): unittest.TestCase.__init__(self,method) self.ctx = ctx def setUp(self): # the testcomponent from the testtools project self.tobj = self.ctx.ServiceManager.createInstanceWithContext( 'com.sun.star.test.bridge.CppTestObject' , self.ctx ) self.tobj.Bool = 1 self.tobj.Char = 'h' self.tobj.Byte = 43 self.tobj.Short = -42 self.tobj.UShort = 44 self.tobj.Long = 42 self.tobj.ULong = 41 self.tobj.Hyper = 46 self.tobj.UHyper = 47 self.tobj.Float = 4.3 self.tobj.Double = 4.2 self.tobj.Enum = 4 self.tobj.String = "yabadabadoo" self.tobj.Interface = self.ctx self.tobj.Any = self.tobj.String mystruct = uno.createUnoStruct( "test.testtools.bridgetest.TestData" ) assign( mystruct, 1, 'h', 43, -42,44,42,41,46,47,4.3,4.2,4,"yabadabadoo",self.ctx,"yabadabadoo") self.tobj.Struct = mystruct self.testElement = uno.createUnoStruct( "test.testtools.bridgetest.TestElement" ) self.testElement.String = "foo" self.testElement2 = uno.createUnoStruct( "test.testtools.bridgetest.TestElement" ) self.testElement2.String = "42" self.tobj.Sequence = (self.testElement,self.testElement2) def testBaseTypes(self): self.failUnless( 42 == self.tobj.Long , "Long attribute" ) self.failUnless( 41 == self.tobj.ULong , "ULong attribute" ) self.failUnless( 43 == self.tobj.Byte , "Byte attribute" ) self.failUnless( 44 == self.tobj.UShort , "UShort attribute" ) self.failUnless( -42 == self.tobj.Short , "Short attribute" ) self.failUnless( 46 == self.tobj.Hyper , "Hyper attribute" ) self.failUnless( 47 == self.tobj.UHyper , "UHyper attribute" ) self.failUnless( self.tobj.Bool , "Bool attribute2" ) self.failUnless( "yabadabadoo" == self.tobj.String , "String attribute" ) self.failUnless( self.tobj.Sequence[0] == self.testElement , "Sequence test") self.failUnless( self.tobj.Sequence[1] == self.testElement2 , "Sequence2 test") self.failUnless( equalsEps( 4.3,self.tobj.Float,0.0001) , "float test" ) self.failUnless( 4.2 == self.tobj.Double , "double test" ) self.failUnless( self.ctx == self.tobj.Interface , "object identity test with C++ object" ) self.failUnless( not self.ctx == self.tobj , "object not identical test " ) self.failUnless( 42 == self.tobj.transportAny( 42 ), "transportAny long" ) self.failUnless( "woo, this is python" == self.tobj.transportAny( "woo, this is python" ), \ "string roundtrip via any test" ) def testEnum( self ): e1 = uno.Enum( "com.sun.star.uno.TypeClass" , "LONG" ) e2 = uno.Enum( "com.sun.star.uno.TypeClass" , "LONG" ) e3 = uno.Enum( "com.sun.star.uno.TypeClass" , "UNSIGNED_LONG" ) e4 = uno.Enum( "test.testtools.bridgetest.TestEnum" , "TWO" ) self.failUnless( e1 == e2 , "equal enum test" ) self.failUnless( not (e1 == e3) , "different enums test" ) self.failUnless( self.tobj.transportAny( e3 ) == e3, "enum roundtrip test" ) self.tobj.Enum = e4 self.failUnless( e4 == self.tobj.Enum , "enum assignment failed" ) def testType(self ): t1 = uno.getTypeByName( "com.sun.star.lang.XComponent" ) t2 = uno.getTypeByName( "com.sun.star.lang.XComponent" ) t3 = uno.getTypeByName( "com.sun.star.lang.EventObject" ) self.failUnless( t1.typeClass == \ uno.Enum( "com.sun.star.uno.TypeClass", "INTERFACE" ), "typeclass of type test" ) self.failUnless( t3.typeClass == \ uno.Enum( "com.sun.star.uno.TypeClass", "STRUCT" ), "typeclass of type test") self.failUnless( t1 == t2 , "equal type test" ) self.failUnless( t1 == t2 , "equal type test" ) self.failUnless( t1 == self.tobj.transportAny( t1 ), "type rountrip test" ) def testBool( self ): self.failUnless( uno.Bool(1) , "uno.Bool true test" ) self.failUnless( not uno.Bool(0) , "uno.Bool false test" ) self.failUnless( uno.Bool( "true") , "uno.Bool true1 test" ) self.failUnless( not uno.Bool( "false") , "uno.Bool true1 test" ) self.tobj.Bool = uno.Bool(1) self.failUnless( self.tobj.Bool , "bool true attribute test" ) self.tobj.Bool = uno.Bool(0) self.failUnless( not self.tobj.Bool , "bool true attribute test" ) # new boolean semantic self.failUnless( id( self.tobj.transportAny( True ) ) == id(True) , "boolean preserve test") self.failUnless( id( self.tobj.transportAny( False ) ) == id(False) , "boolean preserve test" ) self.failUnless( id( self.tobj.transportAny(1) ) != id( True ), "boolean preserve test" ) self.failUnless( id( self.tobj.transportAny(0) ) != id( False ), "boolean preserve test" ) def testChar( self ): self.tobj.Char = uno.Char( u'h' ) self.failUnless( self.tobj.Char == uno.Char( u'h' ), "char type test" ) self.failUnless( isinstance( self.tobj.transportAny( uno.Char(u'h') ),uno.Char),"char preserve test" ) def testStruct( self ): mystruct = uno.createUnoStruct( "test.testtools.bridgetest.TestData" ) assign( mystruct, 1, 'h', 43, -42,44,42,41,46,47,4.3,4.2,4,"yabadabadoo",self.ctx,"yabadabadoo") self.tobj.Struct = mystruct aSecondStruct = self.tobj.Struct self.failUnless( self.tobj.Struct == mystruct, "struct roundtrip for equality test" ) self.failUnless( aSecondStruct == mystruct, "struct roundtrip for equality test2" ) aSecondStruct.Short = 720 self.failUnless( not aSecondStruct == mystruct , "different structs equality test" ) self.failUnless( not self.ctx == mystruct , "object is not equal to struct test" ) self.failUnless( mystruct == self.tobj.transportAny( mystruct ), "struct roundtrip with any test" ) my2ndstruct = uno.createUnoStruct( "test.testtools.bridgetest.TestData", \ 1, 'h', 43, -42,44,42,41,46,47,4.3,4.2,4,"yabadabadoo",self.ctx,"yabadabadoo",()) self.failUnless( my2ndstruct == mystruct, "struct non-default ctor test" ) def testUnicode( self ): uni = u'\0148' self.tobj.String = uni self.failUnless( uni == self.tobj.String ) self.tobj.String = u'dubidu' self.failUnless( u'dubidu' == self.tobj.String , "unicode comparison test") self.failUnless( 'dubidu' == self.tobj.String , "unicode vs. string comparison test" ) def testConstant( self ): self.failUnless( uno.getConstantByName( "com.sun.star.beans.PropertyConcept.ATTRIBUTES" ) == 4,\ "constant retrieval test" ) def testExceptions( self ): unoExc = uno.getClass( "com.sun.star.uno.Exception" ) ioExc = uno.getClass( "com.sun.star.io.IOException" ) dispExc = uno.getClass( "com.sun.star.lang.DisposedException" ) wasHere = 0 try: raise ioExc( "huhuh" , self.tobj ) except unoExc , instance: wasHere = 1 self.failUnless( wasHere , "exceptiont test 1" ) wasHere = 0 try: raise ioExc except ioExc: wasHere = 1 else: self.failUnless( wasHere, "exception test 2" ) wasHere = 0 try: raise dispExc except ioExc: pass except unoExc: wasHere = 1 self.failUnless(wasHere, "exception test 3") illegalArg = uno.getClass( "com.sun.star.lang.IllegalArgumentException" ) wasHere = 0 try: self.tobj.raiseException( 1 , "foo" , self.tobj ) self.failUnless( 0 , "exception test 5a" ) except ioExc: self.failUnless( 0 , "exception test 5b" ) except illegalArg, i: self.failUnless( 1 == i.ArgumentPosition , "exception member test" ) self.failUnless( "foo" == i.Message , "exception member test 2 " ) wasHere = 1
import sys import time import subprocess from .config import config # uno.py directory (package) path sys.path.append(config['libreoffice']['python_uno_location']) # ***** UNO ***** import uno NoConnectException = uno.getClass('com.sun.star.connection.NoConnectException') # from com.sun.star.connection import NoConnectException now = time.time class LOprocess: def __init__(self, connection=config['libreoffice']['connection']): # command flags array self.flags = config['libreoffice']['flags'] # libreoffice binary location self.libreoffice_bin = connection['binary_location'] # # UNO socket connection settings self.host = connection['host'] self.port = connection['port'] # will become content of '--accept=' flag, like f"--accept='{accept_open}'" # something like "socket,host=%s,port=%s,tcpNoDelay=1;urp;StarOffice.ComponentContext" self.accept_open = connection['accept_open'] # this is used when connetion to running libreoffice process # something like "uno:socket,host=%s,port=%s,tcpNoDalay=1;urp;StarOffice.ComponentContext" self.connection_url = connection['connection_url']
from django.http import HttpResponse from django.conf import settings from oogalo import Writer from com.sun.star.uno import Exception as UnoException import uno import tempfile import os import subprocess import signal import time import unicodedata TEMPFILE_PREFIX='oogalo' TEMPDIR='/opt/tmp' NoConnectionException = uno.getClass("com.sun.star.connection.NoConnectException") class DjangoWriter (Writer): def __init__ (self): self.OOpid = None while True: try: Writer.__init__(self) break except UnoException, e: if (e.Message == 'OpenOffice processs not found') and (settings.DEBUG): self.start_OOo() else: raise e def HttpResponseFILE (self, filetype = 'odt', filename = None):
and a text document. I guess that should be I guess we want to import this conditionally - if uno is not there, then the user may not care about libreoffice at all. Well, I guess this kind of stuff can ultimately go into a config file. Is it a good idea to throw this into one pot with the LaTeX editors? Fewer shortcuts, but the process IS kind of involved. I will give it a miss then. ''' import os, sys, uno # , pprint from hub import hub, RefdbError, IntegrityError from config import config NoConnectException = uno.getClass("com.sun.star.connection.NoConnectException") RuntimeException = uno.getClass("com.sun.star.uno.RuntimeException") IllegalArgumentException = uno.getClass( "com.sun.star.lang.IllegalArgumentException") DisposedException = uno.getClass("com.sun.star.lang.DisposedException") IOException = uno.getClass("com.sun.star.io.IOException") NoSuchElementException = uno.getClass( "com.sun.star.container.NoSuchElementException") PropertyValue = uno.getClass("com.sun.star.beans.PropertyValue") DIRECT_VALUE = uno.Enum("com.sun.star.beans.PropertyState", "DIRECT_VALUE") class ConnectionError(Exception): pass
def test_getClass(self): from com.sun.star.uno import Exception as UNOException ex = uno.getClass("com.sun.star.uno.Exception") self.assertEqual(ex, UNOException)
import atexit import logging try: import uno import unohelper except ImportError: print >> sys.stderr, 'Unable to find pyUno -- aborting!', # Note on com.sun.star.* imports -- using the uno.getClass() and # uno.getContantByName() methods is necessary for compatibility with # cx_freeze -- not too sure if I care about this or not... # Exceptions UnoException = uno.getClass('com.sun.star.uno.Exception') NoConnectException = uno.getClass('com.sun.star.connection.NoConnectException') RuntimeException = uno.getClass('com.sun.star.uno.RuntimeException') IllegalArgumentException = uno.getClass( 'com.sun.star.lang.IllegalArgumentException') DisposedException = uno.getClass('com.sun.star.lang.DisposedException') IOException = uno.getClass('com.sun.star.io.IOException') NoSuchElementException = uno.getClass( 'com.sun.star.container.NoSuchElementException') # Control Characters PARAGRAPH_BREAK = uno.getConstantByName( 'com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK') LINE_BREAK = uno.getConstantByName( 'com.sun.star.text.ControlCharacter.LINE_BREAK')
for path in extrapaths: try: sys.path.append(path) import uno os.environ['PATH'] = '%s:' % path + os.environ['PATH'] break except ImportError: sys.path.remove(path) continue else: print >> sys.stderr, "PyODConverter: Cannot find the pyuno.so library in sys.path and known paths." sys.exit(1) from com.sun.star.beans import PropertyValue NoConnectException = uno.getClass("com.sun.star.connection.NoConnectException") IllegalArgumentException = uno.getClass( "com.sun.star.lang.IllegalArgumentException") RuntimeException = uno.getClass("com.sun.star.uno.RuntimeException") IOException = uno.getClass("com.sun.star.io.IOException") url_original = uno.systemPathToFileUrl(sys.argv[1]) url_save = uno.systemPathToFileUrl(sys.argv[2]) try: ### Get Service Manager context = uno.getComponentContext() resolver = context.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", context) ctx = resolver.resolve( "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext")