Search code examples
pythonmacroslibreofficeuno

How do I test in a LibreOffice python macro whether I'm in a Writer or Calc document?


I am working in libreoffice and need a python macro that can insert data into the current document from an external source.
Given that the insert methods are different for a spreadsheet and a document using the UNO API, how do I code the macro to discover whether I am in a writer document or a calc spreadsheet and use the appropriate insert method for the type of document?


Solution

  • def fs2InvoiceNo(*args):
    #get the doc from the scripting context which is made available to all scripts
        desktop = XSCRIPTCONTEXT.getDesktop()                                      
        model = desktop.getCurrentComponent()
    #get the XText interface
        method = ""
        try:
            text = model.Text
            tRange = text.End
            cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
            oTable = cursor.TextTable
            oCurCell = cursor.Cell
            method = "Doc"
        except:
            pass
        try:
            sheets = model.getSheets()
            sheet = model.CurrentController.getActiveSheet()
            oSelection = model.getCurrentSelection()
            oArea = oSelection.getRangeAddress()
            first_row = oArea.StartRow
            last_row = oArea.EndRow
            first_col = oArea.StartColumn
            last_col = oArea.EndColumn
            method = "Calc"
        except:
            pass
        if method == "":
            raise Exception("Unknown environment for this script")
    #and get the string from Footswitch2 via a TCP port
        import os, socket, time
        from configobj import ConfigObj
        configuration_dir = os.environ["HOME"]
        config_filename = configuration_dir + "/fs2.cfg"
        if  os.access(config_filename, os.R_OK):
            pass
        else:
            return None
        cfg = ConfigObj(config_filename)
        #define values to use from the configuration file
        tcp_port = int(cfg["control"]["TCP_PORT"])
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        try:
            sock.connect(("localhost", tcp_port))
        except:
            return None
        sock.settimeout(0.5)
        try:
            sock.send(bytes('invoicenumber\n', 'UTF-8'))
        except:
            return None
        try:
            time.sleep(0.2)
            s_list = sock.recv(1024).decode('UTF-8')
            s_list = s_list.split("\n")
        except:
            return None
        lines_in_response = len(s_list)
        if lines_in_response is None:
            return None
        invoice_no = s_list[0]
        if invoice_no == "":
            invoice_no = "None"
        if method == "Doc":
            if oCurCell == None: # Are we inserting into a table or not?
                text.insertString(cursor, invoice_no, 0)
            else:
                cell = oTable.getCellByName(oCurCell.CellName)
                cellCursor = cell.createTextCursor() # use this cursor if you want the text inserted at the beginning of the cell
                cell.insertString(cursor, invoice_no, False) # use the standard cursor to insert at the current position
        else:
            cell = sheet.getCellByPosition(first_col, first_row)
            cell.String = invoice_no
        sock.close()
        return None