def write_wordlist_file(self, FILEPATH): props = ( util.createProp('FilterName', 0), util.createProp('Overwrite', 1), ) wordListDoc = self.unoObjs.getOpenDocs(util.UnoObjs.DOCTYPE_CALC)[0] wordListDoc.document.storeAsURL(uno.systemPathToFileUrl(FILEPATH), props) return wordListDoc
def convert_to_odt(self): """Opens a file such as .doc, saves as .odt and then closes it.""" logger.debug(util.funcName('begin')) self.incrementProgressPart() basename = os.path.basename(self.fileconfig.filepath) name, dummy_ext = os.path.splitext(basename) newpath = os.path.join(self.tempBaseDir, name + "_converted.odt") if os.path.exists(newpath): logger.warning("File already exists: %s", newpath) self.fileconfig.filepath = newpath logger.debug(util.funcName('return')) return doc_loader = doc_reader.DocReader(self.fileconfig, self.unoObjs, 0) doc_loader.loadDoc(self.fileconfig.filepath) loaded_doc = doc_loader.doc uno_args = ( #util.createProp("FilterName", "StarOffice XML (Writer)"), #util.createProp("FilterName", "writer8"), util.createProp("Overwrite", False), ) logger.debug("Saving as %s", newpath) fileUrl = uno.systemPathToFileUrl(os.path.realpath(newpath)) try: loaded_doc.document.storeAsURL(fileUrl, uno_args) except ErrorCodeIOException: raise exceptions.FileAccessError("Error saving %s", newpath) try: loaded_doc.document.close(True) except CloseVetoException: logger.warning("Could not close %s", newpath) self.fileconfig.filepath = newpath self.incrementProgressPart() logger.debug(util.funcName('end'))
def getWriterDoc(self): """Typically called from a Calc spreadsheet. Make sure we have a Writer document ready for user variables. Takes an object of type util.UnoObjs that has service objs but probably not writer doc objs. Returns unoObjs of a writer document to hold UserVars settings. Finds the best candidate found to store user variables. If no candidate is found, opens a blank document. """ maxHasSettings, twoDocsHaveMax, docFound = self.findBestDoc() if docFound: return docFound else: ## Open a blank document in the background. uno_args = (util.createProp("Minimized", True), ) newDoc = self.unoObjs.desktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, uno_args) # this won't modify the original reference kept by calling code writerUnoObjs = self.unoObjs.getDocObjs(newDoc) writerUnoObjs.window.setVisible(True) userVars = UserVars(self.VAR_PREFIX, writerUnoObjs.document, logger) setHasSettings(userVars, maxHasSettings, twoDocsHaveMax) preparer = SettingsDocPreparer(self.VAR_PREFIX, writerUnoObjs) preparer.addContents() return writerUnoObjs
def loadUnoObjs(self, genericUnoObjs): """Initialize and get current OpenOffice locale.""" if self.unoObjs: # Already loaded. return theLocale self.unoObjs = genericUnoObjs ## Get locale setting configProvider = self.unoObjs.smgr.createInstanceWithContext( "com.sun.star.configuration.ConfigurationProvider", self.unoObjs.ctx) args = ( # trailing comma is required to make a tuple util.createProp("nodepath", "/org.openoffice.Setup/L10N"), ) settings = configProvider.createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", args) OOLang = settings.getByName("ooLocale") self.code = OOLang[:2] # grab first two characters logger.debug("locale = %s", self.code) ## Make the English key values case insensitive translationsLower = dict() for en in self.translations: translationsLower[en.lower()] = self.translations[en] self.translations.update(translationsLower) return theLocale
def moveExNumber(self): """ Move the example number from the old example to the new one. Before this method is called, the cursor is expected to be one line below two tables with examples, and there should be no empty line between the two tables -- they should be touching. """ logger.debug(util.funcName('begin')) oVC = self.unoObjs.viewcursor # shorthand variable name ## Delete paragraph break inserted by outputmanager.insertEx() self.unoObjs.dispatcher.executeDispatch(self.unoObjs.frame, ".uno:Delete", "", 0, ()) ## Go to ex number of old example. oVC.goUp(2, False) oVC.gotoStartOfLine(False) oVC.gotoEndOfLine(True) oTextCurs = oVC.getText().createTextCursorByRange(oVC) strval = oTextCurs.getString() # FIXME: This can cause a crash in some cases. # It happened when repeatedly updating the same example. logger.debug("Cut begin") self.unoObjs.dispatcher.executeDispatch(self.unoObjs.frame, ".uno:Cut", "", 0, ()) logger.debug("Cut finished") ## Cut ex number from old example. ## Paste unformatted text of ex number. self.unoObjs.dispatcher.executeDispatch(self.unoObjs.frame, ".uno:Cut", "", 0, ()) uno_args = ( util.createProp("SelectedFormat", 1), # paste unformatted ) self.unoObjs.dispatcher.executeDispatch(self.unoObjs.frame, ".uno:ClipboardFormatItems", "", 0, uno_args) ## Paste ex number into new example oVC.goDown(1, False) oVC.gotoStartOfLine(False) oVC.gotoEndOfLine(True) self.unoObjs.dispatcher.executeDispatch(self.unoObjs.frame, ".uno:Paste", "", 0, ()) # If a new example was just added and then updated, # we need to save this range to add the example number. # The original range will be invalid now. if strval == "()": oVC.goLeft(1, False) self.exampleManager.exnumRanges.append(oVC.getStart()) logger.debug(util.funcName('end'))
def getProductName(self): """Reads value in an XML file stored at a location like C:/Program Files/LibreOffice 5/share/registry/main.xcd Returns either "LibreOffice" or "OpenOffice". """ if self.product_name is None: ctx = self.getContext() smgr = ctx.ServiceManager aConfigProvider = smgr.createInstanceWithContext( "com.sun.star.configuration.ConfigurationProvider", ctx) prop = util.createProp("nodepath", "/org.openoffice.Setup/Product") oNode = aConfigProvider.createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", (prop, )) self.product_name = oNode.getByName("ooName") return self.product_name
def scopeFont(self): """ This only searches direct formatting, that is, not including styles. """ logger.debug(util.funcName('begin', args=self.config.fontName)) if self.config.fontType in ['Complex', 'Asian']: self.scopeComplexFont() return search = self.unoObjs.document.createSearchDescriptor() search.SearchString = "" search.SearchAll = True attrName = "CharFontName" attrs = ( # trailing comma is required to make a tuple util.createProp(attrName, self.config.fontName), ) search.setSearchAttributes(attrs) self.doSearch(search)
def loadDoc(self, filepath): """Sets self.calcUnoObjs to a loaded Calc doc. File will open minimized if not already open. """ logger.debug("Opening file %s", filepath) if not os.path.exists(filepath): raise exceptions.FileAccessError("Cannot find file %s", filepath) fileUrl = uno.systemPathToFileUrl(os.path.realpath(filepath)) uno_args = (util.createProp("Minimized", True), ) newDoc = self.unoObjs.desktop.loadComponentFromURL( fileUrl, "_default", 0, uno_args) try: self.calcUnoObjs = self.unoObjs.getDocObjs( newDoc, doctype=util.UnoObjs.DOCTYPE_CALC) except AttributeError: raise exceptions.DocAccessError() self.calcUnoObjs.window.setVisible(True) # otherwise it will be hidden logger.debug("Opened file.")
def set_noTableSpacing(table, unoObjs): """Sets a table to have no spacing. As a side effect, this function also currently sets borders to none. """ # move view cursor to first cell in table unoObjs.controller.select(table) unoObjs.dispatcher.executeDispatch(unoObjs.frame, ".uno:SelectTable", "", 0, ()) ZERO_BORDER = (0, 0, 0, 0) uno_args = (util.createProp("BorderOuter.LeftBorder", ZERO_BORDER), util.createProp("BorderOuter.LeftDistance", 0), util.createProp("BorderOuter.RightBorder", ZERO_BORDER), util.createProp("BorderOuter.RightDistance", 0), util.createProp("BorderOuter.TopBorder", ZERO_BORDER), util.createProp("BorderOuter.TopDistance", 0), util.createProp("BorderOuter.BottomBorder", ZERO_BORDER), util.createProp("BorderOuter.BottomDistance", 0)) unoObjs.dispatcher.executeDispatch(unoObjs.frame, ".uno:BorderOuter", "", 0, uno_args) # move view cursor to first cell in table unoObjs.controller.select(table)
def loadDoc(self, filepath): logger.debug(util.funcName('begin', args=filepath)) if not os.path.exists(filepath): raise exceptions.FileAccessError("Cannot find file %s", filepath) fileUrl = uno.systemPathToFileUrl(os.path.realpath(filepath)) uno_args = ( util.createProp("Minimized", True), # Setting a filter makes some files work but then .odt fails. # Instead just have the user open the file first. #util.createProp("FilterName", "Text"), ) # Loading the document hidden was reported to frequently crash # before OOo 2.0. It seems to work fine now though. newDoc = self.unoObjs.desktop.loadComponentFromURL( fileUrl, "_default", 0, uno_args) try: self.doc = self.unoObjs.getDocObjs(newDoc) except AttributeError: raise exceptions.DocAccessError() logger.debug(util.funcName('end'))
def addExampleNumbers(self): """Inserts example numbers at the specified locations. self.exnumRanges is of type com.sun.star.text.XTextRange. This function is needed because the .uno:InsertField call seems to fail when called within a dialog event handler. API calls succeed, but there does not seem to be a way to create a "Number Range" master field or text field with the API, only SetExpression items which are not as flexible. """ logger.debug(util.funcName('begin')) originalRange = self.unoObjs.viewcursor.getStart() for exnumRange in self.exnumRanges: logger.debug("Going to a range.") try: self.unoObjs.viewcursor.gotoRange(exnumRange, False) except (IllegalArgumentException, RuntimeException): # Give up on this range and go on to the next one. logger.warning("Failed to locate range.") continue if (self.config.methodTables and self.config.insertNumbering and not self.config.makeOuterTable): ## Delete "xxxx" that we inserted earlier. self.unoObjs.viewcursor.goRight(4, True) self.unoObjs.viewcursor.String = "" uno_args = (util.createProp("Type", 23), util.createProp("SubType", 127), util.createProp("Name", "AutoNr"), util.createProp("Content", ""), util.createProp("Format", 4), util.createProp("Separator", " ")) self.unoObjs.dispatcher.executeDispatch(self.unoObjs.frame, ".uno:InsertField", "", 0, uno_args) logger.debug("Inserted AutoNr field") self.unoObjs.viewcursor.gotoRange(originalRange, False) logger.debug(util.funcName('end'))