def getFormResults(self):
        """Reads form fields and gets settings."""
        logger.debug(util.funcName('begin'))

        charcompString = self.dlgCtrls.txtCharComp.getText()
        self.app.setCharCompFromInput(charcompString)
        self.userVars.store("CharComparison", charcompString)

        ## Font name and size

        fontName = self.dlgCtrls.comboFont.getText()
        if fontName == "(None)":
            fontName = None
        fontSize = FontSize(default=DEFAULT_FONT_SIZE)
        fontSize.loadCtrl(self.dlgCtrls.txtFontSize)
        self.userVars.store('Font', fontName)
        self.userVars.store('FontSize', fontSize.getString())
        self.userVars.store("OnlyKnownFonts",
                            str(self.dlgCtrls.chkKnownFonts.getState()))

        self.userVars.store("Script", self.dlgCtrls.comboScript.getText())

        ## Checkbox var list

        for chk in self.dlgCtrls.checkboxVarList:
            self.userVars.store(chk.varname, str(chk.ctrl.getState()))

        logger.debug(util.funcName('end'))
 def readContentFile(self, dom):
     """Read in content.xml."""
     logger.debug(util.funcName('begin'))
     # Unlike common styles, automatic styles are not visible to the user.
     auto_styles = dom.getElementsByTagName("office:automatic-styles")[0]
     if auto_styles:
         for style in auto_styles.childNodes:
             self.styleReader.read_text_props(style,
                                              BasicStyleType.AUTOMATIC)
     for paragraph in xmlutil.getElementsByTagNames(dom,
                                                    ["text:h", "text:p"]):
         xmlStyleName = paragraph.getAttribute("text:style-name")
         paraStyleItem = self.stylesDict.get(xmlStyleName,
                                             self.defaultStyleItem)
         para_texts = xmlutil.getElemTextList(paragraph)
         styleItemAppender = StyleItemAppender(self.data, paraStyleItem,
                                               self.scopeType)
         styleItemAppender.add_texts(para_texts)
         for span in paragraph.getElementsByTagName("text:span"):
             xmlStyleName = span.getAttribute("text:style-name")
             spanStyleItem = self.stylesDict.get(xmlStyleName,
                                                 paraStyleItem)
             span_texts = xmlutil.getElemTextList(span)
             styleItemAppender = StyleItemAppender(self.data, spanStyleItem,
                                                   self.scopeType)
             styleItemAppender.add_texts(span_texts)
     logger.debug(util.funcName('end'))
    def create(self, mainTextcursor):
        """Create outer table with example number in smaller left column and
        data in larger right column.
        Leaves viewcursor in smaller left column to the right of "()"
        """
        logger.debug(util.funcName('begin'))
        unoObjs = self.unoObjs  # shorthand variable name
        if self.config.makeOuterTable:
            outer_table = unoObjs.document.createInstance(
                "com.sun.star.text.TextTable")
            outer_table.initialize(1, 2)    # 1 row, 2 columns
            unoObjs.text.insertTextContent(mainTextcursor, outer_table, False)
            set_noTableSpacing(outer_table, self.unoObjs)
            outer_table.Split = False # Text Flow -> don't split pages
            outer_table.KeepTogether = True  # Text Flow -> keep w/next para
            rows = outer_table.getRows()
            self.top_row = rows.getByIndex(0)
            self.fixedSize()
            logger.debug("Created outer table %s.", outer_table.getName())
            self.insertNumberInTable(outer_table)

            # Get cursor in main column
            self.text = outer_table.getCellByPosition(1, 0) # second col
            self.cursor = self.text.createTextCursor()
        else:
            self.text = unoObjs.text
            self.cursor = unoObjs.text.createTextCursorByRange(
                mainTextcursor.getStart())
            if self.config.methodFrames:
                self.insertNumberInText(self.text, self.cursor)

        logger.debug(util.funcName('end'))
        return self.text, self.cursor
Example #4
0
    def storeAndClose(self):
        logger.debug(util.funcName('begin'))
        outSettings = lingex_structs.PhonOutputSettings(self.userVars)
        outSettings.showBrackets = bool(
            self.dlgCtrls.checkboxBrackets.getState())
        outSettings.phonemicLeftmost = bool(
            self.dlgCtrls.optionPhonemicFirst.getState())
        outSettings.storeUserVars()

        inSettings = lingex_structs.PhonInputSettings(self.userVars)
        inSettings.filepath = self.dlgCtrls.fileControl.getText()
        inSettings.phoneticWS = self.dlgCtrls.txtWritingSys.getText()
        inSettings.isLexemePhonetic = bool(
            self.dlgCtrls.optionLexemePht.getState())
        inSettings.storeUserVars()
        try:
            self.app.verifyRefnums()
        except (exceptions.DataNotFoundError,
                exceptions.DataInconsistentError) as exc:
            ok = self.msgbox.displayOkCancel(exc.msg, *exc.msg_args)
            if not ok:
                return

        PhonologyStyles(self.unoObjs, self.userVars).createStyles()
        PhonologyTags(self.userVars).loadUserVars()
        self.dlgClose()
        logger.debug(util.funcName('end'))
 def scopeWholeDocTraverse(self):
     """Enumerating often splits up words because new sections get created
     when a character is typed out of order.
     Here is a presumably slower, less accurate method that preserves whole
     words.
     Traverse the document with cursors to split into chunks,
     since just adding self.unoObjs.text whole gets slow after about 100
     pages.
     """
     logger.debug(util.funcName('begin'))
     oText = self.unoObjs.text
     cursor = oText.createTextCursorByRange(oText.getStart())
     cursor.collapseToStart()
     MANY_CHARACTERS = 16384  # perhaps 5 pages, but this varies greatly
     cursLeft = oText.createTextCursorByRange(cursor.getStart())
     cursLeft.collapseToStart()
     while cursor.goRight(MANY_CHARACTERS, True):
         while cursor.goRight(1, True):
             # Find a wordbreak
             if cursor.getString().endswith(" "):
                 break
         cursRight = oText.createTextCursorByRange(cursLeft.getStart())
         cursRight.collapseToStart()
         cursRight.gotoRange(cursor.getEnd(), True)
         self.ranger.addRange(cursRight)
         cursLeft.gotoRange(cursor.getEnd(), False)
         cursLeft.collapseToStart()
     cursRight = oText.createTextCursorByRange(cursLeft.getStart())
     cursRight.collapseToStart()
     cursRight.gotoRange(oText.getEnd(), True)
     self.ranger.addRange(cursRight)
     logger.debug(util.funcName('end'))
    def addRange(self, oSel):
        """Adds the selection to self.ranges
        oSels implements type com.sun.star.text.XTextRange.
        """
        logger.debug(util.funcName('begin'))
        #util.xray(oSel, self.unoObjs)
        txtRange = TxtRange()
        txtRange.sel = oSel  # contains the location range
        txtRange.inTable = False
        txtRange.inFrame = False
        txtRange.inSomething = False

        # These attributes are mentioned in TextRangeContentProperties
        try:
            if oSel.TextTable:
                txtRange.inTable = True
            if oSel.TextFrame:
                txtRange.inFrame = True
            if oSel.TextTable or oSel.TextFrame or oSel.TextField:
                txtRange.inSomething = True
        except AttributeError:
            # leave them all set to False
            pass

        self.ranges.append(txtRange)

        # -- For debugging only --
        # Note: oSel.getString() isn't as reliable as this method.
        #
        #cursor = oSel.getText().createTextCursorByRange(oSel)
        #logger.debug("range text = %s", cursor.getString())
        logger.debug(util.funcName('end'))
    def outputToColumn(self, colLetter, stringList, skipFirstRow=True):
        """Takes a list of strings."""
        logger.debug(util.funcName('begin'))

        chunkSize = 25  # make this value bigger or smaller for optimization
        for i1 in range(0, len(stringList), chunkSize):
            i2 = i1 + chunkSize - 1
            if i2 >= len(stringList):
                i2 = len(stringList) - 1

            data = []
            for i in range(i1, i2 + 1):
                data.append((stringList[i], ))
            if skipFirstRow:
                offset = 2  # start at second row
            else:
                offset = 1
            row1 = str(i1 + offset)
            row2 = str(i2 + offset)
            rangeName = colLetter + row1 + ":" + colLetter + row2
            logger.debug(rangeName)
            logger.debug(repr(data))
            try:
                oRange = self.unoObjs.sheet.getCellRangeByName(rangeName)
                oRange.setDataArray(tuple(data))
            except RuntimeException:
                raise exceptions.DocAccessError()
        logger.debug(util.funcName('end'))
Example #8
0
    def viewAbbrev(self, checkForUpdates):
        """
        Fill the form with values of the selected abbreviation.
        :param checkForUpdates: set to true to update current item if needed
        """
        logger.debug(util.funcName('begin'))
        if checkForUpdates:
            newSelectedItem = self.dlgCtrls.listboxAbbrevs.getSelectedItem()
            logger.debug("newSelectedItem '%s'", newSelectedItem)
            self.updateAbbrev(False)
            if newSelectedItem:
                # Select the new item again,
                # since it may have been deselected while refreshing the list.
                self.dlgCtrls.listboxAbbrevs.selectItem(newSelectedItem, True)
        try:
            self.selectedIndex = dutil.get_selected_index(
                self.dlgCtrls.listboxAbbrevs)
            logger.debug("self.selectedIndex %d", self.selectedIndex)
        except exceptions.ChoiceProblem:
            return
        abbr = self.abbrevList[self.selectedIndex]
        logger.debug("Abbrev %s", abbr.abbrevText)

        self.dlgCtrls.txtAbbrev.setText(abbr.abbrevText)
        self.dlgCtrls.txtFullName.setText(abbr.fullName)
        if abbr.forceOutput:
            self.dlgCtrls.chkForceOutput.setState(True)
        else:
            self.dlgCtrls.chkForceOutput.setState(False)
        self.dlgCtrls.txtOccurrences.setText(abbr.occurrences)
        logger.debug(util.funcName('end'))
 def getColumnStringListByLen(self, colLetter, skipFirstRow, listLen):
     """Returns a list of length listLen of strings.
     Cells may be empty.
     """
     logger.debug(util.funcName('begin'))
     row1 = 1
     if skipFirstRow:
         row1 = 2
     row2 = row1 + listLen - 1
     if row2 < row1:
         logger.debug("Range too small to contain data.")
         return []
     rangeName = "%s%d:%s%d" % (colLetter, row1, colLetter, row2)
     logger.debug(rangeName)
     try:
         oRange = self.unoObjs.sheet.getCellRangeByName(rangeName)
         rowTuples = oRange.getDataArray()
     except RuntimeException:
         raise exceptions.DocAccessError()
     if len(rowTuples) == 0:
         logger.debug("Could not get data.")
         return []
     columnTuples = list(zip(*rowTuples))  # arrange the data by columns
     logger.debug(util.funcName('end'))
     return list(columnTuples[0])
Example #10
0
 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'))
Example #11
0
 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 findNext(self, searchConfig, currentAbbrevList):
        """
        Look for possible abbreviations.
        Search by regular expression on a certain paragraph style.
        Param searchConfig should be of type AbbrevSearchSettings.
        """
        logger.debug(util.funcName('begin'))
        self.searchConfig = searchConfig
        self.currentAbbrevList = currentAbbrevList
        search = self.unoObjs.document.createSearchDescriptor()
        search.SearchStyles = True
        search.SearchString = searchConfig.searchParaStyle

        if searchConfig.startFromBeginning:
            logger.debug("Start from beginning")
            self.selectionFound = self.unoObjs.document.findFirst(search)
            searchConfig.startFromBeginning = False
        elif self.selectionFound:
            logger.debug("Start from previous match")
            self.selectionFound = self.unoObjs.document.findNext(
                self.selectionFound.getEnd(), search)
        else:
            logger.debug("Start from current loc")
            self.selectionFound = self.unoObjs.document.findNext(
                self.unoObjs.viewcursor.getEnd(), search)
        while self.selectionFound:
            self.possibilities = []
            self._checkString(self.selectionFound.String)
            if self.possibilities:
                return self.possibilities
            self.selectionFound = self.unoObjs.document.findNext(
                self.selectionFound.getEnd(), search)
        logger.debug(util.funcName('end'))
        return []
Example #13
0
    def createInDoc(self, styleKey, fontDef=None, color=None, margins=None,
                    modify=False):
        """
        Create a style with the attributes specified.

        :param modify: true to modify attributes of an existing style
        :returns: newly created style, or None if style already exists
        """
        createdObj = None
        styleName = self.styleNames[styleKey]
        if styleKey in self:
            if modify:
                logger.debug(
                    "Modifying %s style '%s'", self.familyName, styleName)
                styleObj = self.styleObjs.getByName(styleName)
            else:
                logger.debug(util.funcName('return'))
                return None
        else:
            logger.debug(
                "Creating %s style '%s'", self.familyName, styleName)
            styleObj = self.unoObjs.document.createInstance(
                "com.sun.star.style.%sStyle" % self.familyName)
            self.styleObjs.insertByName(styleName, styleObj)
            createdObj = styleObj
        if self.familyName == 'Frame':
            setFrameAttrs(styleObj, margins)
        else:
            setFontAttrs(styleObj, fontDef, color)
        logger.debug(util.funcName('end'))
        return createdObj
Example #14
0
 def updateFile(self, selectNewItem):
     logger.debug(util.funcName('begin'))
     if not 0 <= self.selectedIndex < len(self.fileItems):
         if selectNewItem:
             self.msgbox.displayExc(self.fileItems.noItemSelected())
         else:
             logger.debug(util.funcName('return'))
         return
     newItem = fileitemlist.LingExFileItem(self.userVars)
     newItem.filepath = self.fileItems[self.selectedIndex].filepath
     newItem.setPrefixNoSpaces(self.dlgCtrls.txtPrefix.getText())
     newItem.use_segnum = bool(self.dlgCtrls.chkUseSegnum.getState())
     oldItem = self.fileItems[self.selectedIndex]
     if oldItem:
         if (newItem.filepath == oldItem.filepath
                 and newItem.prefix == oldItem.prefix
                 and newItem.use_segnum == oldItem.use_segnum):
             logger.debug(
                 util.funcName('return',
                               args="%s same as %s" % (newItem, oldItem)))
             return
         logger.debug("%s not same as %s", newItem, oldItem)
         try:
             self.fileItems.updateItem(self.selectedIndex, newItem)
         except exceptions.ChoiceProblem as exc:
             self.msgbox.displayExc(exc)
             return
     if selectNewItem:
         self.refreshListAndSelectItem(newItem)
     else:
         self.refreshList()
     logger.debug(util.funcName('end'))
    def showDlg(self):
        logger.debug(util.funcName('begin', obj=self))
        dlg = dutil.createDialog(self.unoObjs, _dlgdef)
        if not dlg:
            return
        ctrl_getter = dutil.ControlGetter(dlg)
        self.evtHandler = DlgEventHandler(self)
        self.dlgCtrls = DlgControls(self.unoObjs, ctrl_getter, self.evtHandler)
        self.evtHandler.setCtrls(self.dlgCtrls)

        styleNames = styles.getListOfStyles('ParagraphStyles', self.unoObjs)
        self.paraStyleNames = dict(styleNames)
        paraStyleDispNames = tuple([dispName for dispName, name in styleNames])

        styleNames = styles.getListOfStyles('CharacterStyles', self.unoObjs)
        self.charStyleNames = dict(styleNames)
        charStyleDispNames = tuple([dispName for dispName, name in styleNames])
        self.dlgCtrls.loadValues(paraStyleDispNames,
                                 charStyleDispNames, self.fileItem,
                                 self.getTypesTuple(), self.fileTypeDict,
                                 self.fillFieldList)
        self.dlgCtrls.enableDisable(self.filetype)

        self.dlgClose = dlg.endExecute
        self.dlgDispose = dlg.dispose
        logger.debug(util.funcName('end', obj=self))
        dlg.execute()
Example #16
0
 def showNextQuestion(self):
     logger.debug(util.funcName('begin'))
     nextQuestion = self.questions.getNextQuestion()
     self.dlgCtrls.txtQuestion.setText(nextQuestion)
     self.stats.newQuestion()
     self.prepareAnswerBox()
     logger.debug(util.funcName('end'))
Example #17
0
    def makeChanges(self, fontChanges):
        logger.debug(util.funcName('begin'))
        if not self.odt_reader:
            logger.warning("No odt_reader.")
        changer = OdtChanger(self.odt_reader, fontChanges)
        numChanges = changer.makeChanges()
        if numChanges == 0:
            return numChanges

        ## Zip the XML files back into a single ODT file

        resultFilepath = ""
        MAX_TRIES = 1000
        for fileNum in range(1, MAX_TRIES):
            basename, extension = os.path.splitext(
                os.path.basename(self.fileconfig.filepath))
            filename = "%s_%03d%s" % (basename, fileNum, extension)
            resultCandidate = os.path.join(self.outdir, filename)
            if not os.path.exists(resultCandidate):
                resultFilepath = resultCandidate
                break
        if not resultFilepath:
            self.msgbox.display("Too many files named like %s.",
                                resultCandidate)
            return 0
        logger.debug("Writing to file %s", resultFilepath)
        zipper = zipfile.ZipFile(resultFilepath, 'w')
        for abs_path, rel_path in paths_to_all_files(self.tempDir):
            zipper.write(abs_path, rel_path)
        zipper.close()
        logger.debug(util.funcName('end'))
        return numChanges
Example #18
0
 def read(self):
     """Read in the data.
     Returns list with elements of type FontItem.
     Tries to overcome several zipfile reading exceptions that may occur.
     """
     logger.debug(util.funcName('begin'))
     try:
         self.make_temp_dir()
     except exceptions.FileAccessError as exc:
         self.msgbox.displayExc(exc)
         return list()
     data = None
     self.progressRange_partNum = 0
     try:
         data = self.readFile()
     except zipfile.BadZipFile as exc:
         logger.warning(exc)
         self.convert_to_odt()
         data = self.readFile()
     except exceptions.FileAccessError as exc:
         if exc.msg.startswith("Error reading file"):
             logger.warning(exc)
             self.convert_to_odt()
             data = self.readFile()
         else:
             raise exc
     except FileNotFoundError as exc:
         raise exceptions.FileAccessError(str(exc))
     #self.cleanup()
     logger.debug(util.funcName('end'))
     return data
 def addRangesForCursor(self, oSel):
     """If there is different formatting, then we handle each string
     separately that is formatted differently.
     """
     logger.debug(util.funcName('begin'))
     if not self.checkForFormatting:
         self.addRange(oSel)
         logger.debug(util.funcName('return'))
         return
     simpleTextRanges = []  # ranges that have only one formatting
     self.traveler = Traveler(self.unoObjs)
     self.traveler.createCursors(oSel)
     self.chunker = Chunker()
     self.selFormatting = None
     while True:
         #logger.debug(
         #   "moreToGo %s", self.traveler.rangeRight.compareVC())
         if (self.traveler.rangeRight.compareVC() == 0
                 or self._formattingChanges() or self.chunker.tooBig()):
             self.addCurrentRange(simpleTextRanges)
             self.selFormatting = None
         if self.traveler.rangeRight.compareVC() < 0:
             if self.moveRight():
                 self.chunker.stringLonger()
                 continue
         # We've reached the end of the string.
         break
     logger.debug(util.funcName('end'))
     self.addRangeList(simpleTextRanges)
Example #20
0
 def changeAllCaps(self):
     logger.debug(util.funcName('begin'))
     self.abbrevList.changeAllCaps()
     self.refreshList()
     dutil.select_index(self.dlgCtrls.listboxAbbrevs, self.selectedIndex)
     self.viewAbbrev(False)
     logger.debug(util.funcName('end'))
    def pickConverter(self):
        """Let the user pick a converter."""
        logger.debug(util.funcName('begin'))
        self.loadLibrary()
        if not self.loaded:
            return
        if not self.funcIsEcInstalled():
            raise exceptions.FileAccessError(
                "EncConverters does not seem to be installed properly.")
        bufConverterName = createBuffer(1024)
        c_forward = ctypes.c_bool(False)
        c_normForm = ctypes.c_ushort(0)
        logger.debug("Calling funcSelectConverter.")
        status = self.funcSelectConverter(bufConverterName,
                                          ctypes.byref(c_forward),
                                          ctypes.byref(c_normForm))
        if status == -1:
            logger.debug(
                "EncConverters returned %d.  User probably pressed Cancel.",
                status)
            return
        verifyStatusOk(status)

        logger.debug("Converter name was %r", bufConverterName.value)
        self.config = ConverterSettings(self.config.userVars)
        if platform.system() == "Windows":
            self.config.convName = bufConverterName.value
        else:
            self.config.convName = bufConverterName.value.decode("utf-8")
        self.config.forward = c_forward.value
        self.config.normForm = c_normForm.value
        logger.debug(util.funcName('end'))
Example #22
0
 def updateAbbrev(self, selectNewItem):
     """
     Update abbrev attributes from dialog fields if changed.
     :param selectNewItem: set to True to select item when refreshing list
     """
     logger.debug(util.funcName('begin'))
     if not 0 <= self.selectedIndex < len(self.abbrevList):
         if selectNewItem:
             self.msgbox.displayExc(self.abbrevList.noItemSelected())
         return
     newAbbrev = abbreviations.Abbrev()
     newAbbrev.abbrevText = self.dlgCtrls.txtAbbrev.getText()
     if not newAbbrev.abbrevText:
         return
     newAbbrev.fullName = self.dlgCtrls.txtFullName.getText()
     if self.dlgCtrls.chkForceOutput.getState() == 1:  # checked
         newAbbrev.forceOutput = True
     oldAbbrev = self.abbrevList[self.selectedIndex]
     if oldAbbrev:
         if newAbbrev.sameAs(oldAbbrev):
             return
         logger.debug("%r not sameAs %r", newAbbrev, oldAbbrev)
         if newAbbrev.abbrevText == oldAbbrev.abbrevText:
             newAbbrev.occurrences = oldAbbrev.occurrences
         try:
             self.abbrevList.updateItem(self.selectedIndex, newAbbrev)
         except exceptions.ChoiceProblem as exc:
             self.msgbox.displayExc(exc)
             return
     if selectNewItem:
         self.refreshListAndSelectItem(newAbbrev)
     else:
         self.refreshList()
     logger.debug(util.funcName('end'))
 def make(self):
     logger.debug(util.funcName('begin'))
     progressBar = ProgressBar(self.unoObjs, "Getting data...")
     progressBar.show()
     progressBar.updateBeginning()
     try:
         columnOrder = ColumnOrder(self.userVars)
         columnOrder.loadUserVars()
         changeList = getChangeList(self.unoObjs, columnOrder)
         progressBar.updateFinishing()
     except exceptions.DocAccessError:
         self.msgbox.display("Error reading spreadsheet.")
     progressBar.close()
     progressBar = ProgressBar(self.unoObjs, "Saving file...")
     progressBar.show()
     progressBar.updatePercent(50)
     if self.exportType == "ReplacementCCT":
         outputter = CCT_Writer(self.filepath)
         outputter.writeSimpleReplacements(changeList)
     elif self.exportType == "SFM_CCT":
         outputter = CCT_Writer(self.filepath)
         outputter.writeComplete(changeList, self.sfMarkers)
     elif self.exportType == "XSLT":
         outputter = XSLT_Writer(self.filepath)
         outputter.write(changeList, self.xpathExprs, self.matchPartial)
     progressBar.updateFinishing()
     progressBar.close()
     logger.debug(util.funcName('end'))
def fill_list_ctrl(listCtrl, values, selectedValue=""):
    """
    Fill a control with the given values.

    :param listCtrl: the UNO control, either a listbox or combobox
    :param values: values to fill the listbox, either list or tuple
    :param selectedValue: select this value when filled

    The UNO methods selectItem(), selectItemPos() and setText() will call
    any listening event handlers before this function is finished,
    so calling this function from within an event handler for the same
    control can cause infinite recursion.
    (Actually it's not infinite, because UNO seems to limit the
    maximum recursion to a depth of about 20).
    """
    logger.debug("%s selectedValue=%s", util.funcName('begin'), selectedValue)
    listCtrl.removeItems(0, listCtrl.getItemCount())
    listCtrl.addItems(tuple(values), 0)
    if listCtrl.supportsService("com.sun.star.awt.UnoControlListBox"):
        if selectedValue and selectedValue in values:
            listCtrl.selectItem(selectedValue, True)
        else:
            listCtrl.selectItemPos(0, True)
    elif listCtrl.supportsService("com.sun.star.awt.UnoControlComboBox"):
        if selectedValue and selectedValue in values:
            listCtrl.setText(selectedValue)
        else:
            listCtrl.setText("")
    logger.debug(util.funcName('end'))
    def getFormResults(self):
        """Reads form fields and sets self.config and self.converter.
        In setAndVerifyConfig() in app layer, the settings will be checked for
        inconsistencies.
        """
        logger.debug(util.funcName('begin'))

        ## Converter

        self.converter = ConverterSettings(self.userVars)
        self.converter.loadUserVars()  # for normForm
        self.converter.convName = self.dlgCtrls.txtConverterName.getText()
        self.converter.forward = (
            self.dlgCtrls.chkDirectionReverse.getState() == 0)
        self.converter.storeUserVars()

        ## Radio buttons and the corresponding combo box selection

        self.config = ConversionSettings()
        searchConfig = self.config.searchConfig  # shorthand name
        self.config.whichScope = dutil.whichSelected(
            self.dlgCtrls.radiosWhichScope)
        self.userVars.store('WhichScope', self.config.whichScope)
        if self.config.whichScope == 'Font':
            searchConfig.fontName = self.dlgCtrls.comboScopeFont.getText()
            searchConfig.fontType = dutil.whichSelected(
                self.dlgCtrls.radiosScopeFont)
            self.userVars.store('ScopeFontType', searchConfig.fontType)
        searchConfig.load_userVars(self.userVars)

        self.config.whichTarget = dutil.whichSelected(
            self.dlgCtrls.radiosWhichTarget)
        self.userVars.store('WhichTarget', self.config.whichTarget)

        ## Target font

        targetFontName = self.dlgCtrls.listTargetFont.getSelectedItem()
        if targetFontName == "(None)":
            targetFontName = None
        targetFontSize = FontSize()
        targetFontSize.loadCtrl(self.dlgCtrls.txtFontSize)
        if self.config.whichTarget == 'Font':
            self.userVars.store('TargetFontName', targetFontName)
            self.userVars.store('TargetFontSize', targetFontSize.getString())
        targetFontType = dutil.whichSelected(
            self.dlgCtrls.radiosTargetFont)
        self.userVars.store('TargetFontType', targetFontType)
        self.config.targetFont = styles.FontDefStruct(
            targetFontName, targetFontType, targetFontSize)

        self.config.askEach = (self.dlgCtrls.chkVerify.getState() == 1)

        ## Save selections for next time

        for combo in self.dlgCtrls.combos:
            self.userVars.store(combo.varname, combo.ctrl.getText())
        self.userVars.store('AskEachChange',
                            str(self.dlgCtrls.chkVerify.getState()))
        logger.debug(util.funcName('end'))
Example #26
0
 def addAbbrev(self):
     logger.debug(util.funcName('begin'))
     newAbbrev = abbreviations.Abbrev()
     newAbbrev.abbrevText = "---"
     newAbbrev.fullName = ""
     self.abbrevList.addItem(newAbbrev, allowDuplicates=True)
     self.refreshListAndSelectItem(newAbbrev)
     logger.debug(util.funcName('end'))
Example #27
0
 def rescan(self):
     logger.debug(util.funcName('begin'))
     abbrevSearch = search.AbbrevSearch(self.unoObjs)
     abbrevSearch.findOccurrences(self.abbrevList)
     self.refreshList()
     dutil.select_index(self.dlgCtrls.listboxAbbrevs, self.selectedIndex)
     self.viewAbbrev(False)
     logger.debug(util.funcName('end'))
Example #28
0
    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'))
Example #29
0
 def closeAndRun(self):
     logger.debug(util.funcName('begin'))
     try:
         self.settings = self.dlgCtrls.getFormResults()
         self.runOnClose = True
         self.dlgClose()
     except exceptions.ChoiceProblem as exc:
         self.msgbox.displayExc(exc)
     logger.debug(util.funcName('end'))
Example #30
0
    def resizeNumberingCol(self, colWidthText, prevColWidth):
        """
        Resize the width of the column that contains example numbering.
        Size is an integer percentage of the page width.
        @param string colWidthText
        @param int    prevColWidth
        throws exceptions.ChoiceProblem

        It would be nice if there were such a thing as table styles.
        Then this function would presumably not be needed.
        """
        logger.debug(util.funcName('begin'))
        if colWidthText == "":
            raise exceptions.ChoiceProblem(
                "Please enter a value for column width.")
        try:
            newVal = int(colWidthText)
        except:
            raise exceptions.ChoiceProblem("Column width is not a number.")
        if newVal == prevColWidth:
            logger.debug("No need to change.")
            return
        if newVal > 50:     # more than 50% is unreasonable
            raise exceptions.ChoiceProblem(
                "Value %d for column width is too high.", newVal)
        elif newVal <= 0:
            raise exceptions.ChoiceProblem(
                "Value for column width must be more than zero.")

        PERCENT_TO_SEP = 100  # Separator width 10,000 is 100%.
                               # The user enters a number like 5 meaning 5%.
                               # So 5 * 100 would be 500 which is 5% of 10,000
        MARGIN_OF_ERROR = 2
        prevVal = prevColWidth * PERCENT_TO_SEP
        newVal = newVal * PERCENT_TO_SEP
        tables = self.unoObjs.document.getTextTables()
        logger.debug(
            "looping through %d tables.  prevVal = %d",
            tables.getCount(), prevVal)
        for table in iteruno.byIndex(tables):
            separators = table.getPropertyValue("TableColumnSeparators")
            if separators is None:
                logger.debug(
                    "No separators set for table %s", table.getName())
                continue
            sep0Pos = separators[0].Position
            logger.debug(
                "table %s separator is %d", table.getName(), sep0Pos)
            if (sep0Pos > prevVal - MARGIN_OF_ERROR and
                    sep0Pos < prevVal + MARGIN_OF_ERROR):
                separators[0].Position = newVal
                table.TableColumnSeparators = separators
                logger.debug("changed to %d", newVal)

        self.userVars.store("NumberingColWidth", str(newVal // PERCENT_TO_SEP))
        logger.debug(util.funcName('end'))