Search in sources :

Example 6 with SourceTextEntry

use of org.omegat.core.data.SourceTextEntry in project omegat by omegat-org.

the class EditorController method loadDocument.

/**
 * Displays the {@link Preferences#EDITOR_INITIAL_SEGMENT_LOAD_COUNT}
 * segments surrounding the entry with index {@link #displayedEntryIndex}.
 */
protected void loadDocument() {
    UIThreadsUtil.mustBeSwingThread();
    // Currently displayed file
    IProject.FileInfo file;
    try {
        file = Core.getProject().getProjectFiles().get(displayedFileIndex);
    } catch (IndexOutOfBoundsException ex) {
        // there is no displayedFileIndex file in project - load first file
        file = Core.getProject().getProjectFiles().get(0);
    }
    // remove old segments
    if (m_docSegList != null) {
        markerController.removeAll();
    }
    // check if RTL support required for document
    boolean hasRTL = sourceLangIsRTL || targetLangIsRTL || EditorUtils.localeIsRTL() || currentOrientation != Document3.ORIENTATION.ALL_LTR;
    Map<Language, ProjectTMX> otherLanguageTMs = Core.getProject().getOtherTargetLanguageTMs();
    for (Map.Entry<Language, ProjectTMX> entry : otherLanguageTMs.entrySet()) {
        hasRTL = hasRTL || EditorUtils.isRTL(entry.getKey().getLanguageCode().toLowerCase(Locale.ENGLISH));
    }
    Document3 doc = new Document3(this);
    // Create all SegmentBuilders now...
    ArrayList<SegmentBuilder> tmpSegList = new ArrayList<SegmentBuilder>(file.entries.size());
    for (SourceTextEntry ste : file.entries) {
        if (entriesFilter == null || entriesFilter.allowed(ste)) {
            SegmentBuilder sb = new SegmentBuilder(this, doc, settings, ste, ste.entryNum(), hasRTL);
            tmpSegList.add(sb);
        }
    }
    m_docSegList = tmpSegList.toArray(new SegmentBuilder[tmpSegList.size()]);
    // Clamp displayedSegment to actually available entries.
    displayedEntryIndex = Math.max(0, Math.min(m_docSegList.length - 1, displayedEntryIndex));
    // Calculate start, end indices of a span of initialSegCount segments
    // centered around displayedEntryIndex and clamped to [0, m_docSegList.length).
    final int initialSegCount = Preferences.getPreferenceDefault(Preferences.EDITOR_INITIAL_SEGMENT_LOAD_COUNT, Preferences.EDITOR_INITIAL_SEGMENT_LOAD_COUNT_DEFAULT);
    firstLoaded = Math.max(0, displayedEntryIndex - initialSegCount / 2);
    lastLoaded = Math.min(file.entries.size() - 1, firstLoaded + initialSegCount - 1);
    // ...but only display the ones in [firstLoaded, lastLoaded]
    for (int i = 0; i < m_docSegList.length; i++) {
        if (i >= firstLoaded && i <= lastLoaded) {
            SegmentBuilder sb = m_docSegList[i];
            sb.createSegmentElement(false, Core.getProject().getTranslationInfo(sb.ste));
            sb.addSegmentSeparator();
        }
    }
    doc.setDocumentFilter(new DocumentFilter3());
    // add locate for target language to editor
    Locale targetLocale = Core.getProject().getProjectProperties().getTargetLanguage().getLocale();
    editor.setLocale(targetLocale);
    editor.setDocument(doc);
    doc.addUndoableEditListener(editor.undoManager);
    editor.undoManager.reset();
    doc.addDocumentListener(new DocumentListener() {

        // we cannot edit the document here, only other stuff.
        public void changedUpdate(DocumentEvent e) {
            showLengthMessage();
            onTextChanged();
        }

        public void insertUpdate(DocumentEvent e) {
            showLengthMessage();
            onTextChanged();
        }

        public void removeUpdate(DocumentEvent e) {
            showLengthMessage();
            onTextChanged();
        }
    });
    markerController.process(m_docSegList);
    editor.repaint();
}
Also used : ProjectTMX(org.omegat.core.data.ProjectTMX) Locale(java.util.Locale) DocumentListener(javax.swing.event.DocumentListener) ArrayList(java.util.ArrayList) DocumentEvent(javax.swing.event.DocumentEvent) IProject(org.omegat.core.data.IProject) Point(java.awt.Point) Language(org.omegat.util.Language) SourceTextEntry(org.omegat.core.data.SourceTextEntry) FileInfo(org.omegat.core.data.IProject.FileInfo) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Example 7 with SourceTextEntry

use of org.omegat.core.data.SourceTextEntry in project omegat by omegat-org.

the class EditorController method commitAndDeactivate.

void commitAndDeactivate(ForceTranslation forceTranslation, String newTrans) {
    UIThreadsUtil.mustBeSwingThread();
    Document3 doc = editor.getOmDocument();
    doc.stopEditMode();
    // segment was active
    SegmentBuilder sb = m_docSegList[displayedEntryIndex];
    SourceTextEntry entry = sb.ste;
    TMXEntry oldTE = Core.getProject().getTranslationInfo(entry);
    PrepareTMXEntry newen = new PrepareTMXEntry();
    newen.source = sb.ste.getSrcText();
    newen.note = Core.getNotes().getNoteText();
    if (forceTranslation != null) {
        // there is force translation
        switch(forceTranslation) {
            case UNTRANSLATED:
                newen.translation = null;
                break;
            case EMPTY:
                newen.translation = "";
                break;
            case EQUALS_TO_SOURCE:
                newen.translation = newen.source;
                break;
        }
    } else {
        // translation from editor
        if (newTrans.isEmpty()) {
            // empty translation
            if (oldTE.isTranslated() && "".equals(oldTE.translation)) {
                // It's an empty translation which should remain empty
                newen.translation = "";
            } else {
                // will be untranslated
                newen.translation = null;
            }
        } else if (newTrans.equals(newen.source)) {
            // equals to source
            if (Preferences.isPreference(Preferences.ALLOW_TRANS_EQUAL_TO_SRC)) {
                // translation can be equals to source
                newen.translation = newTrans;
            } else {
                // translation can't be equals to source
                if (oldTE.source.equals(oldTE.translation)) {
                    // but it was equals to source before
                    newen.translation = oldTE.translation;
                } else {
                    // set untranslated
                    newen.translation = null;
                }
            }
        } else {
            // new translation is not empty and not equals to source - just change
            newen.translation = newTrans;
        }
    }
    boolean defaultTranslation = sb.isDefaultTranslation();
    boolean isNewAltTrans = !defaultTranslation && oldTE.defaultTranslation;
    boolean translationChanged = !Objects.equals(oldTE.translation, newen.translation);
    boolean noteChanged = !StringUtil.nvl(oldTE.note, "").equals(StringUtil.nvl(newen.note, ""));
    if (!isNewAltTrans && !translationChanged && noteChanged) {
        // Only note was changed, and we are not making a new alt translation.
        Core.getProject().setNote(entry, oldTE, newen.note);
    } else if (translationChanged || noteChanged) {
        while (true) {
            // iterate before optimistic locking will be resolved
            try {
                Core.getProject().setTranslation(entry, newen, defaultTranslation, null, previousTranslations);
                break;
            } catch (OptimisticLockingFail ex) {
                String result = new ConflictDialogController().show(ex.getOldTranslationText(), ex.getNewTranslationText(), newen.translation);
                if (result == newen.translation) {
                    // next iteration
                    previousTranslations = ex.getPrevious();
                } else {
                    // use remote - don't save user's translation
                    break;
                }
            }
        }
    }
    m_docSegList[displayedEntryIndex].createSegmentElement(false, Core.getProject().getTranslationInfo(m_docSegList[displayedEntryIndex].ste));
    // find all identical sources and redraw them
    for (int i = 0; i < m_docSegList.length; i++) {
        if (i == displayedEntryIndex) {
            // current entry, skip
            continue;
        }
        SegmentBuilder builder = m_docSegList[i];
        if (!builder.hasBeenCreated()) {
            // Skip because segment has not been drawn yet
            continue;
        }
        if (builder.ste.getSrcText().equals(entry.getSrcText())) {
            // the same source text - need to update
            builder.createSegmentElement(false, Core.getProject().getTranslationInfo(builder.ste));
            // then add new marks
            markerController.reprocessImmediately(builder);
        }
    }
    Core.getNotes().clear();
    // then add new marks
    markerController.reprocessImmediately(m_docSegList[displayedEntryIndex]);
    editor.undoManager.reset();
    // validate tags if required
    if (entry != null && Preferences.isPreference(Preferences.TAG_VALIDATE_ON_LEAVE)) {
        String file = getCurrentFile();
        new SwingWorker<Boolean, Void>() {

            protected Boolean doInBackground() throws Exception {
                return Core.getTagValidation().checkInvalidTags(entry);
            }

            @Override
            protected void done() {
                try {
                    if (!get()) {
                        Core.getIssues().showForFiles(Pattern.quote(file), entry.entryNum());
                    }
                } catch (InterruptedException | ExecutionException e) {
                    LOGGER.log(Level.SEVERE, "Exception when validating tags on leave", e);
                }
            }
        }.execute();
    }
    // team sync for save thread
    if (Core.getProject().isTeamSyncPrepared()) {
        try {
            Core.executeExclusively(false, Core.getProject()::teamSync);
        } catch (InterruptedException ex) {
        } catch (TimeoutException ex) {
        }
    }
}
Also used : Point(java.awt.Point) TimeoutException(java.util.concurrent.TimeoutException) BadLocationException(javax.swing.text.BadLocationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ConflictDialogController(org.omegat.gui.dialogs.ConflictDialogController) SourceTextEntry(org.omegat.core.data.SourceTextEntry) PrepareTMXEntry(org.omegat.core.data.PrepareTMXEntry) OptimisticLockingFail(org.omegat.core.data.IProject.OptimisticLockingFail) TMXEntry(org.omegat.core.data.TMXEntry) PrepareTMXEntry(org.omegat.core.data.PrepareTMXEntry) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with SourceTextEntry

use of org.omegat.core.data.SourceTextEntry in project omegat by omegat-org.

the class EditorController method markActiveEntrySource.

/**
 * {@inheritDoc}
 */
public void markActiveEntrySource(final SourceTextEntry requiredActiveEntry, final List<Mark> marks, final String markerClassName) {
    UIThreadsUtil.mustBeSwingThread();
    for (Mark m : marks) {
        if (m.entryPart != Mark.ENTRY_PART.SOURCE) {
            throw new RuntimeException("Mark must be for source only");
        }
    }
    SourceTextEntry realActive = m_docSegList[displayedEntryIndex].ste;
    if (realActive != requiredActiveEntry) {
        return;
    }
    int mi = markerController.getMarkerIndex(markerClassName);
    EntryMarks ev = new EntryMarks(m_docSegList[displayedEntryIndex], m_docSegList[displayedEntryIndex].getDisplayVersion(), mi);
    ev.result = marks;
    markerController.queueMarksOutput(ev);
}
Also used : EntryMarks(org.omegat.gui.editor.mark.EntryMarks) SourceTextEntry(org.omegat.core.data.SourceTextEntry) Mark(org.omegat.gui.editor.mark.Mark) Point(java.awt.Point)

Example 9 with SourceTextEntry

use of org.omegat.core.data.SourceTextEntry in project omegat by omegat-org.

the class EditorController method gotoEntry.

public void gotoEntry(final int entryNum, final CaretPosition pos) {
    UIThreadsUtil.mustBeSwingThread();
    if (!Core.getProject().isProjectLoaded()) {
        return;
    }
    if (m_docSegList == null) {
        // document didn't loaded yet
        return;
    }
    Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    Cursor oldCursor = editor.getCursor();
    editor.setCursor(hourglassCursor);
    commitAndDeactivate();
    if (entryNum == 0) {
        // it was empty project, need to display first entry
        displayedFileIndex = 0;
        displayedEntryIndex = 0;
        loadDocument();
    } else {
        IProject dataEngine = Core.getProject();
        for (int i = 0; i < dataEngine.getProjectFiles().size(); i++) {
            IProject.FileInfo fi = dataEngine.getProjectFiles().get(i);
            SourceTextEntry firstEntry = fi.entries.get(0);
            SourceTextEntry lastEntry = fi.entries.get(fi.entries.size() - 1);
            if (firstEntry.entryNum() <= entryNum && lastEntry.entryNum() >= entryNum) {
                // this file
                if (i != displayedFileIndex) {
                    // it's other file than displayed
                    displayedFileIndex = i;
                    loadDocument();
                }
                // find correct displayedEntryIndex
                for (int j = 0; j < m_docSegList.length; j++) {
                    if (m_docSegList[j].segmentNumberInProject >= entryNum) {
                        // 
                        displayedEntryIndex = j;
                        break;
                    }
                }
                break;
            }
        }
    }
    activateEntry(pos);
    editor.setCursor(oldCursor);
}
Also used : SourceTextEntry(org.omegat.core.data.SourceTextEntry) FileInfo(org.omegat.core.data.IProject.FileInfo) Cursor(java.awt.Cursor) IProject(org.omegat.core.data.IProject) Point(java.awt.Point)

Example 10 with SourceTextEntry

use of org.omegat.core.data.SourceTextEntry in project omegat by omegat-org.

the class EditorController method activateEntry.

/**
 * Activates the current entry (if available) by displaying source text and embedding displayed text in
 * markers.
 * <p>
 * Also moves document focus to current entry, and makes sure fuzzy info displayed if available.
 */
public void activateEntry(CaretPosition pos) {
    UIThreadsUtil.mustBeSwingThread();
    SourceTextEntry ste = getCurrentEntry();
    if (ste == null) {
        return;
    }
    if (scrollPane.getViewport().getView() != editor) {
        // editor not displayed
        return;
    }
    if (!Core.getProject().isProjectLoaded()) {
        return;
    }
    SegmentBuilder builder = m_docSegList[displayedEntryIndex];
    // document centered at the destination segment.
    if (!builder.hasBeenCreated()) {
        loadDocument();
        activateEntry(pos);
        return;
    }
    previousTranslations = Core.getProject().getAllTranslations(ste);
    TMXEntry currentTranslation = previousTranslations.getCurrentTranslation();
    // forget about old marks
    builder.createSegmentElement(true, currentTranslation);
    Core.getNotes().setNoteText(currentTranslation.note);
    // then add new marks
    markerController.reprocessImmediately(builder);
    editor.undoManager.reset();
    history.insertNew(builder.segmentNumberInProject);
    setMenuEnabled();
    showStat();
    showLengthMessage();
    if (Preferences.isPreference(Preferences.EXPORT_CURRENT_SEGMENT)) {
        segmentExportImport.exportCurrentSegment(ste);
    }
    int te = editor.getOmDocument().getTranslationEnd();
    int ts = editor.getOmDocument().getTranslationStart();
    // 
    if (pos.position != null) {
        // check if outside of entry
        pos.position = Math.max(0, pos.position);
        pos.position = Math.min(pos.position, te - ts);
    }
    if (pos.selectionStart != null && pos.selectionEnd != null) {
        // check if outside of entry
        pos.selectionStart = Math.max(0, pos.selectionStart);
        pos.selectionEnd = Math.min(pos.selectionEnd, te - ts);
        if (pos.selectionStart >= pos.selectionEnd) {
            // if end after start
            pos.selectionStart = null;
            pos.selectionEnd = null;
        }
    }
    scrollForDisplayNearestSegments(pos);
    // check if file was changed
    if (previousDisplayedFileIndex != displayedFileIndex) {
        previousDisplayedFileIndex = displayedFileIndex;
        CoreEvents.fireEntryNewFile(Core.getProject().getProjectFiles().get(displayedFileIndex).filePath);
    }
    editor.autoCompleter.setVisible(false);
    editor.repaint();
    // fire event about new segment activated
    CoreEvents.fireEntryActivated(ste);
}
Also used : SourceTextEntry(org.omegat.core.data.SourceTextEntry) TMXEntry(org.omegat.core.data.TMXEntry) PrepareTMXEntry(org.omegat.core.data.PrepareTMXEntry) Point(java.awt.Point)

Aggregations

SourceTextEntry (org.omegat.core.data.SourceTextEntry)32 Point (java.awt.Point)14 TMXEntry (org.omegat.core.data.TMXEntry)12 PrepareTMXEntry (org.omegat.core.data.PrepareTMXEntry)9 ArrayList (java.util.ArrayList)8 IProject (org.omegat.core.data.IProject)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 EntryKey (org.omegat.core.data.EntryKey)5 FileInfo (org.omegat.core.data.IProject.FileInfo)5 Language (org.omegat.util.Language)5 List (java.util.List)4 Before (org.junit.Before)4 ProtectedPart (org.omegat.core.data.ProtectedPart)4 NearString (org.omegat.core.matching.NearString)4 Cursor (java.awt.Cursor)3 File (java.io.File)2 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 Locale (java.util.Locale)2