Search in sources :

Example 1 with DocumentEvent

use of org.eclipse.jface.text.DocumentEvent in project che by eclipse.

the class MultiStateTextFileChange method getPreviewContent.

/*
	 * @see org.eclipse.ltk.core.refactoring.TextEditBasedChange#getPreviewContent(org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup[],org.eclipse.jface.text.IRegion,boolean,int,org.eclipse.core.runtime.IProgressMonitor)
	 */
public final String getPreviewContent(final TextEditBasedChangeGroup[] groups, final IRegion region, final boolean expand, final int surround, final IProgressMonitor monitor) throws CoreException {
    final Set cachedGroups = new HashSet(Arrays.asList(groups));
    final IDocument document = new Document(getCurrentDocument(monitor).get());
    // Marks the region in the document to be previewed
    final Position range = new Position(region.getOffset(), region.getLength());
    try {
        ComposableBufferChange change = null;
        final TextEditBasedChangeGroup[] changedGroups = getChangeGroups();
        LinkedList compositeUndo = new LinkedList();
        for (int index = 0; index < fChanges.size(); index++) {
            change = (ComposableBufferChange) fChanges.get(index);
            TextEdit copy = null;
            try {
                // Have to use a copy
                fCopier = new TextEditCopier(change.getEdit());
                copy = fCopier.perform();
                // Create a mapping from the copied edits to its originals
                final Map originalMap = new HashMap();
                for (final Iterator outer = change.getGroups().iterator(); outer.hasNext(); ) {
                    final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) outer.next();
                    for (final Iterator inner = group.getCachedEdits().iterator(); inner.hasNext(); ) {
                        final TextEdit originalEdit = (TextEdit) inner.next();
                        final TextEdit copiedEdit = fCopier.getCopy(originalEdit);
                        if (copiedEdit != null)
                            originalMap.put(copiedEdit, originalEdit);
                        else
                            //$NON-NLS-1$
                            RefactoringCorePlugin.logErrorMessage("Could not find a copy for the indexed text edit " + originalEdit.toString());
                    }
                }
                final ComposableBufferChangeGroup[] currentGroup = { null };
                final TextEdit[] currentEdit = { null };
                // Text edit processor which sets the change group and
                // current edit when processing
                final TextEditProcessor processor = new TextEditProcessor(document, copy, TextEdit.NONE) {

                    protected final boolean considerEdit(final TextEdit edit) {
                        final TextEdit originalEdit = (TextEdit) originalMap.get(edit);
                        if (originalEdit != null) {
                            currentEdit[0] = originalEdit;
                            boolean found = false;
                            for (int offset = 0; offset < changedGroups.length && !found; offset++) {
                                final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) changedGroups[offset];
                                if (group.containsEdit(originalEdit)) {
                                    currentGroup[0] = group;
                                    found = true;
                                }
                            }
                            if (!found)
                                currentGroup[0] = null;
                        } else if (!(edit instanceof MultiTextEdit)) {
                            //$NON-NLS-1$
                            RefactoringCorePlugin.logErrorMessage("Could not find the original of the copied text edit " + edit.toString());
                        }
                        return true;
                    }
                };
                final LinkedList eventUndos = new LinkedList();
                // Listener to record the undos on the document (offsets
                // relative to the document event)
                final IDocumentListener listener = new IDocumentListener() {

                    public final void documentAboutToBeChanged(final DocumentEvent event) {
                        final ComposableUndoEdit edit = new ComposableUndoEdit();
                        edit.setGroup(currentGroup[0]);
                        edit.setOriginal(currentEdit[0]);
                        edit.setUndo(createUndoEdit(document, event.getOffset(), event.getLength(), event.getText()));
                        eventUndos.addFirst(edit);
                    }

                    public final void documentChanged(final DocumentEvent event) {
                    // Do nothing
                    }
                };
                try {
                    // Record undos in LIFO order
                    document.addDocumentListener(listener);
                    processor.performEdits();
                } finally {
                    document.removeDocumentListener(listener);
                }
                compositeUndo.addFirst(eventUndos);
            } finally {
                fCopier = null;
            }
        }
        final IPositionUpdater positionUpdater = new IPositionUpdater() {

            public final void update(final DocumentEvent event) {
                final int eventOffset = event.getOffset();
                final int eventLength = event.getLength();
                final int eventOldEndOffset = eventOffset + eventLength;
                final String eventText = event.getText();
                final int eventNewLength = eventText == null ? 0 : eventText.length();
                final int eventNewEndOffset = eventOffset + eventNewLength;
                final int deltaLength = eventNewLength - eventLength;
                try {
                    final Position[] positions = event.getDocument().getPositions(COMPOSABLE_POSITION_CATEGORY);
                    for (int index = 0; index < positions.length; index++) {
                        final Position position = positions[index];
                        if (position.isDeleted())
                            continue;
                        final int offset = position.getOffset();
                        final int length = position.getLength();
                        final int end = offset + length;
                        if (offset > eventOldEndOffset) {
                            // position comes way after change - shift
                            position.setOffset(offset + deltaLength);
                        } else if (end < eventOffset) {
                        // position comes way before change - leave
                        // alone
                        } else if (offset == eventOffset) {
                        // leave alone, since the edits are overlapping
                        } else if (offset <= eventOffset && end >= eventOldEndOffset) {
                            // event completely internal to the position
                            // -
                            // adjust length
                            position.setLength(length + deltaLength);
                        } else if (offset < eventOffset) {
                            // event extends over end of position - include
                            // the
                            // replacement text into the position
                            position.setLength(eventNewEndOffset - offset);
                        } else if (end > eventOldEndOffset) {
                            // event extends from before position into it -
                            // adjust
                            // offset and length, including the replacement
                            // text into
                            // the position
                            position.setOffset(eventOffset);
                            int deleted = eventOldEndOffset - offset;
                            position.setLength(length - deleted + eventNewLength);
                        } else {
                            // event comprises the position - keep it at the
                            // same
                            // position, but always inside the replacement
                            // text
                            int newOffset = Math.min(offset, eventNewEndOffset);
                            int newEndOffset = Math.min(end, eventNewEndOffset);
                            position.setOffset(newOffset);
                            position.setLength(newEndOffset - newOffset);
                        }
                    }
                } catch (BadPositionCategoryException exception) {
                // ignore and return
                }
            }
        };
        try {
            document.addPositionCategory(COMPOSABLE_POSITION_CATEGORY);
            document.addPositionUpdater(positionUpdater);
            // Apply undos in LIFO order to get to the original document
            // Track the undos of edits which are in change groups to be
            // previewed and insert
            // Undo edits for them (corresponding to the linearized net
            // effect on the original document)
            final LinkedList undoQueue = new LinkedList();
            for (final Iterator outer = compositeUndo.iterator(); outer.hasNext(); ) {
                for (final Iterator inner = ((List) outer.next()).iterator(); inner.hasNext(); ) {
                    final ComposableUndoEdit edit = (ComposableUndoEdit) inner.next();
                    final ReplaceEdit undo = edit.getUndo();
                    final int offset = undo.getOffset();
                    final int length = undo.getLength();
                    final String text = undo.getText();
                    ComposableEditPosition position = new ComposableEditPosition();
                    if (cachedGroups.contains(edit.getGroup())) {
                        if (text == null || text.equals("")) {
                            //$NON-NLS-1$
                            position.offset = offset;
                            if (length != 0) {
                                // Undo is a delete, create final insert
                                // edit
                                position.length = 0;
                                position.setText(edit.getOriginalText());
                            } else
                                //$NON-NLS-1$
                                RefactoringCorePlugin.logErrorMessage("Dubious undo edit found: " + undo.toString());
                        } else if (length == 0) {
                            position.offset = offset;
                            // Undo is an insert, create final delete
                            // edit
                            //$NON-NLS-1$
                            position.setText("");
                            position.length = text.length();
                        } else {
                            // Undo is a replace, create final replace edit
                            position.offset = offset;
                            position.length = length;
                            position.setText(edit.getOriginalText());
                        }
                        document.addPosition(COMPOSABLE_POSITION_CATEGORY, position);
                    }
                    position = new ComposableEditPosition();
                    position.offset = undo.getOffset();
                    position.length = undo.getLength();
                    position.setText(undo.getText());
                    undoQueue.add(position);
                }
                for (final Iterator iterator = undoQueue.iterator(); iterator.hasNext(); ) {
                    final ComposableEditPosition position = (ComposableEditPosition) iterator.next();
                    document.replace(position.offset, position.length, position.getText());
                    iterator.remove();
                }
            }
            // Use a simple non deleting position updater for the range
            final IPositionUpdater markerUpdater = new NonDeletingPositionUpdater(MARKER_POSITION_CATEGORY);
            try {
                final Position[] positions = document.getPositions(COMPOSABLE_POSITION_CATEGORY);
                document.addPositionCategory(MARKER_POSITION_CATEGORY);
                document.addPositionUpdater(markerUpdater);
                document.addPosition(MARKER_POSITION_CATEGORY, range);
                for (int index = 0; index < positions.length; index++) {
                    final ComposableEditPosition position = (ComposableEditPosition) positions[index];
                    //$NON-NLS-1$
                    document.replace(position.offset, position.length, position.getText() != null ? position.getText() : "");
                }
            } catch (BadPositionCategoryException exception) {
                RefactoringCorePlugin.log(exception);
            } finally {
                document.removePositionUpdater(markerUpdater);
                try {
                    document.removePosition(MARKER_POSITION_CATEGORY, range);
                    document.removePositionCategory(MARKER_POSITION_CATEGORY);
                } catch (BadPositionCategoryException exception) {
                // Cannot happen
                }
            }
        } catch (BadPositionCategoryException exception) {
            RefactoringCorePlugin.log(exception);
        } finally {
            document.removePositionUpdater(positionUpdater);
            try {
                document.removePositionCategory(COMPOSABLE_POSITION_CATEGORY);
            } catch (BadPositionCategoryException exception) {
                RefactoringCorePlugin.log(exception);
            }
        }
        return getContent(document, new Region(range.offset, range.length), expand, surround);
    } catch (MalformedTreeException exception) {
        RefactoringCorePlugin.log(exception);
    } catch (BadLocationException exception) {
        RefactoringCorePlugin.log(exception);
    }
    return getPreviewDocument(monitor).get();
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) TextEditProcessor(org.eclipse.text.edits.TextEditProcessor) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) TextEditCopier(org.eclipse.text.edits.TextEditCopier) NonDeletingPositionUpdater(org.eclipse.ltk.internal.core.refactoring.NonDeletingPositionUpdater) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) Position(org.eclipse.jface.text.Position) IDocumentListener(org.eclipse.jface.text.IDocumentListener) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) DocumentEvent(org.eclipse.jface.text.DocumentEvent) LinkedList(java.util.LinkedList) IPositionUpdater(org.eclipse.jface.text.IPositionUpdater) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) BadPositionCategoryException(org.eclipse.jface.text.BadPositionCategoryException) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IRegion(org.eclipse.jface.text.IRegion) Region(org.eclipse.jface.text.Region) Map(java.util.Map) HashMap(java.util.HashMap) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 2 with DocumentEvent

use of org.eclipse.jface.text.DocumentEvent in project translationstudio8 by heartsome.

the class StyledTextCellEditor method createTextControl.

protected StyledText createTextControl(Composite parent) {
    TagStyleManager tagStyleManager = xliffEditor.getTagStyleManager();
    IStyle cellStyle = this.hsCellEditor.getCellStyle();
    int styled = HorizontalAlignmentEnum.getSWTStyle(cellStyle);
    styled |= SWT.MULTI | SWT.WRAP;
    viewer = new SegmentViewer(parent, styled, tagStyleManager.getTagStyle());
    // 添加标记样式改变监听
    // addTagStyleChangeListener();
    // 注册标记样式调节器
    net.heartsome.cat.ts.ui.innertag.tagstyle.TagStyleConfigurator.configure(viewer);
    // TagStyleConfigurator.configure(viewer);
    // 将原来直接创建StyledText的方式改为由TextViewer提供
    final StyledText textControl = viewer.getTextWidget();
    initStyle(textControl, cellStyle);
    textControl.addFocusListener(new FocusListener() {

        public void focusLost(FocusEvent e) {
        }

        public void focusGained(FocusEvent e) {
            getActionHandler().updateGlobalActionHandler();
        }
    });
    viewer.getDocument().addDocumentListener(new IDocumentListener() {

        public void documentChanged(DocumentEvent e) {
            // 自动行高
            autoResize();
        }

        public void documentAboutToBeChanged(DocumentEvent event) {
        }
    });
    // 实现编辑模式下添加右键菜单
    // dispose textControl前应去掉右键menu,因为右键menu是和nattable共享的,不能在这儿dispose,说见close()方法
    final Menu menu = (Menu) xliffEditor.getTable().getData(Menu.class.getName());
    textControl.setMenu(menu);
    return textControl;
}
Also used : IStyle(net.sourceforge.nattable.style.IStyle) ISegmentViewer(net.heartsome.cat.ts.ui.innertag.ISegmentViewer) SegmentViewer(net.heartsome.cat.ts.ui.innertag.SegmentViewer) StyledText(org.eclipse.swt.custom.StyledText) IDocumentListener(org.eclipse.jface.text.IDocumentListener) Menu(org.eclipse.swt.widgets.Menu) DocumentEvent(org.eclipse.jface.text.DocumentEvent) FocusListener(org.eclipse.swt.events.FocusListener) FocusEvent(org.eclipse.swt.events.FocusEvent)

Example 3 with DocumentEvent

use of org.eclipse.jface.text.DocumentEvent in project translationstudio8 by heartsome.

the class SegmentViewer method initListeners.

private void initListeners() {
    StyledText styledText = getTextWidget();
    // 去掉默认的复制、粘贴键绑定,以实现在复制、粘贴前对标记的处理
    styledText.setKeyBinding('V' | SWT.MOD1, SWT.NULL);
    styledText.setKeyBinding(SWT.INSERT | SWT.MOD2, SWT.NULL);
    styledText.setKeyBinding('C' | SWT.MOD1, SWT.NULL);
    styledText.setKeyBinding(SWT.INSERT | SWT.MOD1, SWT.NULL);
    getDocument().addDocumentListener(new IDocumentListener() {

        public void documentChanged(DocumentEvent e) {
        }

        public void documentAboutToBeChanged(DocumentEvent event) {
            String method = belongToUndoOrRedo();
            if (event.getLength() > 0 && method != null) {
                try {
                    String text = event.getDocument().get(event.getOffset(), event.getLength());
                    Matcher matcher = PATTERN.matcher(text);
                    List<InnerTag> cache = new ArrayList<InnerTag>();
                    while (matcher.find()) {
                        String placeHolder = matcher.group();
                        InnerTag innerTag = InnerTagUtil.getInnerTag(getInnerTagCacheList(), placeHolder);
                        if (innerTag != null && innerTag.isVisible()) {
                            innerTag.setVisible(false);
                            if ("undo".equals(method) && innerTag.getInnerTagBean().isWrongTag()) {
                                cache.add(innerTag);
                            }
                        }
                    }
                    for (InnerTag t : cache) {
                        innerTagCacheList.remove(t);
                        t.dispose();
                    }
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
			 * 是否属于撤销或者重做的操作。
			 * @return ;
			 */
        private String belongToUndoOrRedo() {
            IUndoManager undoManager = getUndoManager();
            if (undoManager != null) {
                StackTraceElement[] stackTraceElements = new Throwable().getStackTrace();
                for (StackTraceElement stackTraceElement : stackTraceElements) {
                    if (undoManager.getClass().getName().equals(stackTraceElement.getClassName())) {
                        String methodName = stackTraceElement.getMethodName();
                        if ("undo".equals(methodName) || "redo".equals(methodName)) {
                            return methodName;
                        }
                    }
                }
            }
            return null;
        }
    });
    /**
		 * 处理在显示非打印隐藏字符的情况光标移动问题。兼容非打印字符替换符号
		 */
    styledText.addKeyListener(new KeyListener() {

        public void keyReleased(KeyEvent e) {
            if (!XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) {
                return;
            }
            if (e.stateMask == SWT.NONE && (e.keyCode == SWT.ARROW_UP || e.keyCode == SWT.ARROW_DOWN)) {
                StyledText styledText = (StyledText) e.widget;
                int offset = styledText.getCaretOffset();
                if (offset < 1 || offset >= styledText.getCharCount()) {
                    return;
                }
                char c = styledText.getText().charAt(offset);
                char _c = styledText.getText().charAt(offset - 1);
                if (c == '\n' && (_c == Constants.LINE_SEPARATOR_CHARACTER)) {
                    styledText.setCaretOffset(offset - 1);
                }
            }
        }

        public void keyPressed(KeyEvent e) {
            if (!XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) {
                return;
            }
            if (e.stateMask == SWT.NONE && (e.keyCode == SWT.ARROW_LEFT || e.keyCode == SWT.ARROW_RIGHT)) {
                StyledText styledText = (StyledText) e.widget;
                int offset = styledText.getCaretOffset();
                if (offset < 1 || offset >= styledText.getCharCount()) {
                    return;
                }
                char c = styledText.getText().charAt(offset);
                char _c = styledText.getText().charAt(offset - 1);
                if ((c == '​' && (_c == Constants.TAB_CHARACTER || _c == Constants.SPACE_CHARACTER)) || (c == '\n' && (_c == Constants.LINE_SEPARATOR_CHARACTER))) {
                    if (e.keyCode == SWT.ARROW_LEFT) {
                        styledText.setCaretOffset(offset - 1);
                    } else if (e.keyCode == SWT.ARROW_RIGHT) {
                        styledText.setCaretOffset(offset + 1);
                    }
                }
            } else if (e.stateMask == SWT.CTRL && (e.keyCode == SWT.ARROW_LEFT || e.keyCode == SWT.ARROW_RIGHT)) {
                // 单独对 ctrl + right ,ctrl + left 换行的处理
                StyledText styledText = (StyledText) e.widget;
                int offset = styledText.getCaretOffset();
                char c = styledText.getText().charAt(offset);
                if (offset < 1 || offset >= styledText.getCharCount()) {
                    return;
                }
                char _c = styledText.getText().charAt(offset - 1);
                if (c == '\n' && (_c == Constants.LINE_SEPARATOR_CHARACTER)) {
                    if (e.keyCode == SWT.ARROW_LEFT) {
                        styledText.setCaretOffset(offset - 1);
                    } else if (e.keyCode == SWT.ARROW_RIGHT) {
                        styledText.setCaretOffset(offset + 1);
                    }
                }
            } else if ((e.stateMask == SWT.SHIFT || e.stateMask == (SWT.SHIFT | SWT.CTRL)) && (e.keyCode == SWT.ARROW_LEFT || e.keyCode == SWT.ARROW_RIGHT)) {
                StyledText styledText = (StyledText) e.widget;
                int offset = styledText.getCaretOffset();
                char c = styledText.getText().charAt(offset);
                if (offset < 1 || offset >= styledText.getCharCount()) {
                    return;
                }
                char _c = styledText.getText().charAt(offset - 1);
                if ((c == '​' && (_c == Constants.TAB_CHARACTER || _c == Constants.SPACE_CHARACTER)) || (c == '\n' && (_c == Constants.LINE_SEPARATOR_CHARACTER))) {
                    if (e.keyCode == SWT.ARROW_LEFT) {
                        styledText.invokeAction(ST.SELECT_COLUMN_PREVIOUS);
                    } else if (e.keyCode == SWT.ARROW_RIGHT) {
                        styledText.invokeAction(ST.SELECT_COLUMN_NEXT);
                    }
                }
            } else if ((e.stateMask == SWT.SHIFT) && (e.keyCode == SWT.ARROW_UP || e.keyCode == SWT.ARROW_DOWN)) {
                StyledText styledText = (StyledText) e.widget;
                int offset = styledText.getCaretOffset();
                char c = styledText.getText().charAt(offset);
                if (offset < 1 || offset >= styledText.getCharCount()) {
                    return;
                }
                char _c = styledText.getText().charAt(offset - 1);
                if (c == '\n' && (_c == Constants.LINE_SEPARATOR_CHARACTER)) {
                    if (e.keyCode == SWT.ARROW_UP) {
                        styledText.invokeAction(ST.SELECT_COLUMN_PREVIOUS);
                    } else if (e.keyCode == SWT.ARROW_DOWN) {
                        styledText.invokeAction(ST.SELECT_COLUMN_NEXT);
                    }
                }
            }
        }
    });
    /**
		 * 处理在显示非打印隐藏字符的情况光标移动问题。兼容非打印字符替换符号
		 */
    styledText.addMouseListener(new MouseListener() {

        public void mouseUp(MouseEvent e) {
        }

        public void mouseDown(MouseEvent e) {
            if (!XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) {
                return;
            }
            StyledText styledText = (StyledText) e.widget;
            int offset = styledText.getCaretOffset();
            if (offset < 1 || offset >= styledText.getCharCount()) {
                return;
            }
            // hidden character
            char c = styledText.getText().charAt(offset);
            // display character
            char _c = styledText.getText().charAt(offset - 1);
            if ((_c == Constants.LINE_SEPARATOR_CHARACTER || _c == Constants.TAB_CHARACTER || _c == Constants.SPACE_CHARACTER) && (c == '\n' || c == '​')) {
                styledText.setCaretOffset(offset + 1);
            }
        }

        public void mouseDoubleClick(MouseEvent e) {
        }
    });
    /**
		 * 选择内容时对非打印字符的处理
		 */
    styledText.addMouseMoveListener(new MouseMoveListener() {

        public void mouseMove(MouseEvent e) {
            StyledText styledText = (StyledText) e.widget;
            int offset = styledText.getCaretOffset();
            if (offset < 1 || offset >= styledText.getCharCount()) {
                return;
            }
            char c = styledText.getText().charAt(offset);
            char _c = styledText.getText().charAt(offset - 1);
            if ((c == '​' && (_c == Constants.TAB_CHARACTER || _c == Constants.SPACE_CHARACTER)) || (c == '\n' && (_c == Constants.LINE_SEPARATOR_CHARACTER))) {
                int caretOffset = styledText.getCaretOffset();
                Point p = styledText.getSelection();
                if (caretOffset == p.x) {
                    styledText.invokeAction(ST.SELECT_COLUMN_PREVIOUS);
                } else if (caretOffset == p.y) {
                    styledText.invokeAction(ST.SELECT_COLUMN_NEXT);
                }
            }
        }
    });
    styledText.addVerifyListener(new VerifyListener() {

        public void verifyText(final VerifyEvent e) {
            String t = e.text;
            if ((e.start == e.end) || (e.start != e.end && !e.text.equals(""))) {
                // 添加内容时
                if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) {
                    t = t.replace("\t", Constants.TAB_CHARACTER + "​").replace(" ", Constants.SPACE_CHARACTER + "​");
                    t = t.replace(System.getProperty("line.separator"), "\n");
                    StringBuffer bf = new StringBuffer(t);
                    int i = bf.indexOf("\n");
                    if (i != -1) {
                        if (i == 0) {
                            bf.insert(i, Constants.LINE_SEPARATOR_CHARACTER);
                        } else if (i != 0 && bf.charAt(i - 1) != Constants.LINE_SEPARATOR_CHARACTER) {
                            bf.insert(i, Constants.LINE_SEPARATOR_CHARACTER);
                        }
                        i = bf.indexOf("\n", i + 1);
                    }
                    e.text = bf.toString();
                }
                return;
            }
            final StyledText styledText = (StyledText) e.widget;
            final String text = styledText.getText(e.start, e.end - 1);
            final Matcher matcher = PATTERN.matcher(text);
            if (matcher.find()) {
                // 被删除的部分中存在标记的的情况,进行特殊处理。
                if (isSource()) {
                    e.doit = false;
                    setToolTipMessage(Messages.getString("innertag.SegmentViewer.msg1"));
                    return;
                }
                matcher.reset();
                styledText.getDisplay().syncExec(new Runnable() {

                    public void run() {
                        deleteInnerTagInPairs(e, matcher);
                    }
                });
            }
            if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) {
                if (text.length() == 1 && (text.equals("\n") || text.indexOf('​') != -1)) {
                    char c = styledText.getText().charAt(e.start - 1);
                    if (c == Constants.LINE_SEPARATOR_CHARACTER || c == Constants.SPACE_CHARACTER || c == Constants.TAB_CHARACTER) {
                        styledText.replaceTextRange(e.start - 1, 2, "");
                        e.doit = false;
                    }
                } else if (text.length() == 1 && (text.indexOf(Constants.LINE_SEPARATOR_CHARACTER) != -1 || text.indexOf(Constants.TAB_CHARACTER) != -1 || text.indexOf(Constants.TAB_CHARACTER) != -1)) {
                    char c = styledText.getText().charAt(e.start + 1);
                    if (c == '\n' || c == '​') {
                        styledText.replaceTextRange(e.start, 2, "");
                        e.doit = false;
                    }
                }
            }
        }

        /**
			 * 成对删除内部标记
			 */
        private void deleteInnerTagInPairs(final VerifyEvent e, Matcher matcher) {
            StyledText styledText = (StyledText) e.widget;
            // 记录被删除的标记的索引。
            ArrayList<Integer> tagIndexes = new ArrayList<Integer>();
            while (matcher.find()) {
                String placeHolder = matcher.group();
                InnerTag innerTag = InnerTagUtil.getInnerTag(SegmentViewer.this.getInnerTagCacheList(), placeHolder);
                if (innerTag != null && innerTag.isVisible()) {
                    innerTag.setVisible(false);
                    // 保存成对标记中未完全删除的标记索引
                    TagType tagType = innerTag.getInnerTagBean().getType();
                    if (tagType == TagType.START || tagType == TagType.END) {
                        // 处理成对标记的成对删除
                        // 标记索引
                        Integer tagIndex = Integer.valueOf(innerTag.getInnerTagBean().getIndex());
                        if (tagIndexes.contains(tagIndex)) {
                            // 如果已经包含此索引,说明成对标记的2个部分都已经删除。
                            tagIndexes.remove(tagIndex);
                        } else {
                            // 如果未包含此索引,则说明只删除了一个部分(开始或结束)的标记。
                            tagIndexes.add(tagIndex);
                        }
                    }
                }
            }
            if (!tagIndexes.isEmpty()) {
                // 存在未删除的情况。
                getUndoManager().beginCompoundChange();
                // 上一步已经修改,取消修改操作。
                e.doit = false;
                // 替换改动内容
                styledText.getContent().replaceTextRange(e.start, e.end - e.start, e.text);
                for (int i = 0; i < errorTagStart; i++) {
                    // 删除成对标记中未被删除的部分。
                    InnerTag innerTag = innerTagCacheList.get(i);
                    if (innerTag != null && innerTag.isVisible()) {
                        if (tagIndexes.contains(innerTag.getInnerTagBean().getIndex())) {
                            innerTag.setVisible(false);
                            String placeHolder = placeHolderBuilder.getPlaceHolder(null, i);
                            int start = -1;
                            if ((start = styledText.getText().indexOf(placeHolder)) != -1) {
                                styledText.getContent().replaceTextRange(start, placeHolder.length(), "");
                            }
                            tagIndexes.remove(Integer.valueOf(innerTag.getInnerTagBean().getIndex()));
                            if (tagIndexes.isEmpty()) {
                                break;
                            }
                        }
                    }
                }
                getUndoManager().endCompoundChange();
                /**
					 * 通知更新主菜单(actionBar)中“撤销重做”等菜单项的状态,参见
					 * net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorActionHandler
					 */
                styledText.notifyListeners(SWT.Selection, null);
            }
        }
    });
    /**
		 * 重绘时,将当前文本段中存在的内部标记对应的控件显示出来
		 */
    styledText.addPaintObjectListener(new PaintObjectListener() {

        public void paintObject(PaintObjectEvent event) {
            StyleRange styleRange = event.style;
            if (styleRange != null) {
                String text = ((StyledText) event.widget).getText();
                int end = styleRange.start + styleRange.length;
                if (text.length() < end) {
                    return;
                }
                String styledString = text.substring(styleRange.start, end);
                Matcher matcher = PATTERN.matcher(styledString);
                if (matcher.matches()) {
                    InnerTag tag = InnerTagUtil.getInnerTag(SegmentViewer.this.getInnerTagCacheList(), styledString);
                    if (tag != null) {
                        if (!tag.isVisible()) {
                            tag.setVisible(true);
                        }
                        // int y = event.y + event.ascent - styleRange.metrics.ascent;
                        int lineHeight = getTextWidget().getLineHeight();
                        // innerTag.setLocation(event.x + SEGMENT_LINE_SPACING / 2, event.y + SEGMENT_LINE_SPACING /
                        // 2 /* 行距的一半 */);
                        int y = event.y + lineHeight / 2 - tag.getBounds().height / 2;
                        tag.setLocation(event.x + SEGMENT_LINE_SPACING, y);
                    }
                }
            }
        }
    });
    /**
		 * 鼠标移动时,清除错误消息。
		 */
    styledText.addMouseMoveListener(new MouseMoveListener() {

        public void mouseMove(MouseEvent e) {
            if (getTextWidget().getToolTipText() != null && getTextWidget().getToolTipText().length() > 0) {
                setToolTipMessage("");
            }
        }
    });
    // 处理修改内容时,需要非打印字符添加样式。
    styledText.addListener(SWT.Modify, new Listener() {

        public void handleEvent(Event event) {
            if (!XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) {
                return;
            }
            String s = event.text;
            Matcher matcher = Constants.NONPRINTING_PATTERN.matcher(s);
            TextStyle style = new TextStyle(null, GUIHelper.getColor(new RGB(100, 100, 100)), null);
            List<StyleRange> ranges = new ArrayList<StyleRange>();
            while (matcher.find()) {
                int start = event.start + matcher.start();
                StyleRange range = new StyleRange(style);
                range.start = start;
                range.length = 1;
                ranges.add(range);
            }
            for (StyleRange range : ranges) {
                getTextWidget().setStyleRange(range);
            }
        }
    });
    styledText.addListener(SWT.Selection, new Listener() {

        public void handleEvent(Event event) {
            for (InnerTag tag : innerTagCacheList) {
                if (tag.isSelected()) {
                    tag.setSelected(false);
                    tag.redraw();
                }
            }
            String styledString = getTextWidget().getSelectionText();
            Matcher matcher = PATTERN.matcher(styledString);
            while (matcher.find()) {
                String s = matcher.group();
                InnerTag tag = InnerTagUtil.getInnerTag(SegmentViewer.this.getInnerTagCacheList(), s);
                if (tag != null) {
                    tag.setSelected(true);
                    tag.redraw();
                }
            }
        }
    });
}
Also used : MouseMoveListener(org.eclipse.swt.events.MouseMoveListener) VerifyListener(org.eclipse.swt.events.VerifyListener) PaintObjectListener(org.eclipse.swt.custom.PaintObjectListener) MouseListener(org.eclipse.swt.events.MouseListener) IDocumentListener(org.eclipse.jface.text.IDocumentListener) Listener(org.eclipse.swt.widgets.Listener) KeyListener(org.eclipse.swt.events.KeyListener) Matcher(java.util.regex.Matcher) StyleRange(org.eclipse.swt.custom.StyleRange) ArrayList(java.util.ArrayList) KeyEvent(org.eclipse.swt.events.KeyEvent) MouseListener(org.eclipse.swt.events.MouseListener) TextStyle(org.eclipse.swt.graphics.TextStyle) InnerTag(net.heartsome.cat.common.ui.innertag.InnerTag) List(java.util.List) ArrayList(java.util.ArrayList) PaintObjectListener(org.eclipse.swt.custom.PaintObjectListener) VerifyEvent(org.eclipse.swt.events.VerifyEvent) StyledText(org.eclipse.swt.custom.StyledText) MouseEvent(org.eclipse.swt.events.MouseEvent) VerifyListener(org.eclipse.swt.events.VerifyListener) IUndoManager(org.eclipse.jface.text.IUndoManager) IDocumentListener(org.eclipse.jface.text.IDocumentListener) PaintObjectEvent(org.eclipse.swt.custom.PaintObjectEvent) Point(org.eclipse.swt.graphics.Point) DocumentEvent(org.eclipse.jface.text.DocumentEvent) RGB(org.eclipse.swt.graphics.RGB) Point(org.eclipse.swt.graphics.Point) TagType(net.heartsome.cat.common.innertag.TagType) MouseMoveListener(org.eclipse.swt.events.MouseMoveListener) KeyEvent(org.eclipse.swt.events.KeyEvent) DocumentEvent(org.eclipse.jface.text.DocumentEvent) MouseEvent(org.eclipse.swt.events.MouseEvent) PaintObjectEvent(org.eclipse.swt.custom.PaintObjectEvent) Event(org.eclipse.swt.widgets.Event) VerifyEvent(org.eclipse.swt.events.VerifyEvent) KeyListener(org.eclipse.swt.events.KeyListener) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 4 with DocumentEvent

use of org.eclipse.jface.text.DocumentEvent in project tdi-studio-se by Talend.

the class ReconcilerViewer method addDocumentListener.

private void addDocumentListener(final IDocument document) {
    final ExecutionLimiter documentReconcilerLimiter = new ExecutionLimiter(500, true) {

        @Override
        protected void execute(boolean isFinalExecution, Object data) {
            if (isFinalExecution) {
                if (getControl() != null && !getControl().isDisposed()) {
                    getControl().getDisplay().asyncExec(new Runnable() {

                        @Override
                        public void run() {
                            // System.out.println(System.currentTimeMillis())
                            // ;
                            updateContents();
                            if (document.get().length() != 0) {
                                calculatePositions();
                            }
                            // (bug 4289)
                            updateVisibleRegion();
                        }
                    });
                }
            }
        }
    };
    document.addDocumentListener(new IDocumentListener() {

        @Override
        public void documentAboutToBeChanged(DocumentEvent event) {
        // nothing
        }

        @Override
        public void documentChanged(DocumentEvent event) {
            documentReconcilerLimiter.resetTimer();
            documentReconcilerLimiter.startIfExecutable(true, null);
        }
    });
}
Also used : IDocumentListener(org.eclipse.jface.text.IDocumentListener) ExecutionLimiter(org.talend.commons.utils.threading.ExecutionLimiter) DocumentEvent(org.eclipse.jface.text.DocumentEvent)

Aggregations

DocumentEvent (org.eclipse.jface.text.DocumentEvent)4 IDocumentListener (org.eclipse.jface.text.IDocumentListener)4 ArrayList (java.util.ArrayList)2 List (java.util.List)2 BadLocationException (org.eclipse.jface.text.BadLocationException)2 StyledText (org.eclipse.swt.custom.StyledText)2 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Set (java.util.Set)1 Matcher (java.util.regex.Matcher)1 TagType (net.heartsome.cat.common.innertag.TagType)1 InnerTag (net.heartsome.cat.common.ui.innertag.InnerTag)1 ISegmentViewer (net.heartsome.cat.ts.ui.innertag.ISegmentViewer)1 SegmentViewer (net.heartsome.cat.ts.ui.innertag.SegmentViewer)1 IStyle (net.sourceforge.nattable.style.IStyle)1 BadPositionCategoryException (org.eclipse.jface.text.BadPositionCategoryException)1 Document (org.eclipse.jface.text.Document)1