Пример #1
0
 def setUp(self):
     logger.debug("DlgGramSettingsTestCase setUp()")
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     USERVAR_PREFIX = "LTg_"  # for LinguisticTools Grammar variables
     self.userVars = UserVars(
         USERVAR_PREFIX, self.unoObjs.document, logger)
     self.dlg = DlgGramSettings(self.unoObjs)
Пример #2
0
 def __init__(self, unoObjs):
     self.unoObjs = unoObjs
     self.userVars = UserVars(Prefix.ABBREVIATIONS, unoObjs.document,
                              logger)
     self.msgbox = MessageBox(unoObjs)
     self.abbrevList = abbreviations.AbbrevList(self.unoObjs, self.userVars)
     self.selectedIndex = -1  # position in abbrevList and listboxAbbrevs
     self.selectedAbbrev = None
     self.dlgCtrls = None
     self.evtHandler = None
     self.dlgClose = None
 def __init__(self, unoObjs):
     self.unoObjs = unoObjs
     self.userVars = UserVars(Prefix.PHONOLOGY, unoObjs.document, logger)
     self.msgbox = MessageBox(unoObjs)
     self.dlgCtrls = None
     self.evtHandler = None
     self.dlgClose = None
 def __init__(self, exType, unoObjs):
     self.exType = exType
     self.unoObjs = unoObjs
     logger.debug("DlgGrabExamples() %s", exType)
     self.msgbox = MessageBox(unoObjs)
     if exType == EXTYPE_PHONOLOGY:
         USERVAR_PREFIX = Prefix.PHONOLOGY
         self.titleText = theLocale.getText("Get Phonology Examples")
     else:
         USERVAR_PREFIX = Prefix.INTERLINEAR
         self.titleText = theLocale.getText("Get Interlinear Examples")
     self.userVars = UserVars(USERVAR_PREFIX, unoObjs.document, logger)
     self.app = lingexamples.ExServices(exType, unoObjs)
     self.dlgCtrls = None
     self.evtHandler = None
     self.dlgClose = None
     logger.debug("DlgGrabExamples init() finished")
Пример #5
0
 def __init__(self, unoObjs):
     self.unoObjs = unoObjs
     self.userVars = UserVars(Prefix.PHONOLOGY, unoObjs.document, logger)
     self.msgbox = MessageBox(unoObjs)
     self.app = lingexamples.ExServices(EXTYPE_PHONOLOGY, unoObjs)
     self.dlgCtrls = None
     self.evtHandler = None
     self.dlgClose = None
Пример #6
0
    def createComparisonDoc(self):
        """
        Create an empty writer doc.
        If the main file has a saved path, then only one comparison doc
        should be created.
        Returns True if a new document was created.
        """
        if not self.makeDoc:
            return
        if self.writerDoc is not None:
            if self.writerDoc.document is not None:
                ## Document is already open
                return

        varname = "ComparisonDocForFile"
        currentFilepath = None  # file path of main document
        url = self.mainDoc.document.getURL()
        if url:
            currentFilepath = uno.fileUrlToSystemPath(url)
            doclist = self.mainDoc.getOpenDocs(util.UnoObjs.DOCTYPE_WRITER)
            for docUnoObjs in doclist:
                logger.debug("Checking writer document for settings.")
                userVars = UserVars(self.VAR_PREFIX, docUnoObjs.document,
                                    logger)
                if not userVars.isEmpty(varname):
                    varFilepath = userVars.get(varname)
                    if varFilepath == currentFilepath:
                        logger.debug("found comparison doc")
                        self.writerDoc = docUnoObjs
                        return False
                    else:
                        logger.debug("%s != %s", varFilepath, currentFilepath)

        logger.debug("opening new document for comparison")
        newDoc = self.mainDoc.desktop.loadComponentFromURL(
            "private:factory/swriter", "_blank", 0, ())
        self.writerDoc = self.mainDoc.getDocObjs(newDoc)
        self.writerDoc.text.insertString(
            self.writerDoc.viewcursor,
            "Here are the changes that have been made.  " +
            "You may want to look through these changes, and make any " +
            "corrections in the main document.  " +
            "When finished checking, just close this window without saving.",
            0)
        self.writerDoc.text.insertControlCharacter(self.writerDoc.viewcursor,
                                                   PARAGRAPH_BREAK, 0)
        self.writerDoc.text.insertControlCharacter(self.writerDoc.viewcursor,
                                                   PARAGRAPH_BREAK, 0)
        if currentFilepath:
            userVars = UserVars(self.VAR_PREFIX, self.writerDoc.document,
                                logger)
            userVars.store(varname, currentFilepath)
        self.emptyDoc = True
        logger.debug(util.funcName('end'))
 def _harvestWords(self, fileItem):
     """Harvest words from the specified file."""
     fileType = fileItem.filetype  # short variable name
     logger.debug(util.funcName(args=fileType))
     words = []
     if fileType in WordsReader.supportedNames():
         reader = WordsReader(fileItem, self.unoObjs)
         words = reader.read()
     elif fileType in SFM_Reader.supportedNames():
         reader = SFM_Reader(fileItem, self.unoObjs)
         words = reader.read()
     elif fileType in InterlinReader.supportedNames():
         config = fileitemlist.InterlinInputSettings(self.userVars)
         config.showMorphLine2 = True
         config.separateMorphColumns = True
         lingExFileItem = fileitemlist.LingExFileItem(self.userVars)
         lingExFileItem.filepath = fileItem.filepath
         config.fileList.addItem(lingExFileItem)
         reader = InterlinReader(self.unoObjs, self.userVars, config)
         words = reader.grabWords(fileItem.thingsToGrab)
     elif fileType in PhonReader.supportedNames():
         config = lingex_structs.PhonInputSettings(self.userVars)
         config.filepath = fileItem.filepath
         config.phoneticWS = fileItem.writingSystem
         config.isLexemePhonetic = True
         phonUserVars = UserVars(
             Prefix.PHONOLOGY, self.unoObjs.document, logger)
         if phonUserVars.get("FlexLexeme") == 'phonemic':
             config.isLexemePhonetic = False
         reader = PhonReader(self.unoObjs, self.userVars, config)
         words = reader.grabWords(fileItem.thingsToGrab)
     elif fileType in DocReader.supportedNames():
         settings = TextSearchSettings()
         settings.load_userVars(self.userVars)
         reader = DocReader(fileItem, self.unoObjs, settings.matchesLimit)
         words = reader.read()
     elif fileType in CalcFileReader.supportedNames():
         reader = CalcFileReader(self.unoObjs)
         reader.setFileConfig(fileItem)
         words = reader.read()
     return words
Пример #8
0
    def loadValues(self, userVars, abbrevList):
        logger.debug(util.funcName('begin'))
        abbrevList.loadUserVars()
        dutil.fill_list_ctrl(self.listboxAbbrevs, abbrevList.getItemTextList())

        styleNames = styles.getListOfStyles("ParagraphStyles", self.unoObjs)
        displayNames = [dispName for dispName, name in styleNames]
        selectedValue = userVars.get("SearchParaStyle")
        if selectedValue == "":
            userVarsGrammar = UserVars(Prefix.GRAMMAR, self.unoObjs.document,
                                       logger)
            selectedValue = userVarsGrammar.get("StyleName_Gloss")
        dutil.fill_list_ctrl(self.cmbxSearchParaStyle, displayNames,
                             selectedValue)

        searchAffix = userVars.get("SearchAffix")
        if searchAffix == "suffix":
            self.optSearchSuffix.setState(True)
        elif searchAffix == "prefix":
            self.optSearchPrefix.setState(True)
        elif searchAffix == "any":
            self.optSearchAny.setState(True)

        varname = "MaxSearchLength"
        if userVars.isEmpty(varname):
            defaultCtrlText = "5"
            userVars.store(varname, defaultCtrlText)
            userVarVal = defaultCtrlText
        else:
            userVarVal = userVars.getInt(varname)
        self.txtMaxSearchLength.setText(userVarVal)

        if userVars.getInt("SearchUpperCase") == 1:
            self.chkSearchUpperCase.setState(True)

        self.addRemainingListeners()
        logger.debug(util.funcName('end'))
Пример #9
0
 def test2_empty_list(self):
     userVars = UserVars(Prefix.BULK_CONVERSION, self.unoObjs.document,
                         logger)
     itemlist = fileitemlist.FileItemList(fileitemlist.BulkFileItem,
                                          userVars)
     self.assertEqual(len(itemlist), 0)
     with self.assertRaises(IndexError):
         dummy = itemlist[0]
     self.assertEqual(itemlist.getItemTextList(), [])
     itemlist.sortItems()
     item = itemlist.makeNewItem()
     item.filepath = "a.txt"
     with self.assertRaises(exceptions.ChoiceProblem) as cm:
         itemlist.updateItem(0, item)
     self.assertEqual(cm.exception.msg, "Please select a file in the list.")
Пример #10
0
 def __init__(self, exType, unoObjs):
     self.exType = exType
     self.unoObjs = unoObjs
     if self.exType == EXTYPE_PHONOLOGY:
         USERVAR_PREFIX = Prefix.PHONOLOGY
     else:
         USERVAR_PREFIX = Prefix.GRAMMAR
     self.userVars = UserVars(
         USERVAR_PREFIX, unoObjs.document, logger)
     self.msgbox = MessageBox(unoObjs)
     self.settings = ExSettings(self.exType, self.unoObjs, self.userVars)
     self.operations = ExOperations(
         self.exType, self.unoObjs, self.userVars, self.settings)
     self.replacingRefs = True  # find and replace ref numbers
     logger.debug("ExGrabber init() finished")
Пример #11
0
 def test2_empty_list(self):
     USERVAR_PREFIX = 'LTbc_'  # LinguisticTools Bulk Conversion vars
     userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
     itemlist = fileitemlist.FileItemList(fileitemlist.BulkFileItem,
                                          userVars)
     self.assertEqual(len(itemlist), 0)
     with self.assertRaises(IndexError):
         dummy = itemlist[0]
     self.assertEqual(itemlist.getItemTextList(), [])
     itemlist.sortItems()
     item = itemlist.makeNewItem()
     item.filepath = "a.txt"
     with self.assertRaises(exceptions.ChoiceProblem) as cm:
         itemlist.updateItem(0, item)
     self.assertEqual(cm.exception.msg, "Please select a file in the list.")
def doTests(filepath, allRefNums, unoObjs):
    msgr.endl()
    msgr.write(DASHES)
    msgr.endl()
    msgr.write(filepath)
    msgr.endl()
    msgr.endl()
    userVars = UserVars("LTp_", unoObjs.document, logger)
    PhonologyStyles(unoObjs, userVars).createStyles()
    PhonologyTags(userVars).loadUserVars()
    resetUserVars(userVars)
    for exrefnum in allRefNums:
        for leftmost in ["phonemic", "phonetic"]:
            for showBrackets in ["1", "0"]:
                userVars.store("XML_filePath", filepath)
                userVars.store("Leftmost", leftmost)
                userVars.store("ShowBrackets", showBrackets)
                app = ExServices(EXTYPE_PHONOLOGY, unoObjs)
                app.insertByRefnum(exrefnum)
Пример #13
0
    def test4_uservars(self):
        USERVAR_PREFIX = 'LTbc_'  # LinguisticTools Bulk Conversion vars
        userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
        itemlist = fileitemlist.FileItemList(fileitemlist.BulkFileItem,
                                             userVars)
        add_new_item(itemlist, "a.txt")
        add_new_item(itemlist, "b.txt")
        add_new_item(itemlist, "c.txt")
        mock_store = mock.Mock()
        #mock_store.return_value = None
        with mock.patch.object(userVars, 'store', mock_store):
            itemlist.storeUserVars()
        expected = [
            mock.call("infile_count", "3"),
            mock.call("infile00_path", "a.txt"),
            mock.call("infile01_path", "b.txt"),
            mock.call("infile02_path", "c.txt"),
        ]
        logger.debug(mock_store.call_args_list)
        self.assertEqual(mock_store.call_args_list, expected)

        def mock_get_side_effect(varname):
            values = {
                "infile_count": "3",
                "infile00_path": "a.txt",
                "infile01_path": "b.txt",
                "infile02_path": "c.txt",
            }
            return values[varname]

        itemlist = fileitemlist.FileItemList(fileitemlist.BulkFileItem,
                                             userVars)
        mock_get = mock.Mock()
        mock_get.side_effect = mock_get_side_effect
        with mock.patch.object(userVars, 'get', mock_get):
            itemlist.loadUserVars()
        self.assertEqual(len(itemlist), 3)
        self.assertEqual(itemlist.getItemTextList(),
                         ["a.txt", "b.txt", "c.txt"])
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     self.exnumRanges = []
     USERVAR_PREFIX = "LTg_"  # for Grammar
     self.userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
     self.styles = styles.GrammarStyles(self.unoObjs, self.userVars)
     self.styles.createStyles()
     self.baseConfig = lingex_structs.InterlinOutputSettings(None)
     self.baseConfig.makeOuterTable = True
     self.baseConfig.methodFrames = True
     self.baseConfig.methodTables = False
     self.baseConfig.showOrthoTextLine = True
     self.baseConfig.showText = True
     self.baseConfig.showOrthoMorphLine = True
     self.baseConfig.showMorphemeBreaks = True
     self.baseConfig.showPartOfSpeech = True
     self.baseConfig.insertNumbering = True
     self.baseConfig.separateMorphColumns = True
     self.baseConfig.POS_aboveGloss = False
     self.baseConfig.freeTransInQuotes = True
     self.baseConfig.startingOuterRowHeight = 2
     self.baseConfig.tableBottomMargin = 0.5
     self.baseConfig.numberingColumnWidth = 5
Пример #15
0
 def test3_add_items(self):
     USERVAR_PREFIX = 'LTbc_'  # LinguisticTools Bulk Conversion vars
     userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
     itemlist = fileitemlist.FileItemList(fileitemlist.BulkFileItem,
                                          userVars)
     item = add_new_item(itemlist, "a.txt")
     self.assertEqual(len(itemlist), 1)
     itemdup = itemlist.makeNewItem()
     itemdup.filepath = item.filepath
     with self.assertRaises(exceptions.ChoiceProblem) as cm:
         itemlist.addItem(itemdup)
     self.assertEqual(cm.exception.msg, "File is already in the list.")
     self.assertEqual(len(itemlist), 1)
     itemlist.addItem(itemdup, allowDuplicates=True)
     self.assertEqual(len(itemlist), 2)
     add_new_item(itemlist, "b.txt")
     self.assertEqual(len(itemlist), 3)
     item = itemlist.makeNewItem()
     item.filepath = "a.txt"
     self.assertTrue(itemlist.alreadyContains(item))
     item = itemlist.makeNewItem()
     item.filepath = "b.txt"
     self.assertTrue(itemlist.alreadyContains(item, excludeItemPos=1))
     self.assertFalse(itemlist.alreadyContains(item, excludeItemPos=2))
     add_new_item(itemlist, "d.txt")
     add_new_item(itemlist, "c.txt")
     self.assertEqual(len(itemlist), 5)
     self.assertEqual(itemlist[-2].filepath, "c.txt")
     self.assertEqual(itemlist[-1].filepath, "d.txt")
     item = itemlist.makeNewItem()
     item.filepath = "e.txt"
     itemlist.updateItem(-1, item)
     self.assertEqual(len(itemlist), 5)
     self.assertEqual(itemlist[-1].filepath, "e.txt")
     itemlist.deleteItem(-1)
     self.assertEqual(len(itemlist), 4)
     self.assertEqual(itemlist[-1].filepath, "c.txt")
Пример #16
0
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     self.exnumRanges = []
     self.userVars = UserVars(Prefix.INTERLINEAR, self.unoObjs.document,
                              logger)
     self.styles = styles.InterlinStyles(self.unoObjs, self.userVars)
     self.config = lingex_structs.InterlinOutputSettings(None)
     self.config.makeOuterTable = True
     self.config.insertNumbering = False
     self.config.methodFrames = True
     self.config.startingOuterRowHeight = 2
     self.config.numberingColumnWidth = 5
     self.config.showOrthoTextLine = False
     self.config.showText = True
     self.config.showOrthoMorphLine = False
     self.config.showMorphemeBreaks = True
     self.config.showPartOfSpeech = True
     self.config.insertNumbering = True
     self.config.separateMorphColumns = True
     self.config.POS_aboveGloss = False
     self.config.tableBottomMargin = 0
     self.styles.parastyles.createInDoc("numP")
     self.styles.styleNames = {}
     self.styles.styleNames['numP'] = 'User Index 1'
    def _generateCalcList(self):
        """Generate list in calc."""
        listOutput = WordlistIO(self.unoObjs, self.columnOrder)
        listOutput.outputList(self.words, self.progressBar)
        msgbox = listOutput.getMsgbox()  # for Calc spreadsheet

        ## Copy some user vars for the Spelling component.

        userVarsSp = UserVars(
            Prefix.SPELLING, self.unoObjs.document, logger)
        varname = "HasSettings"
        userVarsSp.store(varname, self.userVars.get(varname))
        columnOrderSp = ColumnOrder(userVarsSp)
        columnOrderSp.sortOrder = self.columnOrder.sortOrder
        columnOrderSp.storeUserVars()

        # Initialize some user vars for Calc dialogs.  We do this here
        # to reset properly if a new word list is made.
        self.userVars.store("ConvSourceColumn",
                            self.columnOrder.getColLetter('colWord'))
        self.userVars.store("ConvTargetColumn",
                            self.columnOrder.getColLetter('colConv1'))
        userVarsSp.store("CurrentRow", "")
        msgbox.display("Made list of %d words.", len(self.words))
    def testUserVars(self):
        USERVAR_PREFIX = "Test_"  # variables for testing
        userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
        userVars.store("TestVar_1", "hamburger")
        result = userVars.get("TestVar_1")
        self.assertEqual(result, "hamburger")

        userVars.store("TestVar_2", "0")
        result = userVars.get("TestVar_2")
        self.assertEqual(result, "0")

        result = userVars.get("TestVar_3")
        self.assertEqual(result, "")

        userVars.store("TestVar_4", "something")
        userVars.store("TestVar_4", "")
        result = userVars.get("TestVar_4")
        self.assertEqual(result, "")

        userVars.delete("TestVar_1")
        result = userVars.get("TestVar_1")
        self.assertEqual(result, "")
        result = userVars.get("TestVar_2")
        self.assertEqual(result, "0")

        userVars.delete("TestVar_2")
        userVars.delete("TestVar_3")
        userVars.delete("TestVar_4")
        result = userVars.get("TestVar_2")
        self.assertEqual(result, "")
        result = userVars.get("TestVar_3")
        self.assertEqual(result, "")
Пример #19
0
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     self.userVars = UserVars(Prefix.BULK_CONVERSION, self.unoObjs.document,
                              logger)
     self.msgbox = MessageBox(self.unoObjs)
Пример #20
0
class DlgAbbreviations:
    """Main class for this dialog."""
    def __init__(self, unoObjs):
        self.unoObjs = unoObjs
        self.userVars = UserVars(Prefix.ABBREVIATIONS, unoObjs.document,
                                 logger)
        self.msgbox = MessageBox(unoObjs)
        self.abbrevList = abbreviations.AbbrevList(self.unoObjs, self.userVars)
        self.selectedIndex = -1  # position in abbrevList and listboxAbbrevs
        self.selectedAbbrev = None
        self.dlgCtrls = None
        self.evtHandler = None
        self.dlgClose = None

    def showDlg(self):
        logger.debug(util.funcName(obj=self))
        dlg = dutil.createDialog(self.unoObjs, _dlgdef)
        if not dlg:
            return
        ctrl_getter = dutil.ControlGetter(dlg)
        self.dlgClose = dlg.endExecute
        self.evtHandler = DlgEventHandler(self)
        self.dlgCtrls = DlgControls(self.unoObjs, ctrl_getter, self.evtHandler)
        logger.debug("Got controls.")

        self.dlgCtrls.loadValues(self.userVars, self.abbrevList)
        self.viewAbbrev(False)

        ## Display the dialog and then close it

        dlg.execute()
        self.storeResults()
        dlg.dispose()

    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 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 refreshList(self):
        dutil.fill_list_ctrl(self.dlgCtrls.listboxAbbrevs,
                             self.abbrevList.getItemTextList())

    def refreshListAndSelectItem(self, selItem):
        logger.debug(util.funcName('begin'))
        dutil.fill_list_ctrl(self.dlgCtrls.listboxAbbrevs,
                             self.abbrevList.getItemTextList(), str(selItem))
        try:
            self.selectedIndex = dutil.get_selected_index(
                self.dlgCtrls.listboxAbbrevs)
            logger.debug("self.selectedIndex %d", self.selectedIndex)
            self.viewAbbrev(False)
        except exceptions.ChoiceProblem:
            return
        logger.debug(util.funcName('end'))

    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'))

    def deleteAbbrev(self):
        logger.debug(util.funcName('begin'))
        try:
            self.abbrevList.deleteItem(self.selectedIndex)
        except exceptions.ChoiceProblem as exc:
            self.msgbox.displayExc(exc)
            return
        self.refreshList()

        ## Select the next item

        if self.dlgCtrls.listboxAbbrevs.getItemCount() > 0:
            dutil.select_index(self.dlgCtrls.listboxAbbrevs,
                               self.selectedIndex)
            self.viewAbbrev(False)
        else:
            ## The list is empty.  Clear the fields.
            logger.debug("Clearing fields.")
            self.dlgCtrls.txtAbbrev.setText("")
            self.dlgCtrls.txtFullName.setText("")
            self.dlgCtrls.chkForceOutput.setState(False)
            self.dlgCtrls.txtOccurrences.setText(0)
            self.selectedIndex = -1
        logger.debug(util.funcName('end'))

    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 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'))

    def insertList(self):
        logger.debug(util.funcName('begin'))

        ## Rescan and prepare for output

        abbrevSearch = search.AbbrevSearch(self.unoObjs)
        abbrevSearch.findOccurrences(self.abbrevList)
        self.refreshList()
        self.abbrevList.storeUserVars()
        abbrevStyles = styles.AbbrevStyles(self.unoObjs, self.userVars)
        abbrevStyles.createStyles()

        ## Output the list and close

        writerOutput = outputmanager.AbbrevManager(self.unoObjs, abbrevStyles)
        try:
            writerOutput.outputList(self.abbrevList)
        except exceptions.MessageError as exc:
            self.msgbox.displayExc(exc)
        self.dlgClose()
        logger.debug(util.funcName('end'))

    def findNext(self):
        logger.debug(util.funcName('begin'))

        ## Get search form results

        displayName = self.dlgCtrls.cmbxSearchParaStyle.getText()
        if not displayName:
            self.msgbox.display("Please select a paragraph style.")
            return
        searchConfig = search.AbbrevSearchSettings()
        searchConfig.searchParaStyle = displayName
        self.userVars.store("SearchParaStyle", displayName)

        searchConfig.searchAffix = "any"
        if self.dlgCtrls.optSearchSuffix.getState() == 1:  # checked
            searchConfig.searchAffix = "suffix"
        elif self.dlgCtrls.optSearchPrefix.getState() == 1:  # checked
            searchConfig.searchAffix = "prefix"
        self.userVars.store("SearchAffix", searchConfig.searchAffix)

        try:
            searchConfig.maxSearchLength = int(
                self.dlgCtrls.txtMaxSearchLength.getText())
        except ValueError:
            self.msgbox.display("Please enter a number for max length.")
            return
        self.userVars.store("MaxSearchLength", searchConfig.maxSearchLength)

        searchConfig.searchUpperCase = False
        chkValue = self.dlgCtrls.chkSearchUpperCase.getState()
        if chkValue == 1:
            searchConfig.searchUpperCase = True
        self.userVars.store("SearchUpperCase", str(chkValue))

        searchConfig.startFromBeginning = False
        if self.dlgCtrls.chkStartFromBeginning.getState() == 1:
            searchConfig.startFromBeginning = True
            self.dlgCtrls.chkStartFromBeginning.setState(False)

        searchConfig.searchDelimiters = self.userVars.get("SearchDelimiters")

        ## Search

        abbrevSearch = search.AbbrevSearch(self.unoObjs)
        while True:
            possibleAbbrevs = abbrevSearch.findNext(
                searchConfig, self.abbrevList.getUniqueList())
            if len(possibleAbbrevs) == 0:
                self.msgbox.display("No more possible abbreviations found.")
                return
            for possibleAbbrevText in possibleAbbrevs:
                if possibleAbbrevText.strip() == "":
                    continue
                result = self.msgbox.displayYesNoCancel(
                    "Add '%s' as a new abbreviation?", possibleAbbrevText)
                if result == "yes":
                    logger.debug("Adding abbreviation from search.")
                    newAbbrev = abbreviations.Abbrev()
                    newAbbrev.abbrevText = possibleAbbrevText
                    newAbbrev.occurrences = 1
                    try:
                        self.abbrevList.addItem(newAbbrev)
                        self.refreshListAndSelectItem(newAbbrev)
                    except exceptions.ChoiceProblem as exc:
                        self.msgbox.displayExc(exc)
                elif result == "cancel":
                    return
                elif result == "no":
                    ## continue
                    pass
        logger.debug(util.funcName('end'))

    def storeResults(self):
        logger.debug(util.funcName('begin'))
        self.updateAbbrev(False)
        self.abbrevList.storeUserVars()
        logger.debug(util.funcName('end'))
Пример #21
0
def doTests():
    unoObjs = testutil.unoObjsForCurrentDoc()
    userVars = UserVars("LTg_", unoObjs.document, logger)
    GrammarStyles(unoObjs, userVars).createStyles()
    GrammarTags(userVars).loadUserVars()
    resetUserVars(userVars)
    allRefNums = ["JPDN60.01", "Hunt06", "Hunt39"]
    #allRefNums = ["JPDN60.01"]
    #allRefNums = ["FW-1.1", "FW-1.2", "FW-2.1"]

    ## Just do one test

    #userVars.store('MakeOuterTable', "0")
    #userVars.store('Method', "tables")
    #userVars.store('InsertNumbering', "1")
    #doCall("JPDN60.01", unoObjs)
    #return

    ## Basic tests

    #numTests = len(allRefNums)
    #msgr.write(DASHES + "Basic Tests (" + str(numTests) + " tests)" + DASHES)
    #msgr.endl()
    #for exrefnum in allRefNums:
    #    doCall(exrefnum, unoObjs)
    #return  # do only basic tests

    ## Showing / hiding lines

    resetUserVars(userVars)
    numTests = 2 * 2 * 2 * 2 * 2 * 2 * 2 * len(allRefNums)
    msgr.endl()
    msgr.write(DASHES + "Showing / hiding lines (" + str(numTests) +
               " tests)" + DASHES)
    msgr.endl()
    for method in ["frames", "tables"]:
        msgr.write("Method = " + method)
        for separateMorphCols in ["0", "1"]:
            msgr.write("SeparateMorphColumns = " + separateMorphCols)
            for showText in ["1", "0"]:
                msgr.write("ShowText = " + showText)
                for showMorphBreaks in ["1", "0"]:
                    msgr.write("ShowMorphBreaks = " + showMorphBreaks)
                    for showOrtho in ["0", "1"]:
                        msgr.write("ShowOrthoTextLine = " + showOrtho)
                        for showPOS in ["1", "0"]:
                            msgr.write("ShowPartOfSpeech = " + showPOS)
                            for aboveGloss in ["0", "1"]:
                                if showPOS == 0 and aboveGloss != 0:
                                    continue
                                msgr.write("POS_AboveGloss = " + aboveGloss)
                                msgr.endl()
                                for exrefnum in allRefNums:
                                    userVars.store('Method', method)
                                    userVars.store('ShowText', showText)
                                    userVars.store('ShowMorphBreaks',
                                                   showMorphBreaks)
                                    userVars.store('ShowPartOfSpeech', showPOS)
                                    userVars.store('POS_AboveGloss',
                                                   aboveGloss)
                                    userVars.store("SeparateMorphColumns",
                                                   separateMorphCols)
                                    userVars.store('ShowOrthoTextLine',
                                                   showOrtho)
                                    doCall(exrefnum, unoObjs)

    ## Numbering

    resetUserVars(userVars)
    numTests = 2 * 2 * 2 * len(allRefNums) + 4 * len(allRefNums)
    msgr.endl()
    msgr.write(DASHES + "Numbering (" + str(numTests) + " tests)" + DASHES)
    msgr.endl()
    for makeOuterTable in ["1", "0"]:
        msgr.write("MakeOuterTable = " + makeOuterTable)
        for method in ["frames", "tables"]:
            msgr.write("Method = " + method)
            for insertNumbering in ["1", "0"]:
                msgr.write("InsertNumbering = " + insertNumbering)
                for separateMorphCols in ["0", "1"]:
                    msgr.write("SeparateMorphColumns = " + separateMorphCols)
                    msgr.endl()
                    for exrefnum in allRefNums:
                        userVars.store('MakeOuterTable', makeOuterTable)
                        userVars.store('Method', method)
                        userVars.store("SeparateMorphColumns",
                                       separateMorphCols)
                        userVars.store('InsertNumbering', insertNumbering)
                        doCall(exrefnum, unoObjs)
    resetUserVars(userVars)
    for method in ["frames", "tables"]:
        msgr.write("Method = " + method)
        for numberingColWidth in ["7", "10", "50"]:
            msgr.write("NumberingColWidth = " + numberingColWidth)
            msgr.endl()
            for exrefnum in allRefNums:
                userVars.store('Method', method)
                userVars.store('NumberingColWidth', numberingColWidth)
                doCall(exrefnum, unoObjs)
Пример #22
0
class PhonTestCase(unittest.TestCase):
    def setUp(self):
        self.unoObjs = testutil.unoObjsForCurrentDoc()
        USERVAR_PREFIX = "LTp_"  # LinguisticTools Phonology variables
        self.userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)

    def testPA(self):
        config = lingex_structs.PhonInputSettings(None)
        config.filepath = os.path.join(util.TESTDATA_FOLDER, "PAdata.paxml")
        config.phoneticWS = ""
        config.isLexemePhonetic = False
        xmlReader = phon_reader.PhonReader(self.unoObjs, self.userVars, config)
        self.assertEqual(xmlReader.get_filetype(), "paxml")

        exampleDict = xmlReader.read()
        self.assertTrue("JPDN23.1".lower() in exampleDict)
        phonEx = exampleDict["JPDN23.1".lower()]
        self.assertEqual(phonEx.refText, "JPDN23.1")
        self.assertEqual(phonEx.gloss, "unmarried cousin")
        self.assertNotEqual(phonEx.phonetic, "")
        self.assertNotEqual(phonEx.phonemic, "")

        self.assertTrue("JPDN37.4".lower() in exampleDict)
        phonEx = exampleDict["JPDN37.4".lower()]
        self.assertEqual(phonEx.refText, "JPDN37.4")
        self.assertEqual(phonEx.gloss, "")
        self.assertNotEqual(phonEx.phonetic, "")
        self.assertNotEqual(phonEx.phonemic, "")

        suggestions = xmlReader.getSuggestions()
        self.assertEqual(len(suggestions), 1)
        self.assertEqual(suggestions[0], "JPDN58.02")

    def testTbx1(self):
        config = lingex_structs.PhonInputSettings(None)
        config.filepath = os.path.join(util.TESTDATA_FOLDER,
                                       "TbxPhonCorpus.xml")
        config.phoneticWS = ""
        config.isLexemePhonetic = False
        xmlReader = phon_reader.PhonReader(self.unoObjs, self.userVars, config)
        self.assertEqual(xmlReader.get_filetype(), "xml")

        exampleDict = xmlReader.read()
        self.assertTrue("JPDN21.5".lower() in exampleDict)
        phonEx = exampleDict["JPDN21.5".lower()]
        self.assertEqual(phonEx.refText, "JPDN21.5")
        self.assertEqual(phonEx.gloss, "elder sister")
        self.assertNotEqual(phonEx.phonetic, "")
        self.assertNotEqual(phonEx.phonemic, "")

        self.assertTrue("EGAN03.37".lower() in exampleDict)
        phonEx = exampleDict["EGAN03.37".lower()]
        self.assertEqual(phonEx.refText, "EGAN03.37")
        self.assertEqual(phonEx.gloss, "five")
        self.assertNotEqual(phonEx.phonetic, "")
        self.assertEqual(phonEx.phonemic, "")

        suggestions = xmlReader.getSuggestions()
        self.assertEqual(len(suggestions), 1)
        self.assertEqual(suggestions[0], "JPDN37.6")

    def testTbx2(self):
        self.userVars.store("SFMarker_Gloss", "gl123")  # doesn't exist
        config = lingex_structs.PhonInputSettings(None)
        config.filepath = os.path.join(util.TESTDATA_FOLDER,
                                       "TbxPhonCorpus.xml")
        config.phoneticWS = ""
        config.isLexemePhonetic = False
        xmlReader = phon_reader.PhonReader(self.unoObjs, self.userVars, config)

        exampleDict = xmlReader.read()
        self.assertTrue("JPDN21.5".lower() in exampleDict)
        phonEx = exampleDict["JPDN21.5".lower()]
        self.assertEqual(phonEx.refText, "JPDN21.5")
        self.assertEqual(phonEx.gloss, "")
        self.assertNotEqual(phonEx.phonetic, "")
        self.assertNotEqual(phonEx.phonemic, "")

        suggestions = xmlReader.getSuggestions()
        self.assertEqual(len(suggestions), 1)
        self.assertEqual(suggestions[0], "JPDN37.6")

        self.userVars.store("SFMarker_Gloss", "")  # reset
Пример #23
0
class GramTestCase(unittest.TestCase):
    def setUp(self):
        self.unoObjs = testutil.unoObjsForCurrentDoc()
        USERVAR_PREFIX = "LTg_"  # Grammar
        self.userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)

    def testTbx(self):
        filepath = os.path.join(util.TESTDATA_FOLDER, "TbxIntHunt06.xml")
        fileItem = LingExFileItem(self.userVars)
        fileItem.filepath = filepath
        config = InterlinInputSettings(None)
        config.fileList = [fileItem]
        config.separateMorphColumns = True
        config.showMorphemeBreaks = True

        xmlReader = interlin_reader.InterlinReader(self.unoObjs, self.userVars,
                                                   config)
        exampleDict = xmlReader.read()
        self.assertEqual(xmlReader.get_filetype(filepath, xmlReader.dom),
                         "toolbox")

        self.assertTrue("Hunt06".lower() in exampleDict)
        gramEx = exampleDict["Hunt06".lower()]
        self.assertEqual(gramEx.refText, "Hunt06")
        self.assertEqual(
            gramEx.freeTrans,
            '"Not so.  Tell him, "We should take along the sister\'s ' +
            'husband and go to the hill for hunting.\'" Only when he hunts ' +
            'they will go.')
        self.assertEqual(len(gramEx.wordList), 13)

        word1 = gramEx.wordList[0]
        self.assertNotEqual(word1.text1, "")
        self.assertEqual(word1.text2, "")
        self.assertEqual(len(word1.morphList), 1)
        morph1 = word1.morphList[0]
        self.assertEqual(morph1.gloss, "like.that")
        self.assertEqual(morph1.pos, "adv")
        self.assertNotEqual(morph1.text1, "")
        self.assertEqual(morph1.text2, "")

        word4 = gramEx.wordList[3]
        self.assertEqual(len(word4.morphList), 2)
        morph1 = word4.morphList[0]
        self.assertEqual(morph1.gloss, "sister")
        self.assertEqual(morph1.pos, "n")
        self.assertNotEqual(morph1.text1, "")
        self.assertEqual(morph1.text2, "")

        suggestions = xmlReader.getSuggestions()
        self.assertEqual(len(suggestions), 1)
        self.assertEqual(suggestions[0], "Hunt01")

    def testTbxOrth(self):
        filepath = os.path.join(util.TESTDATA_FOLDER, "TbxIntHunt06.xml")
        fileItem = LingExFileItem(self.userVars)
        fileItem.filepath = filepath
        config = InterlinInputSettings(None)
        config.fileList = [fileItem]
        config.separateMorphColumns = True
        config.showMorphemeBreaks = True
        self.userVars.store("SFMarker_Word2", "or")
        self.userVars.store("SFMarker_Morpheme2", "mbtam")

        xmlReader = interlin_reader.InterlinReader(self.unoObjs, self.userVars,
                                                   config)
        exampleDict = xmlReader.read()
        gramEx = exampleDict["Hunt06".lower()]
        word1 = gramEx.wordList[0]
        self.assertNotEqual(word1.text2, "")
        morph1 = word1.morphList[0]
        self.assertNotEqual(morph1.text2, "")

        word4 = gramEx.wordList[3]
        self.assertNotEqual(word4.text2, "")
        morph1 = word4.morphList[0]
        self.assertNotEqual(morph1.text2, "")

        self.userVars.store("SFMarker_Word2", "")  # reset
        self.userVars.store("SFMarker_Morpheme2", "")  # reset

    def testFw(self):
        filepath = os.path.join(util.TESTDATA_FOLDER, "FWtextPigFox.xml")
        fileItem = LingExFileItem(self.userVars)
        fileItem.filepath = filepath
        fileItem.prefix = "Prefix-"
        config = InterlinInputSettings(None)
        config.fileList = [fileItem]
        config.separateMorphColumns = True
        config.showMorphemeBreaks = True

        xmlReader = interlin_reader.InterlinReader(self.unoObjs, self.userVars,
                                                   config)
        exampleDict = xmlReader.read()
        self.assertEqual(xmlReader.get_filetype(filepath, xmlReader.dom),
                         "fieldworks")

        self.assertTrue("Prefix-1.1".lower() in exampleDict)
        self.assertTrue("Prefix-1.2".lower() in exampleDict)
        self.assertTrue(not "Prefix-1.3".lower() in exampleDict)
        self.assertTrue("Prefix-2.1".lower() in exampleDict)
        self.assertTrue(not "Prefix-2.2".lower() in exampleDict)

        gramEx = exampleDict["Prefix-1.2".lower()]
        self.assertEqual(gramEx.refText, "Prefix-1.2")
        self.assertEqual(
            gramEx.freeTrans,
            u" \u200e\u200eIn his house he kept one pig and one fox ")
        self.assertEqual(len(gramEx.wordList), 7)

        word2 = gramEx.wordList[1]
        self.assertNotEqual(word2.text1, "")
        self.assertEqual(word2.text2, "")
        self.assertEqual(len(word2.morphList), 2)
        morph2 = word2.morphList[1]
        self.assertEqual(morph2.gloss, "LOC.in")
        self.assertEqual(morph2.pos, "case ")
        self.assertNotEqual(morph2.text1, "")
        self.assertEqual(morph2.text2, "")

    def testFlexText(self):
        filepath = os.path.join(util.TESTDATA_FOLDER, "Sena Int.flextext")
        fileItem = LingExFileItem(self.userVars)
        fileItem.filepath = filepath
        fileItem.prefix = "ABC "
        config = InterlinInputSettings(None)
        config.fileList = [fileItem]
        config.separateMorphColumns = True
        config.showMorphemeBreaks = True

        xmlReader = interlin_reader.InterlinReader(self.unoObjs, self.userVars,
                                                   config)
        exampleDict = xmlReader.read()
        self.assertEqual(xmlReader.get_filetype(filepath, xmlReader.dom),
                         "fieldworks")

        self.assertTrue("ABC 1.1".lower() in exampleDict)
        self.assertTrue("ABC 1.2".lower() in exampleDict)
        self.assertTrue(not "ABC 2.1".lower() in exampleDict)

        gramEx = exampleDict["ABC 1.2".lower()]
        self.assertEqual(gramEx.refText, "ABC 1.2")
        self.assertEqual(gramEx.freeTrans, "[1.2 ft]")
        self.assertEqual(len(gramEx.wordList), 4)

        word1 = gramEx.wordList[0]
        self.assertEqual(word1.text1, "Tonsene")

        word2 = gramEx.wordList[2]
        self.assertEqual(word2.text1, "yathu")
        self.assertEqual(word2.text2, "")
        morph2 = word2.morphList[1]
        self.assertEqual(morph2.text1, "a-")
        self.assertEqual(morph2.gloss, "assocpx")
        self.assertEqual(morph2.pos, "Poss:assocpx")
        self.assertEqual(morph2.text2, "")
Пример #24
0
class DlgGramSettingsTestCase(unittest.TestCase):
    def __init__(self, testCaseName):
        unittest.TestCase.__init__(self, testCaseName)
        testutil.modifyClass_showDlg(DlgGramSettings)

    @classmethod
    def setUpClass(cls):
        unoObjs = util.UnoObjs(
            testutil.stored.getContext(), loadDocObjs=False)
        testutil.blankWriterDoc(unoObjs)

    def setUp(self):
        logger.debug("DlgGramSettingsTestCase setUp()")
        self.unoObjs = testutil.unoObjsForCurrentDoc()
        USERVAR_PREFIX = "LTg_"  # for LinguisticTools Grammar variables
        self.userVars = UserVars(
            USERVAR_PREFIX, self.unoObjs.document, logger)
        self.dlg = DlgGramSettings(self.unoObjs)

    def test1_enableDisable(self):
        # For this test, dialog should be set to its default settings.
        def useDialog(dummy_innerSelf):
            pass
        DlgGramSettings.useDialog = useDialog
        self.dlg.showDlg()
        self.dlg.dlgCtrls.enableDisable()
        self.assertEqual(
            self.dlg.dlgCtrls.chkMorphsSeparate.getModel().Enabled, True)
        self.assertEqual(
            self.dlg.dlgCtrls.chkPOS_aboveGloss.getModel().Enabled, False)

    def test2_enableDisable(self):
        def useDialog(innerSelf):
            innerSelf.dlgCtrls.chkMorphLine1.setState(0)
            innerSelf.dlgCtrls.chkPOS_Line.setState(1)
            innerSelf.dlgCtrls.chkOuterTable.setState(0)
            innerSelf.dlgCtrls.optTables.setState(0)
        DlgGramSettings.useDialog = useDialog
        self.dlg.showDlg()
        self.dlg.dlgCtrls.enableDisable()
        self.assertEqual(self.dlg.dlgCtrls.chkMorphLine1.getState(), 0)
        self.assertEqual(
            self.dlg.dlgCtrls.chkMorphLine1.getModel().Enabled, True)
        self.assertEqual(
            self.dlg.dlgCtrls.chkMorphsSeparate.getModel().Enabled, False)
        self.assertEqual(
            self.dlg.dlgCtrls.chkPOS_aboveGloss.getModel().Enabled, True)
        self.assertEqual(
            self.dlg.dlgCtrls.txtNumColWidth.getModel().Enabled, False)
        self.assertEqual(
            self.dlg.dlgCtrls.lblNumColWidth.getModel().Enabled, False)

    def test3_enableDisable(self):
        def useDialog(innerSelf):
            innerSelf.dlgCtrls.chkMorphLine1.setState(1)
            innerSelf.dlgCtrls.chkPOS_Line.setState(0)
            innerSelf.dlgCtrls.chkOuterTable.setState(1)
            innerSelf.dlgCtrls.optTables.setState(1)
        DlgGramSettings.useDialog = useDialog
        self.dlg.showDlg()
        self.dlg.dlgCtrls.enableDisable()
        self.assertEqual(
            self.dlg.dlgCtrls.chkMorphsSeparate.getModel().Enabled, True)
        self.assertEqual(
            self.dlg.dlgCtrls.chkPOS_aboveGloss.getModel().Enabled, False)
        self.assertEqual(
            self.dlg.dlgCtrls.txtNumColWidth.getModel().Enabled, True)
        self.assertEqual(
            self.dlg.dlgCtrls.lblNumColWidth.getModel().Enabled, True)

    def test4_interlinLines(self):
        def useDialog(innerSelf):
            innerSelf.dlgCtrls.chkWordLine1.setState(0)
            innerSelf.dlgCtrls.chkWordLine2.setState(1)
            innerSelf.dlgCtrls.chkMorphLine1.setState(1)
            innerSelf.dlgCtrls.chkMorphLine2.setState(1)
            innerSelf.dlgCtrls.chkPOS_Line.setState(1)
            innerSelf.dlgCtrls.optTables.setState(1)
        DlgGramSettings.useDialog = useDialog
        self.dlg.showDlg()
        self.assertEqual(self.dlg.dlgCtrls.chkPOS_Line.getState(), 1)
        self.assertEqual(self.dlg.dlgCtrls.chkWordLine2.getState(), 1)
        self.assertEqual(self.dlg.dlgCtrls.optFrames.getState(), 0)
        self.assertEqual(self.dlg.dlgCtrls.optTables.getState(), 1)
        self.dlg.evtHandler.actionPerformed(MyActionEvent("OK"))
        self.dlg = None
        self.assertEqual(self.userVars.get("Method"), "tables")
        self.assertEqual(self.userVars.getInt("ShowPartOfSpeech"), 1)

    def test5_fileList(self):
        def useDialog(dummy_innerSelf):
            pass
        DlgGramSettings.useDialog = useDialog
        self.dlg.showDlg()
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getItemCount(), 0)
        filepath = os.path.join(util.TESTDATA_FOLDER, "testText1.xml")
        testutil.modifyFilePicker(filepath)
        self.dlg.evtHandler.actionPerformed(MyActionEvent("FileAdd"))
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getItemCount(), 1)
        self.assertEqual(len(self.dlg.fileItems), 1)

        filepath = os.path.join(util.TESTDATA_FOLDER, "testText2.xml")
        testutil.modifyFilePicker(filepath)
        self.dlg.evtHandler.actionPerformed(MyActionEvent("FileAdd"))
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getItemCount(), 2)
        self.assertEqual(len(self.dlg.fileItems), 2)
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getSelectedItemPos(), 1)

        filepath = os.path.join(util.TESTDATA_FOLDER, "a_testText3.xml")
        testutil.modifyFilePicker(filepath)
        self.dlg.evtHandler.actionPerformed(MyActionEvent("FileAdd"))
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getItemCount(), 3)
        self.assertEqual(len(self.dlg.fileItems), 3)
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getSelectedItemPos(), 0)

        self.dlg.dlgCtrls.listboxFiles.selectItemPos(1, True)    # testText1.xml
        self.dlg.dlgCtrls.txtPrefix.setText("PREF-")
        self.dlg.evtHandler.actionPerformed(MyActionEvent("FileUpdate"))
        fileItem = self.dlg.fileItems[1]
        self.assertEqual(fileItem.prefix, "PREF-")
        self.assertEqual(str(fileItem), "PREF-    testText1.xml")

        self.dlg.evtHandler.actionPerformed(MyActionEvent("FileRemove"))
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getItemCount(), 2)
        self.assertEqual(len(self.dlg.fileItems), 2)
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getSelectedItemPos(), 1)
        fileItem = self.dlg.fileItems[1]
        self.assertEqual(str(fileItem), "testText2.xml")

        self.dlg.evtHandler.actionPerformed(MyActionEvent("FileRemove"))
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getItemCount(), 1)
        self.assertEqual(len(self.dlg.fileItems), 1)
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getSelectedItemPos(), 0)
        fileItem = self.dlg.fileItems[0]
        self.assertEqual(str(fileItem), "a_testText3.xml")

        self.dlg.evtHandler.actionPerformed(MyActionEvent("FileRemove"))
        self.assertEqual(self.dlg.dlgCtrls.listboxFiles.getItemCount(), 0)
        self.assertEqual(len(self.dlg.fileItems), 0)

    def tearDown(self):
        if self.dlg:
            if hasattr(self.dlg, "dlgDispose"):
                testutil.do_dispose(self.dlg)
                self.dlg = None
Пример #25
0
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     USERVAR_PREFIX = "LTg_"  # Grammar
     self.userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     USERVAR_PREFIX = 'LTbc_'  # LinguisticTools Bulk Conversion vars
     self.userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
     self.msgbox = MessageBox(self.unoObjs)
Пример #27
0
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     USERVAR_PREFIX = "LTp_"  # LinguisticTools Phonology variables
     self.userVars = UserVars(USERVAR_PREFIX, self.unoObjs.document, logger)
Пример #28
0
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     self.userVars = UserVars(Prefix.INTERLINEAR, self.unoObjs.document,
                              logger)
Пример #29
0
class DlgGrabExamples:
    """Main class for this dialog."""

    def __init__(self, exType, unoObjs):
        self.exType = exType
        self.unoObjs = unoObjs
        logger.debug("DlgGrabExamples() %s", exType)
        self.msgbox = MessageBox(unoObjs)
        if exType == EXTYPE_PHONOLOGY:
            USERVAR_PREFIX = Prefix.PHONOLOGY
            self.titleText = theLocale.getText("Get Phonology Examples")
        else:
            USERVAR_PREFIX = Prefix.GRAMMAR
            self.titleText = theLocale.getText(
                "Get Interlinear Grammar Examples")
        self.userVars = UserVars(USERVAR_PREFIX, unoObjs.document, logger)
        self.app = lingexamples.ExServices(exType, unoObjs)
        self.dlgCtrls = None
        self.evtHandler = None
        self.dlgClose = None
        logger.debug("DlgGrabExamples init() finished")

    def showDlg(self):
        logger.debug(util.funcName(obj=self))
        dlg = dutil.createDialog(self.unoObjs, _dlgdef)
        if not dlg:
            return
        ctrl_getter = dutil.ControlGetter(dlg)
        self.evtHandler = DlgEventHandler(self, self.app)
        self.dlgCtrls = DlgControls(
            self.unoObjs, ctrl_getter, self.evtHandler)
        self.evtHandler.setCtrls(self.dlgCtrls)
        dlg.setTitle(self.titleText)
        self.dlgCtrls.loadValues(self.userVars)
        self.dlgCtrls.enableDisable(self.app, self.userVars)
        if self.dlgCtrls.single_refnum():
            self.dlgCtrls.comboRefnum.setFocus()
        else:
            self.dlgCtrls.listboxRefnum.setFocus()

        self.dlgClose = dlg.endExecute
        dlg.execute()

        if self.exType == EXTYPE_GRAMMAR:
            self.app.addExampleNumbers()
        dlg.dispose()

    def insertEx(self):
        logger.debug(util.funcName('begin'))
        if self.dlgCtrls.single_refnum():
            ref_texts = [self.dlgCtrls.comboRefnum.getText()]
        else:
            ref_texts = self.dlgCtrls.listboxRefnum.getSelectedItems()
        for ref_text in ref_texts:
            self.app.insertByRefnum(ref_text)
        self.userVars.store("EXREFNUM", ref_texts[0])

    def findNext(self):
        logger.debug(util.funcName('begin'))
        startFromBeginning = (
            self.dlgCtrls.chkStartFromBeginning.getState() == 1)
        found = self.app.findNext(startFromBeginning)
        if found:
            self.dlgCtrls.chkStartFromBeginning.setState(False)

    def replace(self):
        logger.debug(util.funcName('begin'))
        startFromBeginning = (
            self.dlgCtrls.chkStartFromBeginning.getState() == 1)
        found = self.app.replace(startFromBeginning)
        if found:
            self.dlgCtrls.chkStartFromBeginning.setState(False)

    def replaceAll(self):
        logger.debug(util.funcName('begin'))
        if self.app.isUpdatingExamples():
            result = self.msgbox.displayOkCancel(
                "Update all examples now?  "
                "It is recommended to save a copy of your document first.")
            if not result:
                return
            ## Refresh the window
            oContainerWindow = self.unoObjs.frame.getContainerWindow()
            oContainerWindow.setVisible(False)
            oContainerWindow.setVisible(True)

        self.dlgCtrls.chkStartFromBeginning.setState(True)
        self.app.replaceAll()
Пример #30
0
 def setUp(self):
     self.unoObjs = testutil.unoObjsForCurrentDoc()
     self.userVars = UserVars(Prefix.PHONOLOGY, self.unoObjs.document,
                              logger)