Beispiel #1
0
def xray(myObject):
    try:
        sm = uno.getComponentContext().ServiceManager
        mspf = sm.createInstanceWithContext("com.sun.star.script.provider.MasterScriptProviderFactory", uno.getComponentContext())
        scriptPro = mspf.createScriptProvider("")
        xScript = scriptPro.getScript("vnd.sun.star.script:XrayTool._Main.Xray?language=Basic&location=application")
        xScript.invoke((myObject,), (), ())
        return
    except:
        raise _rtex("Basic library Xray is not installed", uno.getComponentContext())
Beispiel #2
0
    def __connectOpenOfficeService(self, host, puerto):
        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", uno.getComponentContext())
        
        #self.dispatchHelper = localContext.ServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", uno.getComponentContext())

        smgr = resolver.resolve("uno:socket,host=" + host + ",port=" + puerto + ";urp;StarOffice.ServiceManager")
        remoteContext = smgr.getPropertyValue("DefaultContext")
        return smgr.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext)
Beispiel #3
0
def connect(args = [], path = '', wait = 0):
    """Deze functie maakt het mogelijk om openoffice vanaf de python-interpeter te starten en te bedienen.
    
    path is het pad naar OpenOffice en args een list van command-line argumenten.
    wait is het aantal seconden dat deze functie wacht met retourneren wanneer hij klaar is. Dit is handig wanneer je
    bestanden aan het laden bent, wat de OOConext is pas bruikbaar wanneer dat bestand geladen is.
    """
    if not path:
        path = getoopath()

    exe = os.path.join(path, 'scalc')
    if sys.platform.startswith('win'):
        exe += '.exe'

    command = [exe, '-accept=pipe,name=unopipe;urp;']
    command.extend(args)
    os.spawnv(os.P_NOWAIT, exe, command)

    xlc = uno.getComponentContext()
    resolver = xlc.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', xlc)

    con = 'uno:pipe,name=unopipe;urp;StarOffice.ComponentContext'
    for i in range(20):
        try:
            print 'Poging %i' % i
            ctx = resolver.resolve(con)
            OOContext(ctx)
            if wait:
                print 'Even wachten...'
                sleep(wait)
            print 'Gelukt'
            return
        except:
            sleep(0.5)
    print 'Mislukt'
Beispiel #4
0
    def documentEventOccured(self,ev):

        ctx = uno.getComponentContext()
        smgr = ctx.ServiceManager
        toolkit = smgr.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)    
        desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
        
        if ev.EventName == 'OnLayoutFinished':
            self.eventb.removeDocumentEventListener(self.listener)

            try:
                # um den Listener nur einmal anzusprechen
                if g.geladen == 'neu':
                    g.geladen = 'alt'    
                if desktop.Name == '':
                    desktop.Name = 'gestartet'
                    
                    from threading import Thread

                    def sleeper(desktop1):   
                        import time
                        #time.sleep(2)  
                        URL="private:factory/swriter"
                        desktop1.ActiveFrame.loadComponentFromURL(URL,'_top','',())  

                    t = Thread(target=sleeper,args=(desktop,))
                    t.start()
                    
            except Exception as e:
                log(inspect.stack,tb())
Beispiel #5
0
        def __init__(self, filename):
            """Create a reader"""
            local = uno.getComponentContext()
            resolver = local.ServiceManager.createInstanceWithContext(
                                "com.sun.star.bridge.UnoUrlResolver", local)

            try:
                context = resolver.resolve(
                    "uno:socket,host=localhost,port=2002;"
                    "urp;StarOffice.ComponentContext")
            except NoConnectException:
                raise Exception(CONNECT_MSG)

            desktop = context.ServiceManager.createInstanceWithContext(
                                        "com.sun.star.frame.Desktop", context)

            cwd = systemPathToFileUrl(os.getcwd())
            file_url = absolutize(cwd, systemPathToFileUrl(
                    os.path.join(os.getcwd(), filename)))
            in_props = PropertyValue("Hidden", 0, True, 0),
            document = desktop.loadComponentFromURL(
                file_url, "_blank", 0, in_props)
            self.rules = document.Sheets.getByName(u'rules')
            try:
                self.invalid = document.Sheets.getByName(u'invalid')
            except NoSuchElementException:
                self.invalid = None
Beispiel #6
0
 def suche(self):  
     # Fuer eine Fehlersuche, die bei jedem Methodenaufruf gestartet wird
     
     try:
         ctx = uno.getComponentContext()  
         smgr = ctx.ServiceManager
         desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
         doc = desktop.getCurrentComponent()
         
         secs = doc.TextSections
         el_names = secs.ElementNames
         
         for n in el_names:
             if 'Bereich' in n:
                 pd()
         
     except Exception as e:
         print(tb())
         #pd()
         return e
     
     return None
     
     
          
 def get_uno_desktop(self):
     """
     On non-Windows platforms, use Uno. Get the OpenOffice desktop
     which will be used to manage impress
     """
     log.debug(u'get UNO Desktop Openoffice')
     uno_instance = None
     loop = 0
     log.debug(u'get UNO Desktop Openoffice - getComponentContext')
     context = uno.getComponentContext()
     log.debug(u'get UNO Desktop Openoffice - createInstaneWithContext - UnoUrlResolver')
     resolver = context.ServiceManager.createInstanceWithContext(u'com.sun.star.bridge.UnoUrlResolver', context)
     while uno_instance is None and loop < 3:
         try:
             uno_instance = get_uno_instance(resolver)
         except:
             log.warn(u'Unable to find running instance ')
             self.start_process()
             loop += 1
     try:
         self.manager = uno_instance.ServiceManager
         log.debug(u'get UNO Desktop Openoffice - createInstanceWithContext'
             u' - Desktop')
         desktop = self.manager.createInstanceWithContext("com.sun.star.frame.Desktop", uno_instance)
         return desktop
     except:
         log.warn(u'Failed to get UNO desktop')
         return None
Beispiel #8
0
def OdtConverter(conf,inputs,outputs):
	# get the uno component context from the PyUNO runtime  
	localContext = uno.getComponentContext()

	# create the UnoUrlResolver 
	# on a single line
	resolver = 	localContext.ServiceManager.createInstanceWithContext	("com.sun.star.bridge.UnoUrlResolver", localContext )

	# connect to the running office                                 
	ctx = resolver.resolve( conf["oo"]["server"].replace("::","=")+";urp;StarOffice.ComponentContext" )
	smgr = ctx.ServiceManager

	# get the central desktop object
	desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

	# get the file name
	adressDoc=systemPathToFileUrl(conf["main"]["dataPath"]+"/"+inputs["InputDoc"]["value"])

	propFich=PropertyValue("Hidden", 0, True, 0),

	myDocument=0
	try:
	    myDocument = desktop.loadComponentFromURL(adressDoc,"_blank",0,propFich)
	except CannotConvertException, e:
	    print >> sys.stderr,  'Impossible de convertir le fichier pour les raisons suivantes : \n'
	    print >> sys.stderr,  e
	    sys.exit(0)
    def create_document(self):
        localContext = uno.getComponentContext()
        				   
        resolver = localContext.ServiceManager.createInstanceWithContext(
        				"com.sun.star.bridge.UnoUrlResolver", localContext )
        
        self.smgr = resolver.resolve( "uno:socket,host=localhost,port=2003;urp;StarOffice.ServiceManager" )
        remoteContext = self.smgr.getPropertyValue( "DefaultContext" )

        desktop = self.smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)
        
        # open a writer document
        self.doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
        
        # shortcuts
        self.text = self.doc.Text
        self.cursor = self.text.createTextCursor()

        doc_id = uuid.uuid1().hex
        self.docs[doc_id] = {
            'text':   self.text,
            'cursor': self.cursor,
            'doc':    self.doc
        }

        return doc_id
Beispiel #10
0
def getServiceManager(host, port, uno_path, office_binary_path):
  """Get the ServiceManager from the running OpenOffice.org.
  """
  # Add in sys.path the path of pyuno
  if uno_path not in sys.path:
    sys.path.append(uno_path)
  fundamentalrc_file = '%s/fundamentalrc' % office_binary_path
  if os.path.exists(fundamentalrc_file) and \
      'URE_BOOTSTRAP' not in os.environ:
    os.putenv('URE_BOOTSTRAP', 'vnd.sun.star.pathname:%s' % fundamentalrc_file)
  import uno
  # Get the uno component context from the PyUNO runtime
  uno_context = uno.getComponentContext()
  # Create the UnoUrlResolver on the Python side.
  url_resolver = "com.sun.star.bridge.UnoUrlResolver"
  resolver = uno_context.ServiceManager.createInstanceWithContext(url_resolver,
                                                                  uno_context)
  # Connect to the running OpenOffice.org and get its
  # context.
  # Retry 10 times if needed.
  for i in range(10):
    try:
      uno_connection = resolver.resolve("uno:socket,host=%s,port=%s;urp;StarOffice.ComponentContext" % (host, port))
      break
    except:
      # I don't know how to import com.sun.star.connection.NoConnectException
      time.sleep(1)
  # Get the ServiceManager object
  return uno_connection.ServiceManager
Beispiel #11
0
def FolderPathBox(title='Get directory path'):
    ctx = uno.getComponentContext()
    smgr = ctx.getServiceManager()
    folder_picker = smgr.createInstanceWithContext("com.sun.star.ui.dialogs.FolderPicker", ctx)
    folder_picker.setTitle(title)
    folder_picker.execute()
    return folder_picker.getDirectory()
Beispiel #12
0
def unoConnect(host, port):
    ctx = uno.getComponentContext()
    srv_manager = ctx.getServiceManager() 
    resolver = ctx.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", ctx)
    context = resolver.resolve("uno:socket,host="+ str(host) +",port="+ str(port) +";urp;StarOffice.ComponentContext")
    desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
    return desktop
Beispiel #13
0
 def setUp(self):
        
 
     Cmd = "libreoffice"
     Cmd = '%s --headless --norestore "--accept=socket,host=localhost,port=2002;urp;"'%(Cmd)
        
     print "issuing: %s"%Cmd
     # os.system( Cmd ) wont work, since it wait for the process to end...
     os.popen(Cmd)
     time.sleep(0.5)
     
     # get the uno component context from the PyUNO runtime
     self.localContext = uno.getComponentContext()
     
     # create the UnoUrlResolver
     self.resolver = self.localContext.ServiceManager.createInstanceWithContext(
                     "com.sun.star.bridge.UnoUrlResolver", self.localContext )
     
     # connect to the running office
     self.ctx = self.resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
     self.smgr = self.ctx.ServiceManager
     
     # get the central desktop object
     self.desktop = self.smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",self.ctx)
     
     # access the current calc document
     self.model = self.desktop.getCurrentComponent()
     pass
def main():
    args = parse_args()

    connect_string = 'socket,host=localhost,port=2002;urp'

    # Start OpenOffice.org, listen for connections and open testing document
    os.system(
        "/usr/bin/libreoffice '--accept={};' --calc ./costing_test_doc.ods &"
        .format(connect_string))

    # Get local context info
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", localContext)

    ctx = None

    # Wait until the OO.o starts and connection is established
    while ctx is None:
        try:
            ctx = resolver.resolve(
                "uno:{};StarOffice.ComponentContext".format(connect_string))
        except:
            pass

    # Execute our job
    if args.command == 'import_pricing':
        blah = ImportEC2Pricing(ctx)
        blah.execute(())
    elif args.command == 'import_instance_data':
        blah2 = ImportEC2InstanceData(ctx)
        blah2.execute(())
Beispiel #15
0
def startOOAndConnect():
    """
    Start OO in child process and connect to them.
    Return OO component context object.
    """
    pid = os.fork()
    if not pid:
      pid = os.getpid()
      os.setpgid(pid,pid)
      os.system("soffice -headless -norestore '-accept=socket,host=localhost,port=%s;urp;' &" % OOCONV_PORT)
      while 1:
          time.sleep(1)
    else:
        limit = time.time() + OOCONV_MAX_STARTUP_TIME
        ctx = None
        context = uno.getComponentContext()
        resolver=context.ServiceManager.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", context)

        while time.time() < limit:
            try:
                ctx = resolver.resolve(
                    "uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % OOCONV_PORT)
                break
            except:
                pass
            time.sleep(5)
        if ctx is None:
            pgid = os.getpgid(pid)
            os.killpg(pgid, signal.SIGTERM)                        
            return None, None
        return ctx, pid
   def __init__(self, headless = False):
      if "UNO_PATH" in os.environ:
         office = os.environ["UNO_PATH"]
      else:
         if platform.startswith("win"):
            # XXX
            office = ""
         else:
            # Lets hope that works..
            office = '/usr/bin'
      office = os.path.join(office, "soffice")
      if platform.startswith("win"):
          office += ".exe"

      self._pidfile = "/tmp/markup_renderer_OOinstance" #XXX Windows compat needed
      xLocalContext = uno.getComponentContext()
      self._resolver = xLocalContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", xLocalContext)
      self._socket = "name=markupRendererPipe"

      args = ["--invisible", "--nologo", "--nodefault", "--norestore", "--nofirststartwizard"]
      if headless:
         args.append("--headless")

      if platform.startswith("win"):
         cmdArray = ['"' + office + '"']
      else:
         cmdArray = [office]
      cmdArray += args + ["--accept=pipe,%s;urp" % self._socket]
      if( not os.path.isfile(self._pidfile)):
         self.pid = os.spawnv(os.P_NOWAIT, office, cmdArray)
         f = open(self._pidfile,"w")
         f.write(str(self.pid))
Beispiel #17
0
 def start_ooo(self):
     """
     Start OpenOffice.org process
     TODO: The presentation/Impress plugin may already have it running
     """
     if is_win():
         self.start_ooo_process()
         self.desktop = self.ooo_manager.createInstance('com.sun.star.frame.Desktop')
     else:
         context = uno.getComponentContext()
         resolver = context.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', context)
         uno_instance = None
         loop = 0
         while uno_instance is None and loop < 5:
             try:
                 uno_instance = get_uno_instance(resolver)
             except NoConnectException:
                 time.sleep(0.1)
                 log.exception("Failed to resolve uno connection")
                 self.start_ooo_process()
                 loop += 1
             else:
                 manager = uno_instance.ServiceManager
                 self.desktop = manager.createInstanceWithContext("com.sun.star.frame.Desktop", uno_instance)
                 return
         raise Exception('Unable to start LibreOffice')
Beispiel #18
0
def main():
  try:
    # Log
    f = open('/var/log/mediboard/doctopdf', 'a');
    f.write('---' + time.strftime('%d/%m/%y %H:%M',time.localtime()) + '---\n')
    f.write('Convert '+ sys.argv[1] + ' to ' + sys.argv[2] + '\n');
    
    local = uno.getComponentContext()
    resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
    context = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext")
    desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
    
    document = desktop.loadComponentFromURL("file://"+sys.argv[1], "_blank", 0, ())
    
    from com.sun.star.beans import PropertyValue
    property = (
      PropertyValue("FilterName", 0, "writer_pdf_Export", 0),
    )
    
    document.storeToURL("file://"+sys.argv[2], property)
    
    document.close(True)
    print '1'
    
    # Fin de log
    f.write('Successfully converted \n')
    f.close()
  except Exception as inst:
    f.write(traceback.format_exc() + '\n')
    f.close()
    print '0'
Beispiel #19
0
	def __init__(self, host, port):
		localContext = uno.getComponentContext()
		localServiceManager = localContext.ServiceManager
		resolver = localServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
		self.context = resolver.resolve("uno:socket,host=" + host + ",port=" + str(port) + ";urp;StarOffice.ComponentContext")
		self.svcManager = self.context.ServiceManager
		self.inputProps = (PropertyValue("Hidden", 0, True, 0),)
Beispiel #20
0
def ooo_connect():
    """
    Connection to open office server.
    Fill a dictionnary and return it
    """
    # get the uno component context from the PyUNO runtime
    localContext = uno.getComponentContext()

    # create the UnoUrlResolver
    resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )

    # connect to the running office
    try:
        ctx = resolver.resolve("uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext"%(options.port))
    except:
        raise Exception("Can't connect to openoffice.org server")

    smgr = ctx.ServiceManager

    # get the central desktop object
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)
    d = dict()
    d['ctx'] = ctx
    d['smgr'] = smgr
    d['doc'] = None
    d['desktop'] = desktop
    return d
    def __init__(self, host='localhost', port=DEFAULT_OPENOFFICE_PORT, ooo_restart_cmd=None):
        self._host = host
        self._port = port
        self.logger = logging.getLogger('main')
        self._ooo_restart_cmd = ooo_restart_cmd
        self.localContext = uno.getComponentContext()
        self.serviceManager = self.localContext.ServiceManager
        resolvervector = "com.sun.star.bridge.UnoUrlResolver"
        self._resolver = self.serviceManager.createInstanceWithContext(resolvervector, self.localContext)
        try:
            self.connectOffice()
        except IllegalArgumentException as exception:
            raise DocumentConversionException("The url is invalid (%s)" % exception)
        except NoConnectException as exception:
            if self._restart_ooo():
                # We try again once
                try:
                    self.connectOffice()
                except NoConnectException as exception:
                    raise DocumentConversionException(
                        "Failed to connect to OpenOffice.org on host %s, port %s. %s" % (host, port, exception))
            else:
                raise DocumentConversionException(
                    "Failed to connect to OpenOffice.org on host %s, port %s. %s" % (host, port, exception))

        except ConnectionSetupException as exception:
            raise DocumentConversionException("Not possible to accept on a local resource (%s)" % exception)
Beispiel #22
0
 def connect(self, connectStr):
     localContext = uno.getComponentContext()
     resolver = localContext.ServiceManager.createInstanceWithContext(
                     "com.sun.star.bridge.UnoUrlResolver", localContext)
     ctx = resolver.resolve( connectStr )
     orb = ctx.ServiceManager
     return orb
Beispiel #23
0
def expandUri(uri):
    if uri.startswith("vnd.sun.star.expand:"):
        uri = uri.replace("vnd.sun.star.expand:", "", 1)
        uri = uno.getComponentContext().getByName("/singletons/com.sun.star.util.theMacroExpander").expandMacros(uri)
    if uri.startswith("file:"):
        uri = uno.absolutize("", uri)  # necessary to get rid of .. in uri
    return uri
Beispiel #24
0
def main():
    connectionString = "socket,host=localhost,port=2002"

    url = "uno:" + connectionString + ";urp;StarOffice.ComponentContext"

    localCtx = uno.getComponentContext()
    localSmgr = localCtx.ServiceManager
    resolver = localSmgr.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", localCtx)
    ctx = resolver.resolve(url)
    smgr = ctx.ServiceManager

    rowset =smgr.createInstanceWithContext("com.sun.star.sdb.RowSet", ctx)
    rowset.DataSourceName = "Bibliography"
    rowset.CommandType = COMMAND
    rowset.Command = "SELECT IDENTIFIER, AUTHOR FROM biblio"

    rowset.execute();

    print("Identifier\tAuthor")

    id = rowset.findColumn("IDENTIFIER")
    author = rowset.findColumn("AUTHOR")
    while rowset.next():
        print(rowset.getString(id) + "\t" + repr(rowset.getString(author)))

    rowset.dispose();
Beispiel #25
0
 def connect(self):
     '''Connects to OpenOffice'''
     if os.name == 'nt':
         import socket
     import uno
     from com.sun.star.connection import NoConnectException
     try:
         # Get the uno component context from the PyUNO runtime
         localContext = uno.getComponentContext()
         # Create the UnoUrlResolver
         resolver = localContext.ServiceManager.createInstanceWithContext(
             "com.sun.star.bridge.UnoUrlResolver", localContext)
         # Connect to the running office
         self.ooContext = resolver.resolve(
             'uno:socket,host=localhost,port=%d;urp;StarOffice.' \
             'ComponentContext' % self.port)
         # Is seems that we can't define a timeout for this method.
         # I need it because, for example, when a web server already listens
         # to the given port (thus, not a OpenOffice instance), this method
         # blocks.
         smgr = self.ooContext.ServiceManager
         # Get the central desktop object
         self.oo = smgr.createInstanceWithContext(
             'com.sun.star.frame.Desktop', self.ooContext)
     except NoConnectException, nce:
         raise ConverterError(CONNECT_ERROR % (self.port, nce))
Beispiel #26
0
def main():
    retVal = 0
    outputfile = "output.swx"

    opts, args = getopt.getopt(sys.argv[1:], "hco:", ["help", "connection-string=", "outfile" ])
    url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-c", "--connection-string" ):
            url = "uno:" + a + ";urp;StarOffice.ComponentContext"
        if o in ("-o", "--outfile"):
            outputfile = a
        
    if not len( args ):
        usage()
        sys.exit()
    
    try:
        ctxLocal = uno.getComponentContext()
        smgrLocal = ctxLocal.ServiceManager

        resolver = smgrLocal.createInstanceWithContext(
                   "com.sun.star.bridge.UnoUrlResolver", ctxLocal )
        ctx = resolver.resolve( url )
        smgr = ctx.ServiceManager
        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx )
    except NoConnectException, e:
        sys.stderr.write("OpenOffice process not found or not listening (" + e.Message + ")\n")
        sys.exit(1)
	def initialize(self):
		logging.debug("PropertyManager.initialize: starting")
		self.__setUiLanguage()

		VoikkoHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.VOIKKO_OPT_IGNORE_DOT, True)
		VoikkoHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.VOIKKO_OPT_NO_UGLY_HYPHENATION, True)

		# Set these options globally until OOo bug #97945 is resolved.
		VoikkoHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.VOIKKO_OPT_ACCEPT_TITLES_IN_GC, True)
		VoikkoHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.VOIKKO_OPT_ACCEPT_BULLETED_LISTS_IN_GC, True)

		VoikkoHandlePool.getInstance().setGlobalBooleanOption(PropertyManager.VOIKKO_OPT_ACCEPT_UNFINISHED_PARAGRAPHS_IN_GC, True)

		compContext = uno.getComponentContext()
		servManager = compContext.ServiceManager
		self.__linguPropSet = servManager.createInstanceWithContext("com.sun.star.linguistic2.LinguProperties", compContext)
		self.__linguPropSet.addPropertyChangeListener("IsSpellWithDigits", self)
		self.__linguPropSet.addPropertyChangeListener("IsSpellUpperCase", self)
		logging.debug("PropertyManager.initialize: property manager initalized")

		# synchronize the local settings from global preferences
		self.__setProperties(self.__linguPropSet)
		self.readVoikkoSettings()
		# request that all users of linguistic services run the spellchecker and hyphenator
		# again with updated settings
		event = LinguServiceEvent()
		event.nEvent = SPELL_CORRECT_WORDS_AGAIN | SPELL_WRONG_WORDS_AGAIN | HYPHENATE_AGAIN | PROOFREAD_AGAIN
		self.__sendLinguEvent(event)
Beispiel #28
0
    def convert(self):
        """Convert the document"""

        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", localContext
        )
        ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext")
        smgr = ctx.ServiceManager
        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)

        # load the document
        url = unohelper.systemPathToFileUrl(self.fullname)
        doc = desktop.loadComponentFromURL(url, "_blank", 0, ())

        filterName = "swriter: HTML (StarWriter)"
        storeProps = (PropertyValue("FilterName", 0, filterName, 0),)

        # pre-create a empty file for security reason
        url = unohelper.systemPathToFileUrl(self.outputfile)
        doc.storeToURL(url, storeProps)

        try:
            doc.close(True)
        except CloseVetoException:
            pass

        # maigic to release some resource
        ctx.ServiceManager
Beispiel #29
0
def oless_from_inputstream(inputstream):
    import uno
    context = uno.getComponentContext()
    sm = context.ServiceManager
    name = 'com.sun.star.embed.OLESimpleStorage'
    args = (inputstream, )
    return sm.createInstanceWithArgumentsAndContext(name, args, context)
 def createAvailableResourcesDialog(self,query,textList,imagesList):
     #localContext = uno.getComponentContext()
     #resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
     #ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
     ctx=uno.getComponentContext()
     smgr = ctx.ServiceManager
     desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
     doc = desktop.getCurrentComponent()
     if not hasattr(doc, "Text"):
         doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
     oDialog = smgr.createInstanceWithContext("com.sun.star.awt.UnoControlDialog",ctx)      
     oDialogModel = self.createDialog(ctx,smgr,120,True,"DialogResourceList",100,100,0,0,"Resource List",200)        
     self.createLabel(oDialogModel, "formulaLabel", query, 10, 100, 5, 5)  
     oDialog.setVisible(False)
     self.createDialogButton(oDialogModel, "GetResourcesButton", 15, 50, 25, 100, "Get Resources")
     txtEnd = self.addTextCheckBoxesToDialog(textList, oDialogModel)                 #get the end of the text
     imgEnd = self.addImageTextBoxesToDialog(query,txtEnd,imagesList, oDialogModel)  #get the end of the images
     oDialogModel.Width =imgEnd                                          #set the dialog width
     oDialogModel.Height = max(100,txtEnd+25)                            #set the dialog height
     oDialog.setModel(oDialogModel)
     oButton1 = oDialog.getControl("GetResourcesButton")
     oButton1.getModel().PositionY = txtEnd+5                            #reposition the button
     oButton1.setActionCommand("commanded")
     oButton1.addActionListener(MyActionListener(oDialog))
     oToolkit = smgr.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)
     oDialog.createPeer(oToolkit,oToolkit.getDesktopWindow()) 
     return oDialog     
Beispiel #31
0
    def connect(self, no_startup=False):
        """
        Connect to OpenOffice.
        If a connection cannot be established try to start OpenOffice.
        """
        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", localContext)
        context = None
        did_start = False

        n = 0
        while n < 6:
            try:
                context = resolver.resolve(
                    "uno:socket,host=localhost,port=%d;urp;StarOffice.ComponentContext"
                    % self.port)
                break
            except NoConnectException:
                pass

            # If first connect failed then try starting OpenOffice.
            if n == 0:
                # Exit loop if startup not desired.
                if no_startup:
                    break
                self.startup()
                did_start = True

            # Pause and try again to connect
            time.sleep(1)
            n += 1

        if not context:
            raise Exception, "Failed to connect to OpenOffice on port %d" % self.port

        desktop = context.ServiceManager.createInstanceWithContext(
            "com.sun.star.frame.Desktop", context)

        if not desktop:
            raise Exception, "Failed to create OpenOffice desktop on port %d" % self.port

        if did_start:
            _started_desktops[self.port] = desktop

        return desktop
Beispiel #32
0
def getPathesFromPackage( rootUrl, sfa ):
    ret = ()
    try:
        fileUrl = rootUrl + "/META-INF/manifest.xml" 
        inputStream = sfa.openFileRead( fileUrl )
        parser = uno.getComponentContext().ServiceManager.createInstance( "com.sun.star.xml.sax.Parser" )
        handler = ManifestHandler( rootUrl )
        parser.setDocumentHandler( handler )
        parser.parseStream( InputSource( inputStream , "", fileUrl, fileUrl ) )
        for i in tuple(handler.urlList):
            if not isPyFileInPath( sfa, i ):
                handler.urlList.remove(i)
        ret = tuple( handler.urlList )
    except UnoException, e:
        text = lastException2String()
        log.debug( "getPathesFromPackage " + fileUrl + " Exception: " +text )
        pass
def configuration_access(path, write=False):
    """Creates a XNameAccess instance for read and write access to the
    configuration at the given node path."""

    ctx = uno.getComponentContext()
    configurationProvider = ctx.ServiceManager.createInstance(
        'com.sun.star.configuration.ConfigurationProvider')
    value = PropertyValue()
    value.Name = 'nodepath'
    value.Value = path
    if write:
        servicename = 'com.sun.star.configuration.ConfigurationUpdateAccess'
    else:
        servicename = 'com.sun.star.configuration.ConfigurationAccess'
    configurationAccess = configurationProvider.createInstanceWithArguments(
        servicename, (value, ))
    return configurationAccess
Beispiel #34
0
def TestDialogs():
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", localContext)
    ctx = resolver.resolve(
        "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
    doc = desktop.getCurrentComponent()
    if not hasattr(doc, "Text"):
        doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank",
                                           0, ())
    oDialogModel = smgr.createInstanceWithContext(
        "com.sun.star.awt.UnoControlDialogModel", ctx)
    print(oDialogModel)
    oDialog = smgr.createInstanceWithContext(
        "com.sun.star.awt.UnoControlDialog", ctx)
    oDialog.setModel(oDialogModel)
    oDialogControl = oDialog.getControls()
    sPropNames = [
        'Height', 'Moveable', 'Name', 'PositionX', 'PositionY', 'Step',
        'TabIndex', 'Title', 'Width'
    ]
    #sValues = [uno.Any('Numeric',380),uno.Any('bool',True),uno.Any("MyTestDialog"),uno.Any(102),41,0,0,'OpenOffice',250]
    #oDialogModel.setPropertyValues(sPropNames,sValues)
    oDialogModel.Height = 100
    oDialogModel.Moveable = True
    oDialogModel.Name = "MyTestDialog"
    oDialogModel.PositionX = 102
    oDialogModel.PositionY = 41
    oDialogModel.Step = 0
    oDialogModel.TabIndex = 0
    oDialogModel.Title = "Select The Formula Resources"
    oDialogModel.Width = 250
    oButtonModel = smgr.createInstanceWithContext(
        "com.sun.star.awt.UnoControlButtonModel", ctx)
    #oUnoControlModel = smgr.createInstanceWithContext("com.sun.star.awt.UnoControlDialogElement",ctx)
    #parentWin = oDialogModel.CurrentController.Frame.ContainerWindow

    createCheckBox(ctx, oDialogModel)
    #oDialogModel.insertByName("CheckBox2",addCheckBox(ctx,"formula2",0))
    oDialog.setVisible(False)
    oToolkit = smgr.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)
    oDialog.createPeer(oToolkit, oToolkit.getDesktopWindow())
    print(oDialog.execute())
    print(oDialogControl)
Beispiel #35
0
def main(*args):
    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager
    try:
        ui_locale = gettext.translation(
            'base',
            localedir=urllib.url2pathname(
                get_main_directory("com.addon.pagenumbering") +
                'python/locales'),
            languages=[getLanguage()])
    except Exception, e:
        ui_locale = gettext.translation(
            'base',
            localedir=urllib.url2pathname(
                get_main_directory("com.addon.pagenumbering") +
                'python/locales'),
            languages=["en"])
Beispiel #36
0
    def __init__(self, nPositionX=None, nPositionY=None, nWidth=None, nHeight=None, sTitle=None):
        self.sTitle = sTitle
        self.LocalContext = uno.getComponentContext()
        self.ServiceManager = self.LocalContext.ServiceManager
        self.Toolkit = self.ServiceManager.createInstanceWithContext("com.sun.star.awt.ExtToolkit", self.LocalContext)

        # --------------create dialog container and set model and properties
        self.DialogContainer = self.ServiceManager.createInstanceWithContext("com.sun.star.awt.UnoControlDialog", self.LocalContext)
        self.DialogModel = self.ServiceManager.createInstance("com.sun.star.awt.UnoControlDialogModel")
        self.DialogContainer.setModel(self.DialogModel)
        self.DialogModel.PositionX = nPositionX
        self.DialogModel.PositionY = nPositionY
        self.DialogModel.Height = nHeight
        self.DialogModel.Width = nWidth
        self.DialogModel.Name = "Default"
        self.DialogModel.Closeable = True
        self.DialogModel.Moveable = True
Beispiel #37
0
 def __init__(self, ctx, *args):
     global spellchecker
     global SMGR
     self.ctx = ctx
     self.ServiceName = "com.sun.star.linguistic2.Proofreader"
     self.ImplementationName = "org.openoffice.comp.pyuno.Lightproof." + pkg
     self.SupportedServiceNames = (self.ServiceName, )
     self.locales = []
     for i in locales:
         l = locales[i]
         self.locales += [Locale(l[0], l[1], l[2])]
     self.locales = tuple(self.locales)
     currentContext = uno.getComponentContext()
     SMGR = currentContext.ServiceManager
     spellchecker = SMGR.createInstanceWithContext(
         "com.sun.star.linguistic2.SpellChecker", currentContext)
     lightproof_handler_nb_NO.load(currentContext)
Beispiel #38
0
    def _connect(self):
        try:
            localContext = uno.getComponentContext()

            resolver = localContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", localContext)

            smgr = resolver.resolve(self.connectstr)
            remoteContext = smgr.getPropertyValue("DefaultContext")

            self.desktop = smgr.createInstanceWithContext(
                "com.sun.star.frame.Desktop", remoteContext)
            return self.desktop

        except (NoConnectException, ConnectionSetupException):
            logging.exception("UNO server not started.")
            raise
Beispiel #39
0
def showPanels(panelWin, url):
    """
    Create a new panel object when the sidebar is initialized
    or whenever a panel becomes visible
    """

    ctx = uno.getComponentContext()
    # url is set in Sidebar.xcu
    if url == 'private:resource/toolpanel/autotextaddon/Panel1':

        pos_y = 20

        app = Panel1(panelWin)
        app.showDialog()
        panel_height = app.getHeight()

        return panel_height + pos_y
Beispiel #40
0
def insert_hd1(*args):
    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager

    # get the doc from the scripting context which is made available to all scripts

    Doc = XSCRIPTCONTEXT.getDocument()
    UndoManager = Doc.getUndoManager()
    ParaStyles = Doc.StyleFamilies.getByName("ParagraphStyles")
    #xray(smgr, ctx, ParaStyles)

    #Create view cursor to take current cursor position
    ViewCursor = Doc.CurrentController.getViewCursor()
    #xray(smgr, ctx, ViewCursor)
    UndoManager.enterUndoContext("Style to Heading 1")
    ViewCursor.ParaStyleName = "Heading 1"
    UndoManager.leaveUndoContext()
Beispiel #41
0
    def connect(self):
        proc = self.get_proc()
        if proc is None:
            self.start()

        for attempt in range(15):
            try:
                context = uno.getComponentContext()
                resolver = self._svc_create(context, RESOLVER)
                context = resolver.resolve("uno:%s" % CONNECTION)
                return self._svc_create(context, DESKTOP)
            except NoConnectException:
                log.warning("No connection to LibreOffice (%s)", attempt)
                time.sleep(2)
            except DisposedException:
                raise SystemFailure("Bridge is disposed.")
        raise SystemFailure("No connection to LibreOffice")
Beispiel #42
0
def copyUsingPropertySetInfo(srcObj, dstObj):
    """
    Cope the whole PropertySet of an UNO object to an other instance.
    """
    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager
    sPInfo = srcObj.getPropertySetInfo()
    dPInfo = dstObj.getPropertySetInfo()
    oProps = sPInfo.getProperties()

    for i in xrange(len(oProps)):
        oProp = oProps[i]
        try:
            if dPInfo.hasPropertyByName(oProp.Name):

                xray(smgr, ctx, oProp.Type)
                if oProp.Type.getName() == dPInfo.getPropertyByName(
                        oProp.Name).Type.getName():

                    oSValue = srcObj.getPropertyValue(oProp.Name)
                    if canCopyTypeWithAssignment(oSValue):
                        if (uno.getConstantByName(
                                "com.sun.star.beans.PropertyAttribute.READONLY"
                        ) and oProp.Attributes) == False:
                            if oProp.Name != "GridLines":
                                dstObj.setPropertyValue(oProp.Name, oSValue)
                    elif uno.IsArray(oSValue):
                        pass
                    else:
                        oDValue = dstObj.getPropertyValue(oProp.Name)
                        if oDValue == None or uno.IsEmpty(oDValue):
                            if (uno.getConstantByName(
                                    "com.sun.star.beans.PropertyAttribute.READONLY"
                            ) and oProp.Attributes) == False:
                                dstObj.setPropertyValue(oProp.Name, oSValue)
                            elif uno.HasUnoInterfaces(
                                    oSValue,
                                    "com.sun.star.beans.XPropertySet"):
                                if oSValue.SupportsService(
                                        "com.sun.star.text.Text"):
                                    pass
                                else:
                                    copyUsingPropertySetInfo(oSValue, oDValue)
        except Exception, e:
            xray(smgr, ctx, e.message)
            return
Beispiel #43
0
def uno_open(file):
    """This function should really just be in uno
    file -- Location of the file to open - must be a FieldFile
    returns an uno document
    """
    local = uno.getComponentContext()
    resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
    context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
    desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
    if 'amazonaws' in settings.STATIC_URL and hasattr(file, 'url'):
        file_url = file.url
    else:
        if isinstance(file, FieldFile):
            # We want the File then
            file = file.file
        file_url = "file://" + str(file)
    return desktop.loadComponentFromURL(file_url ,"_blank", 0, ())
Beispiel #44
0
 def createWriterDocument(
     self
 ):  #get the doc from the scripting context which is made available to all scripts
     localContext = uno.getComponentContext()
     resolver = localContext.ServiceManager.createInstanceWithContext(
         "com.sun.star.bridge.UnoUrlResolver", localContext)
     ctx = resolver.resolve(
         "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
     )
     smgr = ctx.ServiceManager
     desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",
                                              ctx)
     doc = desktop.getCurrentComponent()
     if not hasattr(doc, "Text"):
         doc = desktop.loadComponentFromURL("private:factory/swriter",
                                            "_blank", 0, ())
     return doc
Beispiel #45
0
    def connect(self, socket):
        """ Tries to connect to the LibreOffice instance through the specified socket"""
        xLocalContext = uno.getComponentContext()
        xUnoResolver = xLocalContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
        url = "uno:" + socket + ";urp;StarOffice.ComponentContext"
        print("OfficeConnection: connecting to: " + url)
        while True:
            if self.soffice and self.soffice.poll() is not None:
                raise Exception("soffice has stopped.")

            try:
                xContext = xUnoResolver.resolve(url)
                return xContext
            except pyuno.getClass("com.sun.star.connection.NoConnectException"):
                print("NoConnectException: sleeping...")
                time.sleep(1)
Beispiel #46
0
    def __init__(self,
                 autostart=False,
                 office='soffice \
--accept="socket,host=localhost,port=2002;urp;"',
                 connection_string="\
uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext",
                 timeout=30,
                 attempt_period=0.1):
        """
        Constructor

        @type  autostart: bool
        @param autostart: Auto Starts Libre/Open Office with a listening socket

        @type  office: string
        @param office: Libre/Open Office startup string

        @type  connection_string: string
        @param connection_string: Libre/Open office initialization string

        @type  timeout: int
        @param timeout: Timeout for starting Libre/Open Office in seconds

        @type  attempt_period: int
        @param attempt_period: Timeout between attempts in seconds
        """
        self._sheets = None
        self._fields = None
        self._connection_string = connection_string

        # LibreOffice variables.
        self._oResolver = None
        self._oContext = None
        self._oDesktop = None
        self._oDoc = None
        self._oLocal = uno.getComponentContext()

        if self._oLocal:
            self._oResolver = \
                self._oLocal.ServiceManager.createInstanceWithContext(
                    "com.sun.star.bridge.UnoUrlResolver", self._oLocal)
            if autostart:
                self._autostart_office(office, timeout, attempt_period)
            else:
                self._init_doc()
Beispiel #47
0
def getSelectedText():
    connected = False
    while not connected:
        try:
            # Establish a connection with the LO API Service
            localContext = uno.getComponentContext()
            resolver = localContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", localContext)
            ctx = resolver.resolve(
                "uno:pipe,name=open365_LO;urp;StarOffice.ComponentContext")
            smgr = ctx.ServiceManager
            connected = True
        except Exception:
            time.sleep(0.5)

    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
    getSelectedTextFunc = getSelectedTextFuncs[sys.argv[1]]
    return getSelectedTextFunc(desktop)
Beispiel #48
0
def MyMacro(*args):
    """Write Helo World in Writer"""

    try:
        ctx = remote_ctx  # use in development
    except:
        ctx = uno.getComponentContext()  # use in production

    # get desktop
    desktop = ctx.getByName("/singletons/com.sun.star.frame.theDesktop")
    # get document
    document = desktop.getCurrentComponent()
    # access the document's text property
    text = document.Text
    # create a cursor
    cursor = text.createTextCursor()
    # insert the text into the document
    text.insertString(cursor, "Hello World", 0)
    def __init__(self, port=DEFAULT_OPENOFFICE_PORT):
        self.parser = OOoDocumentParser()
        self.vnConverter = VietnameseTextConverter(decoderPrefix='internal_')
        self.oVnConverter = OOoVietnameseTextConverter(self.vnConverter)
        self.parser.setTextPortionConverter(self.oVnConverter)

        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", localContext)
        try:
            context = resolver.resolve(
                "uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext"
                % port)
        except NoConnectException:
            raise DocumentConversionException, "failed to connect to OpenOffice.org on port %s" % port
        self.desktop = context.ServiceManager.createInstanceWithContext(
            "com.sun.star.frame.Desktop", context)
        self._setupLogging()
Beispiel #50
0
def get_connection(retry=2):
    while retry > 0:
        try:
            localContext = uno.getComponentContext()

            resolver = localContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", localContext)

            ctx = resolver.resolve(CONN_STRING)
            return ctx
        except:
            retry -= 1
            kill_and_relaunch_oo()
            time.sleep(8)

    raise Exception(
        'could not launch oo, please read README.txt section Openoffice for troubleshooting'
    )
Beispiel #51
0
 def __init__(self, input, output):
     self.url_input=input
     self.url_output=output
     self.localContext = uno.getComponentContext()
     self.resolver = self.localContext.ServiceManager.createInstanceWithContext(
             "com.sun.star.bridge.UnoUrlResolver", self.localContext)
     self.ctx = self.resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext")
     self.smgr = self.ctx.ServiceManager
     self.desktop = self.smgr.createInstanceWithContext("com.sun.star.frame.Desktop", self.ctx)
     #self.loader = self.smgr.createInstanceWithContext("com.sun.star.frame.XComponentLoader", self.desktop)
     #load files
     properties = []
     p=PropertyValue()
     p.Name = "Hidden"
     p.Value = True
     properties.append(p)
     
     self.doc = self.desktop.loadComponentFromURL(self.url_input, "_default", 0, tuple(properties))
def open_filepicker(title, path=None, mode=10, filter_tuple=None):
    """
    Possible modes: http://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1ui_1_1dialogs_1_1TemplateDescription.html
    mode 0: simple open
    mode 10 : file save with option "automatic file name extension"
    """
    oCtx = uno.getComponentContext()
    oServiceManager = oCtx.getServiceManager()

    filepicker = oServiceManager.createInstanceWithArgumentsAndContext(
        "com.sun.star.ui.dialogs.OfficeFilePicker", (mode, ), oCtx)
    if path:
        filepicker.setDisplayDirectory(path)
    if filter_tuple:
        filepicker.appendFilter(filter_tuple[0], filter_tuple[1])
    filepicker.Title = title
    if filepicker.execute():
        return filepicker.getFiles()[0]
def initializeOptionsOnce():
    ctx = uno.getComponentContext()
    smgr = ctx.getServiceManager()
    readConfig, writeConfig = optionsdialog.createConfigAccessor(
        ctx, smgr,
        "/com.philolog.hoplitekb.ExtensionData/Leaves/HKBSettingsNode")
    defaults = readConfig("Defaults/Width", "Defaults/Height",
                          "Defaults/UnicodeMode")
    #set current value
    cfgnames = "Width", "Height", "UnicodeMode"
    maxwidth, maxheight, umode = readConfig(*cfgnames)
    umode = umode or defaults[2]
    if umode == "PrecomposedPUA":
        setUnicodeMode(1)
    elif umode == "CombiningOnly":
        setUnicodeMode(2)
    else:
        setUnicodeMode(0)
 def __init__(self,
              host=DEFAULT_OPENOFFICE_HOST,
              port=DEFAULT_OPENOFFICE_PORT):
     # UNO component context
     self.localContext = uno.getComponentContext()
     self.serviceManager = self.localContext.ServiceManager
     # UnoUrlResolver
     self.resolver = self.localContext.ServiceManager.createInstanceWithContext(
         "com.sun.star.bridge.UnoUrlResolver", self.localContext)
     try:
         self.context = self.resolver.resolve(
             "uno:socket,host=%s,port=%s;urp;StarOffice.ComponentContext" %
             (host, port))
     except NoConnectException:
         raise (DocumentConversionException,
                "failed to connect to OpenOffice.org on port %s" % port)
     self.desktop = self.context.ServiceManager.createInstanceWithContext(
         "com.sun.star.frame.Desktop", self.context)
Beispiel #55
0
 def __init__(self,
              host='localhost',
              port=DEFAULT_OPENOFFICE_PORT,
              ooo_restart_cmd=None):
     self._host = host
     self._port = port
     self._ooo_restart_cmd = ooo_restart_cmd
     self.localContext = uno.getComponentContext()
     self.serviceManager = self.localContext.ServiceManager
     self._resolver = self.serviceManager.createInstanceWithContext(
         "com.sun.star.bridge.UnoUrlResolver", self.localContext)
     try:
         self._context = self._resolver.resolve(
             "uno:socket,host=%s,port=%s;urp;StarOffice.ComponentContext" %
             (host, port))
     except IllegalArgumentException, exception:
         raise DocumentConversionException("The url is invalid (%s)" %
                                           exception)
Beispiel #56
0
    def __init__( self, ctx, *args ):
        if log.isDebugLevel():
            mystr = ""
            for i in args:
                if len(mystr) > 0:
                    mystr = mystr +","
                mystr = mystr + str(i)
            log.debug( "Entering PythonScriptProvider.ctor" + mystr )

        storageType = ""
        if isinstance(args[0],unicode ):
            storageType = args[0]
        else:
            storageType = args[0].SCRIPTING_DOC_URI
        isPackage = storageType.endswith( ":uno_packages" )

        try:
#            urlHelper = ctx.ServiceManager.createInstanceWithArgumentsAndContext(
#                "com.sun.star.script.provider.ScriptURIHelper", (LANGUAGENAME, storageType), ctx)
            urlHelper = MyUriHelper( ctx, storageType )
            log.isDebugLevel() and log.debug( "got urlHelper " + str( urlHelper ) )
        
            rootUrl = expandUri( urlHelper.getRootStorageURI() )
            log.isDebugLevel() and log.debug( storageType + " transformed to " + rootUrl )

            ucbService = "com.sun.star.ucb.SimpleFileAccess"
            sfa = ctx.ServiceManager.createInstanceWithContext( ucbService, ctx )
            if not sfa:
                log.debug("PythonScriptProvider couldn't instantiate " +ucbService)
                raise RuntimeException(
                    "PythonScriptProvider couldn't instantiate " +ucbService, self)
            self.provCtx = ProviderContext(
                storageType, sfa, urlHelper, ScriptContext( uno.getComponentContext(), None ) )
            if isPackage:
                mapPackageName2Path = getPackageName2PathMap( sfa, storageType )
                self.provCtx.setPackageAttributes( mapPackageName2Path , rootUrl )
                self.dirBrowseNode = PackageBrowseNode( self.provCtx, LANGUAGENAME, rootUrl )
            else:
                self.dirBrowseNode = DirBrowseNode( self.provCtx, LANGUAGENAME, rootUrl )
            
        except Exception, e:
            text = lastException2String()
            log.debug( "PythonScriptProvider could not be instantiated because of : " + text )
            raise e
Beispiel #57
0
def connect():
    """
    Start LibreOffice with
    libreoffice -calc -accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
    and call this from a Python interactive console
    """
    import uno

    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
                                    "com.sun.star.bridge.UnoUrlResolver", localContext )
    ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)


    # get current document model
    model = desktop.getCurrentComponent()
    return SpreadSheet(model.Sheets)
Beispiel #58
0
    def mousePressed(self, ev):
        global sorted_by_title
        dialog = ev.Source.getContext()
        action_command = ev
        smgr = self.ctx.ServiceManager

        auto_list = dialog.getControl("SavedAutotext")
        selected_pos = auto_list.getSelectedItemPos()
        psm = uno.getComponentContext().ServiceManager
        dps = psm.createInstance("com.sun.star.text.AutoTextContainer")

        oRange = dps.getByName(current_group)

        selected_autotext = oRange.getByIndex(sorted_by_title[selected_pos][1])
        # getString

        preview_label = dialog.getControl("PreviewLabel")

        preview_label.setText(selected_autotext.getString())
Beispiel #59
0
def get_parent():

    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)

    if desktop.CurrentFrame:
        parent = desktop.CurrentFrame.ContainerWindow
    else:
        enum = desktop.Components.createEnumeration()
        comps = []

        while enum.hasMoreElements():
            comps.append(enum.nextElement())

        doc = comps[0]
        parent = doc.CurrentController.Frame.ContainerWindow

    return parent
Beispiel #60
0
def getServiceManager(cHost="localhost", cPort="2002"):
    """Get the ServiceManager from the running OpenOffice.org.
        Then retain it in the global variable goServiceManager for future use.
        This is similar to the GetProcessServiceManager() in OOo Basic.
    """
    global goServiceManager
    if not goServiceManager:
        # Get the uno component context from the PyUNO runtime
        oLocalContext = uno.getComponentContext()
        # Create the UnoUrlResolver on the Python side.
        oLocalResolver = oLocalContext.ServiceManager.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", oLocalContext)
        # Connect to the running OpenOffice.org and get its context.
        oContext = oLocalResolver.resolve("uno:socket,host=" + cHost +
                                          ",port=" + cPort +
                                          ";urp;StarOffice.ComponentContext")
        # Get the ServiceManager object
        goServiceManager = oContext.ServiceManager
    return goServiceManager