Search in sources :

Example 56 with KeyEvent

use of org.eclipse.swt.events.KeyEvent 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 57 with KeyEvent

use of org.eclipse.swt.events.KeyEvent in project translationstudio8 by heartsome.

the class XLFEditor method hookListener.

/**
	 * 初始化监听器。
	 */
private void hookListener() {
    // 添加文本修改监听器,用于调整文本框大小,使其高度自适应文本内容。
    textModifyListener = new ModifyListener() {

        public void modifyText(ModifyEvent e) {
            StyledText st = (StyledText) e.widget;
            GridData gd = (GridData) st.getLayoutData();
            if (gd == null) {
                gd = new GridData(GridData.FILL_BOTH);
            }
            Point computeSize = st.computeSize(st.getSize().x, SWT.DEFAULT, false);
            // 此行代码是为了保持列宽不变。减 10 是因为 computeSize 后宽度每次会增加 5 个像素,
            // 因此需要减去上次和本次增加的共10像素。为什么会这样原因不明。
            gd.widthHint = computeSize.x - 10;
            st.setLayoutData(gd);
            editorContentComposite.layout();
            oScrolledComposite.setMinSize(editorContentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
        }
    };
    // 添加鼠标跟踪监听器,用于监听鼠标位置,根据编辑器模式切换光标样式。
    mouseTrackListener = new MouseTrackListener() {

        private void setArrowCursor(MouseEvent arg0) {
            Widget srcWidget = arg0.widget;
            if (isEditModel && srcWidget instanceof StyledText) {
                ((StyledText) srcWidget).setCursor(cursorIbeam);
            } else {
                ((StyledText) srcWidget).setCursor(cursorArrow);
            }
        }

        public void mouseEnter(MouseEvent arg0) {
            setArrowCursor(arg0);
        }

        public void mouseExit(MouseEvent arg0) {
            setArrowCursor(arg0);
        }

        public void mouseHover(MouseEvent arg0) {
            setArrowCursor(arg0);
        }
    };
    mouseListener = new MouseListener() {

        public void mouseDoubleClick(MouseEvent arg0) {
            // 切换为编辑模式
            isEditModel = true;
            System.out.println("It's running edit model.");
            Control ctrl = arg0.display.getCursorControl();
            ctrl.setCursor(cursorIbeam);
        }

        public void mouseDown(MouseEvent arg0) {
            int inx = (Integer) arg0.widget.getData(DATAKEY_INDEX);
            setSelectionRowColor(inx);
            // 选中模式下要隐藏光标。
            if (!isEditModel) {
                // 通过为容器组件设置焦点,实现在选中模式时隐藏文本框组件中闪烁的光标
                txtComposites[inx].forceFocus();
            }
        }

        public void mouseUp(MouseEvent arg0) {
        }
    };
    keyListener = new KeyListener() {

        public void keyPressed(KeyEvent arg0) {
            // 按 Esc 键切换到选择模式。
            if (arg0.keyCode == SWT.ESC) {
                isEditModel = false;
                Control ctrl = arg0.display.getCursorControl();
                ctrl.setCursor(cursorArrow);
            }
        }

        public void keyReleased(KeyEvent arg0) {
        }
    };
}
Also used : KeyEvent(org.eclipse.swt.events.KeyEvent) ModifyEvent(org.eclipse.swt.events.ModifyEvent) Control(org.eclipse.swt.widgets.Control) StyledText(org.eclipse.swt.custom.StyledText) MouseEvent(org.eclipse.swt.events.MouseEvent) MouseListener(org.eclipse.swt.events.MouseListener) ModifyListener(org.eclipse.swt.events.ModifyListener) MouseTrackListener(org.eclipse.swt.events.MouseTrackListener) GridData(org.eclipse.swt.layout.GridData) Widget(org.eclipse.swt.widgets.Widget) KeyListener(org.eclipse.swt.events.KeyListener) Point(org.eclipse.swt.graphics.Point)

Example 58 with KeyEvent

use of org.eclipse.swt.events.KeyEvent in project OpenGrok by OpenGrok.

the class ResultsDialog method createDialogArea.

@Override
protected Control createDialogArea(Composite parent) {
    parent.setLayout(new GridLayout(1, true));
    filter = new Text(parent, SWT.FILL);
    filter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    TextUtils.setToDefault(filter, FILTER_DEFAULT);
    filter.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {
            if ("".equals(filter.getText())) {
                TextUtils.setToDefault(filter, FILTER_DEFAULT);
            }
        }

        @Override
        public void focusGained(FocusEvent e) {
            TextUtils.makeEditable(filter);
        }
    });
    filter.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent e) {
            viewer.refresh();
        }
    });
    return parent;
}
Also used : KeyEvent(org.eclipse.swt.events.KeyEvent) GridLayout(org.eclipse.swt.layout.GridLayout) KeyAdapter(org.eclipse.swt.events.KeyAdapter) GridData(org.eclipse.swt.layout.GridData) Text(org.eclipse.swt.widgets.Text) FocusListener(org.eclipse.swt.events.FocusListener) FocusEvent(org.eclipse.swt.events.FocusEvent)

Example 59 with KeyEvent

use of org.eclipse.swt.events.KeyEvent in project OpenGrok by OpenGrok.

the class ToolBarControl method createControl.

@Override
protected Control createControl(Composite parent) {
    final Text searchBox = new Text(parent, SWT.FILL | SWT.BORDER);
    TextUtils.setToDefault(searchBox, "{OpenGrok");
    searchBox.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {
            if (!disableFocusLostEvent) {
                TextUtils.setToDefault(searchBox, "{OpenGrok");
            }
        }

        @Override
        public void focusGained(FocusEvent e) {
            TextUtils.makeEditable(searchBox);
        }
    });
    searchBox.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {
                doSearch();
            } else if (e.keyCode == SWT.ARROW_UP) {
                historyIndex++;
                if (historyIndex > history.size()) {
                    historyIndex = history.size();
                }
                if (historyIndex >= 0 && history.size() >= historyIndex) {
                    searchBox.setText(history.get(historyIndex - 1));
                }
            } else if (e.keyCode == SWT.ARROW_DOWN) {
                historyIndex--;
                if (historyIndex < 0) {
                    historyIndex = 0;
                } else if (history.size() > historyIndex) {
                    searchBox.setText(history.get(historyIndex));
                }
            } else if ((e.stateMask & SWT.CTRL) == SWT.CTRL && e.keyCode == 'v') {
                searchBox.setText("");
                searchBox.paste();
                if ((e.stateMask & SWT.SHIFT) == SWT.SHIFT) {
                    doSearch();
                }
            } else if (e.stateMask == SWT.CTRL && e.keyCode == 'c') {
                searchBox.copy();
            }
        }

        private void doSearch() {
            String text = searchBox.getText();
            if (text != null && !"".equals(text)) {
                history.add(0, text);
                historyIndex = 0;
                Rectangle bounds = searchBox.getBounds();
                Point topLeft = new Point(bounds.x, bounds.y + bounds.height);
                topLeft = searchBox.getShell().toDisplay(topLeft);
                final ResultsDialog dialog = new ResultsDialog(Display.getCurrent().getActiveShell(), text, topLeft);
                Query query = new Query(text);
                disableFocusLostEvent = true;
                query.run(dialog);
                disableFocusLostEvent = false;
            }
        }
    });
    return parent;
}
Also used : KeyEvent(org.eclipse.swt.events.KeyEvent) Query(org.opensolaris.opengrok.egrok.query.Query) KeyAdapter(org.eclipse.swt.events.KeyAdapter) Rectangle(org.eclipse.swt.graphics.Rectangle) Text(org.eclipse.swt.widgets.Text) Point(org.eclipse.swt.graphics.Point) FocusListener(org.eclipse.swt.events.FocusListener) FocusEvent(org.eclipse.swt.events.FocusEvent)

Example 60 with KeyEvent

use of org.eclipse.swt.events.KeyEvent in project dbeaver by serge-rider.

the class DatabaseConsumerPageMapping method createControl.

@Override
public void createControl(Composite parent) {
    initializeDialogUnits(parent);
    final DatabaseConsumerSettings settings = getWizard().getPageSettings(this, DatabaseConsumerSettings.class);
    Composite composite = new Composite(parent, SWT.NULL);
    GridLayout gl = new GridLayout();
    gl.marginHeight = 0;
    gl.marginWidth = 0;
    composite.setLayout(gl);
    composite.setLayoutData(new GridData(GridData.FILL_BOTH));
    {
        // Target container
        Composite containerPanel = new Composite(composite, SWT.NONE);
        containerPanel.setLayout(new GridLayout(4, false));
        containerPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        UIUtils.createControlLabel(containerPanel, "Target container");
        containerIcon = new Label(containerPanel, SWT.NONE);
        containerIcon.setImage(DBeaverIcons.getImage(DBIcon.TYPE_UNKNOWN));
        containerName = new Text(containerPanel, SWT.BORDER | SWT.READ_ONLY);
        containerName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        containerName.setText("");
        Button browseButton = new Button(containerPanel, SWT.PUSH);
        browseButton.setImage(DBeaverIcons.getImage(DBIcon.TREE_FOLDER));
        browseButton.setText("...");
        browseButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                IProject activeProject = DBeaverCore.getInstance().getProjectRegistry().getActiveProject();
                if (activeProject != null) {
                    final DBNModel navigatorModel = DBeaverCore.getInstance().getNavigatorModel();
                    final DBNProject rootNode = navigatorModel.getRoot().getProject(activeProject);
                    DBNNode selectedNode = settings.getContainerNode();
                    if (selectedNode == null && !settings.getDataMappings().isEmpty()) {
                        // Use first source object as cur selection (it's better than nothing)
                        DBSDataContainer firstSource = settings.getDataMappings().keySet().iterator().next();
                        selectedNode = navigatorModel.getNodeByObject(firstSource);
                        while (selectedNode != null) {
                            if (selectedNode instanceof DBSWrapper && ((DBSWrapper) selectedNode).getObject() instanceof DBSObjectContainer) {
                                break;
                            } else {
                                selectedNode = selectedNode.getParentNode();
                            }
                        }
                    }
                    DBNNode node = BrowseObjectDialog.selectObject(getShell(), "Choose container", rootNode.getDatabases(), selectedNode, new Class[] { DBSObjectContainer.class }, null);
                    if (node instanceof DBNDatabaseNode) {
                        settings.setContainerNode((DBNDatabaseNode) node);
                        containerIcon.setImage(DBeaverIcons.getImage(node.getNodeIconDefault()));
                        containerName.setText(settings.getContainerFullName());
                        // Reset mappings
                        for (DatabaseMappingContainer mappingContainer : settings.getDataMappings().values()) {
                            if (mappingContainer.getMappingType() == DatabaseMappingType.create) {
                                try {
                                    mappingContainer.refreshMappingType(getContainer(), DatabaseMappingType.create);
                                } catch (DBException e1) {
                                    log.error(e1);
                                }
                            }
                        }
                        mappingViewer.refresh();
                        updatePageCompletion();
                    }
                }
            }
        });
    }
    createMappingsTree(composite);
    {
        // Control buttons
        Composite buttonsPanel = new Composite(composite, SWT.NONE);
        buttonsPanel.setLayout(new GridLayout(4, false));
        buttonsPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        final Button mapTableButton = new Button(buttonsPanel, SWT.PUSH);
        mapTableButton.setImage(DBeaverIcons.getImage(DBIcon.TREE_TABLE));
        mapTableButton.setText("Existing table ...");
        mapTableButton.setEnabled(false);
        mapTableButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                mapExistingTable((DatabaseMappingContainer) getSelectedMapping());
            }
        });
        final Button createNewButton = new Button(buttonsPanel, SWT.PUSH);
        createNewButton.setImage(DBeaverIcons.getImage(DBIcon.TREE_VIEW));
        createNewButton.setText("New table...");
        createNewButton.setEnabled(false);
        createNewButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                mapNewTable((DatabaseMappingContainer) getSelectedMapping());
            }
        });
        final Button columnsButton = new Button(buttonsPanel, SWT.PUSH);
        columnsButton.setImage(DBeaverIcons.getImage(DBIcon.TREE_COLUMNS));
        columnsButton.setText("Columns' mappings ...");
        columnsButton.setEnabled(false);
        columnsButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                DatabaseMappingObject selectedMapping = getSelectedMapping();
                mapColumns(selectedMapping instanceof DatabaseMappingContainer ? (DatabaseMappingContainer) selectedMapping : ((DatabaseMappingAttribute) selectedMapping).getParent());
            }
        });
        final Button ddlButton = new Button(buttonsPanel, SWT.PUSH);
        ddlButton.setImage(DBeaverIcons.getImage(UIIcon.SQL_TEXT));
        ddlButton.setText("DDL ...");
        ddlButton.setEnabled(false);
        ddlButton.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                DatabaseMappingObject selectedMapping = getSelectedMapping();
                showDDL(selectedMapping instanceof DatabaseMappingContainer ? (DatabaseMappingContainer) selectedMapping : ((DatabaseMappingAttribute) selectedMapping).getParent());
            }
        });
        mappingViewer.getTree().addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                try {
                    boolean updated = false;
                    Object element = null;
                    if (e.character == SWT.CR) {
                    //Object element = mappingViewer.getStructuredSelection().getFirstElement();
                    //mappingViewer.editElement(element, 1);
                    } else if (e.character == SWT.DEL) {
                        for (TreeItem item : mappingViewer.getTree().getSelection()) {
                            element = item.getData();
                            if (element instanceof DatabaseMappingAttribute) {
                                DatabaseMappingAttribute attribute = (DatabaseMappingAttribute) element;
                                attribute.setMappingType(DatabaseMappingType.skip);
                            } else if (element instanceof DatabaseMappingContainer) {
                                DatabaseMappingContainer container = (DatabaseMappingContainer) element;
                                container.refreshMappingType(getContainer(), DatabaseMappingType.skip);
                            }
                        }
                        updated = true;
                    } else if (e.character == SWT.SPACE) {
                        for (TreeItem item : mappingViewer.getTree().getSelection()) {
                            element = item.getData();
                            if (element instanceof DatabaseMappingAttribute) {
                                DatabaseMappingAttribute attribute = (DatabaseMappingAttribute) item.getData();
                                attribute.setMappingType(DatabaseMappingType.existing);
                                attribute.updateMappingType(VoidProgressMonitor.INSTANCE);
                            } else if (element instanceof DatabaseMappingContainer) {
                                DatabaseMappingContainer container = (DatabaseMappingContainer) element;
                                setMappingTarget(container, container.getSource().getName());
                            }
                        }
                        updated = true;
                    }
                    if (updated) {
                        mappingViewer.refresh();
                        updatePageCompletion();
                        if (element instanceof DatabaseMappingContainer) {
                            // Select next container
                            @SuppressWarnings("unchecked") List<DatabaseMappingContainer> model = (List<DatabaseMappingContainer>) mappingViewer.getInput();
                            int curIndex = model.indexOf(element);
                            if (curIndex < model.size() - 1) {
                                mappingViewer.setSelection(new StructuredSelection(model.get(curIndex + 1)), true);
                            }
                        }
                    }
                } catch (DBException e1) {
                    UIUtils.showDatabaseError(getShell(), "Mapping error", "Error mapping table", e1);
                }
            }
        });
        mappingViewer.addSelectionChangedListener(new ISelectionChangedListener() {

            @Override
            public void selectionChanged(SelectionChangedEvent event) {
                DatabaseMappingObject mapping = getSelectedMapping();
                mapTableButton.setEnabled(mapping instanceof DatabaseMappingContainer);
                createNewButton.setEnabled(mapping instanceof DatabaseMappingContainer && settings.getContainerNode() != null);
                final boolean hasMappings = (mapping instanceof DatabaseMappingContainer && mapping.getMappingType() != DatabaseMappingType.unspecified) || (mapping instanceof DatabaseMappingAttribute && ((DatabaseMappingAttribute) mapping).getParent().getMappingType() != DatabaseMappingType.unspecified);
                columnsButton.setEnabled(hasMappings);
                ddlButton.setEnabled(hasMappings);
            }
        });
        mappingViewer.addDoubleClickListener(new IDoubleClickListener() {

            @Override
            public void doubleClick(DoubleClickEvent event) {
                DatabaseMappingObject selectedMapping = getSelectedMapping();
                if (selectedMapping != null) {
                    if (selectedMapping instanceof DatabaseMappingContainer) {
                    /*
                            if (selectedMapping.getMappingType() == DatabaseMappingType.unspecified) {
                                mapExistingTable((DatabaseMappingContainer) selectedMapping);
                            } else {
                                mapColumns((DatabaseMappingContainer) selectedMapping);
                            }
*/
                    }
                }
            }
        });
    }
    {
        Composite hintPanel = new Composite(composite, SWT.NONE);
        hintPanel.setLayout(new GridLayout(3, false));
        hintPanel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
        new Label(hintPanel, SWT.NONE).setText("* DEL - skip column(s)  SPACE - map column(s)");
    }
    setControl(composite);
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBNNode(org.jkiss.dbeaver.model.navigator.DBNNode) KeyAdapter(org.eclipse.swt.events.KeyAdapter) DBNModel(org.jkiss.dbeaver.model.navigator.DBNModel) KeyEvent(org.eclipse.swt.events.KeyEvent) GridLayout(org.eclipse.swt.layout.GridLayout) SelectionEvent(org.eclipse.swt.events.SelectionEvent) ArrayList(java.util.ArrayList) List(java.util.List) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode) DBNProject(org.jkiss.dbeaver.model.navigator.DBNProject) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) IProject(org.eclipse.core.resources.IProject) GridData(org.eclipse.swt.layout.GridData)

Aggregations

KeyEvent (org.eclipse.swt.events.KeyEvent)98 KeyAdapter (org.eclipse.swt.events.KeyAdapter)63 GridData (org.eclipse.swt.layout.GridData)54 GridLayout (org.eclipse.swt.layout.GridLayout)42 Composite (org.eclipse.swt.widgets.Composite)42 SelectionEvent (org.eclipse.swt.events.SelectionEvent)41 Text (org.eclipse.swt.widgets.Text)34 KeyListener (org.eclipse.swt.events.KeyListener)32 SelectionAdapter (org.eclipse.swt.events.SelectionAdapter)32 Label (org.eclipse.swt.widgets.Label)29 ModifyEvent (org.eclipse.swt.events.ModifyEvent)22 ModifyListener (org.eclipse.swt.events.ModifyListener)22 Point (org.eclipse.swt.graphics.Point)21 Button (org.eclipse.swt.widgets.Button)21 MouseEvent (org.eclipse.swt.events.MouseEvent)20 TableViewer (org.eclipse.jface.viewers.TableViewer)19 StyledText (org.eclipse.swt.custom.StyledText)13 FocusEvent (org.eclipse.swt.events.FocusEvent)13 ISelectionChangedListener (org.eclipse.jface.viewers.ISelectionChangedListener)12 SelectionChangedEvent (org.eclipse.jface.viewers.SelectionChangedEvent)12