def verify(self): """Verify that settings are acceptable.""" logger.debug(util.funcName('begin')) if (not self.filepath or not self.filepath.lower().endswith( (".ods", ".sxc", ".xls", ".xlsx"))): raise exceptions.ChoiceProblem( "Please specify a word list file. To make a new empty " "list, go to Word List and Spelling and then save the " "spreadsheet file.") if not self.whichTask: raise exceptions.LogicError("No task was specified.") if not self.whichScope: raise exceptions.LogicError("No scope was specified.") if self.whichScope == 'Language' and not self.searchConfig.lang: raise exceptions.ChoiceProblem("Please select a language name.") if self.whichScope == 'ParaStyle' and not self.searchConfig.style: raise exceptions.ChoiceProblem( "Please select a scope paragraph style.") if self.whichScope == 'CharStyle' and not self.searchConfig.style: raise exceptions.ChoiceProblem( "Please select a scope character style.") if self.whichScope == 'Font' and not self.searchConfig.fontName: raise exceptions.ChoiceProblem("Please select a scope font.") if self.whichScope == 'SFMs' and not self.searchConfig.SFMs: raise exceptions.ChoiceProblem("Please specify SFMs.") logger.debug(util.funcName('end'))
def getRanges(self): progressBar = ProgressBar(self.unoObjs, "Finding text...") progressBar.show() progressBar.updateBeginning() textSearch = TextSearch(self.unoObjs, progressBar) textSearch.setConfig(self.config.searchConfig) try: if self.config.whichScope == 'WholeDoc': textSearch.scopeWholeDocTraverse() elif self.config.whichScope == 'Selection': textSearch.scopeSelection() elif self.config.whichScope == 'Language': textSearch.scopeLocale() elif self.config.whichScope == 'ParaStyle': textSearch.scopeParaStyle() elif self.config.whichScope == 'CharStyle': textSearch.scopeCharStyle() elif self.config.whichScope == 'Font': textSearch.scopeFont() elif self.config.whichScope == 'SFMs': textSearch.scopeSFMs() else: raise exceptions.LogicError( "Unexpected value %s", self.config.whichScope) progressBar.updateFinishing() except exceptions.MessageError as exc: raise exc finally: progressBar.close() return textSearch.getRanges()
def isCorrect_str(self): if self.isCorrect is Tribool('Indeterminate'): return "" elif self.isCorrect is Tribool('True'): return "OK" elif self.isCorrect is Tribool('False'): return "X" raise exceptions.LogicError("Unexpected value %r", self.isCorrect)
def setAndVerifyConfig(self, newConfig): """Sets self.config from newConfig, which should be type ConversionSettings. Throws exceptions.ChoiceProblem if the choices are not acceptable. """ logger.debug(util.funcName('begin')) if not self.styleFonts: raise exceptions.LogicError("Expected styleFonts to be set.") if not newConfig.whichScope: raise exceptions.ChoiceProblem("Please specify a scope.") if (newConfig.whichScope == 'ParaStyle' and not newConfig.searchConfig.style): raise exceptions.ChoiceProblem( "Please select a scope paragraph style.") if (newConfig.whichScope == 'CharStyle' and not newConfig.searchConfig.style): raise exceptions.ChoiceProblem( "Please select a scope character style.") if (newConfig.whichScope == 'Font' and not newConfig.searchConfig.fontName): raise exceptions.ChoiceProblem("Please select a scope font.") if (newConfig.whichScope == 'SFMs' and not newConfig.searchConfig.SFMs): raise exceptions.ChoiceProblem("Please specify SFMs.") if not newConfig.whichTarget: raise exceptions.ChoiceProblem("Please specify a target.") if (newConfig.whichTarget == 'ParaStyle' and not newConfig.targetStyle): raise exceptions.ChoiceProblem("Please select a target style.") if (newConfig.whichTarget == 'CharStyle' and not newConfig.targetStyle): raise exceptions.ChoiceProblem("Please select a target style.") if (newConfig.whichTarget == 'FontOnly' and not newConfig.targetFont.fontName): raise exceptions.ChoiceProblem("Please select a target font.") self.config = newConfig try: if newConfig.whichTarget == 'ParaStyle': self.styleFonts.setParaStyleWithFont(newConfig.targetFont, newConfig.targetStyle) elif newConfig.whichTarget == 'CharStyle': self.styleFonts.setCharStyleWithFont(newConfig.targetFont, newConfig.targetStyle) except RuntimeException as exc: logger.exception(exc) raise exceptions.StyleError("Could not create style '%s'.", newConfig.targetStyle) logger.debug(util.funcName('end'))
def grabList(self, grabKey): """Return list of strings of the specified GRAB_FIELDS key.""" textList = [] if grabKey == 'ref': textList = [self.refText] elif grabKey == 'pht': textList = [self.phonetic] elif grabKey == 'phm': textList = [self.phonemic] elif grabKey == 'gl': textList = [self.gloss] else: raise exceptions.LogicError("Unknown grabKey '%s'", grabKey) return textList
def attrs(self): """Attributes that uniquely identify this object. Used for magic methods below. """ #logger.debug("StyleItem.attrs()") if self.scopeType == ScopeType.WHOLE_DOC: return 'WholeDoc' # only one unique value for all items elif (self.scopeType == ScopeType.FONT_WITH_STYLE or self.scopeType == ScopeType.FONT_WITHOUT_STYLE): return (self.fontName, self.fontType) elif (self.scopeType == ScopeType.CHARSTYLE or self.scopeType == ScopeType.PARASTYLE): return (self.styleName, self.styleType) else: raise exceptions.LogicError( "Unexpected value %s", self.scopeType)
def addWordData(self, word): """Add columns for one word, many morphemes. Creates another line (a new inner table) if word does not fit on current line. """ logger.debug(util.funcName('begin')) for dummy_which_line in ("current", "wrap to another"): morphRow_startCol = self.wrappingManager.prepareWordColumns( len(word.morphList)) for morph_i, morph in enumerate(word.morphList): self._insertMorphColumnData( word, morph, morphRow_startCol, morph_i) if self.wrappingManager.fit_word_on_line(): logger.debug(util.funcName('return')) return logger.debug("Wrapping to next line.") raise exceptions.LogicError("Word failed to fit properly.")
def __str__(self): if self.scopeType == ScopeType.WHOLE_DOC: strval = "Whole Document" elif (self.scopeType == ScopeType.FONT_WITH_STYLE or self.scopeType == ScopeType.FONT_WITHOUT_STYLE): strval = str(self.fontName) elif (self.scopeType == ScopeType.CHARSTYLE or self.scopeType == ScopeType.PARASTYLE): strval = str(self.styleName) if self.styleDisplayName: strval = self.styleDisplayName else: raise exceptions.LogicError( "Unexpected value %s", self.scopeType) if self.change: strval = "* " + strval return strval
def addConverter(self, mappingName, converterSpec, conversionType, leftEncoding, rightEncoding, processType): """Add a converter to the repository. Used for automated testing. :param mappingName: friendly name key that the converter is to be accessed with :param converterSpec: technical spec of the converter (e.g. TECkit & CC = filespec to map) :param conversionType: ConvType parameter indicating the type of conversion (e.g. "Legacy_to_from_Unicode") :param leftEncoding: optional technical name of the left-hand side encoding (e.g. SIL-ANNAPURNA-05) :param rightEncoding: optional technical name of the right-hand side encoding (e.g. UNICODE) :param processType: ProcessTypeFlags flag to indicate the implementation/transduction type (e.g. UnicodeEncodingConversion) from which you can do later filtering (e.g. ByEncodingID) """ logger.debug( util.funcName('begin', args=(mappingName, converterSpec, conversionType, leftEncoding, rightEncoding, processType))) self.loadLibrary() if not self.funcIsEcInstalled(): raise exceptions.FileAccessError( "EncConverters does not seem to be installed properly.") if not self.funcAddConverter: raise exceptions.FileAccessError( "Could not get AddConverter function. " "Automatically adding a converter requires SEC4.0 or higher.") c_convName = getStringParam(mappingName) if not c_convName: raise exceptions.LogicError("No converter was specified.") c_convSpec = getStringParam(converterSpec) c_convType = ctypes.c_ushort(conversionType) c_leftEnc = getStringParam(leftEncoding) c_rightEnc = getStringParam(rightEncoding) c_processType = ctypes.c_ushort(processType) logger.debug("Calling funcAddConverter.") status = self.funcAddConverter(c_convName, c_convSpec, c_convType, c_leftEnc, c_rightEnc, c_processType) verifyStatusOk(status) logger.debug(util.funcName('end'))
def scopeComplexFont(self): """Similar to character styles, searching for complex fonts using a search descriptor is currently buggy, so we enumerate instead. """ logger.debug(util.funcName('begin')) for simpleTextSection in self.docEnum.documentSections(): if self.config.fontType == "Complex": sectionFont = simpleTextSection.CharFontNameComplex elif self.config.fontType == "Asian": sectionFont = simpleTextSection.CharFontNameAsian else: raise exceptions.LogicError("Unexpected font type %s.", self.config.fontType) if sectionFont == self.config.fontName: logger.debug("Found font %s", self.config.fontName) # TextPortions include the TextRange service. self.ranger.addRange(simpleTextSection)
def setFrameAttrs(styleObj, margins): if not margins: raise exceptions.LogicError("Expected frame margin parameter.") rightMargin, bottomMargin = margins styleObj.AnchorType = AS_CHARACTER styleObj.VertOrient = LINE_TOP styleObj.WidthType = VARIABLE styleObj.LeftMargin = 0 styleObj.TopMargin = 0 styleObj.RightMargin = rightMargin * INCHES_TO_MM100 styleObj.BottomMargin = bottomMargin * INCHES_TO_MM100 styleObj.BorderDistance = 0 BORDER_WIDTH = 0 borderLine = styleObj.getPropertyValue("LeftBorder") borderLine.OuterLineWidth = BORDER_WIDTH styleObj.setPropertyValue("LeftBorder", borderLine) styleObj.setPropertyValue("RightBorder", borderLine) styleObj.setPropertyValue("TopBorder", borderLine) styleObj.setPropertyValue("BottomBorder", borderLine)
def getStyleItem(self, scopeType): """Returns a StyleItem object useful for higher layers.""" styleItem = StyleItem(scopeType) styleItem.inputData = self.inputData styleItem.inputDataOrder = self.inputDataOrder if scopeType == ScopeType.WHOLE_DOC: pass elif (scopeType == ScopeType.FONT_WITH_STYLE or scopeType == ScopeType.FONT_WITHOUT_STYLE): styleItem.fontName = self.fontName styleItem.fontType = self.fontType elif (scopeType == ScopeType.PARASTYLE or scopeType == ScopeType.CHARSTYLE): styleItem.styleType = self.styleType styleItem.styleDisplayName = self.styleDisplayName styleItem.styleName = self.styleName else: raise exceptions.LogicError("Unexpected value %s", scopeType) return styleItem
def scopeFont(self): """The API for Draw does not provide searching by font like Writer, so we enumerate instead. """ logger.debug(util.funcName('begin')) for simpleTextSection in self.docEnum.documentSections(): if self.config.fontType == "Western": sectionFont = simpleTextSection.CharFontName elif self.config.fontType == "Complex": sectionFont = simpleTextSection.CharFontNameComplex elif self.config.fontType == "Asian": sectionFont = simpleTextSection.CharFontNameAsian else: raise exceptions.LogicError( "Unexpected font type %s.", self.config.fontType) if sectionFont == self.config.fontName: logger.debug("Found font %s", self.config.fontName) # TextPortions include the TextRange service. self.ranger.addRange(simpleTextSection)
def grabList(self, grabKey): """Return list of strings of the specified GRAB_FIELDS key.""" textList = [] if grabKey == 'ref': textList = [self.refText] elif grabKey == 'ft': textList = [self.freeTrans] elif grabKey == 'word1': textList = [word.text1 for word in self.wordList] elif grabKey == 'word2': textList = [word.text2 for word in self.wordList] elif grabKey == 'morph1': textList = [morph.text1 for morph in self.getMorphsList()] elif grabKey == 'morph2': textList = [morph.text2 for morph in self.getMorphsList()] elif grabKey == 'gl': textList = [morph.gloss for morph in self.getMorphsList()] elif grabKey == 'ps': textList = [morph.pos for morph in self.getMorphsList()] else: raise exceptions.LogicError("Unknown grabKey '%s'", grabKey) return textList
def setConverter(self, newConfig=None): """Initialize a converter to the specified values. :param newConfig: type ConverterSettings """ logger.debug(util.funcName('begin')) if not newConfig: # Useful for multiple converter objects with different settings. newConfig = self.config self.loadLibrary() if not self.funcIsEcInstalled(): raise exceptions.FileAccessError( "EncConverters does not seem to be installed properly.") c_convName = getStringParam(newConfig.convName) if c_convName is None: raise exceptions.LogicError("No converter was specified.") c_forward = ctypes.c_bool(newConfig.forward) c_normForm = ctypes.c_ushort(newConfig.normForm) logger.debug("calling funcInitConverter with %r", newConfig) status = self.funcInitConverter(c_convName, c_forward, c_normForm) verifyStatusOk(status) self.config = newConfig logger.debug(util.funcName('end'))
def _read(self): filetype = self.get_filetype() self.progressBar.updatePercent(30) logger.debug("Parsing file %s", self.filepath) if not os.path.exists(self.filepath): raise exceptions.FileAccessError("Cannot find file %s", self.filepath) try: self.dom = xml.dom.minidom.parse(self.filepath) except xml.parsers.expat.ExpatError as exc: raise exceptions.FileAccessError("Error reading file %s\n\n%s", self.filepath, str(exc).capitalize()) logger.debug("Parse finished.") self.progressBar.updatePercent(60) if filetype == 'paxml': self.read_paxml_file() elif filetype == 'lift': self.read_lift_file() elif filetype == 'xml': self.read_toolbox_file() else: raise exceptions.LogicError("Unexpected file type %s", filetype)
def convert(self, sInput): """:returns: converted unicode string""" logger.debug(util.funcName('begin')) if not self.config.convName: raise exceptions.LogicError("No converter was specified.") logger.debug("Using conv name %r", self.config.convName) c_convName = getStringParam(self.config.convName) logger.debug(repr(sInput)) c_input = getStringParam(sInput) if c_input is None: raise exceptions.DataNotFoundError("No conversion result.") # ECDriver will truncate the result if we go over this amount. c_outSize = ctypes.c_int(10000) bufOutput = createBuffer(c_outSize.value) logger.debug("Calling ConvertString using %s.", self.config.convName) status = self.funcConvertString(c_convName, c_input, bufOutput, c_outSize) verifyStatusOk(status) sOutput = bufOutput.value if platform.system() != "Windows": sOutput = sOutput.decode("utf-8") logger.debug(repr(sOutput)) logger.debug(util.funcName('end')) return sOutput
def doConversions_writer(self): """For converting data in a Writer doc.""" logger.debug(util.funcName('begin')) ## Start progress bar progressBar = ProgressBar(self.unoObjs, "Converting...") progressBar.show() progressBar.updateBeginning() ## Find the text ranges textSearch = TextSearch(self.unoObjs, progressBar) textSearch.setConfig(self.config.searchConfig) try: if self.config.whichScope == 'WholeDoc': textSearch.scopeWholeDoc() elif self.config.whichScope == 'Selection': textSearch.scopeSelection() elif self.config.whichScope == 'ParaStyle': textSearch.scopeParaStyle() elif self.config.whichScope == 'CharStyle': textSearch.scopeCharStyle() elif self.config.whichScope == 'Font': textSearch.scopeFont() elif self.config.whichScope == 'SFMs': textSearch.scopeSFMs() else: raise exceptions.LogicError("Unexpected value %s", self.config.whichScope) except (exceptions.RangeError, exceptions.LogicError) as exc: self.msgbox.displayExc(exc) progressBar.close() return rangesFound = textSearch.getRanges() if progressBar.getPercent() < 40: progressBar.updatePercent(40) ## Do the changes to those ranges textChanger = TextChanger(self.unoObjs, progressBar, self.changerSettings) if self.secCall.config.convName: textChanger.setConverterCall(self.secCall) if self.config.whichTarget == "ParaStyle": textChanger.setStyleToChange("ParaStyleName", self.config.targetStyle) elif self.config.whichTarget == "CharStyle": textChanger.setStyleToChange("CharStyleName", self.config.targetStyle) elif self.config.whichTarget == "FontOnly": textChanger.setFontToChange(self.config.targetFont) numDataChanges, numStyleChanges = textChanger.doChanges( rangesFound, self.config.askEach) progressBar.updateFinishing() progressBar.close() ## Display results paragraphsFound = len(rangesFound) if paragraphsFound == 0: self.msgbox.display("Did not find scope of change.") elif numDataChanges == 0: if numStyleChanges == 0: self.msgbox.display("No changes.") else: plural = "" if numStyleChanges == 1 else "s" # add "s" if plural self.msgbox.display( "No changes, but modified style of %d paragraph%s.", numStyleChanges, plural) elif paragraphsFound == 1: plural = "" if numDataChanges == 1 else "s" # add "s" if plural self.msgbox.display("Made %d change%s.", numDataChanges, plural) else: plural = "" if numDataChanges == 1 else "s" # add "s" if plural self.msgbox.display("Found %d paragraphs and made %d change%s.", paragraphsFound, numDataChanges, plural)
def raise_unknown_action(action_command): raise exceptions.LogicError("Unknown action command '%s'", action_command)
def doConversions_draw(self): """For converting data in a Draw doc.""" logger.debug(util.funcName('begin')) ## Start progress bar progressBar = ProgressBar(self.unoObjs, "Converting...") progressBar.show() progressBar.updateBeginning() ## Find the text ranges shapeSearch = ShapeSearch(self.unoObjs, progressBar) shapeSearch.setConfig(self.config.searchConfig) try: if self.config.whichScope == 'WholeDoc': shapeSearch.scopeWholeDoc() elif self.config.whichScope == 'Selection': shapeSearch.scopeSelection() elif self.config.whichScope == 'Font': shapeSearch.scopeFont() else: raise exceptions.LogicError("Unexpected value %s", self.config.whichScope) except (exceptions.RangeError, exceptions.LogicError) as exc: self.msgbox.displayExc(exc) progressBar.close() return rangesFound = shapeSearch.getRanges() if progressBar.getPercent() < 40: progressBar.updatePercent(40) ## Do the changes to those ranges textChanger = TextChanger(self.unoObjs, progressBar, self.changerSettings) if self.secCall.config.convName: textChanger.setConverterCall(self.secCall) textChanger.setFontToChange(self.config.targetFont) # Apparently, if we change text in front of a range in Draw, # the range can move. So, start from the end and work backwards. rangesFound.reverse() numDataChanges, numStyleChanges = textChanger.doChanges( rangesFound, self.config.askEach) progressBar.updateFinishing() progressBar.close() ## Display results paragraphsFound = len(rangesFound) if paragraphsFound == 0: self.msgbox.display("Did not find scope of change.") elif numDataChanges == 0: if numStyleChanges == 0: self.msgbox.display("No changes.") else: plural = "" if numStyleChanges == 1 else "s" # add "s" if plural self.msgbox.display( "No changes, but modified style of %d paragraph%s.", numStyleChanges, plural) elif paragraphsFound == 1: plural = "" if numDataChanges == 1 else "s" # add "s" if plural self.msgbox.display("Made %d change%s.", numDataChanges, plural) else: plural = "" if numDataChanges == 1 else "s" # add "s" if plural self.msgbox.display("Found %d paragraphs and made %d change%s.", paragraphsFound, numDataChanges, plural)