Search in sources :

Example 1 with NearString

use of org.omegat.core.matching.NearString in project omegat by omegat-org.

the class FindMatchesThread method search.

@Override
protected List<NearString> search() throws Exception {
    if (!project.isProjectLoaded()) {
        // project is closed
        return Collections.emptyList();
    }
    if (project.getSourceTokenizer() == null) {
        return null;
    }
    long before = System.currentTimeMillis();
    try {
        FindMatches finder = new FindMatches(project, OConsts.MAX_NEAR_STRINGS, true, false);
        List<NearString> result = finder.search(processedEntry.getSrcText(), true, true, this::isEntryChanged);
        LOGGER.finer(() -> "Time for find matches: " + (System.currentTimeMillis() - before));
        return result;
    } catch (FindMatches.StoppedException ex) {
        throw new EntryChangedException();
    }
}
Also used : FindMatches(org.omegat.core.statistics.FindMatches) NearString(org.omegat.core.matching.NearString)

Example 2 with NearString

use of org.omegat.core.matching.NearString in project omegat by omegat-org.

the class MatchesTextArea method populateContextMenu.

private void populateContextMenu(JPopupMenu popup, final int index) {
    boolean hasMatches = Core.getProject().isProjectLoaded() && index >= 0 && index < matches.size();
    if (hasMatches) {
        NearString m = matches.get(index);
        if (m.projs.length > 1) {
            JMenuItem item = popup.add(OStrings.getString("MATCHES_PROJECTS"));
            item.setEnabled(false);
            for (int i = 0; i < m.projs.length; i++) {
                String proj = m.projs[i];
                StringBuilder b = new StringBuilder();
                if (proj.equals("")) {
                    b.append(OStrings.getString("MATCHES_THIS_PROJECT"));
                } else {
                    b.append(proj);
                }
                b.append(" ");
                b.append(m.scores[i].toString());
                JMenuItem pItem = popup.add(b.toString());
                pItem.setEnabled(false);
            }
            popup.addSeparator();
        }
    }
    JMenuItem item = popup.add(OStrings.getString("MATCHES_INSERT"));
    item.addActionListener(new ActionListener() {

        // the action: insert this match
        @Override
        public void actionPerformed(ActionEvent e) {
            if (StringUtil.isEmpty(getSelectedText())) {
                setActiveMatch(index);
            }
            Core.getMainWindow().getMainMenu().invokeAction("editInsertTranslationMenuItem", 0);
        }
    });
    item.setEnabled(hasMatches);
    item = popup.add(OStrings.getString("MATCHES_REPLACE"));
    item.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (StringUtil.isEmpty(getSelectedText())) {
                setActiveMatch(index);
            }
            Core.getMainWindow().getMainMenu().invokeAction("editOverwriteTranslationMenuItem", 0);
        }
    });
    item.setEnabled(hasMatches);
    popup.addSeparator();
    item = popup.add(OStrings.getString("MATCHES_GO_TO_SEGMENT_SOURCE"));
    item.setEnabled(hasMatches);
    if (hasMatches) {
        final NearString ns = matches.get(index);
        String proj = ns.projs[0];
        if (StringUtil.isEmpty(proj)) {
            item.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Core.getEditor().gotoEntry(ns.source, ns.key);
                }
            });
        } else {
            item.setEnabled(false);
        }
    }
}
Also used : ActionListener(java.awt.event.ActionListener) ActionEvent(java.awt.event.ActionEvent) NearString(org.omegat.core.matching.NearString) NearString(org.omegat.core.matching.NearString) JMenuItem(javax.swing.JMenuItem) Point(java.awt.Point)

Example 3 with NearString

use of org.omegat.core.matching.NearString in project omegat by omegat-org.

the class MatchesTextArea method checkForReplaceTranslation.

/**
 * if WORKFLOW_OPTION "Insert best fuzzy match into target field" is set
 *
 * RFE "Option: Insert best match (80%+) into target field"
 *
 * @see <a href="https://sourceforge.net/p/omegat/feature-requests/33/">RFE
 *      #33</a>
 */
private void checkForReplaceTranslation() {
    if (matches.isEmpty()) {
        return;
    }
    if (Preferences.isPreference(Preferences.BEST_MATCH_INSERT)) {
        int percentage = Preferences.getPreferenceDefault(Preferences.BEST_MATCH_MINIMAL_SIMILARITY, Preferences.BEST_MATCH_MINIMAL_SIMILARITY_DEFAULT);
        NearString thebest = matches.get(0);
        if (thebest.scores[0].score >= percentage) {
            SourceTextEntry currentEntry = Core.getEditor().getCurrentEntry();
            TMXEntry te = Core.getProject().getTranslationInfo(currentEntry);
            if (!te.isTranslated()) {
                String prefix = "";
                if (!Preferences.getPreference(Preferences.BEST_MATCH_EXPLANATORY_TEXT).isEmpty()) {
                    prefix = Preferences.getPreferenceDefault(Preferences.BEST_MATCH_EXPLANATORY_TEXT, OStrings.getString("WF_DEFAULT_PREFIX"));
                }
                String translation = thebest.translation;
                if (Preferences.isPreference(Preferences.CONVERT_NUMBERS)) {
                    translation = substituteNumbers(currentEntry.getSrcText(), thebest.source, thebest.translation);
                }
                Core.getEditor().replaceEditText(prefix + translation);
            }
        }
    }
}
Also used : SourceTextEntry(org.omegat.core.data.SourceTextEntry) NearString(org.omegat.core.matching.NearString) NearString(org.omegat.core.matching.NearString) Point(java.awt.Point) TMXEntry(org.omegat.core.data.TMXEntry)

Example 4 with NearString

use of org.omegat.core.matching.NearString in project omegat by omegat-org.

the class MatchesTextArea method setActiveMatch.

/**
 * Sets the index of an active match. It basically highlights the fuzzy
 * match string selected. (numbers start from 0)
 */
@Override
public void setActiveMatch(int activeMatch) {
    UIThreadsUtil.mustBeSwingThread();
    if (activeMatch < 0 || activeMatch >= matches.size() || this.activeMatch == activeMatch) {
        return;
    }
    this.activeMatch = activeMatch;
    StyledDocument doc = (StyledDocument) getDocument();
    doc.setCharacterAttributes(0, doc.getLength(), ATTRIBUTES_EMPTY, true);
    int start = delimiters.get(activeMatch);
    int end = delimiters.get(activeMatch + 1);
    NearString match = matches.get(activeMatch);
    // List tokens = match.str.getSrcTokenList();
    ITokenizer tokenizer = Core.getProject().getSourceTokenizer();
    if (tokenizer == null) {
        return;
    }
    // Apply sourceText styling
    if (sourcePos.get(activeMatch) != -1) {
        Token[] tokens = tokenizer.tokenizeVerbatim(match.source);
        // fix for bug 1586397
        byte[] attributes = match.attr;
        for (int i = 0; i < tokens.length; i++) {
            Token token = tokens[i];
            int tokstart = start + sourcePos.get(activeMatch) + token.getOffset();
            int toklength = token.getLength();
            if ((attributes[i] & StringData.UNIQ) != 0) {
                doc.setCharacterAttributes(tokstart, toklength, ATTRIBUTES_CHANGED, false);
            } else if ((attributes[i] & StringData.PAIR) != 0) {
                doc.setCharacterAttributes(tokstart, toklength, ATTRIBUTES_UNCHANGED, false);
            }
        }
    }
    // Iterate through (up to) 5 fuzzy matches
    for (int i = 0; i < diffInfos.size(); i++) {
        Map<Integer, List<TextRun>> diffInfo = diffInfos.get(i);
        // Iterate through each diff variant (${diff}, ${diffReversed}, ...)
        for (Entry<Integer, List<TextRun>> e : diffInfo.entrySet()) {
            int diffPos = e.getKey();
            if (diffPos != -1) {
                // Iterate through each style chunk (added or deleted)
                for (TextRun r : e.getValue()) {
                    int tokstart = delimiters.get(i) + diffPos + r.start;
                    switch(r.type) {
                        case DELETE:
                            doc.setCharacterAttributes(tokstart, r.length, i == activeMatch ? ATTRIBUTES_DELETED_ACTIVE : ATTRIBUTES_DELETED_INACTIVE, false);
                            break;
                        case INSERT:
                            doc.setCharacterAttributes(tokstart, r.length, i == activeMatch ? ATTRIBUTES_INSERTED_ACTIVE : ATTRIBUTES_INSERTED_INACTIVE, false);
                            break;
                        case NOCHANGE:
                    }
                }
            }
        }
    }
    doc.setCharacterAttributes(start, end - start, ATTRIBUTES_SELECTED, false);
    // two newlines
    setCaretPosition(end - 2);
    final int fstart = start;
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            setCaretPosition(fstart);
        }
    });
}
Also used : StyledDocument(javax.swing.text.StyledDocument) Token(org.omegat.util.Token) NearString(org.omegat.core.matching.NearString) TextRun(org.omegat.core.matching.DiffDriver.TextRun) Point(java.awt.Point) ITokenizer(org.omegat.tokenizer.ITokenizer) List(java.util.List) ArrayList(java.util.ArrayList)

Example 5 with NearString

use of org.omegat.core.matching.NearString in project omegat by omegat-org.

the class MatchesVarExpansion method expandVariables.

@Override
public String expandVariables(NearString match) {
    // do not modify template directly, so that we can reuse for another change
    String localTemplate = this.template;
    localTemplate = localTemplate.replace(VAR_INITIAL_CREATION_ID, match.creator == null ? "" : match.creator);
    // VAR_CREATION_ID is an alias for VAR_CHANGED_ID, for backwards compatibility.
    for (String s : new String[] { VAR_CHANGED_ID, VAR_CREATION_ID }) {
        localTemplate = localTemplate.replace(s, match.changer == null ? "" : match.changer);
    }
    if (match.creationDate > 0) {
        localTemplate = localTemplate.replace(VAR_INITIAL_CREATION_DATE, DateFormat.getInstance().format(new Date(match.creationDate)));
    } else {
        localTemplate = localTemplate.replace(VAR_INITIAL_CREATION_DATE, "");
    }
    // VAR_CREATION_DATE is an alias for VAR_CHANGED_DATE, for backwards compatibility.
    for (String s : new String[] { VAR_CHANGED_DATE, VAR_CREATION_DATE }) {
        if (match.changedDate > 0) {
            localTemplate = localTemplate.replace(s, DateFormat.getInstance().format(new Date(match.changedDate)));
        } else {
            localTemplate = localTemplate.replace(s, "");
        }
    }
    localTemplate = localTemplate.replace(VAR_SCORE_BASE, Integer.toString(match.scores[0].score));
    localTemplate = localTemplate.replace(VAR_SCORE_NOSTEM, Integer.toString(match.scores[0].scoreNoStem));
    localTemplate = localTemplate.replace(VAR_SCORE_ADJUSTED, Integer.toString(match.scores[0].adjustedScore));
    localTemplate = localTemplate.replace(VAR_TARGET_TEXT, match.translation);
    localTemplate = localTemplate.replace(VAR_FUZZY_FLAG, match.fuzzyMark ? (OStrings.getString("MATCHES_FUZZY_MARK") + " ") : "");
    ProjectProperties props = Core.getProject().getProjectProperties();
    if (props != null) {
        localTemplate = expandFileNames(localTemplate, match.projs, props.getTMRoot());
    }
    return localTemplate;
}
Also used : NearString(org.omegat.core.matching.NearString) ProjectProperties(org.omegat.core.data.ProjectProperties) Date(java.util.Date)

Aggregations

NearString (org.omegat.core.matching.NearString)12 Point (java.awt.Point)4 File (java.io.File)3 ArrayList (java.util.ArrayList)3 SourceTextEntry (org.omegat.core.data.SourceTextEntry)3 TMXEntry (org.omegat.core.data.TMXEntry)3 ActionEvent (java.awt.event.ActionEvent)2 ActionListener (java.awt.event.ActionListener)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 JMenuItem (javax.swing.JMenuItem)2 StyledDocument (javax.swing.text.StyledDocument)2 TextRun (org.omegat.core.matching.DiffDriver.TextRun)2 Token (org.omegat.util.Token)2 Component (java.awt.Component)1 Dimension (java.awt.Dimension)1 MouseAdapter (java.awt.event.MouseAdapter)1 MouseEvent (java.awt.event.MouseEvent)1 MouseListener (java.awt.event.MouseListener)1