file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
InsertNextTagHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/InsertNextTagHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.heartsome.cat.common.innertag.InnerTagBean; import net.heartsome.cat.common.ui.innertag.InnerTag; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.NatTableConstant; /** * 插入下一标记 * @author weachy * @version * @since JDK1.5 */ public class InsertNextTagHandler extends AbstractInsertTagHandler { @Override protected int getTagNum() { if (cellEditor.getCellType() == NatTableConstant.SOURCE) { // 此操作是修改源语言,则退出。 return -1; } return getNextTagIndex(); // 得到标记号 } private int getNextTagIndex() { List<InnerTag> currentInnerTag = cellEditor.getSegmentViewer().getCurrentInnerTags(); // 按照标记索引从小到大将当前显示的内部标记排序。 Collections.sort(currentInnerTag, new Comparator<InnerTag>() { public int compare(InnerTag o1, InnerTag o2) { InnerTagBean bean1 = o1.getInnerTagBean(); InnerTagBean bean2 = o2.getInnerTagBean(); if (bean1.getIndex() != bean2.getIndex()) { return bean1.getIndex() - bean2.getIndex(); } else { return bean1.getType().compareTo(bean2.getType()); } } }); int index = 1; for (InnerTag innerTag : currentInnerTag) { if (innerTag.getInnerTagBean().getIndex() != index) { break; } else { switch (innerTag.getInnerTagBean().getType()) { case END: case STANDALONE: index++; break; default: break; } } } // 如果超过了源文本内部标记最大索引,则重置为 -1。 return index <= sourceMaxTagIndex ? index : -1; } }
1,716
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QuickTagsHandler7.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/QuickTagsHandler7.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; /** * 快速插入标记 * @author weachy * @version * @since JDK1.5 */ public class QuickTagsHandler7 extends AbstractInsertTagHandler { @Override protected int getTagNum() { return 7; } }
269
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QuickTagsHandler6.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/QuickTagsHandler6.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; /** * 快速插入标记 * @author weachy * @version * @since JDK1.5 */ public class QuickTagsHandler6 extends AbstractInsertTagHandler { @Override protected int getTagNum() { return 6; } }
269
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AbstractInsertTagHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/AbstractInsertTagHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; import net.heartsome.cat.ts.ui.innertag.ISegmentViewer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.handlers.HandlerUtil; /** * 插入标记 * @author weachy * @version * @since JDK1.5 */ public abstract class AbstractInsertTagHandler extends AbstractHandler { /** 单元格标记器 */ protected StyledTextCellEditor cellEditor; /** ExecutionEvent 对象 */ protected ExecutionEvent event; /** source 内部标记中的最大索引 */ protected int sourceMaxTagIndex; protected ExecutionEvent getEvent() { return event; } public Object execute(ExecutionEvent event) throws ExecutionException { this.event = event; IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; // 不是针对 XLIFFEditorImplWithNatTable 编辑器中的操作,则退出 } cellEditor = HsMultiActiveCellEditor.getFocusCellEditor(); if(cellEditor == null){ return null; } // ICellEditor iCellEditor = HsMultiActiveCellEditor.getTargetEditor().getCellEditor(); // //ActiveCellEditor.getCellEditor(); // if (!(iCellEditor instanceof StyledTextCellEditor)) { // return null; // 不是 StyledTextCellEditor 实例,则退出 // } // // cellEditor = (StyledTextCellEditor) iCellEditor; if (!cellEditor.isEditable()) { cellEditor.showUneditableMessage(); // 显示不可编辑提示信息。 return null; // 不可编辑,则退出 } ISegmentViewer segmentViewer = cellEditor.getSegmentViewer(); int caretOffset = segmentViewer.getTextWidget().getCaretOffset(); // 插入位置 if (caretOffset < 0) { return null; // 文本框已经关闭,则退出 } sourceMaxTagIndex = segmentViewer.getSourceMaxTagIndex(); // source 内部标记中的最大索引 if (sourceMaxTagIndex <= 0) { // source 无内部标记。 return null; } int num = getTagNum(); if (num < 0 || num > sourceMaxTagIndex) { return null; } cellEditor.getSegmentViewer().insertInnerTag(num, caretOffset); return null; } protected abstract int getTagNum(); }
2,554
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QuickTagsHandler2.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/QuickTagsHandler2.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; /** * 快速插入标记 * @author weachy * @version * @since JDK1.5 */ public class QuickTagsHandler2 extends AbstractInsertTagHandler { @Override protected int getTagNum() { return 2; } }
269
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
InsertTagHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/InsertTagHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.handlers.HandlerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.dialog.TagNumberRequest; /** * 插入标记 * @author weachy * @version * @since JDK1.5 */ public class InsertTagHandler extends AbstractInsertTagHandler { @Override protected int getTagNum() { Shell shell = HandlerUtil.getActiveShell(getEvent()); TagNumberRequest request = new TagNumberRequest(shell, sourceMaxTagIndex); request.show(); return request.getNumber(); } }
592
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QuickTagsHandler1.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/QuickTagsHandler1.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; /** * 快速插入标记 * @author weachy * @version * @since JDK1.5 */ public class QuickTagsHandler1 extends AbstractInsertTagHandler { @Override protected int getTagNum() { return 1; } }
269
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QuickTagsHandler8.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/QuickTagsHandler8.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; /** * 快速插入标记 * @author weachy * @version * @since JDK1.5 */ public class QuickTagsHandler8 extends AbstractInsertTagHandler { @Override protected int getTagNum() { return 8; } }
269
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QuickTagsHandler3.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/tags/QuickTagsHandler3.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.tags; /** * 快速插入标记 * @author weachy * @version * @since JDK1.5 */ public class QuickTagsHandler3 extends AbstractInsertTagHandler { @Override protected int getTagNum() { return 3; } }
269
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AcceptMatch3.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/acceptmatch/AcceptMatch3.java
/** * AcceptMatch.java * * Version information : * * Date:2012-11-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.acceptmatch; import net.heartsome.cat.ts.ui.view.IMatchViewPart; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IViewPart; import org.eclipse.ui.PlatformUI; /** * @author Jason * @version * @since JDK1.6 */ public class AcceptMatch3 extends AbstractHandler { /** (non-Javadoc) * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ public Object execute(ExecutionEvent event) throws ExecutionException { IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView( "net.heartsome.cat.ts.ui.translation.view.matchview"); if (viewPart != null && viewPart instanceof IMatchViewPart) { IMatchViewPart matchView = (IMatchViewPart) viewPart; matchView.acceptMatchByIndex(2); } return null; } }
1,617
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AcceptMatch2.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/acceptmatch/AcceptMatch2.java
/** * AcceptMatch.java * * Version information : * * Date:2012-11-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.acceptmatch; import net.heartsome.cat.ts.ui.view.IMatchViewPart; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IViewPart; import org.eclipse.ui.PlatformUI; /** * @author Jason * @version * @since JDK1.6 */ public class AcceptMatch2 extends AbstractHandler { /** (non-Javadoc) * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ public Object execute(ExecutionEvent event) throws ExecutionException { IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView( "net.heartsome.cat.ts.ui.translation.view.matchview"); if (viewPart != null && viewPart instanceof IMatchViewPart) { IMatchViewPart matchView = (IMatchViewPart) viewPart; matchView.acceptMatchByIndex(1); } return null; } }
1,617
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AcceptMatch1.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/acceptmatch/AcceptMatch1.java
/** * AcceptMatch.java * * Version information : * * Date:2012-11-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.acceptmatch; import net.heartsome.cat.ts.ui.view.IMatchViewPart; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IViewPart; import org.eclipse.ui.PlatformUI; /** * @author Jason * @version * @since JDK1.6 */ public class AcceptMatch1 extends AbstractHandler { /** (non-Javadoc) * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ public Object execute(ExecutionEvent event) throws ExecutionException { IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView( "net.heartsome.cat.ts.ui.translation.view.matchview"); if (viewPart != null && viewPart instanceof IMatchViewPart) { IMatchViewPart matchView = (IMatchViewPart) viewPart; matchView.acceptMatchByIndex(0); } return null; } }
1,617
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowPreviousNoteHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowPreviousNoteHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到上一个带批注的文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowPreviousNoteHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int firstSelectedRow = selectedRows[0]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getPreviousNoteSegmentIndex(firstSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在上一个带批注的文本段。"); } return null; } }
1,608
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowPreviousFuzzyHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowPreviousFuzzyHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到上一模糊匹配文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowPreviousFuzzyHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int firstSelectedRow = selectedRows[0]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getPreviousFuzzySegmentIndex(firstSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在上一模糊匹配文本段。"); } return null; } }
1,604
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowPreviousUnapprovedHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowPreviousUnapprovedHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到上一未批准文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowPreviousUnapprovedHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int firstSelectedRow = selectedRows[0]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getPreviousUnapprovedSegmentIndex(firstSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在上一未批准文本段。"); } return null; } }
1,608
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowPreviousUntranslatedHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowPreviousUntranslatedHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到上一未翻译文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowPreviousUntranslatedHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int firstSelectedRow = selectedRows[0]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getPreviousUntranslatedSegmentIndex(firstSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在上一未翻译文本段。"); } return null; } }
1,612
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowFirstSegmentHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowFirstSegmentHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到第一个文本段 * @author weachy * @version * @since JDK1.5 */ public class ShowFirstSegmentHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; xliffEditor.jumpToRow(0); return null; } }
876
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowNextUntranslatedHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowNextUntranslatedHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到下一未翻译文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowNextUntranslatedHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int lastSelectedRow = selectedRows[selectedRows.length - 1]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getNextUntranslatedSegmentIndex(lastSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在下一未翻译文本段。"); } return null; } }
1,624
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowPreviousUntranslatableHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowPreviousUntranslatableHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到上一不可翻译文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowPreviousUntranslatableHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int firstSelectedRow = selectedRows[0]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getPreviousUntranslatableSegmentIndex(firstSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在上一不可翻译文本段。"); } return null; } }
1,622
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowNextSegmentHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowNextSegmentHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.handlers.HandlerUtil; /** * 跳转到下一个文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowNextSegmentHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int lastSelectedRow = selectedRows[selectedRows.length - 1]; XLFHandler handler = xliffEditor.getXLFHandler(); int lastRow = handler.countEditableTransUnit() - 1; if (lastSelectedRow == lastRow) { lastSelectedRow = lastRow - 1; } xliffEditor.jumpToRow(lastSelectedRow + 1); return null; } }
1,391
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowLastSegmentHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowLastSegmentHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.handlers.HandlerUtil; /** * 跳转到最后一个文本段 * @author weachy * @version * @since JDK1.5 */ public class ShowLastSegmentHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; XLFHandler handler = xliffEditor.getXLFHandler(); int lastRow = handler.countEditableTransUnit() - 1; xliffEditor.jumpToRow(lastRow); return null; } }
1,042
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowNextUntranslatableHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowNextUntranslatableHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到下一不可翻译文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowNextUntranslatableHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int lastSelectedRow = selectedRows[selectedRows.length - 1]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getNextUntranslatableSegmentIndex(lastSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在下一不可翻译文本段。"); } return null; } }
1,634
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowPreviousSegmentHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowPreviousSegmentHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.handlers.HandlerUtil; /** * 跳转到上一个文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowPreviousSegmentHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int firstSelectedRow = selectedRows[0]; if (firstSelectedRow == 0) { firstSelectedRow = 1; } xliffEditor.jumpToRow(firstSelectedRow - 1); return null; } }
1,205
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowNextFuzzyHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowNextFuzzyHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到下一模糊匹配文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowNextFuzzyHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int lastSelectedRow = selectedRows[selectedRows.length - 1]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getNextFuzzySegmentIndex(lastSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在下一模糊匹配文本段。"); } return null; } }
1,616
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowNextUnapprovedHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowNextUnapprovedHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到下一未批准文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowNextUnapprovedHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int lastSelectedRow = selectedRows[selectedRows.length - 1]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getNextUnapprovedSegmentIndex(lastSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在下一个未批准文本段。"); } return null; } }
1,623
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ShowNextNoteHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/handler/go/ShowNextNoteHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.go; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; /** * 转到下一个带批注的文本段(此类未使用,因此未做国际化) * @author weachy * @version * @since JDK1.5 */ public class ShowNextNoteHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof XLIFFEditorImplWithNatTable)) { return null; } XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; int[] selectedRows = xliffEditor.getSelectedRows(); if (selectedRows.length < 1) { return null; } Arrays.sort(selectedRows); int lastSelectedRow = selectedRows[selectedRows.length - 1]; XLFHandler handler = xliffEditor.getXLFHandler(); int row = handler.getNextNoteSegmentIndex(lastSelectedRow); if (row != -1) { xliffEditor.jumpToRow(row); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); MessageDialog.openWarning(window.getShell(), "", "不存在下一个带批注的文本段。"); } return null; } }
1,620
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SourceEditMode.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/celleditor/SourceEditMode.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.celleditor; public enum SourceEditMode { /** * 不可编辑 */ DISEDITABLE, /** * 仅可编辑一次 */ ONCE_EDITABLE, /** * 总是可编辑 */ ALWAYS_EDITABLE; /** * 取得下一状态 * @return ; */ public SourceEditMode getNextMode() { switch (this) { case DISEDITABLE: return ONCE_EDITABLE; case ONCE_EDITABLE: return ALWAYS_EDITABLE; case ALWAYS_EDITABLE: return DISEDITABLE; default: return DISEDITABLE; } } /** * 取得下一状态 * @return ; */ public String getImagePath() { switch (this) { case DISEDITABLE: return "images/SourceEditable/disable.png"; case ONCE_EDITABLE: return "images/SourceEditable/once.png"; case ALWAYS_EDITABLE: return "images/SourceEditable/always.png"; default: return "images/SourceEditable/disable.png"; } } }
890
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
EditableManager.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/celleditor/EditableManager.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.celleditor; /** * 可编辑属性管理器,用于 StyledTextCellEditor 的可编辑属性 * @author weachy * @version * @since JDK1.5 */ public abstract class EditableManager { /** 是否可编辑 */ protected boolean editable = true; /** 是否是源文本 */ private boolean isSource; /** 不可编辑状态提示信息 */ private String uneditableMessage; /** * 可编辑属性管理器 * @param isSource * 是否为源文本 */ public EditableManager(boolean isSource) { this.isSource = isSource; } /** 源文本编辑模式 */ private SourceEditMode sourceEditMode = SourceEditMode.DISEDITABLE; /** * 设置源文本编辑模式 * @param editMode * ; */ public void setSourceEditMode(SourceEditMode editMode) { this.sourceEditMode = editMode; } /** * 得到源文本编辑模式 * @return ; */ public SourceEditMode getSourceEditMode() { return sourceEditMode; } /** * 得到可编辑状态 * @return ; */ public boolean getEditable() { if (isSource) { if (sourceEditMode != SourceEditMode.DISEDITABLE) { return true; } } return editable; } /** * 设置可编辑状态 * @param editable * 是否为可编辑; */ public void setEditable(boolean editable) { // this.editable = editable; if (editable) { setupEditMode(); } else { setupReadOnlyMode(); } } /** * 设置不可编辑提示信息,通常提示不可编辑的原因。 * @param uneditableMessage * 不可编辑状态提示信息 ; */ protected void setUneditableMessage(String uneditableMessage) { this.uneditableMessage = uneditableMessage; } /** * 得到不可编辑状态的提示信息。 * @return ; */ public String getUneditableMessage() { return uneditableMessage; } /** * 判断“是否可编辑”状态 ; */ public abstract void judgeEditable(); /** * 设置只读模式 ; */ protected abstract void setupReadOnlyMode(); /** * 设置为编辑模式 ; */ protected abstract void setupEditMode(); }
2,129
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
VerticalViewportLayer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/layer/VerticalViewportLayer.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.layer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.sourceforge.nattable.command.ILayerCommand; import net.sourceforge.nattable.grid.command.ClientAreaResizeCommand; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.IUniqueIndexLayer; import net.sourceforge.nattable.selection.command.MoveSelectionCommand; import net.sourceforge.nattable.selection.command.ScrollSelectionCommand; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.ScrollBar; /** * 垂直布局使用的ViewportLayer * @author weachy * @version * @since JDK1.5 */ public class VerticalViewportLayer extends ViewportLayer { private ScrollBar vBar; // 垂直滚动条 public VerticalViewportLayer(IUniqueIndexLayer underlyingLayer) { super(underlyingLayer); } RowHeightCalculator rowHeightCalculator; public void setRowHeightCalculator(RowHeightCalculator rowHeightCalculator) { this.rowHeightCalculator = rowHeightCalculator; } @Override protected MoveSelectionCommand scrollVerticallyByAPageCommand(ScrollSelectionCommand scrollSelectionCommand) { int rowCount = getRowCount(); return new MoveSelectionCommand(scrollSelectionCommand.getDirection(), rowCount, scrollSelectionCommand.isShiftMask(), scrollSelectionCommand.isControlMask()); } @Override public void moveRowPositionIntoViewport(int scrollableRowPosition, boolean forceEntireCellIntoViewport) { ILayer underlyingLayer = getUnderlyingLayer(); if (underlyingLayer.getRowIndexByPosition(scrollableRowPosition) >= 0) { if (scrollableRowPosition >= getMinimumOriginRowPosition()) { int originRowPosition = getOriginRowPosition(); // 滚动条滚动过的行数 if (scrollableRowPosition < originRowPosition) { // Move up if(scrollableRowPosition %2 != 0){ scrollableRowPosition -=1; } setOriginRowPosition(scrollableRowPosition); } else { scrollableRowPosition = scrollableRowPosition / VerticalNatTableConfig.ROW_SPAN * VerticalNatTableConfig.ROW_SPAN; int clientAreaHeight = getClientAreaHeight(); // 编辑区的高(不包括滚动过的区域) int viewportEndY = underlyingLayer.getStartYOfRowPosition(originRowPosition) + clientAreaHeight; // 编辑区的高(包括滚动过的区域) int scrollableRowStartY = underlyingLayer.getStartYOfRowPosition(scrollableRowPosition); // 当前选中行的起始位置(包括滚动过的区域) if (clientAreaHeight <= 0) { return; } int currentRowHeight = 0; for (int i = 0; i < VerticalNatTableConfig.ROW_SPAN; i++) { if (rowHeightCalculator != null) rowHeightCalculator.recaculateRowHeight(scrollableRowPosition + i); int currentSubRowHeight = underlyingLayer.getRowHeightByPosition(scrollableRowPosition + i); currentRowHeight += currentSubRowHeight; if (currentRowHeight >= clientAreaHeight) { setOriginRowPosition(scrollableRowPosition + i); return; } } int scrollableRowEndY = scrollableRowStartY + currentRowHeight; // 当前选中行的结束位置,包括不可见的部分(包括滚动过的区域) if (viewportEndY < scrollableRowEndY) { // 选中行下半部分没有显示完全时 if (currentRowHeight >= clientAreaHeight) { // 当前行高大于等于编辑区的高 // Move up:设置起始行为当前行 setOriginRowPosition(scrollableRowPosition); } else { // int targetOriginRowPosition = underlyingLayer.getRowPositionByY(scrollableRowEndY // - clientAreaHeight) + 1; // // targetOriginRowPosition = targetOriginRowPosition // // + (VerticalNatTableConfig.ROW_SPAN - targetOriginRowPosition % // VerticalNatTableConfig.ROW_SPAN); // // Move up:将当前选中行显示完全 // setOriginRowPosition(targetOriginRowPosition); scrollableRowPosition = scrollableRowPosition + (VerticalNatTableConfig.ROW_SPAN - scrollableRowPosition % VerticalNatTableConfig.ROW_SPAN); int ch = clientAreaHeight; int r = scrollableRowPosition; for (; r > 0; r--) { int h = rowHeightCalculator.recaculateRowHeight(r); ch -= h; if (ch < 0) { break; } } r += 1; if(r %2 == 0){ r -=1; } setOriginRowPosition(r); } } } } } } @Override public boolean doCommand(ILayerCommand command) { boolean b = super.doCommand(command); if (command instanceof ClientAreaResizeCommand && command.convertToTargetLayer(this)) { ClientAreaResizeCommand clientAreaResizeCommand = (ClientAreaResizeCommand) command; if (vBar == null) { vBar = clientAreaResizeCommand.getScrollable().getVerticalBar(); // 垂直滚动条 Listener[] listeners = vBar.getListeners(SWT.Selection); for (Listener listener : listeners) { // 清除默认的 Selection 监听(在类 ScrollBarHandlerTemplate 中添加的) vBar.removeListener(SWT.Selection, listener); } vBar.addListener(SWT.Selection, new Listener() { // private int lastPosition = 0; // private int lastSelection = 0; private IUniqueIndexLayer scrollableLayer = VerticalViewportLayer.this.getScrollableLayer(); public void handleEvent(Event event) { // 滚动滚动条前提交当前处于编辑状态的文本段 // ActiveCellEditor.commit(); // ScrollBar scrollBar = (ScrollBar) event.widget; // // int selection = scrollBar.getSelection(); // int position = scrollableLayer.getRowPositionByY(selection); // // if (lastSelection == selection) { // return; // } // HsMultiActiveCellEditor.commit(true); // // VerticalViewportLayer.this.invalidateVerticalStructure(); // 清除缓存 // lastPosition = position / VerticalNatTableConfig.ROW_SPAN * VerticalNatTableConfig.ROW_SPAN; // VerticalViewportLayer.this.setOriginRowPosition(lastPosition); // vBar.setIncrement(getRowHeightByPosition(0) * VerticalNatTableConfig.ROW_SPAN); // // 设置滚动条增量为两倍行高 // // lastSelection = selection; // HsMultiActiveCellEditor.commit(true); ScrollBar scrollBar = (ScrollBar) event.widget; int position = scrollableLayer.getRowPositionByY(scrollBar.getSelection()); VerticalViewportLayer.this.invalidateVerticalStructure(); VerticalViewportLayer.this.setOriginRowPosition(position); scrollBar.setIncrement(VerticalViewportLayer.this.getRowHeightByPosition(0)); HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.getCurrent()); } }); } } return b; } }
7,209
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
VerticalLayerRowHeaderLayer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/layer/VerticalLayerRowHeaderLayer.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.layer; import net.sourceforge.nattable.data.IDataProvider; import net.sourceforge.nattable.layer.DataLayer; import net.sourceforge.nattable.layer.cell.LayerCell; public class VerticalLayerRowHeaderLayer extends DataLayer { public VerticalLayerRowHeaderLayer(IDataProvider dataProvider, int defaultColumnWidth, int defaultRowHeight) { super(dataProvider,defaultColumnWidth,defaultRowHeight); } @Override public LayerCell getCellByPosition(int columnPosition, int rowPosition) { if (columnPosition < 0 || columnPosition >= getColumnCount() || rowPosition < 0 || rowPosition >= getRowCount()) { return null; } int rowSpan = 1; int columnSpan = 1; if (columnPosition == 0) { if((rowPosition+1)%3 == 1){ rowSpan = 3; } } return new LayerCell(this, columnPosition, rowPosition, columnPosition, rowPosition, columnSpan, rowSpan); } }
921
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LayerUtil.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/layer/LayerUtil.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.layer; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.layer.CompositeLayer; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.IUniqueIndexLayer; import net.sourceforge.nattable.viewport.ViewportLayer; public class LayerUtil extends net.sourceforge.nattable.layer.LayerUtil { private static int layoutX; private static int layoutY; public static void setBodyLayerPosition(int layoutX, int layoutY) { LayerUtil.layoutX = layoutX; LayerUtil.layoutY = layoutY; } @SuppressWarnings("unchecked") public static <T extends ILayer> T getLayer(NatTable table, Class<T> targetLayerClass) { if (targetLayerClass.equals(NatTable.class)) { return (T) table; } ILayer layer = table.getUnderlyingLayerByPosition(0, 0); // 得到 CompositeLayer if (layer instanceof CompositeLayer) { if (targetLayerClass.equals(CompositeLayer.class)) { return (T) layer; } return getLayer((CompositeLayer) layer, targetLayerClass); } return null; } @SuppressWarnings("unchecked") public static <T extends ILayer> T getLayer(CompositeLayer compositeLayer, Class<T> targetLayerClass) { if (targetLayerClass.equals(CompositeLayer.class)) { return (T) compositeLayer; } ILayer layer = compositeLayer.getChildLayerByLayoutCoordinate(layoutX, layoutY); while (layer != null && !(targetLayerClass.isInstance(layer))) { layer = layer.getUnderlyingLayerByPosition(0, 0); } return (T) layer; } // AbstractLayerTransform public static <T extends IUniqueIndexLayer> int getLowerLayerRowPosition(NatTable table, int sourceRowPosition, Class<T> targetLayerClass) { ViewportLayer viewportLayer = getLayer(table, ViewportLayer.class); int originRowPosition = viewportLayer.getOriginRowPosition(); sourceRowPosition -= originRowPosition + 1; T t = getLayer(table, targetLayerClass); return convertRowPosition(viewportLayer, sourceRowPosition, t); } public static <T extends ILayer> int getUpperLayerRowPosition(NatTable table, int sourceRowPosition, Class<T> sourceLayerClass) { ViewportLayer viewportLayer = getLayer(table, ViewportLayer.class); int originRowPosition = viewportLayer.getOriginRowPosition(); T t = getLayer(table, sourceLayerClass); sourceRowPosition = convertRowPosition(t, sourceRowPosition, viewportLayer); sourceRowPosition += originRowPosition + 1; return sourceRowPosition; } // public static int getRowPosition(ILayer sourceLayer, int sourceRowPosition, // ILayer targetLayer) { // Assert.isNotNull(sourceLayer); // Assert.isNotNull(targetLayer); // // if (sourceLayer.equals(targetLayer)) { // return sourceRowPosition; // } // if (targetLayer instanceof IUniqueIndexLayer) { // return convertRowPosition(sourceLayer, sourceRowPosition, (IUniqueIndexLayer) targetLayer); // } else if (targetLayer instanceof NatTable) { // ViewportLayer viewportLayer = getLayer((NatTable) targetLayer, ViewportLayer.class); // int originRowPosition = viewportLayer.getOriginRowPosition(); // int targetRowPostion = convertRowPosition(sourceLayer, sourceRowPosition, viewportLayer); // return targetRowPostion + originRowPosition + 1; // } else { // throw new IllegalArgumentException("无法识别的参数:参数必须为接口 IUniqueIndexLayer 的实例或 NatTable 的实例。"); // } // } /** * 通过列索引得到列位置 * @param table * NatTable对象 * @param columnIndex * 列索引 * @return 列位置; */ public static int getColumnPositionByIndex(NatTable table, int columnIndex) { int columnCount = table.getColumnCount(); for (int i = 0; i < columnCount; i++) { if (table.getColumnIndexByPosition(i) == columnIndex) { return i; } } return -1; } /** * 通过行索引得到行位置 * @param table * NatTable对象 * @param rowIndex * 列索引 * @return 行位置; */ public static int getRowPositionByIndex(NatTable table, int rowIndex) { int rowCount = table.getRowCount(); for (int i = 0; i < rowCount; i++) { if (table.getRowIndexByPosition(i) == rowIndex) { return i; } } return -1; } }
4,225
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
HorizontalViewportLayer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/layer/HorizontalViewportLayer.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.layer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.sourceforge.nattable.command.ILayerCommand; import net.sourceforge.nattable.grid.command.ClientAreaResizeCommand; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.IUniqueIndexLayer; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.ScrollBar; /** * 水平布局使用的ViewportLayer * @author weachy * @version * @since JDK1.5 */ public class HorizontalViewportLayer extends ViewportLayer { public HorizontalViewportLayer(IUniqueIndexLayer underlyingLayer) { super(underlyingLayer); } RowHeightCalculator rowHeightCalculator; public void setRowHeightCalculator(RowHeightCalculator rowHeightCalculator) { this.rowHeightCalculator = rowHeightCalculator; } public void moveRowPositionIntoViewport(int scrollableRowPosition, boolean forceEntireCellIntoViewport) { ILayer underlyingLayer = getUnderlyingLayer(); if (underlyingLayer.getRowIndexByPosition(scrollableRowPosition) >= 0) { if (scrollableRowPosition >= getMinimumOriginRowPosition()) { int originRowPosition = getOriginRowPosition(); // 滚动条滚动过的行数 if (scrollableRowPosition < originRowPosition) { // Move up setOriginRowPosition(scrollableRowPosition); } else { int scrollableRowStartY = underlyingLayer.getStartYOfRowPosition(scrollableRowPosition); // 当前选中行的起始位置(包括滚动过的区域) if (rowHeightCalculator != null) rowHeightCalculator.recaculateRowHeight(scrollableRowPosition); int currentRowHeight = underlyingLayer.getRowHeightByPosition(scrollableRowPosition); int scrollableRowEndY = scrollableRowStartY + currentRowHeight; // 当前选中行的结束位置,包括不可见的部分(包括滚动过的区域) int clientAreaHeight = getClientAreaHeight(); // 编辑区的高(不包括滚动过的区域) int viewportEndY = underlyingLayer.getStartYOfRowPosition(originRowPosition) + clientAreaHeight; // 编辑区的高(包括滚动过的区域) if (viewportEndY < scrollableRowEndY) { // 选中行下半部分没有显示完全时 if (currentRowHeight >= clientAreaHeight) { // 当前行高大于等于编辑区的高 // Move up:设置起始行为当前行 setOriginRowPosition(scrollableRowPosition); } else { // int targetOriginRowPosition = underlyingLayer.getRowPositionByY(scrollableRowEndY // - clientAreaHeight) + 1; // // Move up:将当前选中行显示完全 // setOriginRowPosition(targetOriginRowPosition); int ch = clientAreaHeight; int r = scrollableRowPosition; for(; r > 0 ;r--){ int h = rowHeightCalculator.recaculateRowHeight(r); ch -= h; if(ch < 0){ break; } } setOriginRowPosition(r + 1); } } } } } } @Override public boolean doCommand(ILayerCommand command) { boolean b = super.doCommand(command); if (command instanceof ClientAreaResizeCommand && command.convertToTargetLayer(this)) { ClientAreaResizeCommand clientAreaResizeCommand = (ClientAreaResizeCommand) command; final ScrollBar vBar = clientAreaResizeCommand.getScrollable().getVerticalBar(); // 垂直滚动条 Listener[] listeners = vBar.getListeners(SWT.Selection); for (Listener listener : listeners) { // 清除默认的 Selection 监听(在类 ScrollBarHandlerTemplate 中添加的) vBar.removeListener(SWT.Selection, listener); } vBar.addListener(SWT.Selection, new Listener() { private ViewportLayer viewportLayer = HorizontalViewportLayer.this; private IUniqueIndexLayer scrollableLayer = viewportLayer.getScrollableLayer(); public void handleEvent(Event event) { // 滚动滚动条前提交当前处于编辑状态的文本段 HsMultiActiveCellEditor.commit(true); ScrollBar scrollBar = (ScrollBar) event.widget; int position = scrollableLayer.getRowPositionByY(scrollBar.getSelection()); viewportLayer.invalidateVerticalStructure(); viewportLayer.setOriginRowPosition(position); vBar.setIncrement(viewportLayer.getRowHeightByPosition(0)); // HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.getCurrent()); } }); } return b; } }
4,755
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
RowHeightCalculator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/layer/RowHeightCalculator.java
/** * RowHeightCalculator.java * * Version information : * * Date:2013-8-12 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.layer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable.BodyLayerStack; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.config.CellConfigAttributes; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.painter.cell.ICellPainter; import net.sourceforge.nattable.selection.SelectionLayer; /** * @author Jason * @version * @since JDK1.6 */ public class RowHeightCalculator { private BodyLayerStack bodyLayer; private NatTable table; private final int defaultRowheight; public RowHeightCalculator(BodyLayerStack bodyLayer, NatTable table, int defaultRowHeight) { this.defaultRowheight = defaultRowHeight; this.bodyLayer = bodyLayer; this.table = table; } public int recaculateRowHeight(int rowIndex) { int height = bodyLayer.getBodyDataLayer().getRowHeightByPosition(rowIndex); // if (height == defaultRowheight) { height = getPreferredRowHeight(rowIndex, table.getConfigRegistry(), table.getClientArea().height); bodyLayer.getBodyDataLayer().setRowHeightByPositionWithoutEvent(rowIndex, height); // } return height; } private int getPreferredRowHeight(int rowPosition, IConfigRegistry configRegistry, int clientAreaHeight) { int maxHeight = 0; ICellPainter painter; LayerCell cell; SelectionLayer layer = bodyLayer.getSelectionLayer(); for (int columnPosition = 0; columnPosition < layer.getColumnCount(); columnPosition++) { cell = layer.getCellByPosition(columnPosition, rowPosition); if (cell != null) { painter = configRegistry.getConfigAttribute(CellConfigAttributes.CELL_PAINTER, cell.getDisplayMode(), bodyLayer.getConfigLabelsByPosition(columnPosition, rowPosition).getLabels()); if (painter != null) { int preferedHeight = painter.getPreferredHeight(cell, null, configRegistry); maxHeight = (preferedHeight > maxHeight) ? preferedHeight : maxHeight; } } } if (maxHeight > clientAreaHeight) { return clientAreaHeight; } return maxHeight; } }
2,843
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XLIFFEditorImplWithNatTable.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/XLIFFEditorImplWithNatTable.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import net.heartsome.cat.common.core.Constant; import net.heartsome.cat.common.innertag.TagStyle; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.common.locale.LocaleService; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.core.bean.NoteBean; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.Activator; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.preferencepage.IPreferenceConstants; import net.heartsome.cat.ts.ui.xliffeditor.nattable.UpdateDataBean; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.XLIFFEditorCompositeLayerConfiguration; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.XLIFFEditorSelectionLayerConfiguration; import net.heartsome.cat.ts.ui.xliffeditor.nattable.dataprovider.VerticalLayerBodyDataProvider; import net.heartsome.cat.ts.ui.xliffeditor.nattable.dataprovider.XliffEditorDataProvider; import net.heartsome.cat.ts.ui.xliffeditor.nattable.dialog.CustomFilterDialog; import net.heartsome.cat.ts.ui.xliffeditor.nattable.exception.UnexpectedTypeExcetion; import net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.AutoResizeCurrentRowsCommand; import net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.AutoResizeCurrentRowsCommandHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.UpdateDataAndAutoResizeCommandHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.HorizontalViewportLayer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.RowHeightCalculator; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.VerticalViewportLayer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.menu.BodyMenuConfiguration; import net.heartsome.cat.ts.ui.xliffeditor.nattable.painter.LineNumberPainter; import net.heartsome.cat.ts.ui.xliffeditor.nattable.painter.StatusPainter; import net.heartsome.cat.ts.ui.xliffeditor.nattable.painter.XliffEditorGUIHelper; import net.heartsome.cat.ts.ui.xliffeditor.nattable.painter.XliffEditorGUIHelper.ImageName; import net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester.AddSegmentToTMPropertyTester; import net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester.SignOffPropertyTester; import net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester.UnTranslatedPropertyTester; import net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester.XLIFFEditorSelectionPropertyTester; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.command.FindReplaceCommandHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.selection.HorizontalRowSelectionModel; import net.heartsome.cat.ts.ui.xliffeditor.nattable.selection.IRowIdAccessor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.selection.RowSelectionProvider; import net.heartsome.cat.ts.ui.xliffeditor.nattable.selection.VerticalRowSelectionModel; import net.heartsome.cat.ts.ui.xliffeditor.nattable.sort.NatTableSortModel; import net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable.UpdateSegmentsOperation; import net.heartsome.cat.ts.ui.xliffeditor.nattable.utils.NattableUtil; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.columnRename.RenameColumnHeaderCommand; import net.sourceforge.nattable.config.AbstractRegistryConfiguration; import net.sourceforge.nattable.config.CellConfigAttributes; import net.sourceforge.nattable.config.ConfigRegistry; import net.sourceforge.nattable.config.DefaultNatTableStyleConfiguration; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.config.IConfiguration; import net.sourceforge.nattable.config.IEditableRule; import net.sourceforge.nattable.coordinate.PositionCoordinate; import net.sourceforge.nattable.data.IDataProvider; import net.sourceforge.nattable.data.ISpanningDataProvider; import net.sourceforge.nattable.data.ReflectiveColumnPropertyAccessor; import net.sourceforge.nattable.edit.EditConfigAttributes; import net.sourceforge.nattable.grid.GridRegion; import net.sourceforge.nattable.grid.command.ClientAreaResizeCommand; import net.sourceforge.nattable.grid.data.DefaultColumnHeaderDataProvider; import net.sourceforge.nattable.grid.layer.ColumnHeaderLayer; import net.sourceforge.nattable.hideshow.ColumnHideShowLayer; import net.sourceforge.nattable.layer.AbstractLayerTransform; import net.sourceforge.nattable.layer.CompositeLayer; import net.sourceforge.nattable.layer.DataLayer; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.SpanningDataLayer; import net.sourceforge.nattable.layer.cell.ColumnOverrideLabelAccumulator; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.layer.config.DefaultColumnHeaderStyleConfiguration; import net.sourceforge.nattable.painter.cell.ICellPainter; import net.sourceforge.nattable.resize.command.MultiColumnResizeCommand; import net.sourceforge.nattable.search.command.SearchCommand; import net.sourceforge.nattable.selection.ISelectionModel; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.command.SelectAllCommand; import net.sourceforge.nattable.selection.command.SelectCellCommand; import net.sourceforge.nattable.selection.command.SelectColumnCommand; import net.sourceforge.nattable.sort.SortHeaderLayer; import net.sourceforge.nattable.sort.config.SingleClickSortConfiguration; import net.sourceforge.nattable.style.CellStyleAttributes; import net.sourceforge.nattable.style.CellStyleUtil; import net.sourceforge.nattable.style.DisplayMode; import net.sourceforge.nattable.style.HorizontalAlignmentEnum; import net.sourceforge.nattable.style.Style; import net.sourceforge.nattable.util.GUIHelper; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.IOperationHistory; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.commands.operations.ObjectUndoContext; import org.eclipse.core.commands.operations.OperationHistoryFactory; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.filesystem.URIUtil; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.util.Util; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.window.DefaultToolTip; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorRegistry; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IPropertyListener; import org.eclipse.ui.IURIEditorInput; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.ide.FileStoreEditorInput; import org.eclipse.ui.ide.ResourceUtil; import org.eclipse.ui.operations.UndoRedoActionGroup; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ximpleware.NavException; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * 使用 Nat Table 实现的 XLIFF 编辑器 * @author Cheney,Weachy,Leakey * @since JDK1.5 */ public class XLIFFEditorImplWithNatTable extends EditorPart implements IXliffEditor { private static final Logger LOGGER = LoggerFactory.getLogger(XLIFFEditorImplWithNatTable.class); /** 常量,编辑器ID。 */ public static final String ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable"; /** 标签列的标记 */ public static final String FLAG_CELL_LABEL = "FLAG_Cell_LABEL"; /** 可编辑单元格的标记 */ // public static final String EDIT_CELL_LABEL = "EDIT_Cell_LABEL"; public static final String SOURCE_EDIT_CELL_LABEL = "SOURCE_EDIT_CELL_LABEL"; public static final String TARGET_EDIT_CELL_LABEL = "TARGET_EDIT_CELL_LABEL"; /** 连接符号,用于连接源语言和目标语言的种类,例如“zh-CN -&gt; en” */ private static final String Hyphen = " -> "; /** 编辑器的标题图 */ private Image titleImage; /** 为 NatTable 提供内容的数据提供者 */ private XliffEditorDataProvider<TransUnitBean> bodyDataProvider; /** 需要在 NatTable 中显示的数据对象的属性值 */ private String[] propertyNames; /** 数据对象的属性值对应在 NatTable 中显示的列头名称 */ private Map<String, String> propertyToLabels; /** 数据对象的属性值对应的列在 NatTable 中显示的列宽 */ private Map<String, Double> propertyToColWidths; /** NatTable 中的 Body Region 的 Layout Stack */ private BodyLayerStack bodyLayer; /** NatTable */ private NatTable table; private Combo cmbFilter; /** source 列的列名 */ private String srcColumnName; public String getSrcColumnName() { return srcColumnName; } /** target 列的列名 */ private String tgtColumnName; /** * 获取目标语言列名 */ public String getTgtColumnName() { return tgtColumnName; } /** 是否为水平布局 */ private boolean isHorizontalLayout = true; /** NatTable所在的Composite */ private Composite parent; /** XLIFF 文件处理 */ private XLFHandler handler = new XLFHandler(); /** The editor's property change listener. */ // private IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener(); /** The editor's font properties change listener. */ private IPropertyChangeListener fFontPropertyChangeListener = new FontPropertyChangeListener(); /** 底部状态栏管理器。 */ private IStatusLineManager statusLineManager; /** 显示在状态栏处的条目。 */ private static XLIFFEditorStatusLineItemWithProgressBar translationItem; private static XLIFFEditorStatusLineItemWithProgressBar approveItem; private static Image statusLineImage = net.heartsome.cat.ts.ui.xliffeditor.nattable.Activator.getImageDescriptor( "icons/fileInfo.png").createImage(); /** 打开文件成功 */ private boolean openFileSucceed; /** 语言过滤条件 */ private String langFilterCondition = ""; /** * 获得语言过滤条件 * @return ; */ public String getLangFilterCondition() { return langFilterCondition; } /** 此编辑器的内部标记显示状态 */ private TagStyleManager tagStyleManager = new TagStyleManager(); /** * 得到内部标记样式管理器 * @return ; */ public TagStyleManager getTagStyleManager() { return tagStyleManager; } private boolean multiFile = false; /** 当前editor所打开的多个文件的集合 --robert */ private List<File> multiFileList = new ArrayList<File>(); /** 是否保存该编辑器,下次系统打开时会重新加载 --robert */ private boolean isStore = false; /** Xliff切割点的list , 其保存的是切割点的rowID, <div style="color:red">这个未排序,请注意</div> --robert */ private List<String> splitXliffPoints = new ArrayList<String>(); /** * 是否打开了多文件 * @return ; */ public boolean isMultiFile() { return multiFile; } public XLIFFEditorImplWithNatTable() { } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#getXLFHandler() */ public XLFHandler getXLFHandler() { return handler; } public NatTable getTable() { return table; } public void setSplitXliffPoints(List<String> splitXliffPoints) { this.splitXliffPoints = splitXliffPoints; } /** * 是否是水平布局显示 * @return ; */ public boolean isHorizontalLayout() { return isHorizontalLayout; } /** “重做”、“撤销”操作的历史记录 */ private static final IOperationHistory HISTORY = OperationHistoryFactory.getOperationHistory(); /** 绑定到此编辑器实例的“重做”上下文 */ private IUndoContext undoContext; /** “撤销”、“重做” ActionGroup */ private UndoRedoActionGroup undoRedoGroup; /* * Initialize the workbench operation history for our undo context. */ private void initializeOperationHistory() { // create a unique undo context to // represent this view's undo history undoContext = new ObjectUndoContext(this); // set the undo limit for this context based on the preference HISTORY.setLimit(undoContext, 99); // 初始化“重做、”“撤销”菜单项 undoRedoGroup = new UndoRedoActionGroup(getSite(), undoContext, true); } /** * 设置全局的 Action:CUT、COPY、PASTE、SELECT_ALL、DELETE ; */ private void setGlobalActionHandler() { IActionBars actionBars = getEditorSite().getActionBars(); if (undoRedoGroup != null) { undoRedoGroup.fillActionBars(actionBars); // 设置“重做”、“撤销”菜单项 } actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), tableSelectAllAction); // 设置“全选”菜单项 actionBars.updateActionBars(); } /* * Get the operation history from the workbench. */ // private IOperationHistory getOperationHistory() { // return OperationHistoryFactory.getOperationHistory(); // // 或者使用:PlatformUI.getWorkbench().getOperationSupport().getOperationHistory(); // } @Override public void doSave(IProgressMonitor monitor) { // Add By Leakey 释放资源 handler = null; table = null; System.gc(); } @Override public void doSaveAs() { performSaveAs(getProgressMonitor()); } /** * 执行另存为 * @param progressMonitor * 进度条; */ private void performSaveAs(IProgressMonitor progressMonitor) { Shell shell = getSite().getShell(); final IEditorInput input = getEditorInput(); final IEditorInput newInput; // 新的EditorInput final File oldFile; // 原始的file // if (input instanceof IURIEditorInput && !(input instanceof IFileEditorInput)) { // 外部文件 FileDialog dialog = new FileDialog(shell, SWT.SAVE); URI uri = ((IURIEditorInput) input).getURI(); IPath oldPath = URIUtil.toPath(uri); if (oldPath != null) { dialog.setFileName(oldPath.lastSegment()); dialog.setFilterPath(oldPath.removeLastSegments(1).toOSString()); // 设置所在文件夹 oldFile = oldPath.toFile(); } else { oldFile = new File(uri); } String newPath = dialog.open(); // 得到保存路径 if (newPath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } // 检查文件是否存在,如果存在则确认是否覆盖 final File localFile = new File(newPath); if (localFile.exists()) { String msg = MessageFormat.format(Messages.getString("editor.XLIFFEditorImplWithNatTable.msg1"), newPath); MessageDialog overwriteDialog = new MessageDialog(shell, Messages.getString("editor.XLIFFEditorImplWithNatTable.overwriteDialog"), null, msg, MessageDialog.WARNING, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 1 /* 'No' is the default */); if (overwriteDialog.open() != MessageDialog.OK) { if (progressMonitor != null) { progressMonitor.setCanceled(true); return; } } } IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFileForLocation(URIUtil.toPath(localFile.toURI())); // 得到新文件 if (file != null) { // 是“WorkSpace”内的文件 newInput = new FileEditorInput(file); } else { // 不是“WorkSpace”内的文件 try { IFileStore fileStore = EFS.getStore(localFile.toURI()); newInput = new FileStoreEditorInput(fileStore); } catch (CoreException ex) { // EditorsPlugin.log(ex.getStatus()); LOGGER.error("", ex); String title = Messages.getString("editor.XLIFFEditorImplWithNatTable.msgTitle1"); String msg = MessageFormat.format(Messages.getString("editor.XLIFFEditorImplWithNatTable.msg2"), ex.getMessage()); MessageDialog.openError(shell, title, msg); return; } } // } else { // SaveAsDialog dialog = new SaveAsDialog(shell); // // 源文件 // IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; // if (original != null) { // dialog.setOriginalFile(original); // 添加源文件信息 // oldFile = original.getLocation().toFile(); // if ((!oldFile.exists() || !oldFile.canRead()) && original != null) { // String message = MessageFormat.format( // "The original file ''{0}'' has been deleted or is not accessible.", original.getName()); // dialog.setErrorMessage(null); // dialog.setMessage(message, IMessageProvider.WARNING); // } // } else { // oldFile = null; // } // dialog.create(); // // if (dialog.open() == MessageDialog.CANCEL) { // 打开“另存为”对话框,用户点击了“取消”按钮 // if (progressMonitor != null) // progressMonitor.setCanceled(true); // return; // } // // IPath filePath = dialog.getResult(); // 获得用户选择的路径 // if (filePath == null) { // 检查路径 // if (progressMonitor != null) // progressMonitor.setCanceled(true); // return; // } // // IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); // IFile file = root.getFile(filePath); // newInput = new FileEditorInput(file); // } saveAs(newInput, oldFile, progressMonitor); } /** * 另存文件 * @param newInput * @param oldFile * @param monitor * ; */ private void saveAs(IEditorInput newInput, File oldFile, IProgressMonitor monitor) { if (newInput == null || oldFile == null) { return; } boolean success = false; try { if (newInput instanceof FileEditorInput) { IFile newFile = (IFile) newInput.getAdapter(IFile.class); if (newFile != null) { FileInputStream fis = new FileInputStream(oldFile); BufferedInputStream bis = new BufferedInputStream(fis); if (newFile.exists()) { newFile.setContents(bis, false, true, monitor); } else { newFile.create(bis, true, monitor); } bis.close(); fis.close(); } } else if (newInput instanceof FileStoreEditorInput) { FileStoreEditorInput storeEditorInput = (FileStoreEditorInput) newInput; File newFile = new File(storeEditorInput.getURI()); copyFile(oldFile, newFile); } success = true; } catch (CoreException e) { LOGGER.error("", e); final IStatus status = e.getStatus(); if (status == null || status.getSeverity() != IStatus.CANCEL) { String title = Messages.getString("editor.XLIFFEditorImplWithNatTable.msgTitle1"); String msg = MessageFormat.format(Messages.getString("editor.XLIFFEditorImplWithNatTable.msg2"), e.getMessage()); MessageDialog.openError(getSite().getShell(), title, msg); } } catch (FileNotFoundException e) { LOGGER.error("", e); e.printStackTrace(); } catch (IOException e) { LOGGER.error("", e); e.printStackTrace(); } finally { if (success) { setInput(newInput); } } if (monitor != null) { monitor.setCanceled(!success); } } /** * 复制单个文件 * @param oldPath * String 原文件路径 如:c:/fqf.txt * @param newPath * String 复制后路径 如:f:/fqf.txt * @return boolean */ private void copyFile(File oldFile, File newFile) { try { if (oldFile.exists()) { // 原文件存在时 ResourceUtils.copyFile(oldFile, newFile); } else { throw new Exception(MessageFormat.format(Messages.getString("editor.XLIFFEditorImplWithNatTable.msg3"), oldFile.getAbsolutePath())); } } catch (Exception e) { MessageDialog.openError(getSite().getShell(), Messages.getString("editor.XLIFFEditorImplWithNatTable.msgTitle2"), e.getMessage()); LOGGER.debug(e.getMessage()); e.printStackTrace(); } } @Override protected void setInput(IEditorInput input) { super.setInput(input); setPartName(input.getName()); } /** * 返回与此编辑器相关的进度监视器。 * @return 与此编辑器相关的进度监视器 */ protected IProgressMonitor getProgressMonitor() { IProgressMonitor pm = null; IStatusLineManager manager = getStatusLineManager(); if (manager != null) pm = manager.getProgressMonitor(); return pm != null ? pm : new NullProgressMonitor(); } /** * 获取此编辑器的状态栏管理者。 * @return 状态栏的管理者 */ protected IStatusLineManager getStatusLineManager() { return getEditorSite().getActionBars().getStatusLineManager(); } private String titleToolTip; @Override public String getTitleToolTip() { if (titleToolTip != null) { return titleToolTip; } return super.getTitleToolTip(); } // /** // * 处理首选项改变事件 // * @see // org.eclipse.ui.texteditor.AbstractTextEditor#handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent) // */ // protected void handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent event) { // String property = event.getProperty(); // // if (IPreferenceConstants.CONTEXTBG1.equals(property) || IPreferenceConstants.CONTEXTBG2.equals(property)) { // CompositeLayer compositeLayer = (CompositeLayer) table.getLayer(); // // compositeLayer.clearConfiguration(); // addRowBackgroundColor(compositeLayer); // table.configure(); // } // } /** * 添加行背景色(奇数行和偶数行不同) * @param compositeLayer * ; */ private void addRowBackgroundColor(CompositeLayer compositeLayer) { // Color evenRowBgColor = GUIHelper.getColor(238, 248, 255); // Color oddRowBgColor = GUIHelper.getColor(255, 255, 255); Style oddStyle = new Style(); oddStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_WHITE); Style evenStyle = new Style(); evenStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_WHITE); XLIFFEditorCompositeLayerConfiguration compositeLayerConfiguraion = new XLIFFEditorCompositeLayerConfiguration( compositeLayer, oddStyle, evenStyle, this); compositeLayer.addConfiguration(compositeLayerConfiguraion); } @Override public boolean isDirty() { // TODO Auto-generated method stub return false; } @Override public boolean isSaveAsAllowed() { return true; // 允许“另存为” } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (LOGGER.isDebugEnabled()) { LOGGER.debug(Messages.getString("editor.XLIFFEditorImplWithNatTable.logger1")); } setSite(site); setInput(input); List<File> files = null; if (input instanceof FileStoreEditorInput) { FileStoreEditorInput editorInput = (FileStoreEditorInput) input; files = Arrays.asList(new File(editorInput.getURI())); setPartName(input.getName()); } else if (input instanceof FileEditorInput) { FileEditorInput editorInput = (FileEditorInput) input; try { files = getFilesByFileEditorInput(editorInput); } catch (CoreException e) { throw new PartInitException(e.getMessage(), e); } if (files != null) { if (files instanceof ArrayList<?>) { // “打开项目”的情况,会返回 java.util.ArrayList<?> 对象。 if (files.size() <= 0) { close(); // 关闭此编辑器。 return; } // 设置Editor标题栏的显示名称,否则名称用plugin.xml中的name属性 StringBuffer nameSB = new StringBuffer(); for (File file : files) { nameSB.append(file.getName() + "、"); } nameSB.deleteCharAt(nameSB.length() - 1); String partName = ""; if (nameSB.length() > 17) { partName = nameSB.substring(0, 17) + "..."; } else { partName = nameSB.toString(); } setPartName(partName); titleToolTip = nameSB.toString(); multiFile = true; multiFileList = files; } else { // 打开文件的一般情况 setPartName(input.getName()); String name = input.getName().toLowerCase(); if (!CommonFunction.validXlfExtensionByFileName(name)) { // IFile file = (IFile) input.getAdapter(IFile.class); // 打开正转换对话框 // ConverterCommandTrigger.openConversionDialog(site.getWorkbenchWindow(), file); close(); // 关闭此编辑器。 return; } } } } // if (files == null || !XLFValidator.validateXlifFiles(files)) { // close(); // 关闭此编辑器。 // return; // } openFile(files, input); } /** * 打开文件 * @param files * @param input * @throws PartInitException * ; */ private void openFile(List<File> files, IEditorInput input) throws PartInitException { OpenFile of = new OpenFile(files); try { // TODO 此处偶尔会出现一个异常 PartInitException,但并不影响正常运行。目前原因不明。 /** * 异常信息:<br /> * Warning: Detected recursive attempt by part net.heartsome.cat.ts.ui.xliffeditor.nattable.editor to create * itself (this is probably, but not necessarily, a bug) */ if (!PlatformUI.getWorkbench().isStarting()) { new ProgressMonitorDialog(getSite().getShell()).run(false, true, of); } else { of.run(null); } // of.run(null); } catch (InvocationTargetException e) { throw new PartInitException(e.getMessage(), e); } catch (InterruptedException e) { throw new PartInitException(e.getMessage(), e); } Map<String, Object> result = of.getOpenFileResult(); if (result == null || Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) result.get(Constant.RETURNVALUE_RESULT)) { openFileSucceed = false; Throwable e = (Throwable) result.get(Constant.RETURNVALUE_EXCEPTION); if (e != null) { throw new PartInitException(e.getMessage(), e); } String msg = (String) result.get(Constant.RETURNVALUE_MSG); if (msg == null || msg.length() == 0) { msg = Messages.getString("editor.XLIFFEditorImplWithNatTable.msg4"); } MessageDialog.openError(getSite().getShell(), Messages.getString("editor.XLIFFEditorImplWithNatTable.msgTitle3"), msg); close(); // 关闭此编辑器。 } else { // 成功打开文件时 openFileSucceed = true; // 判断所打开的文件是否为空,如果为空,进行提示,并关闭编辑器, robert 2013-04-01 int tuSize = handler.countTransUnit(); if (tuSize <= 0) { MessageDialog.openWarning(getSite().getShell(), Messages.getString("dialog.UpdateNoteDialog.msgTitle1"), Messages.getString("editor.XLIFFEditorImplWithNatTable.cantOpenNullFile")); close(); } Image oldTitleImage = titleImage; if (input != null) { IEditorRegistry editorRegistry = PlatformUI.getWorkbench().getEditorRegistry(); IEditorDescriptor editorDesc = editorRegistry.findEditor(getSite().getId()); ImageDescriptor imageDesc = editorDesc != null ? editorDesc.getImageDescriptor() : null; titleImage = imageDesc != null ? imageDesc.createImage() : null; } // 如果是合并打开,设置不一样的标志 if (multiFile) { setTitleImage(net.heartsome.cat.ts.ui.xliffeditor.nattable.Activator.getImageDescriptor( "icons/multiFiles.png").createImage()); } else { setTitleImage(titleImage); } if (oldTitleImage != null && !oldTitleImage.isDisposed()) { oldTitleImage.dispose(); } JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener); } } /** * 通过 FileEditorInput 得到当前要打开的文件 * @param input * FileEditorInput 对象 * @return ; * @throws CoreException */ private List<File> getFilesByFileEditorInput(FileEditorInput input) throws CoreException { List<File> files = null; IFile file = (IFile) input.getAdapter(IFile.class); if (file == null) { throw new CoreException(new Status(Status.WARNING, net.heartsome.cat.ts.ui.xliffeditor.nattable.Activator.PLUGIN_ID, Messages.getString("editor.XLIFFEditorImplWithNatTable.msg5"))); } else { if ("xlp".equals(file.getFileExtension()) && ".TEMP".equals(file.getParent().getName())) { List<String> multiFiles = new XLFHandler().getMultiFiles(file); files = new ArrayList<File>(); File mergerFile; for (String multiFileLC : multiFiles) { if (CommonFunction.validXlfExtensionByFileName(multiFileLC)) { mergerFile = new File(multiFileLC); files.add(mergerFile); } } } else { files = Arrays.asList(new File(input.getURI())); } } return files; } @Override public void createPartControl(Composite parent) { if (openFileSucceed) { // 成功打开文件时 GridLayoutFactory.fillDefaults().numColumns(1).spacing(0, 0).applyTo(parent); parent.setLayoutData(new GridData(GridData.FILL_BOTH)); // 增加过滤器和定位器 Add By Leakey addFilterComposite(parent); // 添加下面的面板 addBottomComposite(parent); if (statusLineManager == null) { statusLineManager = getStatusLineManager(); if (statusLineManager.find("translationProgress") == null) { translationItem = new XLIFFEditorStatusLineItemWithProgressBar("translationProgress", Messages.getString("editor.XLIFFEditorImplWithNatTable.translationItem")); statusLineManager.add(translationItem); } if (statusLineManager.find("approvedProgress") == null) { approveItem = new XLIFFEditorStatusLineItemWithProgressBar("approvedProgress", Messages.getString("editor.XLIFFEditorImplWithNatTable.approveItem")); statusLineManager.add(approveItem); } translationItem.setProgressValue(0); approveItem.setProgressValue(0); } changeLayout(isHorizontalLayout); } } /** * 关闭此编辑器。 <li>当编辑器关闭自己会抛出 PartInitException 异常警告,因此此方法最适合在 init(IEditorSite site, IEditorInput input) 方法中调用</li> */ private void close() throws PartInitException { Display display = getSite().getShell().getDisplay(); display.asyncExec(new Runnable() { public void run() { getSite().getPage().closeEditor(XLIFFEditorImplWithNatTable.this, false); // Add By Leakey 释放资源 if (titleImage != null && !titleImage.isDisposed()) { titleImage.dispose(); titleImage = null; } if (statusLineImage != null && !statusLineImage.isDisposed()) { statusLineImage.dispose(); statusLineImage = null; } if (table != null && !table.isDisposed()) { table.dispose(); table = null; } handler = null; System.gc(); JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener); } }); } /** * 添加填充过滤器面板内容的面板 * @param parent * @return 过滤器面板; */ private void addFilterComposite(Composite main) { Composite top = new Composite(main, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(3).equalWidth(false).margins(0, 0).applyTo(top); top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // 输入行号进行定位 final String rowLocationStr = Messages.getString("editor.XLIFFEditorImplWithNatTable.rowLocationStr"); Text txtRowLocation = new Text(top, SWT.BORDER); txtRowLocation.setText(rowLocationStr); int width = 40; if (Util.isLinux()) { width = 35; } GridDataFactory.swtDefaults().hint(width, SWT.DEFAULT).applyTo(txtRowLocation); txtRowLocation.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { Text text = (Text) e.widget; if (rowLocationStr.equals(text.getText())) { text.setText(""); } } @Override public void focusLost(FocusEvent e) { Text text = (Text) e.widget; if ("".equals(text.getText())) { text.setText(rowLocationStr); } } }); txtRowLocation.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent event) { if (event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR) { String rowNumString = ((Text) event.widget).getText().trim(); if (rowNumString != null && !"".equals(rowNumString)) { int rowPosition; try { rowPosition = Integer.parseInt(rowNumString) - 1; jumpToRow(rowPosition, false); updateStatusLine(); } catch (NumberFormatException e) { Text text = (Text) event.widget; text.setText(""); } } } } }); txtRowLocation.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent event) { if (event.keyCode == 0 && event.stateMask == 0) { // 文本框得到焦点时 } else if (Character.isDigit(event.character) || event.character == '\b' || event.keyCode == 127) { // 输入数字,或者按下Backspace、Delete键 if ("".equals(((Text) event.widget).getText().trim()) && event.character == '0') { event.doit = false; } else { event.doit = true; } } else { event.doit = false; } } }); cmbFilter = new Combo(top, SWT.BORDER | SWT.READ_ONLY); cmbFilter.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // TODO 完善过滤器初始化数据。 // cmbFilter.add("所有文本段"); // cmbFilter.add("未翻译文本段"); // cmbFilter.add("已翻译文本段"); // cmbFilter.add("未批准文本段"); // cmbFilter.add("已批准文本段"); // cmbFilter.add("有批注文本段"); // cmbFilter.add("锁定文本段"); // cmbFilter.add("未锁定文本段"); // cmbFilter.add("重复文本段"); // cmbFilter.add("疑问文本段"); // cmbFilter.add("上下文匹配文本段"); // cmbFilter.add("完全匹配文本段"); // cmbFilter.add("模糊匹配文本段"); // cmbFilter.add("快速翻译文本段"); // cmbFilter.add("自动繁殖文本段"); // cmbFilter.add("错误标记文本段"); // cmbFilter.add("术语不一致文本段"); // cmbFilter.add("译文不一致文本段"); // cmbFilter.add("带修订标记文本段"); final Set<String> filterNames = XLFHandler.getFilterNames(); for (String filterName : filterNames) { cmbFilter.add(filterName); } // 添加选项改变监听 cmbFilter.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Fixed Bug #2243 by Jason 当鼠标焦点在源文单元框中使用过滤器,对过滤后的译文进行操作会提示该行锁定不能操作 // ActiveCellEditor.commit(); HsMultiActiveCellEditor.commit(true); Combo cmbFilter = (Combo) e.widget; boolean isUpdated = handler.doFilter(cmbFilter.getText(), langFilterCondition); if (isUpdated) { if (table != null) { bodyLayer.getSelectionLayer().clear(); if (bodyLayer.selectionLayer.getRowCount() > 0) { // 默认选中第一行 HsMultiActiveCellEditor.commit(true); bodyLayer.selectionLayer.doCommand(new SelectCellCommand(bodyLayer.getSelectionLayer(), getTgtColumnIndex(), isHorizontalLayout ? 0 : 1, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.this); } table.setFocus(); } autoResize(); // 自动调整 NatTable 大小 ; updateStatusLine(); // 更新状态栏 NattableUtil.refreshCommand(XLIFFEditorSelectionPropertyTester.PROPERTY_NAMESPACE, XLIFFEditorSelectionPropertyTester.PROPERTY_ENABLED); } } }); Button btnSaveFilter = new Button(top, SWT.NONE); // TODO 考虑换成图片显示。 btnSaveFilter.setText(Messages.getString("editor.XLIFFEditorImplWithNatTable.btnAddFilter")); btnSaveFilter.setToolTipText(Messages.getString("editor.XLIFFEditorImplWithNatTable.btnAddFilterTooltip")); btnSaveFilter.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { CustomFilterDialog dialog = new CustomFilterDialog(table.getShell(), cmbFilter); dialog.open(); // int res = dialog.open(); // if (res == CustomFilterDialog.OK) { // cmbFilter.select(cmbFilter.getItemCount() - 1); // 选中最后一行数据 // cmbFilter.notifyListeners(SWT.Selection, null); // } } }); cmbFilter.select(0); // 默认选中第一行数据 cmbFilter.notifyListeners(SWT.Selection, null); // 更新nattable的列名为语言对 renameColumn(); top.pack(); } /** * 刷新编辑器 ; */ public void refresh() { if (table != null && !table.isDisposed()) { ViewportLayer viewportLayer = bodyLayer.getViewportLayer(); viewportLayer.invalidateVerticalStructure(); viewportLayer.recalculateScrollBars(); table.redraw(); } } public void reloadXliff() { Set<String> filePaths = handler.getVnMap().keySet(); ArrayList<File> files = new ArrayList<File>(); for (String filePath : filePaths) { files.add(new File(filePath)); } try { openFile(files, null); } catch (PartInitException e) { LOGGER.error("", e); e.printStackTrace(); } } /** * 修改 NatTable 某列的列名 * @param columnPosition * 列Position * @param newColumnName * 新列名 ; */ private void renameColumn() { Map<String, ArrayList<String>> languages = handler.getLanguages(); for (Entry<String, ArrayList<String>> entry : languages.entrySet()) { String srcLanguage = entry.getKey(); srcColumnName = srcLanguage; for (String tgtLanguage : entry.getValue()) { tgtColumnName = tgtLanguage; break; } } if (table != null && !table.isDisposed()) { // 更新列首名 if (isHorizontalLayout) { // 列Position int srcColumnIdx = LayerUtil.getColumnPositionByIndex(table, 1); int tgtColumnIdx = LayerUtil.getColumnPositionByIndex(table, 3); table.doCommand(new RenameColumnHeaderCommand(table, srcColumnIdx, srcColumnName)); table.doCommand(new RenameColumnHeaderCommand(table, tgtColumnIdx, tgtColumnName)); } else { String langPairStr = srcColumnName + Hyphen + tgtColumnName; int langPairIdx = VerticalNatTableConfig.SOURCE_COL_INDEX; table.doCommand(new RenameColumnHeaderCommand(table, langPairIdx, langPairStr)); } } } /** * 跳转到指定行的文本段 * @param rowId * 行的唯一标识; */ public void jumpToRow(String rowId) { int rowPosition = handler.getRowIndex(rowId); if (rowPosition > -1) { jumpToRow(rowPosition, false); } } /** * 跳转到指定行的文本段 * @param rowPosition * 行号,从0开始 ; */ public void jumpToRow(int rowPosition) { if (rowPosition < 0) { return; } int[] selectedRows = getSelectedRows(); if (selectedRows.length == 1 && selectedRows[0] == rowPosition) { // 如果已经选中此行 return; } // TODO 已在 target 内容修改的时候判断并将 state 属性值做修改,此处理论上无需再做处理。 // updateCurrentSegmentTranslateProp(); // 若当前目标文本段内容不为空,则自动将其 state 属性值设为“translated” int maxRowNum = handler.countEditableTransUnit() - 1; rowPosition = rowPosition > maxRowNum ? maxRowNum : rowPosition; if (!isHorizontalLayout) { // 处理垂直布局下的行号 rowPosition = rowPosition * VerticalNatTableConfig.ROW_SPAN; } ViewportLayer viewportLayer = bodyLayer.getViewportLayer(); // 先记录下可见区域的范围 HsMultiActiveCellEditor.commit(true); viewportLayer.doCommand(new SelectCellCommand(bodyLayer.getSelectionLayer(), getTgtColumnIndex(), rowPosition, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(this); } /** * 得到当前选中的行的唯一标识 * @return ; */ public List<String> getSelectedRowIds() { SelectionLayer selectionLayer = bodyLayer.getSelectionLayer(); int[] rowPositions = selectionLayer.getFullySelectedRowPositions(); Set<String> rowIds = handler.getRowIds(rowPositions); return new ArrayList<String>(rowIds); } /** * 得到当前选中的行 * @return ; */ public int[] getSelectedRows() { SelectionLayer selectionLayer = bodyLayer.getSelectionLayer(); return selectionLayer.getFullySelectedRowPositions(); } /** * 添加下面的面板 * @param parent * @return 下面的面板; */ private void addBottomComposite(Composite main) { final Composite bottom = new Composite(main, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(1).margins(0, 0).applyTo(bottom); bottom.setLayoutData(new GridData(GridData.FILL_BOTH)); this.parent = bottom; } /** * 给 NatTable 添加可编辑单元格的配置 * @return ; */ private IConfiguration editableGridConfiguration() { return new AbstractRegistryConfiguration() { public void configureRegistry(IConfigRegistry configRegistry) { TextPainterWithPadding painter = new TextPainterWithPadding(true, Constants.SEGMENT_TOP_MARGIN, Constants.SEGMENT_RIGHT_MARGIN, Constants.SEGMENT_BOTTOM_MARGIN, Constants.SEGMENT_LEFT_MARGIN, XLIFFEditorImplWithNatTable.this, JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.XLIFF_EDITOR_TEXT_FONT)); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, painter, DisplayMode.NORMAL, SOURCE_EDIT_CELL_LABEL); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, painter, DisplayMode.NORMAL, TARGET_EDIT_CELL_LABEL); // configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new StyledTextPainter( // table), DisplayMode.NORMAL, GridRegion.BODY); configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, new TagDisplayConverter( XLIFFEditorImplWithNatTable.this), DisplayMode.NORMAL, SOURCE_EDIT_CELL_LABEL); configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, new TagDisplayConverter( XLIFFEditorImplWithNatTable.this), DisplayMode.NORMAL, TARGET_EDIT_CELL_LABEL); configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, DisplayMode.EDIT, SOURCE_EDIT_CELL_LABEL); configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, IEditableRule.ALWAYS_EDITABLE, DisplayMode.EDIT, TARGET_EDIT_CELL_LABEL); configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new StyledTextCellEditor( XLIFFEditorImplWithNatTable.this), DisplayMode.EDIT, SOURCE_EDIT_CELL_LABEL); configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new StyledTextCellEditor( XLIFFEditorImplWithNatTable.this), DisplayMode.EDIT, TARGET_EDIT_CELL_LABEL); // configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, new // TagDisplayConverter( // XLIFFEditorImplWithNatTable.this, innerTagUtil), DisplayMode.EDIT, EDIT_CELL_LABEL); } }; } /* NatTable 可编辑规则定制方法,将来可能会用到,暂时保留 */ // protected IEditableRule getEditRule(final IDataProvider dataProvider) { // return new IEditableRule() { // public boolean isEditable(int columnIndex, int rowIndex) { // if (isHorizontalLayout) { // return true; // } else { // return VerticalNatTableConfig.isTarget(columnIndex, rowIndex); // } // } // }; // } /** * NatTable 全选的 Action。 */ private Action tableSelectAllAction = new Action() { public void runWithEvent(Event event) { if (table != null && !table.isDisposed()) { table.doCommand(new SelectAllCommand()); } }; }; @Override public void setFocus() { if (table != null && !table.isDisposed()) { table.setFocus(); } setGlobalActionHandler(); // 设置全局的菜单项 updateStatusLine(); // 更新状态栏显示信息 } /** * 在状态栏上显示被编辑文件的信息。 */ public void updateStatusLine() { if (table == null || table.isDisposed()) { return; } SelectionLayer selectionLayer = bodyLayer.getSelectionLayer(); ViewportLayer viewportLayer = bodyLayer.getViewportLayer(); PositionCoordinate cellPosition = selectionLayer.getLastSelectedCellPosition(); if (cellPosition == null) { return; } // int order = LayerUtil.convertRowPosition(selectionLayer, cellPosition.rowPosition, viewportLayer); // Bug #2317:选中文本段后排序,不会刷新状态栏中的序号 int[] selectedRowPostions = selectionLayer.getFullySelectedRowPositions(); if (selectedRowPostions.length <= 0) { return; } // 刷新选中行的术语,使其排序后保持高亮显示 // if (!isHorizontalLayout()) { // int rowPosition = selectedRowPostions[0]; // rowPosition *= VerticalNatTableConfig.ROW_SPAN; // cellPosition.set(rowPosition, cellPosition.getColumnPosition()); // } else { // cellPosition.set(selectedRowPostions[0], cellPosition.getColumnPosition()); // } // if (!FindReplaceDialog.isOpen) { // CellRegion cellRegion = new CellRegion(cellPosition, new Region(0, selectionLayer.getWidth())); // ActiveCellRegion.setActiveCellRegion(cellRegion); // } int order = LayerUtil.convertRowPosition(selectionLayer, selectedRowPostions[0], viewportLayer); order += viewportLayer.getOriginRowPosition() + 1; // 垂直布局时order需要进行两行递增的处理 if (!isHorizontalLayout) { order = (int) Math.ceil(order / 2.0); } MessageFormat messageFormat = null; if (order > 0) { /* 一个Xliff文件,可能有多个File节点,这里使用File结点的original属性 */ /* 当前文件:{0} | 顺序号:{1} | 可见文本段数:{2} | 文本段总数:{3} | 当前用户名" */ messageFormat = new MessageFormat(Messages.getString("editor.XLIFFEditorImplWithNatTable.messageFormat1")); } else { messageFormat = new MessageFormat(Messages.getString("editor.XLIFFEditorImplWithNatTable.messageFormat2")); } String fileName = ""; // 添加 Project Name IEditorInput editorInput = getEditorInput(); String filePath = ""; if (isMultiFile()) { if (getSelectedRowIds().size() > 0) { filePath = RowIdUtil.getFileNameByRowId(getSelectedRowIds().get(0)); fileName = ResourceUtils.toWorkspacePath(filePath); } } else { fileName = getEditorInput().getName(); if (editorInput instanceof FileEditorInput) { FileEditorInput fileEditorInput = (FileEditorInput) editorInput; filePath = fileEditorInput.getFile().getLocation().toOSString(); fileName = fileEditorInput.getFile().getFullPath().toOSString(); } } String systemUser = Activator.getDefault().getPreferenceStore().getString(IPreferenceConstants.SYSTEM_USER); int editableTuSum = handler.countEditableTransUnit(); int tuSum = handler.countTransUnit(); // int translatedSum1 = handler // .getNodeCount(filePath, // "/xliff/file/body/trans-unit[@approved = 'yes' and target/@state != 'translated' and target/@state != 'signed-off']"); // int translatedSum2 = handler.getNodeCount(filePath, // "/xliff/file/body/trans-unit/target[@state = 'translated' or @state = 'signed-off']"); // int approveSum1 = handler.getNodeCount(filePath, // "/xliff/file/body/trans-unit[not(@approved='yes') and target/@state='signed-off']"); // int approveSum2 = handler.getNodeCount(filePath, "/xliff/file/body/trans-unit[@approved = 'yes']"); int translatedSum = handler.getTranslatedCount(); int approveedSum = handler.getApprovedCount(); int approveP = (int) Math.floor(approveedSum / (double) tuSum * 100.00); int translatedP = (int) Math.floor(translatedSum / (double) tuSum * 100.00); translationItem.setProgressValue(translatedP); approveItem.setProgressValue(approveP); // 将信息显示在状态栏 String message = messageFormat.format(new String[] { fileName, String.valueOf(order), String.valueOf(editableTuSum), String.valueOf(tuSum), systemUser }); statusLineManager.setMessage(statusLineImage, message); } /** * 设置状态栏信息 * @param message * 状态栏信息 ; */ public void setStatusLine(String message) { getStatusLineManager().setMessage(message); } /** * 构建 NatTable 的数据提供者 * @param isHorizontalLayout * true 为水平布局,false 为垂直布局。 * @return 数据提供者; */ private XliffEditorDataProvider<TransUnitBean> setupBodyDataProvider(boolean isHorizontalLayout) { XliffEditorDataProvider<TransUnitBean> result = null; if (isHorizontalLayout) { result = setupHorizontalLayoutBodyDataProvider(); } else { result = setupVerticalLayoutBodyDataProvider(); } return result; } /** * 构建水平布局的 body data provider * @return 数据提供者; */ private XliffEditorDataProvider<TransUnitBean> setupHorizontalLayoutBodyDataProvider() { propertyToLabels = new HashMap<String, String>(); propertyToLabels.put("id", Messages.getString("editor.XLIFFEditorImplWithNatTable.idColumn")); // Edit By Leakey 动态设置列名 propertyToLabels.put("srcContent", srcColumnName); propertyToLabels.put("flag", Messages.getString("editor.XLIFFEditorImplWithNatTable.statusColumn")); propertyToLabels.put("tgtContent", tgtColumnName); propertyToColWidths = new HashMap<String, Double>(); propertyToColWidths.put("id", 45.0); // 大于1的值为像素值,小于等于1的值为除了像素值剩下部分的百分比(例如0.5,表示50%) propertyToColWidths.put("srcContent", 0.5); propertyToColWidths.put("flag", 85.0); propertyToColWidths.put("tgtContent", 0.5); propertyNames = new String[] { "id", "srcContent", "flag", "tgtContent" }; // Edit by Leakey 在转换布局时需要将修改过的值保存下来 XliffEditorDataProvider<TransUnitBean> dtProvider = new XliffEditorDataProvider<TransUnitBean>(handler, new ReflectiveColumnPropertyAccessor<TransUnitBean>(propertyNames)); return dtProvider; } /** * 构建垂直布局的 body data provider * @param dataList2 * 数据列表 ; */ private XliffEditorDataProvider<TransUnitBean> setupVerticalLayoutBodyDataProvider() { propertyToLabels = new HashMap<String, String>(); propertyToLabels.put("id", Messages.getString("editor.XLIFFEditorImplWithNatTable.idColumn")); propertyToLabels.put("flag", Messages.getString("editor.XLIFFEditorImplWithNatTable.statusColumn")); // Edit By Leakey 动态设置列名 propertyToLabels.put("properties", srcColumnName + Hyphen + tgtColumnName); propertyToColWidths = new HashMap<String, Double>(); propertyToColWidths.put("id", 45.0); propertyToColWidths.put("flag", 85.0); propertyToColWidths.put("properties", 1.0); propertyNames = new String[] { "id", "flag", "properties" }; // Edit by Leakey 在转换布局时需要将修改过的值保存下来 VerticalLayerBodyDataProvider<TransUnitBean> dtProvider = new VerticalLayerBodyDataProvider<TransUnitBean>( handler, new ReflectiveColumnPropertyAccessor<TransUnitBean>(propertyNames)); return dtProvider; } /** * 改变当前布局 ; */ public void changeLayout() { isHorizontalLayout = !isHorizontalLayout; changeLayout(isHorizontalLayout); // 刷新工具栏的改变布局按钮的图片 ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); commandService.refreshElements("net.heartsome.cat.ts.ui.handlers.ChangeXliffEditorModelCommand", null); } public void changeLayout(boolean isHorizontalLayout) { this.isHorizontalLayout = isHorizontalLayout; // 同步布局状态 // 如果当前的 table 已经存在,销毁后再重新创建。 if (table != null && !table.isDisposed()) { table.dispose(); for (Control control : parent.getChildren()) { control.dispose(); } } // 构建 NatTable 的数据提供者 bodyDataProvider = setupBodyDataProvider(isHorizontalLayout); // 构建 NatTable 列头的数据提供者 DefaultColumnHeaderDataProvider colHeaderDataProvider = new DefaultColumnHeaderDataProvider(propertyNames, propertyToLabels); // 构建 NatTable 的 body layer stack bodyLayer = new BodyLayerStack(bodyDataProvider, isHorizontalLayout); // 构建 NatTable 的 column header layout stack ColumnHeaderLayerStack columnHeaderLayer = new ColumnHeaderLayerStack(colHeaderDataProvider); // 构建 NatTable 之下的 composite layer,不使用默认的 configuration(默认的 configuration 是在点击可编辑单元格时,直接进入编辑状态)。 CompositeLayer compositeLayer = new CompositeLayer(1, 2); compositeLayer.setChildLayer(GridRegion.COLUMN_HEADER, columnHeaderLayer, 0, 0); compositeLayer.setChildLayer(GridRegion.BODY, bodyLayer, 0, 1); LayerUtil.setBodyLayerPosition(0, 1); // 标识 BodyLayer 在 CompositeLayer 上的位置 /* 给 composite layer 添加编辑相关的命令和 handler */ // 添加行背景色(奇数行和偶数行不同) addRowBackgroundColor(compositeLayer); // 构建 NatTable table = new NatTable(parent, compositeLayer, false); Language srcLang = LocaleService.getLanguageConfiger().getLanguageByCode(srcColumnName); Language tgtLang = LocaleService.getLanguageConfiger().getLanguageByCode(tgtColumnName); if (srcLang.isBidi() || tgtLang.isBidi()) { table.setOrientation(SWT.RIGHT_TO_LEFT); } table.removePaintListener(table); // 去除默认绘画器 table.addPaintListener(paintListenerWithAutoRowSize); // 使用自定义绘画器,此绘画器,具有自动计算行高功能。 Listener[] ls = table.getListeners(SWT.Resize); for (Listener l : ls) { table.removeListener(SWT.Resize, l); } table.addListener(SWT.Resize, resizeListenerWithColumnResize); table.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { // ActiveCellEditor.commit(); // 关闭编辑时,先提交未提交的单元格,避免造成内容丢失。Bug #2685 HsMultiActiveCellEditor.commit(true); table.removeListener(SWT.Resize, resizeListenerWithColumnResize); table.removePaintListener(paintListenerWithAutoRowSize); } }); table.setLayoutData(new GridData(GridData.FILL_BOTH)); // 给 NatTable 添加相应的配置 DefaultNatTableStyleConfiguration configuration = new DefaultNatTableStyleConfiguration(); configuration.hAlign = HorizontalAlignmentEnum.LEFT; table.addConfiguration(configuration); // To be changed 给NatTable添加选择列的功能 Add By Leakey /* * ColumnGroupModel columnGroupModel = new ColumnGroupModel(); DisplayColumnChooserCommandHandler * columnChooserCommandHandler = new DisplayColumnChooserCommandHandler( bodyLayer.getSelectionLayer(), * bodyLayer.getColumnHideShowLayer(), columnHeaderLayer.getColumnHeaderLayer(), * columnHeaderLayer.getColumnHeaderDataLayer(), columnHeaderLayer.getColumnGroupHeaderLayer(), columnGroupModel * ); bodyLayer.registerCommandHandler(columnChooserCommandHandler); */ /* * 不使用默认的表头菜单,使用自定义的菜单,因此自定义菜单在 corner 中添加了相应的菜单项,所以需要指定这些添加的 command 在哪一层进一处理 */ // 表头中添加自定义菜单会引发一些不可预料的问题,故先去掉 // table.addConfiguration(new HeaderMenuConfiguration(table)); /* * 增加表格的自定义右键菜单 */ table.addConfiguration(new BodyMenuConfiguration(this)); // 注册列头点击监听(处理排序) table.addConfiguration(new SingleClickSortConfiguration()); /* * 初始化“撤销/重做”历史 */ initializeOperationHistory(); table.setData(IUndoContext.class.getName(), undoContext); /* Weachy - 注册修改后保存内容并自适应大小的处理 handler(覆盖默认的handler:UpdateDataCommandHandler) */ bodyLayer.getBodyDataLayer().registerCommandHandler( new UpdateDataAndAutoResizeCommandHandler(table, bodyLayer.getBodyDataLayer())); /* Weachy - 注册当前显示行的行高自适应处理 handler */ compositeLayer.registerCommandHandler(new AutoResizeCurrentRowsCommandHandler(compositeLayer)); /* Weachy - 移除系统默认的查找 handler,添加自定义的查找替换 handler */ bodyLayer.getSelectionLayer().unregisterCommandHandler(SearchCommand.class); bodyLayer.getSelectionLayer().registerCommandHandler( new FindReplaceCommandHandler(bodyLayer.getSelectionLayer())); /* * 下面给 NatTable 添加可编辑单元格的配置 */ table.addConfiguration(editableGridConfiguration()); // 添加标记的自定义显示样式 IConfigRegistry configRegistry = new ConfigRegistry(); /* * 如果是水平布局,则使用 ColumnOverrideLabelAccumulator 实现指定列都使用相同的显示样式;否则使用 CellOverrideLabelAccumulator 实现根据显示的内容来显示样式。 */ if (isHorizontalLayout) { // 第一步:创建一个标签累加器,给需要绘制会不同效果的 cells 添加自定义的标签。在这里是第三列的标签列。 ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(bodyLayer); columnLabelAccumulator.registerColumnOverrides(0, "LINENUMBER_CELL_LABEL"); columnLabelAccumulator.registerColumnOverrides(1, SOURCE_EDIT_CELL_LABEL); columnLabelAccumulator.registerColumnOverrides(2, FLAG_CELL_LABEL); columnLabelAccumulator.registerColumnOverrides(3, TARGET_EDIT_CELL_LABEL); // 第二步:注册这个标签累加器。 bodyLayer.setConfigLabelAccumulator(columnLabelAccumulator); // 第三步:把自定义的 cell painter,cell style 与自定义的标签进行关联。 addFlagLableToColumn(configRegistry); addLineNumberToColumn(configRegistry); } else { ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(bodyLayer); columnLabelAccumulator.registerColumnOverrides(0, "LINENUMBER_CELL_LABEL"); columnLabelAccumulator.registerColumnOverrides(1, FLAG_CELL_LABEL); columnLabelAccumulator.registerColumnOverrides(VerticalNatTableConfig.TARGET_COL_INDEX, SOURCE_EDIT_CELL_LABEL); columnLabelAccumulator.registerColumnOverrides(VerticalNatTableConfig.TARGET_COL_INDEX, TARGET_EDIT_CELL_LABEL); bodyLayer.setConfigLabelAccumulator(columnLabelAccumulator); // CellOverrideLabelAccumulator<TransUnitDummy> cellLabelAccumulator = new // CellOverrideLabelAccumulator<TransUnitDummy>( // (IRowDataProvider) bodyDataProvider); // CellOverrideLabelAccumulator<TransUnitBean> cellLabelAccumulator = new // CellOverrideLabelAccumulator<TransUnitBean>( // (IRowDataProvider) bodyDataProvider); // cellLabelAccumulator.registerOverride("flag", VerticalNatTableConfig.SOURCE_COL_INDEX, // FOCUS_CELL_LABEL); // // bodyLayer.getBodyDataLayer().setConfigLabelAccumulator(cellLabelAccumulator); addFlagLableToColumn(configRegistry); addLineNumberToColumn(configRegistry); } table.setConfigRegistry(configRegistry); // configure manually table.configure(); /* Weachy - 垂直布局下,注册使键盘方向键以 2 行为一个单位移动选中行的处理 handler(覆盖默认的handler:MoveRowSelectionCommandHandler) */ if (!isHorizontalLayout) { // SelectionLayer selectionLayer = bodyLayer.getSelectionLayer(); // selectionLayer.registerCommandHandler(new VerticalMoveRowSelectionCommandHandler(selectionLayer)); } if (bodyLayer.selectionLayer.getRowCount() > 0) { // 默认选中第一行 HsMultiActiveCellEditor.commit(true); bodyLayer.selectionLayer.doCommand(new SelectCellCommand(bodyLayer.getSelectionLayer(), getTgtColumnIndex(), isHorizontalLayout ? 0 : 1, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(this); } IWorkbenchPage page = getSite().getPage(); IViewReference[] viewReferences = page.getViewReferences(); IViewPart view; for (int i = 0; i < viewReferences.length; i++) { view = viewReferences[i].getView(false); if (view == null) { continue; } view.setFocus(); // 切换到其他视图,再切换回来,解决NatTable改变布局后其他视图无法监听到的问题。 // break; } // 改变布局方式后,把焦点给 NatTable table.setFocus(); RowHeightCalculator rowHeightCalculator = new RowHeightCalculator(bodyLayer, table, 32); ILayer lay = bodyLayer.getViewportLayer(); if (lay instanceof HorizontalViewportLayer) { ((HorizontalViewportLayer) bodyLayer.getViewportLayer()).setRowHeightCalculator(rowHeightCalculator); } else if (lay instanceof VerticalViewportLayer) { ((VerticalViewportLayer) bodyLayer.getViewportLayer()).setRowHeightCalculator(rowHeightCalculator); } parent.layout(); NoteToolTip toolTip = new NoteToolTip(table); toolTip.setPopupDelay(10); toolTip.activate(); toolTip.setShift(new Point(10, 10)); StateToolTip stateTip = new StateToolTip(table); stateTip.setPopupDelay(10); stateTip.activate(); stateTip.setShift(new Point(10, 10)); NotSendToTmToolTip notSendToTMToolTip = new NotSendToTmToolTip(table); notSendToTMToolTip.setPopupDelay(10); notSendToTMToolTip.activate(); notSendToTMToolTip.setShift(new Point(10, 10)); HasQustionToolTip hasqustionTooltip = new HasQustionToolTip(table); hasqustionTooltip.setPopupDelay(10); hasqustionTooltip.activate(); hasqustionTooltip.setShift(new Point(10, 10)); // 在状态栏上显示当前文本段的信息。 updateStatusLine(); } /** * 鼠标放在批注图片上时显示批注的 Tooltip * @author peason * @version * @since JDK1.6 */ class NoteToolTip extends DefaultToolTip { private Cursor clickCusor; public NoteToolTip(NatTable table) { super(table, ToolTip.RECREATE, true); } protected Object getToolTipArea(Event event) { int col = table.getColumnPositionByX(event.x); int row = table.getRowPositionByY(event.y); return new Point(col, row); } protected String getText(Event event) { Image image = XliffEditorGUIHelper.getImage(ImageName.HAS_NOTE); int columnPosition = table.getColumnPositionByX(event.x); int rowPosition = table.getRowPositionByY(event.y); LayerCell cell = table.getCellByPosition(columnPosition, rowPosition); Rectangle imageBounds = image.getBounds(); Rectangle cellBounds = cell.getBounds(); int x = cellBounds.x + imageBounds.width * 3 + 20; int y = cellBounds.y + CellStyleUtil .getVerticalAlignmentPadding(CellStyleUtil.getCellStyle(cell, table.getConfigRegistry()), cellBounds, imageBounds.height); String text = null; XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); if (columnPosition == xliffEditor.getStatusColumnIndex() && event.x >= x && event.x <= (x + imageBounds.width) && event.y >= y && event.y <= (y + imageBounds.height)) { Vector<NoteBean> noteBeans = null; try { int rowIndex = table.getRowIndexByPosition(rowPosition); if (!isHorizontalLayout) { rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; } String rowId = xliffEditor.getXLFHandler().getRowId(rowIndex); noteBeans = xliffEditor.getXLFHandler().getNotes(rowId); } catch (NavException e) { LOGGER.error("", e); e.printStackTrace(); } catch (XPathParseException e) { LOGGER.error("", e); e.printStackTrace(); } catch (XPathEvalException e) { LOGGER.error("", e); e.printStackTrace(); } if (noteBeans != null && noteBeans.size() > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < noteBeans.size(); i++) { NoteBean bean = noteBeans.get(i); String strNote = bean.getNoteText(); if (noteBeans.size() > 1) { sb.append((i + 1) + ". "); } if (strNote != null) { strNote = TextUtil.resetSpecialString(strNote); if (strNote.indexOf(":") != -1) { sb.append(strNote.substring(strNote.indexOf(":") + 1)); } else { sb.append(strNote); } sb.append("\n"); } } text = sb.toString(); } } return text; } @Override protected boolean shouldCreateToolTip(Event event) { boolean flag = super.shouldCreateToolTip(event); if (!flag) { return flag; } Image image = XliffEditorGUIHelper.getImage(ImageName.HAS_NOTE); int columnPosition = table.getColumnPositionByX(event.x); int rowPosition = table.getRowPositionByY(event.y); LayerCell cell = table.getCellByPosition(columnPosition, rowPosition); Rectangle imageBounds = image.getBounds(); if (cell == null) { return false; } Rectangle cellBounds = cell.getBounds(); int x = cellBounds.x + imageBounds.width * 3 + 20; int y = cellBounds.y + CellStyleUtil .getVerticalAlignmentPadding(CellStyleUtil.getCellStyle(cell, table.getConfigRegistry()), cellBounds, imageBounds.height); XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); if (xliffEditor == null) { return false; } if (columnPosition == xliffEditor.getStatusColumnIndex() && event.x >= x && event.x <= (x + imageBounds.width) && event.y >= y && event.y <= (y + imageBounds.height)) { Vector<NoteBean> noteBeans = null; try { int rowIndex = table.getRowIndexByPosition(rowPosition); if (!isHorizontalLayout) { rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; } String rowId = xliffEditor.getXLFHandler().getRowId(rowIndex); noteBeans = xliffEditor.getXLFHandler().getNotes(rowId); } catch (NavException e) { LOGGER.error("", e); e.printStackTrace(); } catch (XPathParseException e) { LOGGER.error("", e); e.printStackTrace(); } catch (XPathEvalException e) { LOGGER.error("", e); e.printStackTrace(); } if (noteBeans != null && noteBeans.size() > 0) { clickCusor = new Cursor(Display.getCurrent(), SWT.CURSOR_HAND); setDisplayCursor(clickCusor); return true; } } setDisplayCursor(null); return false; } /** * (non-Javadoc) * @see org.eclipse.jface.window.ToolTip#afterHideToolTip(org.eclipse.swt.widgets.Event) */ @Override protected void afterHideToolTip(Event event) { setDisplayCursor(null); if (null != clickCusor) { clickCusor.dispose(); clickCusor = null; } super.afterHideToolTip(event); } private void setDisplayCursor(Cursor c) { Shell[] shells = Display.getCurrent().getShells(); for (int i = 0; i < shells.length; i++) { shells[i].setCursor(c); } } } /** * 鼠标放在翻译状态图片上时显示批注的 Tooltip * @author yule * @version * @since JDK1.6 */ class StateToolTip extends DefaultToolTip { public StateToolTip(NatTable table) { super(table, ToolTip.RECREATE, true); } protected Object getToolTipArea(Event event) { int col = table.getColumnPositionByX(event.x); int row = table.getRowPositionByY(event.y); return new Point(col, row); } protected String getText(Event event) { Image image = XliffEditorGUIHelper.getImage(ImageName.HAS_NOTE); int columnPosition = table.getColumnPositionByX(event.x); int rowPosition = table.getRowPositionByY(event.y); LayerCell cell = table.getCellByPosition(columnPosition, rowPosition); Rectangle imageBounds = image.getBounds(); Rectangle cellBounds = cell.getBounds(); int x = cellBounds.x; int y = cellBounds.y + CellStyleUtil .getVerticalAlignmentPadding(CellStyleUtil.getCellStyle(cell, table.getConfigRegistry()), cellBounds, imageBounds.height); String text = null; XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); if (columnPosition == xliffEditor.getStatusColumnIndex() && event.x >= x && event.x <= (x + imageBounds.width) && event.y >= y && event.y <= (y + imageBounds.height)) { int rowIndex = table.getRowIndexByPosition(rowPosition); if (!isHorizontalLayout) { rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; } TransUnitBean tu = xliffEditor.getXLFHandler().getTransUnit(rowIndex); text = getStateText(tu); } return text; } @Override protected boolean shouldCreateToolTip(Event event) { boolean flag = super.shouldCreateToolTip(event); if (!flag) { return flag; } int columnPosition = table.getColumnPositionByX(event.x); int rowPosition = table.getRowPositionByY(event.y); LayerCell cell = table.getCellByPosition(columnPosition, rowPosition); Image image = XliffEditorGUIHelper.getImage(ImageName.EMPTY); Rectangle imageBounds = image.getBounds(); if (cell == null) { return false; } Rectangle cellBounds = cell.getBounds(); int x = cellBounds.x; int y = cellBounds.y + CellStyleUtil .getVerticalAlignmentPadding(CellStyleUtil.getCellStyle(cell, table.getConfigRegistry()), cellBounds, imageBounds.height); XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); if (xliffEditor == null) { return false; } if (columnPosition == xliffEditor.getStatusColumnIndex() && event.x >= x && event.x <= (x + imageBounds.width) && event.y >= y && event.y <= (y + imageBounds.height)) { return true; } else { return false; } } public String getStateText(TransUnitBean tu) { String approved = null; String translate = null; String state = null; if (tu != null && tu.getTuProps() != null) { approved = tu.getTuProps().get("approved"); translate = tu.getTuProps().get("translate"); if (tu.getTgtProps() != null) { state = tu.getTgtProps().get("state"); } } if (translate != null && "no".equals(translate)) { // 已锁定 return Messages.getString("editor.XLIFFEditorImplWithNatTable.stateToolLocked"); } else if (state != null && "signed-off".equals(state)) { // 已签发 return Messages.getString("editor.XLIFFEditorImplWithNatTable.stateToolSignedoff"); } else if (approved != null && "yes".equals(approved)) { // 已批准 return Messages.getString("editor.XLIFFEditorImplWithNatTable.stateToolTipapproved"); } else if (state != null && "translated".equals(state)) { // 已翻译 return Messages.getString("editor.XLIFFEditorImplWithNatTable.stateToolTipTranslated"); } else if (state != null && "new".equals(state)) { // 草稿 return Messages.getString("editor.XLIFFEditorImplWithNatTable.stateToolTipDraft"); } else { return Messages.getString("editor.XLIFFEditorImplWithNatTable.stateToolTipNew"); } } } /** * @author yule * @version * @since JDK1.6 */ abstract class StatusToolTips extends DefaultToolTip { protected final int IMG_WIDTH = 16; protected final int MATCH_QUALITY = 20; public StatusToolTips(NatTable table) {// the constructor super(table, ToolTip.RECREATE, true); } protected Object getToolTipArea(Event event) { // tooltips Area int col = table.getColumnPositionByX(event.x); int row = table.getRowPositionByY(event.y); return new Point(col, row); } protected String getText(Event event) { // ToolTips Text Image image = XliffEditorGUIHelper.getImage(ImageName.HAS_NOTE); int columnPosition = table.getColumnPositionByX(event.x); int rowPosition = table.getRowPositionByY(event.y); LayerCell cell = table.getCellByPosition(columnPosition, rowPosition); Rectangle imageBounds = image.getBounds(); Rectangle cellBounds = cell.getBounds(); int x = cellBounds.x + getStatusStartX(); int y = cellBounds.y + CellStyleUtil .getVerticalAlignmentPadding(CellStyleUtil.getCellStyle(cell, table.getConfigRegistry()), cellBounds, imageBounds.height); String text = null; XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); if (columnPosition == xliffEditor.getStatusColumnIndex() && event.x >= x && event.x <= (x + imageBounds.width) && event.y >= y && event.y <= (y + imageBounds.height)) { int rowIndex = table.getRowIndexByPosition(rowPosition); if (!isHorizontalLayout) { rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; } TransUnitBean tu = xliffEditor.getXLFHandler().getTransUnit(rowIndex); text = getStateText(tu); } return text; } @Override protected boolean shouldCreateToolTip(Event event) { boolean flag = super.shouldCreateToolTip(event); if (!flag) { return flag; } int columnPosition = table.getColumnPositionByX(event.x); int rowPosition = table.getRowPositionByY(event.y); LayerCell cell = table.getCellByPosition(columnPosition, rowPosition); Image image = XliffEditorGUIHelper.getImage(ImageName.EMPTY); Rectangle imageBounds = image.getBounds(); if (cell == null) { return false; } Rectangle cellBounds = cell.getBounds(); int x = cellBounds.x + getStatusStartX(); int y = cellBounds.y + CellStyleUtil .getVerticalAlignmentPadding(CellStyleUtil.getCellStyle(cell, table.getConfigRegistry()), cellBounds, imageBounds.height); XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); if (xliffEditor == null) { return false; } if (columnPosition == xliffEditor.getStatusColumnIndex() && event.x >= x && event.x <= (x + imageBounds.width) && event.y >= y && event.y <= (y + imageBounds.height)) { int rowIndex = table.getRowIndexByPosition(rowPosition); if (!isHorizontalLayout) { rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; } TransUnitBean tu = xliffEditor.getXLFHandler().getTransUnit(rowIndex); return null != getStateText(tu); } else { return false; } } protected abstract int getStatusStartX(); protected abstract String getStateText(TransUnitBean tu); } /** * @author yule * @version * @since JDK1.6 */ class NotSendToTmToolTip extends StatusToolTips { /** * @param table */ public NotSendToTmToolTip(NatTable table) { super(table); // TODO Auto-generated constructor stub } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable.StatusToolTips#getStatusStartX() */ @Override protected int getStatusStartX() { // TODO Auto-generated method stub return IMG_WIDTH + MATCH_QUALITY; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable.StatusToolTips#getStateText(net.heartsome.cat.ts.core.bean.TransUnitBean) */ @Override protected String getStateText(TransUnitBean tu) { // TODO Auto-generated method stub if (null == tu) { return null; } String sendToTm = tu.getTuProps().get("hs:send-to-tm"); if (sendToTm != null && ("no").equals(sendToTm)) { return Messages.getString("editor.XLIFFEditorImplWithNatTable.notSendToTm"); } return null; } } /** * @author yule * @version * @since JDK1.6 */ class HasQustionToolTip extends StatusToolTips { /** * @param table */ public HasQustionToolTip(NatTable table) { super(table); // TODO Auto-generated constructor stub } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable.StatusToolTips#getStatusStartX() */ @Override protected int getStatusStartX() { // TODO Auto-generated method stub return 2 * IMG_WIDTH + MATCH_QUALITY; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable.StatusToolTips#getStateText(net.heartsome.cat.ts.core.bean.TransUnitBean) */ @Override protected String getStateText(TransUnitBean tu) { // TODO Auto-generated method stub if (null == tu) { return null; } String needReview = tu.getTuProps().get("hs:needs-review"); if (needReview != null && "yes".equals(needReview)) { return Messages.getString("editor.XLIFFEditorImplWithNatTable.hasQustion"); } return null; } } private Listener resizeListenerWithColumnResize = new Listener() { public void handleEvent(Event event) { HsMultiActiveCellEditor.commit(false); NatTable table = (NatTable) event.widget; if (table == null || table.isDisposed()) { return; } table.doCommand(new ClientAreaResizeCommand(table)); int clientAreaWidth = table.getClientArea().width; if (clientAreaWidth <= 0) { return; } int count = propertyNames.length; // 编辑器中的列数 if (count <= 0) { return; } Collection<Integer> hiddenColumnIndexes = bodyLayer.getColumnHideShowLayer().getHiddenColumnIndexes(); int shownColumnCount = count - hiddenColumnIndexes.size(); int[] columnPositions = new int[shownColumnCount]; // 需要修改的列的列号数组 int[] columnWidths = new int[shownColumnCount]; // 需要修改的列对应的宽度 double shownPercentage = 1; // 显示的百分比,原始为1(即 100%,表示所有列显示,后面要减去被隐藏的列所占的百分比) for (int i = 0, j = 0; i < count; i++) { double width = propertyToColWidths.get(propertyNames[i]); if (!hiddenColumnIndexes.contains(i)) { // 如果没有被隐藏 columnPositions[j] = i; if (width > 1) { // 如果指定的是像素值 columnWidths[j] = (int) width; clientAreaWidth -= (int) width; // 从总宽度中除去明确指定像素的列宽 } j++; } if (hiddenColumnIndexes.contains(i) && width <= 1) { shownPercentage -= width; } } for (int i = 0, j = 0; i < count; i++) { double width = propertyToColWidths.get(propertyNames[i]); if (!hiddenColumnIndexes.contains(i)) { // 如果没有被隐藏 if (width <= 1) { // 如果指定的是百分比 columnWidths[j] = (int) (clientAreaWidth * (width / shownPercentage)); // 按指定百分比计算像素 } j++; } } paintListenerWithAutoRowSize.resetArea(); table.doCommand(new MultiColumnResizeCommand(bodyLayer.getBodyDataLayer(), columnPositions, columnWidths)); // if (HsMultiActiveCellEditor.getSourceEditor() == null) { // HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.this); // } HsMultiActiveCellEditor.recalculateCellsBounds(); } }; /** * 重绘监听,处理 NatTable 自适应大小. */ class PaintListenerWithAutoRowSize implements PaintListener { // private Rectangle area = new Rectangle(-1, -1, -1, -1); private int columnCount = 0; private List<Integer> hasComputedRow = new ArrayList<Integer>(); private int currentRowPosition = -1; public void paintControl(PaintEvent e) { ViewportLayer viewportLayer = bodyLayer.getViewportLayer(); int rowPosition = viewportLayer.getOriginRowPosition() + 1; // 起始行 if (currentRowPosition == -1 || currentRowPosition != rowPosition) { currentRowPosition = rowPosition; } int rowCount = viewportLayer.getRowCount(); // 总行数 List<Integer> rowPositions = new ArrayList<Integer>(); for (int i = 0; i < rowCount; i++) { int rowp = i + rowPosition; if (!hasComputedRow.contains(rowp)) { rowPositions.add(rowp); hasComputedRow.add(rowp); } } if (rowPositions.size() != 0) { int[] temp = new int[rowPositions.size()]; for (int i = 0; i < temp.length; i++) { temp[i] = rowPositions.get(i); } table.doCommand(new AutoResizeCurrentRowsCommand(table, temp, table.getConfigRegistry())); HsMultiActiveCellEditor.recalculateCellsBounds(); // HsMultiActiveCellEditor.synchronizeRowHeight(); } // int width = parent.getClientArea().width; // if (!new Rectangle(rowPosition, rowCount, width, 0).equals(area)) { // area = new Rectangle(rowPosition, rowCount, width, 0); // int[] rowPositions = new int[rowCount]; // for (int j = 0; j < rowPositions.length; j++) { // rowPositions[j] = j + rowPosition; // } // table.doCommand(new AutoResizeCurrentRowsCommand(table, rowPositions, table.getConfigRegistry(), e.gc)); // } if (columnCount != table.getColumnCount()) { columnCount = table.getColumnCount(); table.notifyListeners(SWT.Resize, null); } table.getLayerPainter().paintLayer(table, e.gc, 0, 0, new Rectangle(e.x, e.y, e.width, e.height), table.getConfigRegistry()); } public void resetArea() { // area = new Rectangle(-1, -1, -1, -1); hasComputedRow.clear(); } public void resetColumnCount() { columnCount = 0; } } /** * 重绘监听,处理 NatTable 自适应大小. */ private PaintListenerWithAutoRowSize paintListenerWithAutoRowSize = new PaintListenerWithAutoRowSize(); /** * 自动调整 NatTable 行高; * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#autoResize() */ public void autoResize() { if (table != null) { paintListenerWithAutoRowSize.resetArea(); // paintListenerWithAutoRowSize.resetColumnCount(); if (!table.isDisposed()) { table.redraw(); } } } /** * 自动调整 NatTable 大小 ,只调整行高。不调整列宽 robert 2012-11-21 */ public void autoResizeNotColumn() { if (table != null) { paintListenerWithAutoRowSize.resetArea(); table.redraw(); } } /** * 配置标签列的显示效果 * @param configRegistry * 配置注册表 */ private void addFlagLableToColumn(IConfigRegistry configRegistry) { // Edit by Leakey 实现状态图片的动态显示 StatusPainter painter = new StatusPainter(bodyDataProvider); // CellPainterDecorator flagPainter = new CellPainterDecorator(new BackgroundPainter(), CellEdgeEnum.RIGHT, // painter); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, painter, DisplayMode.NORMAL, FLAG_CELL_LABEL); // Set the color of the cell. This is picked up by the button painter to style the button Style style = new Style(); FontData fd = GUIHelper.DEFAULT_FONT.getFontData()[0]; fd.setStyle(SWT.BOLD); style.setAttributeValue(CellStyleAttributes.FONT, GUIHelper.getFont(fd)); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, style, DisplayMode.NORMAL, FLAG_CELL_LABEL); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, style, DisplayMode.SELECT, FLAG_CELL_LABEL); } /** * 配置行号列的显示效果 * @param configRegistry * 配置注册表 */ private void addLineNumberToColumn(IConfigRegistry configRegistry) { configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new LineNumberPainter(), DisplayMode.NORMAL, "LINENUMBER_CELL_LABEL"); Style style = new Style(); style.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT, HorizontalAlignmentEnum.CENTER); style.setAttributeValue(CellStyleAttributes.FONT, GUIHelper.DEFAULT_FONT); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, style, DisplayMode.NORMAL, "LINENUMBER_CELL_LABEL"); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, style, DisplayMode.SELECT, "LINENUMBER_CELL_LABEL"); } /** * 定义 Body Layer Stack 中包含的 layers * @author cheney * @since JDK1.5 */ public class BodyLayerStack extends AbstractLayerTransform { private DataLayer bodyDataLayer; private SelectionLayer selectionLayer; private ColumnHideShowLayer columnHideShowLayer; private ViewportLayer viewportLayer; public BodyLayerStack(IDataProvider dataProvider, boolean isHorizontalLayout) { if (isHorizontalLayout) { bodyDataLayer = new DataLayer(dataProvider, 244, 32); } else { // 垂直布局时,期望数据提供者为 ISpanningDataProvider,否则抛出 UnexpectedTypeExcetion。 if (dataProvider instanceof ISpanningDataProvider) { bodyDataLayer = new SpanningDataLayer((ISpanningDataProvider) dataProvider, 244, 32); } else { throw new UnexpectedTypeExcetion(MessageFormat.format(Messages .getString("editor.XLIFFEditorImplWithNatTable.msg6"), dataProvider.getClass().toString())); } } // 取消调整列的功能,因为此功能会引发一些问题,如跳转,设置分割点等 // ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(bodyDataLayer); columnHideShowLayer = new ColumnHideShowLayer(bodyDataLayer); selectionLayer = new SelectionLayer(columnHideShowLayer, false); if (isHorizontalLayout) { // 两种布局采用不同的 ViewportLayer viewportLayer = new HorizontalViewportLayer(selectionLayer); } else { viewportLayer = new VerticalViewportLayer(selectionLayer); } setUnderlyingLayer(viewportLayer); setupSelectionLayer(); // 设置SelectionLayer } /** * 设置SelectionLayer ; */ private void setupSelectionLayer() { IRowIdAccessor rowIdAccessor = new IRowIdAccessor() { public Serializable getRowIdByPosition(int rowPosition) { int rowIndex = selectionLayer.getRowIndexByPosition(rowPosition); return handler.getRowId(rowIndex); } public Set<? extends Serializable> getRowIdsByPositionRange(int rowPosition, int length) { int[] rowIndexs = new int[length]; for (int i = 0; i < rowIndexs.length; i++) { rowIndexs[i] = selectionLayer.getRowIndexByPosition(rowPosition + i); } return handler.getRowIds(rowIndexs); } public ArrayList<? extends Serializable> getRowIds() { return handler.getRowIds(); } }; ISelectionModel rowSelectionModel; if (isHorizontalLayout) { rowSelectionModel = new HorizontalRowSelectionModel(selectionLayer); } else { rowSelectionModel = new VerticalRowSelectionModel<TransUnitBean>(selectionLayer, rowIdAccessor); } // Preserve selection on updates and sort selectionLayer.setSelectionModel(rowSelectionModel); selectionLayer.addConfiguration(new XLIFFEditorSelectionLayerConfiguration()); // 移除点击列头触发全选所有行的 Handler selectionLayer.unregisterCommandHandler(SelectColumnCommand.class); // Provides rows where any cell in the row is selected ISelectionProvider selectionProvider = new RowSelectionProvider(selectionLayer, true/* 只在整行选中时触发 */); // NatTable 选中行改变时触发: selectionProvider.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateStatusLine(); // 更新状态栏显示的文本段信息。 // 设置添加文本段到记忆库的可用状态 // NattableUtil.refreshCommand(AddSegmentToTMPropertyTester.PROPERTY_NAMESPACE, // AddSegmentToTMPropertyTester.PROPERTY_ENABLED); // NattableUtil.refreshCommand(SignOffPropertyTester.PROPERTY_NAMESPACE, // SignOffPropertyTester.PROPERTY_ENABLED); // NattableUtil.refreshCommand(UnTranslatedPropertyTester.PROPERTY_NAMESPACE, // UnTranslatedPropertyTester.PROPERTY_ENABLED); } }); getSite().setSelectionProvider(selectionProvider); } /** * 获得 body layer stack 中的 SelectionLayer * @return ; */ public SelectionLayer getSelectionLayer() { return selectionLayer; } /** * 获得 body layer stack 中的 BodyDataLayer * @return ; */ public DataLayer getBodyDataLayer() { return bodyDataLayer; } /** * 获得 body layer stack 中的 ColumnHideShowLayer * @return ; */ public ColumnHideShowLayer getColumnHideShowLayer() { return columnHideShowLayer; } /** * 获得 body layer stack 中的 ViewportLayer * @return ; */ public ViewportLayer getViewportLayer() { return viewportLayer; } } /** * 定义 Column Header Layer Stack 所包含的 layers * @author cheney * @since JDK1.5 */ public class ColumnHeaderLayerStack extends AbstractLayerTransform { public ColumnHeaderLayerStack(IDataProvider dataProvider) { DataLayer dataLayer = new DataLayer(dataProvider, 244, 25); /** * Edit By Leakey 不使用默认配置 */ ColumnHeaderLayer colHeaderLayer = new ColumnHeaderLayer(dataLayer, bodyLayer, bodyLayer.getSelectionLayer(), false); /** * Add By Leakey 添加默认列头的样式(前景色、背景色等) */ colHeaderLayer.addConfiguration(new DefaultColumnHeaderStyleConfiguration() { public void configureRegistry(IConfigRegistry configRegistry) { configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, cellPainter, DisplayMode.NORMAL, GridRegion.COLUMN_HEADER); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, cellPainter, DisplayMode.NORMAL, GridRegion.CORNER); // Normal Style cellStyle = new Style(); cellStyle .setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR, GUIHelper.COLOR_WIDGET_BACKGROUND); cellStyle.setAttributeValue(CellStyleAttributes.FOREGROUND_COLOR, GUIHelper.COLOR_BLACK); cellStyle.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT, hAlign); cellStyle.setAttributeValue(CellStyleAttributes.VERTICAL_ALIGNMENT, vAlign); cellStyle.setAttributeValue(CellStyleAttributes.BORDER_STYLE, borderStyle); cellStyle.setAttributeValue(CellStyleAttributes.FONT, GUIHelper.DEFAULT_FONT); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.NORMAL, GridRegion.COLUMN_HEADER); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.NORMAL, GridRegion.CORNER); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.SELECT, GridRegion.COLUMN_HEADER); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.SELECT, GridRegion.CORNER); configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle, DisplayMode.SELECT, GridRegion.ROW_HEADER); } }); SortHeaderLayer<TransUnitBean> sortHeaderLayer = new SortHeaderLayer<TransUnitBean>(colHeaderLayer, new NatTableSortModel(handler), false); setUnderlyingLayer(sortHeaderLayer); } } /** * Internal property change listener for handling workbench font changes. */ class FontPropertyChangeListener implements IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (table == null || table.isDisposed()) { return; } String property = event.getProperty(); if (net.heartsome.cat.ts.ui.Constants.XLIFF_EDITOR_TEXT_FONT.equals(property)) { Font font = JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.XLIFF_EDITOR_TEXT_FONT); ICellPainter cellPainter = table.getConfigRegistry().getConfigAttribute( CellConfigAttributes.CELL_PAINTER, DisplayMode.NORMAL, SOURCE_EDIT_CELL_LABEL); if (cellPainter instanceof TextPainterWithPadding) { TextPainterWithPadding textPainter = (TextPainterWithPadding) cellPainter; if (textPainter.getFont() == null || !textPainter.getFont().equals(font)) { HsMultiActiveCellEditor.commit(true); textPainter.setFont(font); autoResize(); // HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.this); } } } } } /** * 支持进度条显示的打开文件 * @author leakey * @version * @since JDK1.5 */ class OpenFile implements IRunnableWithProgress { public OpenFile(List<File> files) { this.files = files; } private List<File> files; private Map<String, Object> openFileResult; public Map<String, Object> getOpenFileResult() { return openFileResult; } public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { openFileResult = handler.openFiles(files, monitor); } } /** * 释放编辑器,同时释放其他相关资源。 * @see org.eclipse.ui.part.WorkbenchPart#dispose() */ public void dispose() { // 当该编辑器被释放资源时,检查该编辑器是否被保存,并且是否是同时打开多个文件,若成立,则删除合并打开所产生的临时文件--robert 2012-03-30 if (!isStore && isMultiFile()) { try { IEditorInput input = getEditorInput(); IProject multiProject = ResourceUtil.getResource(input).getProject(); ResourceUtil.getResource(input).delete(true, null); multiProject.refreshLocal(IResource.DEPTH_INFINITE, null); CommonFunction.refreshHistoryWhenDelete(input); } catch (CoreException e) { LOGGER.error("", e); e.printStackTrace(); } } if (titleImage != null && !titleImage.isDisposed()) { titleImage.dispose(); titleImage = null; } if (table != null && !table.isDisposed()) { table.dispose(); table = null; } if (statusLineImage != null && !statusLineImage.isDisposed()) { statusLineImage.dispose(); statusLineImage = null; } handler = null; JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener); NattableUtil.getInstance(this).releaseResource(); super.dispose(); System.gc(); } /** * 得到当前活动的 XLIFF 编辑器实例 * @return ; */ public static XLIFFEditorImplWithNatTable getCurrent() { try { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { IEditorPart editor = page.getActiveEditor(); if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { return (XLIFFEditorImplWithNatTable) editor; } } } } catch (NullPointerException e) { LOGGER.error("", e); e.printStackTrace(); } return null; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#updateCell(int, int, java.lang.String) */ public void updateCell(int row, int columnIndex, String newValue, String matchType, String quality) throws ExecutionException { StyledTextCellEditor editor = HsMultiActiveCellEditor.getTargetStyledEditor(); if (editor != null && editor.getRowIndex() == (isHorizontalLayout ? row : row * 2 + 1) && editor.getColumnIndex() == columnIndex) { editor.viewer.getTextWidget().forceFocus(); } ArrayList<String> rowIds = new ArrayList<String>(handler.getRowIds(new int[] { row })); updateSegments(rowIds, columnIndex, newValue, false, matchType, quality); } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#updateCells(int[], int, java.lang.String) */ public void updateCells(int[] rows, int columnIndex, String newValue) throws ExecutionException { ArrayList<String> rowIds = new ArrayList<String>(handler.getRowIds(rows)); updateSegments(rowIds, columnIndex, newValue, false, null, null); } /** * 修改文本段。(改成不同的值) * @param map * key:rowId;value:新值。 * @param column * 列索引。 * @throws ExecutionException * ; */ public void updateSegments(Map<String, String> map, int columnIndex, String matchType, String quality) throws ExecutionException { updateSegments(map, columnIndex, false, matchType, quality); } /** * 修改文本段。(改成相同的值) * @param rowIds * 行唯一标识的集合 * @param columnIndex * 列索引 * @param newValue * 新值 * @param approved * 是否改为已批准 * @throws ExecutionException * ; */ public void updateSegments(List<String> rowIds, int columnIndex, String newValue, boolean approved, String matchType, String quality) throws ExecutionException { updateCellEditor(columnIndex, newValue, matchType, quality); HISTORY.execute(new UpdateSegmentsOperation(this, handler, rowIds, columnIndex, newValue, approved, matchType, quality), null, null); NattableUtil.refreshCommand(AddSegmentToTMPropertyTester.PROPERTY_NAMESPACE, AddSegmentToTMPropertyTester.PROPERTY_ENABLED); NattableUtil.refreshCommand(SignOffPropertyTester.PROPERTY_NAMESPACE, SignOffPropertyTester.PROPERTY_ENABLED); NattableUtil.refreshCommand(UnTranslatedPropertyTester.PROPERTY_NAMESPACE, UnTranslatedPropertyTester.PROPERTY_ENABLED); } /** * 修改文本段。(改成不同的值) * @param map * key:rowId;value:新值。 * @param columnIndex * 列索引。 * @param approved * 是否改为已批准 * @throws ExecutionException * ; */ public void updateSegments(Map<String, String> map, int columnIndex, boolean approved, String matchType, String quality) throws ExecutionException { int rowIndex = HsMultiActiveCellEditor.sourceRowIndex; if (rowIndex != -1) { if (!isHorizontalLayout) { rowIndex = VerticalNatTableConfig.getRealRowIndex(rowIndex); } String rowId = handler.getRowId(rowIndex); if (!updateCellEditor(columnIndex, map.get(rowId), matchType, quality)) { return; } } HISTORY.execute(new UpdateSegmentsOperation(this, handler, map, columnIndex, approved, matchType, quality), null, null); NattableUtil.refreshCommand(AddSegmentToTMPropertyTester.PROPERTY_NAMESPACE, AddSegmentToTMPropertyTester.PROPERTY_ENABLED); NattableUtil.refreshCommand(SignOffPropertyTester.PROPERTY_NAMESPACE, SignOffPropertyTester.PROPERTY_ENABLED); NattableUtil.refreshCommand(UnTranslatedPropertyTester.PROPERTY_NAMESPACE, UnTranslatedPropertyTester.PROPERTY_ENABLED); } /** * 修改单元格编辑器中的文本。 * @param columnIndex * 列索引 * @param newValue * 新值 * @return ; */ private boolean updateCellEditor(int columnIndex, String newValue, String matchType, String quality) { StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getFocusCellEditor(); if (cellEditor == null) { return false; } // 如果当前的文本是锁定状态,不改变值 String tgt = handler.getCaseTgtContent(handler.getRowId(cellEditor.getRowIndex())); if (null != tgt) { if (tgt.equals("no")) { return true; } } int rowIndex = cellEditor.getRowIndex(); int activeCellEditorColumnIndex = cellEditor.getColumnIndex(); if (rowIndex == -1) { return false; } if (activeCellEditorColumnIndex == -1) { return false; } if (!isHorizontalLayout) { // 垂直布局 int[] selecteds = getSelectedRows(); int seled = getSelectedRows()[selecteds.length - 1]; if ((seled * 2) + 1 != rowIndex) { return false; } } else { if (activeCellEditorColumnIndex != columnIndex) { return false; } } // 解决“修改源或者目标文本时,总是优先修改处于编辑模式的列”的问题。 /** burke 修改复制来源到目标中,当光标在src单元格中,点击复制来源到目标应该不起作用 修改代码 添加合并判断条件 !isHorizontalLayout */ if (activeCellEditorColumnIndex == -1 || (activeCellEditorColumnIndex != columnIndex && !isHorizontalLayout)) { return false; } UpdateDataBean bean = new UpdateDataBean(newValue, matchType, quality); cellEditor.setCanonicalValue(bean); return true; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#getSrcColumnIndex() */ public int getSrcColumnIndex() { return isHorizontalLayout ? 1 : 2; } public int getStatusColumnIndex() { return isHorizontalLayout ? 2 : 1; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#getTgtColumnIndex() */ public int getTgtColumnIndex() { return isHorizontalLayout ? 3 : 2; } public List<String> getSplitXliffPoints() { return splitXliffPoints; } /** * 点击品质检查结果视图的列表项时,重置nattable的排序 robert 2011-11-24 */ public void resetOrder() { if (cmbFilter.getSelectionIndex() != 0) { cmbFilter.select(0); boolean isUpdated = handler.doFilter(cmbFilter.getText(), langFilterCondition); if (isUpdated) { autoResizeNotColumn(); // 自动调整 NatTable 大小 ; updateStatusLine(); // 更新状态栏 refresh(); } } else { // handler.doFilter(cmbFilter.getText(), langFilterCondition); handler.resetRowIdsToUnsorted(); // 重置布局 autoResizeNotColumn(); updateStatusLine(); } } public void reloadData() { boolean isUpdated = handler.doFilter(cmbFilter.getText(), langFilterCondition); if (isUpdated) { autoResizeNotColumn(); // 自动调整 NatTable 大小 ; updateStatusLine(); // 更新状态栏 refresh(); } } public void insertCell(int rowIndex, int columnIndex, String insertText) throws ExecutionException { StyledTextCellEditor editor = HsMultiActiveCellEditor.getTargetStyledEditor(); int editorRowIndex = editor.getRowIndex(); if (!isHorizontalLayout) { editorRowIndex = editorRowIndex / 2; } if (editor != null && editorRowIndex == rowIndex && editor.getColumnIndex() == columnIndex) { editor.insertCanonicalValue(insertText); editor.viewer.getTextWidget().forceFocus(); } } public void setStore(boolean isStore) { this.isStore = isStore; } public List<File> getMultiFileList() { return multiFileList; } public void jumpToRow(int position, boolean isMultiFiles) { // if (position == 0) { // ViewportLayer viewportLayer = bodyLayer.getViewportLayer(); // HsMultiActiveCellEditor.commit(true); // viewportLayer.doCommand(new SelectCellCommand(bodyLayer.getSelectionLayer(), getTgtColumnIndex(), -1, // false, false)); // HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.this); // } jumpToRow(position); } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#getSelectPureText() */ public String getSelectPureText() { StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getFocusCellEditor(); String selectionText = null; if (cellEditor != null && !cellEditor.isClosed()) { StyledText styledText = cellEditor.getSegmentViewer().getTextWidget(); Point p = styledText.getSelection(); if (p != null) { if (p.x != p.y) { selectionText = cellEditor.getSelectedPureText(); } else { selectionText = ""; } } } if (selectionText != null) { // 将换行符替换为空 selectionText = selectionText.replaceAll("\n", ""); } return selectionText; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#getSelectSrcOrTgtPureText(java.lang.StringBuffer, * java.lang.StringBuffer) */ public void getSelectSrcOrTgtPureText(StringBuffer src, StringBuffer tgt) { if (src == null || tgt == null) { return; } HsMultiCellEditor hsCellEditor = HsMultiActiveCellEditor.getSourceEditor(); if (hsCellEditor != null && hsCellEditor.getCellEditor() != null) { StyledTextCellEditor cellEditor = hsCellEditor.getCellEditor(); if (!cellEditor.isClosed()) { StyledText styledText = cellEditor.getSegmentViewer().getTextWidget(); Point p = styledText.getSelection(); if (p != null) { if (p.x != p.y) { // String selectionText = styledText.getSelectionText(); String selectionText = cellEditor.getSelectedPureText(); src.append(selectionText); } } } } hsCellEditor = HsMultiActiveCellEditor.getTargetEditor(); if (hsCellEditor != null && hsCellEditor.getCellEditor() != null) { StyledTextCellEditor cellEditor = hsCellEditor.getCellEditor(); if (!cellEditor.isClosed()) { StyledText styledText = cellEditor.getSegmentViewer().getTextWidget(); Point p = styledText.getSelection(); if (p != null) { if (p.x != p.y) { // String selectionText = styledText.getSelectionText(); String selectionText = cellEditor.getSelectedPureText(); tgt.append(selectionText); } } } } } public void redraw() { table.redraw(); } public TransUnitBean getRowTransUnitBean(int rowIndex) { if (!isHorizontalLayout) { rowIndex *= 2; } return bodyDataProvider.getRowObject(rowIndex); } public void addPropertyListener(IPropertyListener l) { if (tagStyleManager != null) { tagStyleManager.setTagStyle(TagStyle.curStyle); autoResize(); refresh(); } super.addPropertyListener(l); } /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#affterFuzzyMatchApplayTarget(int, String, String, String) */ public void affterFuzzyMatchApplayTarget(int rowIndex, String targetContent, String matchType, String quality) { StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getTargetStyledEditor(); if (cellEditor != null && cellEditor.getRowIndex() == rowIndex) { String currentText = cellEditor.getSegmentViewer().getText(); if (currentText == null || currentText.trim().equals("")) { UpdateDataBean bean = new UpdateDataBean(targetContent, matchType, quality); cellEditor.setCanonicalValue(bean); } } } private Map<Integer, List<String>> termsCache = new HashMap<Integer, List<String>>(); /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#highlightedTerms(java.util.List) */ public void highlightedTerms(int rowIndex, List<String> terms) { if (terms == null || terms.size() == 0) { // terms = HsMultiActiveCellEditor.getCacheSegementTerms(cellEditor.getRowIndex()); // if(terms != null && terms.size() != 0){ // cellEditor.highlightedTerms(terms); // } // HsMultiActiveCellEditor.cacheSegementTerms(HsMultiActiveCellEditor.sourceRowIndex, new // ArrayList<String>()); return; } HsMultiCellEditor cellEditor = HsMultiActiveCellEditor.getSourceEditor(); // HsMultiActiveCellEditor.cacheSegementTerms(HsMultiActiveCellEditor.sourceRowIndex, terms); termsCache.clear(); if (rowIndex == -1 || terms == null) { return; } this.termsCache.put(rowIndex, terms); if (cellEditor != null) { cellEditor.highlightedTerms(terms); } else { table.redraw(); } } public Map<Integer, List<String>> getTermsCache() { return termsCache; }; /** * (non-Javadoc) * @see net.heartsome.cat.ts.ui.editors.IXliffEditor#refreshWithNonprinttingCharacter(boolean) */ public void refreshWithNonprinttingCharacter(boolean isShow) { HsMultiActiveCellEditor.commit(true); Activator.getDefault().getPreferenceStore() .setValue(IPreferenceConstants.XLIFF_EDITOR_SHOWHIDEN_NONPRINTCHARACTER, isShow); HsMultiCellEditorControl.activeSourceAndTargetCell(this); this.refresh(); } public Combo getFilterCombo() { return this.cmbFilter; } public int getRowCount() { return bodyLayer.getRowCount(); } public int getAllRowCount() { int rowCount = bodyLayer.getSelectionLayer().getRowCount(); return isHorizontalLayout() ? rowCount : rowCount / 2; } }
110,230
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TagDisplayConverter.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/TagDisplayConverter.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import java.util.TreeMap; import net.heartsome.cat.common.innertag.InnerTagBean; import net.heartsome.cat.common.innertag.TagStyle; import net.heartsome.cat.common.ui.utils.InnerTagUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.data.convert.DefaultDisplayConverter; import net.sourceforge.nattable.layer.DataLayer; import net.sourceforge.nattable.layer.cell.LayerCell; /** * Tag 显示格式转换器 * @author weachy * @version * @since JDK1.5 */ public class TagDisplayConverter extends DefaultDisplayConverter { private final XLIFFEditorImplWithNatTable xliffEditor; private final NatTable table; private LayerCell currentCell; TagDisplayConverter(XLIFFEditorImplWithNatTable xliffEditor) { this.xliffEditor = xliffEditor; table = xliffEditor.getTable(); } public void setCell(LayerCell cell) { this.currentCell = cell; } /** * (non-Javadoc) * @see net.sourceforge.nattable.data.convert.DefaultDisplayConverter#canonicalToDisplayValue(java.lang.Object) */ public Object canonicalToDisplayValue(Object xmlValue) { if (xmlValue == null || xmlValue.toString().length() == 0) { return ""; } String originalValue = xmlValue.toString(); TagStyle tagStyle = xliffEditor.getTagStyleManager().getTagStyle(); // if (TagStyle.FULL.equals(tagStyle)) { // return originalValue; // } else { StringBuffer displayValue = new StringBuffer(originalValue); int columnIndex = table.getColumnIndexByPosition(currentCell.getColumnPosition()); if (xliffEditor.isHorizontalLayout()) { if (columnIndex == xliffEditor.getSrcColumnIndex()) { InnerTagUtil.parseXmlToDisplayValue(displayValue, tagStyle); // 设置内部标记索引及样式 } else if (columnIndex == xliffEditor.getTgtColumnIndex()) { int rowIndex = currentCell.getLayer().getRowIndexByPosition( currentCell.getRowPosition()) ; int srcColumnPosition = LayerUtil.getColumnPositionByIndex(table, xliffEditor.getSrcColumnIndex()); if (srcColumnPosition != -1) { // 得到Source列的位置 DataLayer dataLayer = LayerUtil.getLayer(table, DataLayer.class); String srcOriginalValue = dataLayer.getDataValueByPosition(srcColumnPosition, rowIndex).toString(); InnerTagUtil.parseXmlToDisplayValueFromSource(srcOriginalValue, displayValue, tagStyle); } else { InnerTagUtil.parseXmlToDisplayValue(displayValue, tagStyle); // 设置内部标记索引及样式 } currentCell = null; // 恢复初始值 } else { // do nothing } } else { int rowIndex = currentCell.getLayer().getRowIndexByPosition( currentCell.getRowPosition()); if (columnIndex == xliffEditor.getSrcColumnIndex() && rowIndex % 2 == 0) { //源语言 InnerTagUtil.parseXmlToDisplayValue(displayValue, tagStyle); // 设置内部标记索引及样式 } else if (columnIndex == xliffEditor.getTgtColumnIndex()) { //目标语言 int srcColumnPosition = LayerUtil.getColumnPositionByIndex(table, xliffEditor.getSrcColumnIndex()); if (srcColumnPosition != -1) { // 得到Source列的位置 // DataLayer dataLayer = LayerUtil.getLayer(table, DataLayer.class); String srcOriginalValue = table.getDataValueByPosition(srcColumnPosition, rowIndex - 1).toString(); InnerTagUtil.parseXmlToDisplayValueFromSource(srcOriginalValue, displayValue, tagStyle); } else { InnerTagUtil.parseXmlToDisplayValue(displayValue, tagStyle); // 设置内部标记索引及样式 } currentCell = null; // 恢复初始值 } else { // do nothing } } return InnerTagUtil.resolveTag(displayValue.toString()); // } } /** * (non-Javadoc) * @see net.sourceforge.nattable.data.convert.DefaultDisplayConverter#displayToCanonicalValue(java.lang.Object) */ public Object displayToCanonicalValue(Object tagValue) { String displayValue = tagValue == null ? "" : tagValue.toString(); String content = InnerTagUtil.escapeTag(displayValue); int rowIndex = currentCell.getLayer().getRowIndexByPosition( currentCell.getRowPosition()); int srcColumnPosition = LayerUtil.getColumnPositionByIndex(table, xliffEditor.getSrcColumnIndex()); if (srcColumnPosition != -1) { // 得到Source列的位置 DataLayer dataLayer = LayerUtil.getLayer(table, DataLayer.class); String srcOriginalValue = dataLayer.getDataValueByPosition(srcColumnPosition, rowIndex).toString(); TreeMap<String, InnerTagBean> sourceTags = InnerTagUtil.parseXmlToDisplayValue(new StringBuffer( srcOriginalValue), xliffEditor.getTagStyleManager().getTagStyle()); return InnerTagUtil.parseDisplayToXmlValue(sourceTags, content); // 换回xml格式的内容 } else { return content; // 设置内部标记索引及样式 } } }
4,894
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
HsMultiCellEditorHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/HsMultiCellEditorHandler.java
/** * HsMultiCellEditorHandler.java * * Version information : * * Date:2012-12-18 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.UpdateDataAndAutoResizeCommand; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.sourceforge.nattable.edit.ICellEditHandler; import net.sourceforge.nattable.layer.CompositeLayer; import net.sourceforge.nattable.layer.DataLayer; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.selection.SelectionLayer.MoveDirectionEnum; import net.sourceforge.nattable.selection.command.MoveSelectionCommand; /** * @author Jason * @version * @since JDK1.6 */ public class HsMultiCellEditorHandler implements ICellEditHandler { private final StyledTextCellEditor cellEditor; private final ILayer layer; public HsMultiCellEditorHandler(StyledTextCellEditor cellEditor, ILayer layer) { this.cellEditor = cellEditor; this.layer = layer; } /** * Just commit the data, will not close the editor control * @see net.sourceforge.nattable.edit.ICellEditHandler#commit(net.sourceforge.nattable.selection.SelectionLayer.MoveDirectionEnum, boolean) */ public boolean commit(MoveDirectionEnum direction, boolean closeEditorAfterCommit) { switch (direction) { case LEFT: layer.doCommand(new MoveSelectionCommand(MoveDirectionEnum.LEFT, 1, false, false)); break; case RIGHT: layer.doCommand(new MoveSelectionCommand(MoveDirectionEnum.RIGHT, 1, false, false)); break; } if (cellEditor.isEditable()) { Object canonicalValue = cellEditor.getCanonicalValue(); DataLayer datalayer = LayerUtil.getLayer((CompositeLayer)layer, DataLayer.class); datalayer.doCommand(new UpdateDataAndAutoResizeCommand(layer, cellEditor.getColumnIndex(), cellEditor.getRowIndex(), canonicalValue)); // layer.doCommand(new UpdateDataCommand(layer, cellEditor.getColumnPosition(), cellEditor.getRowPosition(), canonicalValue)); } return true; } }
2,568
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
StyledTextCellEditor.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/StyledTextCellEditor.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.innertag.ISegmentViewer; import net.heartsome.cat.ts.ui.innertag.SegmentViewer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.UpdateDataBean; import net.heartsome.cat.ts.ui.xliffeditor.nattable.celleditor.EditableManager; import net.heartsome.cat.ts.ui.xliffeditor.nattable.celleditor.SourceEditMode; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester.AddSegmentToTMPropertyTester; import net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester.SignOffPropertyTester; import net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester.UnTranslatedPropertyTester; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; import net.heartsome.cat.ts.ui.xliffeditor.nattable.utils.NattableUtil; import net.sourceforge.nattable.data.convert.IDisplayConverter; import net.sourceforge.nattable.data.validate.IDataValidator; import net.sourceforge.nattable.edit.ICellEditHandler; import net.sourceforge.nattable.edit.editor.EditorSelectionEnum; import net.sourceforge.nattable.edit.editor.ICellEditor; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.SelectionLayer.MoveDirectionEnum; import net.sourceforge.nattable.selection.command.MoveSelectionCommand; import net.sourceforge.nattable.selection.command.ScrollSelectionCommand; import net.sourceforge.nattable.style.CellStyleAttributes; import net.sourceforge.nattable.style.HorizontalAlignmentEnum; import net.sourceforge.nattable.style.IStyle; import net.sourceforge.nattable.util.GUIHelper; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ST; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.IME; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; /** * 基于 StyledText 的单元格编辑器。<br> * <li>使用 {@link #setText(Object)} 方法设置其值。</li> * @author weachy * @since JDK1.5 */ public class StyledTextCellEditor implements DisposeListener, ICellEditor { public StyledTextCellEditor(XLIFFEditorImplWithNatTable xliffEditor) { this.xliffEditor = xliffEditor; this.actionHandler = new XLIFFEditorActionHandler(xliffEditor.getEditorSite().getActionBars()); } private EditorSelectionEnum selectionMode = EditorSelectionEnum.ALL; /** 封装StyledText,提供撤销/重做管理器的组件. */ protected SegmentViewer viewer = null; /** XLIFF 编辑器实例 */ private final XLIFFEditorImplWithNatTable xliffEditor; /** 单元格类型。值为 {@link NatTableConstant#SOURCE}、{@link NatTableConstant#TARGET}之一 */ private String cellType; /** * 得到单元格类型 * @return 值为 {@link NatTableConstant#SOURCE}、{@link NatTableConstant#TARGET} 之一; */ public String getCellType() { return cellType; } public final void setSelectionMode(EditorSelectionEnum selectionMode) { this.selectionMode = selectionMode; } public final EditorSelectionEnum getSelectionMode() { return selectionMode; } /** * 用于标识编辑器关闭状态<br/> * @see net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable#selectedRowChanged() * @see net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor.addListeners().new IPartListener2() * {...}.partActivated(IWorkbenchPartReference partRef) */ private boolean close = true; /** 关闭监听器 */ private HashSet<Listener> closingListeners = new HashSet<Listener>(); /** * 添加关闭单元格关闭时的监听器 * @param closeListener * 关闭监听器 ; */ public void addClosingListener(Listener closeListener) { if (closeListener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } closingListeners.add(closeListener); } /** * 移除关闭单元格关闭时的监听器 * @param closeListener * 关闭监听器 ; */ public void removeClosingListener(Listener closeListener) { for (Listener listener : closingListeners) { if (listener != null && listener.equals(closeListener)) { closingListeners.remove(listener); break; } } } /** 绑定全局 Edit 菜单的处理类 */ private XLIFFEditorActionHandler actionHandler; /** 源文本的值 */ private String source; /** 可编辑状态管理器 */ private EditableManager editableManager = new EditableManager(cellType == NatTableConstant.SOURCE) { @Override protected void setupReadOnlyMode() { checkWidget(); StyledText text = viewer.getTextWidget(); if (!close) { if (!editable) { return; } text.removeVerifyKeyListener(edit_VerifyKey); text.removeTraverseListener(edit_Traverse); } editable = false; text.setEditable(false); text.addVerifyKeyListener(readOnly_VerifyKey); } @Override protected void setupEditMode() { checkWidget(); StyledText text = viewer.getTextWidget(); if (!close) { if (editable) { return; } text.removeVerifyKeyListener(readOnly_VerifyKey); } editable = true; text.setEditable(true); text.addVerifyKeyListener(edit_VerifyKey); text.addTraverseListener(edit_Traverse); } @Override public void judgeEditable() { checkWidget(); if (isApprovedOrLocked()) { setupReadOnlyMode(); setUneditableMessage(Messages.getString("editor.StyledTextCellEditor.msg1")); } else { if (cellType == NatTableConstant.SOURCE) { if (getSourceEditMode() != SourceEditMode.DISEDITABLE) { setupEditMode(); } else { setupReadOnlyMode(); setUneditableMessage(Messages.getString("editor.StyledTextCellEditor.msg2")); } } else if (cellType == NatTableConstant.TARGET) { setupEditMode(); } } } public void checkWidget() { StyledText text = viewer.getTextWidget(); if (text == null || text.isDisposed()) { SWT.error(SWT.ERROR_FAILED_EVALUATE); } } }; /** * 是否可编辑 * @return ; */ public boolean isEditable() { return editableManager.getEditable(); } /** * 是否批准或者锁定 * @return ; */ public boolean isApprovedOrLocked() { int rowIndex = hsCellEditor.getRowIndex(); if (rowIndex == -1) { return true; } if (!xliffEditor.isHorizontalLayout()) { // 是垂直布局 rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; // 得到实际的行索引 } TransUnitBean tu = xliffEditor.getRowTransUnitBean(rowIndex); String translate = tu.getTuProps().get("translate"); if (translate != null && "no".equalsIgnoreCase(translate)) { return true; } return false; } /** * 得到可编辑状态管理器 * @return ; */ public EditableManager getEditableManager() { return editableManager; } private HsMultiCellEditor hsCellEditor; protected Control activateCell(final Composite parent, HsMultiCellEditor hsCellEditor) { this.hsCellEditor = hsCellEditor; StyledText text = createTextControl(parent); text.setBounds(hsCellEditor.getEditorBounds()); // analyzeCellType(); // 分析单元格类型。 this.cellType = hsCellEditor.getType(); if (cellType == NatTableConstant.TARGET) { this.source = HsMultiActiveCellEditor.getSourceEditor().getOriginalCanonicalValue().toString(); viewer.setSource(source); // 设置原文本,用来解析内部标记 } editableManager.judgeEditable(); // 判断“可编辑”状态; // If we have an initial value, then Object originalCanonicalValue = this.hsCellEditor.getOriginalCanonicalValue(); if (originalCanonicalValue != null) { setCanonicalValue(new UpdateDataBean(originalCanonicalValue.toString(), null, null)); } else { setCanonicalValue(new UpdateDataBean()); } // 改变关闭状态标识 close = false; xliffEditor.getTable().addDisposeListener(this); // text.forceFocus(); // 初始化撤销/重做管理器,设置步长为 50。 viewer.initUndoManager(50); // 绑定全局 Edit 菜单 actionHandler.addTextViewer(viewer); text.addKeyListener(movedKeyListener); // 移除向上和向下键默认事件处理,将此部分实现放到upAndDownKeyListener监听中 text.setKeyBinding(SWT.ARROW_DOWN, SWT.NULL); text.setKeyBinding(SWT.ARROW_UP, SWT.NULL); addMouselistener(text); return text; } private Map<String ,Boolean> mouseState = new HashMap<String, Boolean>(); private void addMouselistener(StyledText text){ text.addMouseListener(new MouseListener() { public void mouseUp(MouseEvent e) { // TODO Auto-generated method stub mouseState.put("mouseDown", false); } public void mouseDown(MouseEvent e) { // TODO Auto-generated method stub mouseState.put("mouseDown", true); } public void mouseDoubleClick(MouseEvent e) { } }); } public boolean getMouseState(){ if( mouseState.get("mouseDown")==null){ mouseState.put("mouseDown", false); } return mouseState.get("mouseDown"); } public XLIFFEditorActionHandler getActionHandler() { return actionHandler; } /** * 目标编辑器中需要设置原文本,用来解析内部标记 * @param source * 带有内部标记内容的源文本内容 ; */ public void setSource(String source) { this.source = source; } private VerifyKeyListener readOnly_VerifyKey = new VerifyKeyListener() { public void verifyKey(VerifyEvent event) { showUneditableMessage(); } }; private VerifyKeyListener edit_VerifyKey = new VerifyKeyListener() { public void verifyKey(VerifyEvent event) { NattableUtil.refreshCommand(AddSegmentToTMPropertyTester.PROPERTY_NAMESPACE, AddSegmentToTMPropertyTester.PROPERTY_ENABLED); NattableUtil.refreshCommand(SignOffPropertyTester.PROPERTY_NAMESPACE, SignOffPropertyTester.PROPERTY_ENABLED); NattableUtil.refreshCommand(UnTranslatedPropertyTester.PROPERTY_NAMESPACE, UnTranslatedPropertyTester.PROPERTY_ENABLED); } }; private TraverseListener edit_Traverse = new TraverseListener() { public void keyTraversed(TraverseEvent event) { // StyledText text = viewer.getTextWidget(); // text.gettext } }; /** * 实现编辑模式上下移动光标到底部或者顶部时自动移动到下一行 */ private KeyListener movedKeyListener = new KeyListener() { public void keyReleased(KeyEvent e) { } public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN && e.stateMask == SWT.NONE) { StyledText text = viewer.getTextWidget(); int oldOffset = text.getCaretOffset(); text.invokeAction(ST.LINE_DOWN); int newOffset = text.getCaretOffset(); if (oldOffset == newOffset) { SelectionLayer selectionLayer = LayerUtil.getLayer(xliffEditor.getTable(), SelectionLayer.class); int rowPosition = selectionLayer.getLastSelectedCellPosition().rowPosition; if (rowPosition != selectionLayer.getRowCount() - 1) { // 减去列头行 HsMultiActiveCellEditor.commit(true); int stepSize = 1; if (!xliffEditor.isHorizontalLayout()) { stepSize = 2; } xliffEditor.getTable().doCommand( new MoveSelectionCommand(MoveDirectionEnum.DOWN, stepSize, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } } } else if (e.keyCode == SWT.ARROW_UP && e.stateMask == SWT.NONE) { StyledText text = viewer.getTextWidget(); int oldOffset = text.getCaretOffset(); text.invokeAction(ST.LINE_UP); int newOffset = text.getCaretOffset(); if (oldOffset == newOffset) { SelectionLayer selectionLayer = LayerUtil.getLayer(xliffEditor.getTable(), SelectionLayer.class); int rowPosition = selectionLayer.getLastSelectedCellPosition().rowPosition; if (rowPosition != 0) { HsMultiActiveCellEditor.commit(true); int stepSize = 1; if (!xliffEditor.isHorizontalLayout()) { stepSize = 2; } xliffEditor.getTable().doCommand( new MoveSelectionCommand(MoveDirectionEnum.UP, stepSize, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } } } else if (e.keyCode == SWT.PAGE_UP && e.stateMask == SWT.NONE) { SelectionLayer selectionLayer = LayerUtil.getLayer(xliffEditor.getTable(), SelectionLayer.class); int rowPosition = selectionLayer.getLastSelectedCellPosition().rowPosition; if (rowPosition != 0) { HsMultiActiveCellEditor.commit(true); xliffEditor.getTable().doCommand(new ScrollSelectionCommand(MoveDirectionEnum.UP, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } } else if (e.keyCode == SWT.PAGE_DOWN && e.stateMask == SWT.NONE) { SelectionLayer selectionLayer = LayerUtil.getLayer(xliffEditor.getTable(), SelectionLayer.class); int rowPosition = selectionLayer.getLastSelectedCellPosition().rowPosition; if (rowPosition != selectionLayer.getRowCount() - 1) { HsMultiActiveCellEditor.commit(true); xliffEditor.getTable().doCommand(new ScrollSelectionCommand(MoveDirectionEnum.DOWN, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } } else if (e.keyCode == SWT.HOME && e.stateMask == SWT.CTRL) { HsMultiActiveCellEditor.commit(true); xliffEditor.getTable().doCommand( new MoveSelectionCommand(MoveDirectionEnum.UP, SelectionLayer.MOVE_ALL, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } else if (e.keyCode == SWT.END && e.stateMask == SWT.CTRL) { HsMultiActiveCellEditor.commit(true); xliffEditor.getTable().doCommand( new MoveSelectionCommand(MoveDirectionEnum.DOWN, SelectionLayer.MOVE_ALL, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } else if ((e.keyCode == SWT.ESC) && e.stateMask == SWT.NONE) { HsMultiActiveCellEditor.commit(true); } } }; private void autoResize() { HsMultiActiveCellEditor.synchronizeRowHeight(); } /** * 显示不可编辑信息。 */ public void showUneditableMessage() { viewer.setToolTipMessage(editableManager.getUneditableMessage()); } private void selectText() { StyledText text = viewer.getTextWidget(); if (text == null || text.isDisposed()) { return; } // viewer.setSelectedRange(selectionOffset, selectionLength) int textLength = text.getText().length(); if (textLength > 0) { EditorSelectionEnum selectionMode = getSelectionMode(); if (selectionMode == EditorSelectionEnum.ALL) { text.setSelection(0, textLength); } else if (selectionMode == EditorSelectionEnum.END) { text.setSelection(textLength, textLength); } } text.setCaretOffset(textLength); } 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; } /** * 初始化默认颜色、字体等 * @param textControl * ; */ private void initStyle(final StyledText textControl, IStyle cellStyle) { // textControl.setBackground(cellStyle.getAttributeValue(CellStyleAttributes.BACKGROUND_COLOR)); textControl.setBackground(GUIHelper.getColor(210, 210, 240)); textControl.setForeground(cellStyle.getAttributeValue(CellStyleAttributes.FOREGROUND_COLOR)); textControl.setLineSpacing(Constants.SEGMENT_LINE_SPACING); textControl.setLeftMargin(Constants.SEGMENT_LEFT_MARGIN); textControl.setRightMargin(Constants.SEGMENT_RIGHT_MARGIN); textControl.setTopMargin(Constants.SEGMENT_TOP_MARGIN); textControl.setBottomMargin(Constants.SEGMENT_TOP_MARGIN); // textControl.setLeftMargin(0); // textControl.setRightMargin(0); // textControl.setTopMargin(0); // textControl.setBottomMargin(0); textControl.setFont(JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.XLIFF_EDITOR_TEXT_FONT)); textControl.setIME(new IME(textControl, SWT.NONE)); } /** * 添加标记样式改变监听 ; */ /* * private void addTagStyleChangeListener() { final TagStyleManager tagStyleManager = * xliffEditor.getTagStyleManager(); final Listener tagStyleChangeListener = new Listener() { public void * handleEvent(Event event) { if (event.data != null && event.data instanceof TagStyle) { * viewer.setTagStyle((TagStyle) event.data); } } }; * tagStyleManager.addTagStyleChangeListener(tagStyleChangeListener); * * viewer.getTextWidget().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { * tagStyleManager.removeTagStyleChangeListener(tagStyleChangeListener); } }); } */ /** * 得到当前的值(内部标记被转换为 XML 格式) * @return ; */ public Object getCanonicalValue() { String content = viewer.getText(); if (!content.equals(canonicalValue.getText())) { canonicalValue.setMatchType(null); canonicalValue.setQuality(null); } canonicalValue.setText(content); return canonicalValue; } private UpdateDataBean canonicalValue; public void setCanonicalValue(Object canonicalValue) { this.canonicalValue = (UpdateDataBean) canonicalValue; String text = this.canonicalValue == null ? "" : this.canonicalValue.getText(); // 保留原始值 // 初始化 viewer 内容 viewer.setText(text); selectionMode = EditorSelectionEnum.END; selectText(); } /** * 将指定文本添加到光标所在位置。 robert 2011-12-21 * @param canonicalValue * ; */ public void insertCanonicalValue(Object canonicalValue) { StyledText text = viewer.getTextWidget(); if (text == null || text.isDisposed()) { return; } int offset = text.getCaretOffset(); text.insert(canonicalValue.toString()); text.setCaretOffset(offset + canonicalValue.toString().length()); } public void close() { if (close) { return; } for (Listener listener : closingListeners) { Event event = new Event(); event.data = this; listener.handleEvent(event); } close = true; // 状态改为已经关闭 xliffEditor.getTable().removeDisposeListener(this); StyledText text = viewer.getTextWidget(); if (text != null && !text.isDisposed()) { actionHandler.removeTextViewer(); text.setMenu(null); // dispose前应去掉右键menu,因为右键menu是和nattable共享的 viewer.reset(); text.dispose(); text = null; } // 如果 XLIFF 编辑器仍处于激活状态,则把焦点交给编辑器 try { IWorkbenchPart activepart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActivePart(); if (xliffEditor.equals(activepart)) { xliffEditor.setFocus(); } } catch (NullPointerException e) { } // NatTable table = xliffEditor.getTable(); // int[] rowPositions = new int[] { hsCellEditor.getRowPosition() }; // table.doCommand(new AutoResizeCurrentRowsCommand(table, rowPositions, table.getConfigRegistry())); } /** * 重写关闭状态的判断规则 * @see net.sourceforge.nattable.edit.editor.AbstractCellEditor#isClosed() */ public boolean isClosed() { return close; } /** * 得到实际的光标位置(StyledText中的文本有一部分是已经被转换成内部标记的,与XML文本的分割位置有差异,因此需要此方法得到在XML中实际的分割位置) * @return ; */ public int getRealSplitOffset() { return viewer.getRealSplitOffset(); } /** * 得到实际的光标位置(StyledText中的文本有一部分是已经被转换成内部标记的,与XML文本的分割位置有差异,因此需要此方法得到在XML中实际的分割位置) * @return ; */ public int getRealSplitOffset(int offset) { return viewer.getRealSplitOffset(offset); } /** * 清除所有内部标记 ; */ public void clearTags() { if (isEditable()) { viewer.clearAllInnerTags(); } else { showUneditableMessage(); } } /** * 得到 SegmentViewer 组件。 * @return ; */ public ISegmentViewer getSegmentViewer() { return viewer; } public void widgetDisposed(DisposeEvent e) { this.close(); } /** * 得到选中的原始文本。 * @return XML 中的原始内容; */ public String getSelectedOriginalText() { return viewer.getSelectedOriginalText(); } /** * 得到选中的纯文本内容 * @return XML 中的原始内容; */ public String getSelectedPureText() { return viewer.getSelectedPureText(); } public Control activateCell(Composite parent, Object originalCanonicalValue, Character initialEditValue, IDisplayConverter displayConverter, IStyle cellStyle, IDataValidator dataValidator, ICellEditHandler editHandler, int colIndex, int rowIndex) { return null; } /** @return the columnPosition */ public int getColumnPosition() { return hsCellEditor.getColumnPosition(); } /** @return the rowPosition */ public int getRowPosition() { return hsCellEditor.getRowPosition(); } /** @return the columnIndex */ public int getColumnIndex() { return hsCellEditor.getColumnIndex(); } /** @return the rowIndex */ public int getRowIndex() { return hsCellEditor.getRowIndex(); } }
23,547
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
HsMultiActiveCellEditor.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/HsMultiActiveCellEditor.java
/** * HsMultiActiveCellEditor.java * * Version information : * * Date:2012-12-17 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.coordinate.PositionCoordinate; import net.sourceforge.nattable.layer.CompositeLayer; import net.sourceforge.nattable.layer.DataLayer; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.print.command.TurnViewportOffCommand; import net.sourceforge.nattable.print.command.TurnViewportOnCommand; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.SelectionLayer.MoveDirectionEnum; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Rectangle; /** * @author Jason * @version * @since JDK1.6 */ public class HsMultiActiveCellEditor { private static NatTable parent; private static HsMultiCellEditor sourceEditor; private static HsMultiCellEditor targetEditor; public static int sourceRowPosition = -1; public static int sourceRowIndex = -1; public static int targetRowPosition = -1; public static int targetRowIndex = -1; /** * @param cellEditors */ public static void activateCellEditors(HsMultiCellEditor srcCellEditor, HsMultiCellEditor tgtCellEditor, NatTable natTable) { parent = natTable; sourceEditor = srcCellEditor; sourceRowIndex = srcCellEditor.getRowIndex(); sourceRowPosition = srcCellEditor.getRowPosition(); targetEditor = tgtCellEditor; targetRowIndex = tgtCellEditor.getRowIndex(); targetRowPosition = tgtCellEditor.getRowPosition(); sourceEditor.activeCurrentEditor(natTable); targetEditor.activeCurrentEditor(natTable); SelectionLayer sLayer = LayerUtil.getLayer(natTable, SelectionLayer.class); PositionCoordinate p = sLayer.getLastSelectedCellPosition(); int colPosition = p.columnPosition; if (colPosition == targetEditor.getColumnIndex()) { targetEditor.forceFocus(); } else if (colPosition == sourceEditor.getColumnIndex()) { sourceEditor.forceFocus(); } } public static void commit(boolean closeEditorAfterCommit) { if (sourceEditor != null && sourceEditor.isValid()) { sourceEditor.getEditHandler().commit(MoveDirectionEnum.NONE, closeEditorAfterCommit); } if (targetEditor != null && targetEditor.isValid()) { targetEditor.getEditHandler().commit(MoveDirectionEnum.NONE, closeEditorAfterCommit); } if (closeEditorAfterCommit) { close(); } } private static void close() { parent = null; if (sourceEditor != null) { sourceEditor.close(); sourceEditor = null; } if (targetEditor != null) { targetEditor.close(); targetEditor = null; } sourceRowPosition = -1; sourceRowIndex = -1; targetRowPosition = -1; targetRowIndex = -1; } public static StyledTextCellEditor getFocusCellEditor() { if (sourceEditor != null && sourceEditor.isFocus() && sourceEditor.isValid()) { return sourceEditor.getCellEditor(); } else if (targetEditor != null && targetEditor.isFocus() && sourceEditor.isValid()) { return targetEditor.getCellEditor(); } return null; } public static void setCellEditorForceFocusByIndex(int colIndex, int rowIndex) { if (sourceEditor != null && sourceEditor.isValid() && sourceEditor.getColumnIndex() == colIndex && sourceEditor.getRowIndex() == rowIndex) { sourceEditor.forceFocus(); } else if (targetEditor != null && targetEditor.isValid() && targetEditor.getColumnIndex() == colIndex && targetEditor.getRowIndex() == rowIndex) { targetEditor.forceFocus(); } } public static void setCellEditorForceFocus(int colPosition, int rowPosition) { if (sourceEditor != null && sourceEditor.isValid() && sourceEditor.getColumnPosition() == colPosition && sourceEditor.getRowPosition() == rowPosition) { sourceEditor.forceFocus(); } else if (targetEditor != null && targetEditor.isValid() && targetEditor.getColumnPosition() == colPosition && targetEditor.getRowPosition() == rowPosition) { targetEditor.forceFocus(); } } public static void setSelectionText(StyledTextCellEditor editor, int start, int length) { if (editor != null && !editor.isClosed()) { StyledText text = editor.viewer.getTextWidget(); text.setSelection(start, start + length); } } public static void synchronizeRowHeight() { if (parent == null || sourceEditor == null || !sourceEditor.isValid() || targetEditor == null || !targetEditor.isValid()) { return; } if (sourceRowIndex != targetRowIndex) { // 垂直模式 StyledTextCellEditor focusCell = getFocusCellEditor(); if (sourceEditor.getCellEditor() == focusCell) { // edit source int srcHeight = sourceEditor.computeSize().y; int srcColPosition = sourceEditor.getColumnPosition(); int srcRowPosition = sourceEditor.getRowPosition(); int srcRowIndex = sourceEditor.getRowIndex(); Rectangle srcBounds = parent.getBoundsByPosition(srcColPosition, srcRowPosition); srcHeight += 3; if (srcBounds != null && srcBounds.height != srcHeight) { Rectangle srcEditorBounds = sourceEditor.getEditorBounds(); // int preSrcH = srcEditorBounds.height; srcEditorBounds.height = srcHeight; int cellStartY = srcBounds.y; int cellEndY = cellStartY + srcHeight; Rectangle tgtEditorBounds = targetEditor.getEditorBounds(); int srcAndTgtEndY = cellEndY + tgtEditorBounds.height; Rectangle clientArea = parent.getClientAreaProvider().getClientArea(); int clientAreaEndY = clientArea.y + clientArea.height; if (srcAndTgtEndY > clientAreaEndY) { srcEditorBounds.height = clientAreaEndY - tgtEditorBounds.height - cellStartY - 3; } CompositeLayer comlayer = LayerUtil.getLayer(parent, CompositeLayer.class); DataLayer dataLayer = LayerUtil.getLayer(parent, DataLayer.class); comlayer.doCommand(new TurnViewportOffCommand()); dataLayer.setRowHeightByPosition(dataLayer.getRowPositionByIndex(srcRowIndex), srcEditorBounds.height); comlayer.doCommand(new TurnViewportOnCommand()); // sourceEditor.setEditorBounds(srcEditorBounds, true); // tgtEditorBounds.y = tgtEditorBounds.y + (srcEditorBounds.height - preSrcH); // targetEditor.setEditorBounds(tgtEditorBounds, true); recalculateCellsBounds(); } } else { // edit target int tgtHeight = targetEditor.computeSize().y; int tgtColPosition = targetEditor.getColumnPosition(); int tgtRowPosition = targetEditor.getRowPosition(); int tgtRowIndex = targetEditor.getRowIndex(); Rectangle bounds = parent.getBoundsByPosition(tgtColPosition, tgtRowPosition); tgtHeight += 3; if (bounds != null && bounds.height != tgtHeight) { Rectangle tgtBounds = targetEditor.getEditorBounds(); tgtBounds.height = tgtHeight; int cellStartY = tgtBounds.y; int cellEndY = cellStartY + tgtBounds.height; Rectangle clientArea = parent.getClientAreaProvider().getClientArea(); int clientAreaEndY = clientArea.y + clientArea.height; if (cellEndY > clientAreaEndY) { tgtBounds.height = clientAreaEndY - cellStartY; } CompositeLayer comlayer = LayerUtil.getLayer(parent, CompositeLayer.class); DataLayer dataLayer = LayerUtil.getLayer(parent, DataLayer.class); comlayer.doCommand(new TurnViewportOffCommand()); dataLayer.setRowHeightByPosition(dataLayer.getRowPositionByIndex(tgtRowIndex), tgtBounds.height); comlayer.doCommand(new TurnViewportOnCommand()); // targetEditor.setEditorBounds(tgtBounds, true); recalculateCellsBounds(); } } } else { // 水平模式 int srcHeight = sourceEditor.computeSize().y; int tgtHeight = targetEditor.computeSize().y; int newHeight = srcHeight > tgtHeight ? srcHeight : tgtHeight; int colPosition = sourceEditor.getColumnPosition(); int rowPosition = sourceEditor.getRowPosition(); int rowIndex = sourceEditor.getRowIndex(); Rectangle bounds = parent.getBoundsByPosition(colPosition, rowPosition); newHeight += 3; if (bounds != null && bounds.height == newHeight) { return; } // 加上编辑模式下,StyledTextCellEditor的边框 Rectangle srcBounds = sourceEditor.getEditorBounds(); Rectangle tgtBounds = targetEditor.getEditorBounds(); srcBounds.height = newHeight; tgtBounds.height = newHeight; int cellStartY = srcBounds.y; int cellEndY = cellStartY + srcBounds.height; Rectangle clientArea = parent.getClientAreaProvider().getClientArea(); int clientAreaEndY = clientArea.y + clientArea.height; if (cellEndY > clientAreaEndY) { srcBounds.height = clientAreaEndY - cellStartY; tgtBounds.height = srcBounds.height; } CompositeLayer comlayer = LayerUtil.getLayer(parent, CompositeLayer.class); DataLayer dataLayer = LayerUtil.getLayer(parent, DataLayer.class); comlayer.doCommand(new TurnViewportOffCommand()); dataLayer.setRowHeightByPosition(dataLayer.getRowPositionByIndex(rowIndex), tgtBounds.height); comlayer.doCommand(new TurnViewportOnCommand()); // HorizontalViewportLayer viewLayer = LayerUtil.getLayer(parent, HorizontalViewportLayer.class); // int newRowPosition = viewLayer.getRowPositionByIndex(rowIndex) + 1; // if (newRowPosition != rowPosition) { // sourceEditor.setRowPosition(newRowPosition); // targetEditor.setRowPosition(newRowPosition); // Rectangle newSrcBounds = parent.getBoundsByPosition(colPosition, newRowPosition); // newSrcBounds.height = srcBounds.height; // Rectangle newTgtBounds = parent.getBoundsByPosition(targetEditor.getColumnIndex(), newRowPosition); // sourceEditor.setEditorBounds(newSrcBounds, true); // targetEditor.setEditorBounds(newTgtBounds, true); // } else { // sourceEditor.setEditorBounds(srcBounds, true); // targetEditor.setEditorBounds(tgtBounds, true); recalculateCellsBounds(); // } } } public static void recalculateCellsBounds() { if (parent == null) { return; } ViewportLayer vLayer = LayerUtil.getLayer(parent, ViewportLayer.class); if (vLayer == null) { return; } StyledTextCellEditor fc = getFocusCellEditor(); if (sourceEditor != null && sourceEditor.isValid()) { int rowPosition = vLayer.getRowPositionByIndex(sourceEditor.getRowIndex()); int columnPosition = vLayer.getColumnPositionByIndex(sourceEditor.getColumnIndex()); rowPosition += 1; if (rowPosition < 1) { return; } LayerCell cell = parent.getCellByPosition(columnPosition, rowPosition); if (cell == null) { return; } Rectangle cellBounds = cell.getBounds(); if (cellBounds != null) { Rectangle adjustedCellBounds = parent.getLayerPainter().adjustCellBounds(cellBounds); sourceEditor.setEditorBounds(adjustedCellBounds, true); sourceEditor.setColumnPosition(columnPosition); sourceEditor.setRowPosition(rowPosition); if(fc == sourceEditor.getCellEditor()){ sourceEditor.forceFocus(); } } } if (targetEditor != null && targetEditor.isValid()) { int rowPosition = vLayer.getRowPositionByIndex(targetEditor.getRowIndex()); int columnPosition = vLayer.getColumnPositionByIndex(targetEditor.getColumnIndex()); rowPosition += 1; if (rowPosition < 1) { return; } LayerCell cell = parent.getCellByPosition(columnPosition, rowPosition); if (cell == null) { return; } Rectangle cellBounds = cell.getBounds(); if (cellBounds != null) { Rectangle adjustedCellBounds = parent.getLayerPainter().adjustCellBounds(cellBounds); targetEditor.setEditorBounds(adjustedCellBounds, true); targetEditor.setColumnPosition(columnPosition); targetEditor.setRowPosition(rowPosition); if(fc == targetEditor.getCellEditor()){ targetEditor.forceFocus(); } } } } public static StyledTextCellEditor getTargetStyledEditor() { if (targetEditor != null && targetEditor.isValid()) { return targetEditor.getCellEditor(); } return null; } public static StyledTextCellEditor getSourceStyledEditor() { if (sourceEditor != null && sourceEditor.isValid()) { return sourceEditor.getCellEditor(); } return null; } public static void refrushCellsEditAbility() { StyledTextCellEditor editor = getTargetStyledEditor(); if (editor != null) { editor.getEditableManager().judgeEditable(); } editor = getSourceStyledEditor(); if (editor != null) { editor.getEditableManager().judgeEditable(); } } /** @return the sourceEditor */ public static HsMultiCellEditor getSourceEditor() { return sourceEditor; } /** @return the targetEditor */ public static HsMultiCellEditor getTargetEditor() { return targetEditor; } /** @return the parent */ public static NatTable getParent() { return parent; } }
13,407
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TagStyleManager.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/TagStyleManager.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import java.util.HashSet; import net.heartsome.cat.common.innertag.TagStyle; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * 标记样式管理器 * @author weachy * @version * @since JDK1.5 */ public class TagStyleManager { private TagStyle tagStyle; public TagStyleManager() { tagStyle = TagStyle.getDefault(); } public TagStyle getTagStyle() { return tagStyle; } public void setTagStyle(TagStyle tagStyle) { this.tagStyle = tagStyle; TagStyle.setTagStyle(tagStyle); Event event = new Event(); event.data = tagStyle; for (Listener listener : tagStyleChangeListeners) { listener.handleEvent(event); } } private HashSet<Listener> tagStyleChangeListeners = new HashSet<Listener>(); /** * 添加关闭单元格关闭时的监听器 * @param closeListener * 关闭监听器 ; */ public void addTagStyleChangeListener(Listener tagStyleChangeListener) { if (tagStyleChangeListener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } tagStyleChangeListeners.add(tagStyleChangeListener); } /** * 移除关闭单元格关闭时的监听器 * @param closeListener * 关闭监听器 ; */ public void removeTagStyleChangeListener(Listener tagStyleChangeListener) { for (Listener listener : tagStyleChangeListeners) { if (listener != null && listener.equals(tagStyleChangeListener)) { tagStyleChangeListeners.remove(listener); break; } } } }
1,568
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
HsMultiCellEditor.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/HsMultiCellEditor.java
/** * HsMultiCellEditor.java * * Version information : * * Date:2012-12-17 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import net.heartsome.cat.common.bean.ColorConfigBean; import net.heartsome.cat.common.innertag.factory.PlaceHolderEditModeBuilder; import net.heartsome.cat.ts.core.bean.SingleWord; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.bean.XliffEditorParameter; import net.sourceforge.nattable.data.convert.IDisplayConverter; import net.sourceforge.nattable.data.validate.IDataValidator; import net.sourceforge.nattable.edit.ICellEditHandler; import net.sourceforge.nattable.style.IStyle; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; /** * @author Jason * @version * @since JDK1.6 */ public class HsMultiCellEditor { /** * marked as source editor or target editor <br> * {@link NatTableConstant#SOURCE} */ private String type; private StyledTextCellEditor cellEditor; private Control activeCellEditorControl; private ICellEditHandler editHandler; private int columnPosition = -1; private int rowPosition = -1; private int columnIndex = -1; private int rowIndex = -1; private IDataValidator dataValidator; private Object originalCanonicalValue; // private IDisplayConverter displayConverter; private IStyle cellStyle; private Rectangle editorBounds; /** * @param type * @param cellEditor * @param activeCellEditorControl * @param editHandler * @param columnPosition * @param rowPosition * @param columnIndex * @param rowIndex * @param dataValidator * @param originalCanonicalValue * @param displayConverter * @param cellStyle * @param editorBounds */ public HsMultiCellEditor(String type, StyledTextCellEditor cellEditor, ICellEditHandler editHandler, int columnPosition, int rowPosition, int columnIndex, int rowIndex, IDataValidator dataValidator, Object originalCanonicalValue, IDisplayConverter displayConverter, IStyle cellStyle, Rectangle editorBounds) { this.type = type; this.cellEditor = cellEditor; this.editHandler = editHandler; this.columnPosition = columnPosition; this.rowPosition = rowPosition; this.columnIndex = columnIndex; this.rowIndex = rowIndex; this.dataValidator = dataValidator; this.originalCanonicalValue = originalCanonicalValue; // this.displayConverter = displayConverter; this.cellStyle = cellStyle; this.editorBounds = editorBounds; } public void activeCurrentEditor(Composite parent) { activeCellEditorControl = cellEditor.activateCell(parent, this); // if (activeCellEditorControl != null) { // activeCellEditorControl.setBounds(this.editorBounds); // } } public boolean isFocus() { if (activeCellEditorControl != null && !activeCellEditorControl.isDisposed()) return activeCellEditorControl.isFocusControl(); return false; } public void forceFocus() { if (activeCellEditorControl != null && !activeCellEditorControl.isDisposed()) { activeCellEditorControl.forceFocus(); } } public boolean isValid() { return cellEditor != null && !cellEditor.isClosed(); } public boolean validateCanonicalValue() { if (dataValidator != null) { return dataValidator.validate(columnIndex, rowIndex, getCanonicalValue()); } else { return true; } } public Object getCanonicalValue() { if (isValid()) { return cellEditor.getCanonicalValue(); } else { return null; } } public void close() { if (cellEditor != null && !cellEditor.isClosed()) { cellEditor.close(); } cellEditor = null; editHandler = null; dataValidator = null; if (activeCellEditorControl != null && !activeCellEditorControl.isDisposed()) { activeCellEditorControl.dispose(); } activeCellEditorControl = null; columnPosition = -1; rowPosition = -1; columnIndex = -1; rowIndex = -1; } public void highlightedTerms(List<String> terms) { if (!isValid()) { return; } StyledText styledText = cellEditor.viewer.getTextWidget(); String text = styledText.getText(); char[] source = text.toCharArray(); List<StyleRange> ranges = new ArrayList<StyleRange>(); TextStyle style = new TextStyle(cellEditor.getSegmentViewer().getTextWidget().getFont(), null, ColorConfigBean.getInstance().getHighlightedTermColor()); for (String term : terms) { if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) { term = term.replaceAll("\\n", Constants.LINE_SEPARATOR_CHARACTER + "\n"); term = term.replaceAll("\\t", Constants.TAB_CHARACTER + "\u200B"); term = term.replaceAll(" ", Constants.SPACE_CHARACTER + "\u200B"); } ranges.addAll(calculateTermsStyleRange(source, term.toCharArray(), style)); } for (StyleRange range : ranges) { styledText.setStyleRange(range); } } /** * 实时拼检查时高亮错误单词 robert 2013-01-21 * @param terms */ public void highLightedErrorWord(String tgtText, List<SingleWord> errorWordList) { if (!isValid()) { return; } List<StyleRange> ranges = new ArrayList<StyleRange>(); TextStyle style = new TextStyle(cellEditor.getSegmentViewer().getTextWidget().getFont(), null, null); for(SingleWord singleWord : errorWordList){ Matcher match = PlaceHolderEditModeBuilder.PATTERN.matcher(singleWord.getWord()); // 这里是处理一个单词中有一个或多个标记,从而导致标记绘画失败的BUG,如果其中有标记,那么这个 StyleRange 就应该被切断 boolean hasTag = false; int index = 0; while (match.find()) { StyleRange range = getErrorWordRange(style, singleWord.getStart() + index, match.start() - index); ranges.add(range); index = match.end(); hasTag = true; } if (hasTag) { if (index < singleWord.getLength()) { StyleRange range = getErrorWordRange(style, singleWord.getStart() + index, singleWord.getLength() - index); ranges.add(range); } }else { ranges.add(getErrorWordRange(style, singleWord.getStart(), singleWord.getLength())); } } refreshErrorWordsStyle(ranges); } /** * 刷新拼写检查中错误单词的样式 * @param ranges */ public void refreshErrorWordsStyle(List<StyleRange> ranges){ StyledText styledText = cellEditor.viewer.getTextWidget(); List<StyleRange> oldRangeList = new ArrayList<StyleRange>(); for(StyleRange oldRange : styledText.getStyleRanges()){ if (oldRange.underlineStyle != SWT.UNDERLINE_ERROR) { oldRangeList.add(oldRange); } } styledText.setStyleRange(null); styledText.setStyleRanges(oldRangeList.toArray(new StyleRange[oldRangeList.size()])); if (ranges != null) { for (StyleRange range : ranges) { styledText.setStyleRange(range); } } } /** * 根据传入的相关参数获取错误单词的样式 robert 2013-01-22 * @param style * @param start * @param length * @return */ private StyleRange getErrorWordRange(TextStyle style, int start, int length){ StyleRange range = new StyleRange(style); range.start = start; range.length = length; range.underline = true; range.underlineStyle = SWT.UNDERLINE_ERROR; range.underlineColor = ColorConfigBean.getInstance().getErrorWordColor(); return range; } /** @return the editorBounds */ public Rectangle getEditorBounds() { return editorBounds; } public Point computeSize(){ StyledText textControl = cellEditor.getSegmentViewer().getTextWidget(); Rectangle controlBounds = textControl.getBounds(); Point x = textControl.computeSize(controlBounds.width, SWT.DEFAULT, true); return x; } /** * Set the editor bounds * @param editorBounds * @param isApply * is apply now; */ public void setEditorBounds(Rectangle editorBounds, boolean isApply) { this.editorBounds = editorBounds; if (isApply && this.activeCellEditorControl != null && !this.activeCellEditorControl.isDisposed()) { this.activeCellEditorControl.setBounds(editorBounds); } } /** @return the type */ public String getType() { return type; } /** @return the cellEditor */ public StyledTextCellEditor getCellEditor() { return cellEditor; } /** @return the activeCellEditorControl */ public Control getActiveCellEditorControl() { return activeCellEditorControl; } /** @return the editHandler */ public ICellEditHandler getEditHandler() { return editHandler; } /** @return the columnPosition */ public int getColumnPosition() { return columnPosition; } /** @return the rowPosition */ public int getRowPosition() { return rowPosition; } /** @return the columnIndex */ public int getColumnIndex() { return columnIndex; } /** @return the rowIndex */ public int getRowIndex() { return rowIndex; } /** @return the cellStyle */ public IStyle getCellStyle() { return cellStyle; } /** @return the originalCanonicalValue */ public Object getOriginalCanonicalValue() { return originalCanonicalValue; } /** * @param columnPosition * the columnPosition to set */ public void setColumnPosition(int columnPosition) { this.columnPosition = columnPosition; } /** * @param rowPosition * the rowPosition to set */ public void setRowPosition(int rowPosition) { this.rowPosition = rowPosition; } private List<StyleRange> calculateTermsStyleRange(char[] source, char[] target, TextStyle style) { int sourceOffset = 0; int sourceCount = source.length; int targetOffset = 0, targetCount = target.length; char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); List<StyleRange> rangeList = new ArrayList<StyleRange>(); for (int i = sourceOffset; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first) ; } /* Found first character, now look at the rest of v2 */ if (i <= max) { List<StyleRange> tempList = new ArrayList<StyleRange>(); int start = i; int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end; j++, k++) { Matcher matcher = PlaceHolderEditModeBuilder.PATTERN.matcher(source[j] + ""); if (matcher.matches()) { StyleRange range = new StyleRange(style); range.start = start; range.length = j - start; start = j + 1; k--; end++; if (end > sourceCount) { break; } tempList.add(range); continue; } if (source[j] != target[k]) { break; } } if (j == end) { /* Found whole string. */ StyleRange range = new StyleRange(style); range.start = start; range.length = j - start; rangeList.addAll(tempList); rangeList.add(range); } } } return rangeList; } }
11,593
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NatTableConstant.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/NatTableConstant.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; public class NatTableConstant { /** 源文本的标识 */ public static String SOURCE = "source.value"; /** 目标文本的标识 */ public static String TARGET = "target.value"; /** 添加/编辑批注对话框中的下拉框显示内容 */ public static final String CURRENT_TEXT = Messages.getString("editor.NatTableConstant.CURRENT_TEXT"); /** 添加/编辑批注对话框中的下拉框显示内容 */ public static final String ALL_TEXT = Messages.getString("editor.NatTableConstant.ALL_TEXT"); }
652
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XLIFFEditorStatusLineItem.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/XLIFFEditorStatusLineItem.java
/** * XLIFFEditorStatusLineContributionItem.java * * Version information : * * Date:Mar 5, 2012 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.action.ContributionItem; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.LegacyActionTools; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; /** * @author Jason * @version * @since JDK1.6 */ public class XLIFFEditorStatusLineItem extends ContributionItem { private Label label; private String text = ""; private Image image; public Composite statusLine = null; public XLIFFEditorStatusLineItem(String id, String defaultMessage) { super(id); this.text = defaultMessage; } public void fill(Composite parent) { statusLine = parent; new Label(parent, SWT.SEPARATOR); Composite container = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(1, false); gl.marginWidth = 0; gl.marginHeight = 0; gl.marginTop = 0; gl.marginRight = 0; gl.marginBottom = 0; container.setLayout(gl); label = new Label(container, SWT.SHADOW_NONE); label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1)); label.setAlignment(SWT.CENTER); label.setText(text); if (image != null) { label.setImage(image); label.setToolTipText(text); } // Point preferredSize = label.computeSize(SWT.DEFAULT, SWT.DEFAULT); // int widthHint = preferredSize.x; // int heightHint = preferredSize.y; // if (widthHint < 0) { // // Compute the size base on 'charWidth' average char widths // GC gc = new GC(statusLine); // gc.setFont(statusLine.getFont()); // FontMetrics fm = gc.getFontMetrics(); // widthHint = fm.getAverageCharWidth() * 40; // heightHint = fm.getHeight(); // gc.dispose(); // } // StatusLineLayoutData data = new StatusLineLayoutData(); // data.widthHint = widthHint; // label.setLayoutData(data); // StatusLineLayoutData data = new StatusLineLayoutData(); // data.heightHint = heightHint; // speLb.setLayoutData(data); } public void setText(String text) { Assert.isNotNull(text); this.text = LegacyActionTools.escapeMnemonics(text); if (label != null && !label.isDisposed()) { label.setText(this.text); } if (this.text.length() == 0) { if (isVisible()) { setVisible(false); IContributionManager contributionManager = getParent(); if (contributionManager != null) { contributionManager.update(true); } } } else { if (!isVisible()) { setVisible(true); IContributionManager contributionManager = getParent(); if (contributionManager != null) { contributionManager.update(true); } } } } public void setText(String text, Image image) { Assert.isNotNull(image); Assert.isNotNull(text); this.text = LegacyActionTools.escapeMnemonics(text); this.image = image; if (label != null && !label.isDisposed()) { label.setText(this.text); label.setImage(this.image); } if (this.text.length() == 0) { if (isVisible()) { setVisible(false); IContributionManager contributionManager = getParent(); if (contributionManager != null) { contributionManager.update(true); } } } else { if (!isVisible()) { setVisible(true); IContributionManager contributionManager = getParent(); if (contributionManager != null) { contributionManager.update(true); } } } } @Override public void dispose() { if(image != null && !image.isDisposed()){ image.dispose(); } super.dispose(); } }
4,308
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TextPainterWithPadding.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/TextPainterWithPadding.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import static net.heartsome.cat.ts.ui.Constants.SEGMENT_LINE_SPACING; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.regex.Matcher; import net.heartsome.cat.common.bean.ColorConfigBean; import net.heartsome.cat.common.innertag.InnerTagBean; import net.heartsome.cat.common.innertag.factory.PlaceHolderEditModeBuilder; import net.heartsome.cat.common.innertag.factory.XliffInnerTagFactory; import net.heartsome.cat.common.ui.innertag.InnerTagRender; import net.heartsome.cat.common.ui.utils.InnerTagUtil; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.bean.XliffEditorParameter; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; import net.sourceforge.nattable.config.CellConfigAttributes; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.data.convert.IDisplayConverter; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.painter.cell.BackgroundPainter; import net.sourceforge.nattable.style.CellStyleAttributes; import net.sourceforge.nattable.style.CellStyleUtil; import net.sourceforge.nattable.style.IStyle; import net.sourceforge.nattable.util.GUIHelper; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.GlyphMetrics; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.widgets.Display; /** * 文本绘画器——用于绘制 NatTable 的单元格内容。 * @author weachy * @version * @since JDK1.5 */ public class TextPainterWithPadding extends BackgroundPainter { private final int topPadding; private final int rightPadding; private final int bottomPadding; private final int leftPadding; private final int tabSize = 4; private int tabWidth; private PlaceHolderEditModeBuilder placeHolderBuilder = new PlaceHolderEditModeBuilder(); private InnerTagRender tagRender; private static Map<String, Integer> temporaryMap = new WeakHashMap<String, Integer>(); private static Map<Font, FontData[]> fontDataCache = new WeakHashMap<Font, FontData[]>(); private final boolean wrapText; private XLIFFEditorImplWithNatTable editor; private XliffInnerTagFactory innerTagFactory = new XliffInnerTagFactory(placeHolderBuilder); private Font font; private int ascent, descent; public TextPainterWithPadding(XLIFFEditorImplWithNatTable editor) { this(true, 0, editor, null); } public TextPainterWithPadding(boolean wrapText, XLIFFEditorImplWithNatTable editor, Font font) { this(wrapText, 0, editor, font); } public TextPainterWithPadding(boolean wrapText, int padding, XLIFFEditorImplWithNatTable editor, Font font) { this(wrapText, padding, padding, padding, padding, editor, font); } public TextPainterWithPadding(boolean wrapText, int topPadding, int rightPadding, int bottomPadding, int leftPadding, final XLIFFEditorImplWithNatTable editor, Font font) { Assert.isNotNull(editor.getTable(), Messages.getString("editor.TextPainterWithPadding.msg1")); this.wrapText = wrapText; this.topPadding = topPadding; this.rightPadding = rightPadding; this.bottomPadding = bottomPadding; this.leftPadding = leftPadding; this.editor = editor; if (font == null) { font = JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.XLIFF_EDITOR_TEXT_FONT); } setFont(font); tagRender = new InnerTagRender(); } public int getPreferredHeight(LayerCell cell, GC gc, IConfigRegistry configRegistry) { if (innerTagFactory == null) { innerTagFactory = new XliffInnerTagFactory(placeHolderBuilder); } innerTagFactory.reset(); TextLayout layout = getCellTextLayout(cell); int counts = layout.getLineCount(); int contentHeight = 0; for (int i = 0; i < counts; i++) { contentHeight += layout.getLineBounds(i).height; } layout.dispose(); contentHeight += Math.max(counts - 1, 0) * SEGMENT_LINE_SPACING; contentHeight += 4;// 加上编辑模式下,StyledTextCellEditor的边框 contentHeight += topPadding; contentHeight += bottomPadding; return contentHeight; } /** * (non-Javadoc) * @see net.sourceforge.nattable.painter.cell.BackgroundPainter#paintCell(net.sourceforge.nattable.layer.cell.LayerCell, * org.eclipse.swt.graphics.GC, org.eclipse.swt.graphics.Rectangle, * net.sourceforge.nattable.config.IConfigRegistry) */ @Override public void paintCell(LayerCell cell, GC gc, Rectangle rectangle, IConfigRegistry configRegistry) { super.paintCell(cell, gc, rectangle, configRegistry); IStyle cellStyle = CellStyleUtil.getCellStyle(cell, configRegistry); setupGCFromConfig(gc, cellStyle); if (innerTagFactory == null) { innerTagFactory = new XliffInnerTagFactory(placeHolderBuilder); } innerTagFactory.reset(); int rowIndex = cell.getLayer().getRowIndexByPosition(cell.getRowPosition()); int columnIndex = cell.getLayer().getColumnIndexByPosition(cell.getColumnPosition()); if (!editor.isHorizontalLayout()) { // 垂直 if (rowIndex % 2 != 0) { LayerCell srcCell = cell.getLayer().getCellByPosition(cell.getColumnPosition(), cell.getRowPosition() - 1); if (srcCell != null) { String sourceVal = (String) srcCell.getDataValue(); innerTagFactory.parseInnerTag(sourceVal); } } } else { // 水平 if (columnIndex == editor.getTgtColumnIndex()) { LayerCell srcCell = cell.getLayer().getCellByPosition(1, cell.getRowPosition()); if (srcCell != null) { String sourceVal = (String) srcCell.getDataValue(); innerTagFactory.parseInnerTag(sourceVal); } } } TextLayout layout = getCellTextLayout(cell); int tempIndx = rowIndex; if (!editor.isHorizontalLayout()) { tempIndx = tempIndx / 2; } if (tempIndx == editor.getSelectedRows()[0] && (editor.isHorizontalLayout() ? columnIndex == editor.getSrcColumnIndex() : rowIndex % 2 == 0)) { List<String> terms = editor.getTermsCache().get(tempIndx); if (terms != null && terms.size() > 0) { List<StyleRange> ranges = new ArrayList<StyleRange>(); TextStyle style = new TextStyle(getFont(), null, ColorConfigBean.getInstance() .getHighlightedTermColor()); char[] source = layout.getText().toCharArray(); for (String term : terms) { if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) { term = term.replaceAll("\\n", Constants.LINE_SEPARATOR_CHARACTER + "\n"); term = term.replaceAll("\\t", Constants.TAB_CHARACTER + "\u200B"); term = term.replaceAll(" ", Constants.SPACE_CHARACTER + "\u200B"); } ranges.addAll(calculateTermsStyleRange(source, term.toCharArray(), style)); } for (StyleRange range : ranges) { layout.setStyle(range, range.start, range.start + range.length - 1); } } } try { String displayText = layout.getText(); Rectangle bounds = cell.getBounds(); if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) { appendNonprintingStyle(layout); } layout.draw(gc, bounds.x + leftPadding, bounds.y + topPadding); List<InnerTagBean> innerTagBeans = innerTagFactory.getInnerTagBeans(); for (InnerTagBean innerTagBean : innerTagBeans) { String placeHolder = placeHolderBuilder.getPlaceHolder(innerTagBeans, innerTagBeans.indexOf(innerTagBean)); int start = displayText.indexOf(placeHolder); if (start == -1) { continue; } Point p = layout.getLocation(start, false); int x = bounds.x + p.x + leftPadding; x += SEGMENT_LINE_SPACING; Point tagSize = tagRender.calculateTagSize(innerTagBean); int lineIdx = layout.getLineIndex(start); Rectangle r = layout.getLineBounds(lineIdx); int y = bounds.y + p.y + topPadding + r.height / 2 - tagSize.y / 2;// - // layout.getLineMetrics(0).getDescent(); // if (y + r.height > tagSize.y) { // FontMetrics fm = layout.getLineMetrics(lineIdx); // y = y + r.height - tagSize.y - fm.getDescent(); // } tagRender.draw(gc, innerTagBean, x, y); } } finally { layout.dispose(); } } @Override public int getPreferredWidth(LayerCell cell, GC gc, IConfigRegistry configRegistry) { setupGCFromConfig(gc, CellStyleUtil.getCellStyle(cell, configRegistry)); return leftPadding + getWidthFromCache(gc, convertDataType(cell, configRegistry)) + rightPadding; } public void setupGCFromConfig(GC gc, IStyle cellStyle) { Color fg = cellStyle.getAttributeValue(CellStyleAttributes.FOREGROUND_COLOR); Color bg = cellStyle.getAttributeValue(CellStyleAttributes.BACKGROUND_COLOR); gc.setAntialias(GUIHelper.DEFAULT_ANTIALIAS); gc.setTextAntialias(GUIHelper.DEFAULT_TEXT_ANTIALIAS); gc.setFont(font); gc.setForeground(fg != null ? fg : GUIHelper.COLOR_LIST_FOREGROUND); gc.setBackground(bg != null ? bg : GUIHelper.COLOR_LIST_BACKGROUND); } public Font getFont() { return font; } public void setFont(Font font) { TextLayout layout = new TextLayout(Display.getDefault()); try { if (font != null) { this.font = font; Font boldFont = getFont(SWT.BOLD), italicFont = getFont(SWT.ITALIC), boldItalicFont = getFont(SWT.BOLD | SWT.ITALIC); layout.setText(" "); layout.setFont(font); layout.setStyle(new TextStyle(font, null, null), 0, 0); layout.setStyle(new TextStyle(boldFont, null, null), 1, 1); layout.setStyle(new TextStyle(italicFont, null, null), 2, 2); layout.setStyle(new TextStyle(boldItalicFont, null, null), 3, 3); FontMetrics metrics = layout.getLineMetrics(0); ascent = metrics.getAscent() + metrics.getLeading(); descent = metrics.getDescent(); boldFont.dispose(); italicFont.dispose(); boldItalicFont.dispose(); boldFont = italicFont = boldItalicFont = null; } layout.dispose(); layout = new TextLayout(Display.getDefault()); layout.setFont(this.font); StringBuffer tabBuffer = new StringBuffer(tabSize); for (int i = 0; i < tabSize; i++) { tabBuffer.append(' '); } layout.setText(tabBuffer.toString()); tabWidth = layout.getBounds().width; layout.dispose(); } finally { if (layout != null && !layout.isDisposed()) { layout.dispose(); } } } /** * Convert the data value of the cell using the {@link IDisplayConverter} from the {@link IConfigRegistry} */ protected String convertDataType(LayerCell cell, IConfigRegistry configRegistry) { IDisplayConverter displayConverter = configRegistry.getConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, cell.getDisplayMode(), cell.getConfigLabels().getLabels()); if (displayConverter instanceof TagDisplayConverter) { ((TagDisplayConverter) displayConverter).setCell(cell); } String text = displayConverter != null ? (String) displayConverter.canonicalToDisplayValue(cell.getDataValue()) : null; return (text == null) ? "" : text; } private TextLayout getCellTextLayout(LayerCell cell) { int orientation = editor.getTable().getStyle() & (SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT); TextLayout layout = new TextLayout(editor.getTable().getDisplay()); layout.setOrientation(orientation); layout.setSpacing(Constants.SEGMENT_LINE_SPACING); layout.setFont(font); layout.setAscent(ascent); layout.setDescent(descent); // 和 StyledTextEditor 同步 layout.setTabs(new int[] { tabWidth }); Rectangle rectangle = cell.getBounds(); int width = rectangle.width - leftPadding - rightPadding; width -= 1; if (wrapText && width > 0) { layout.setWidth(width); } String displayText = InnerTagUtil.resolveTag(innerTagFactory.parseInnerTag((String) cell.getDataValue())); if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) { displayText = displayText.replaceAll("\\n", Constants.LINE_SEPARATOR_CHARACTER + "\n"); displayText = displayText.replaceAll("\\t", Constants.TAB_CHARACTER + "\u200B"); displayText = displayText.replaceAll(" ", Constants.SPACE_CHARACTER + "\u200B"); } layout.setText(displayText); List<InnerTagBean> innerTagBeans = innerTagFactory.getInnerTagBeans(); for (InnerTagBean innerTagBean : innerTagBeans) { String placeHolder = placeHolderBuilder.getPlaceHolder(innerTagBeans, innerTagBeans.indexOf(innerTagBean)); int start = displayText.indexOf(placeHolder); if (start == -1) { continue; } TextStyle style = new TextStyle(); Point rect = tagRender.calculateTagSize(innerTagBean); style.metrics = new GlyphMetrics(rect.y, 0, rect.x + SEGMENT_LINE_SPACING * 2); layout.setStyle(style, start, start + placeHolder.length() - 1); } return layout; } private void appendNonprintingStyle(TextLayout layout) { TextStyle style = new TextStyle(font, GUIHelper.getColor(new RGB(100, 100, 100)), null); String s = layout.getText(); Matcher matcher = Constants.NONPRINTING_PATTERN.matcher(s); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); // style.metrics = new GlyphMetrics(10, 0, 1); layout.setStyle(style, start, end - 1); } } private int getWidthFromCache(GC gc, String text) { String originalString = text; StringBuilder buffer = new StringBuilder(); buffer.append(text); if (gc.getFont() != null) { FontData[] datas = fontDataCache.get(gc.getFont()); if (datas == null) { datas = gc.getFont().getFontData(); fontDataCache.put(gc.getFont(), datas); } if (datas != null && datas.length > 0) { buffer.append(datas[0].getName()); buffer.append(","); buffer.append(datas[0].getHeight()); buffer.append(","); buffer.append(datas[0].getStyle()); } } text = buffer.toString(); Integer width = temporaryMap.get(text); if (width == null) { width = Integer.valueOf(gc.textExtent(originalString).x); temporaryMap.put(text, width); } return width.intValue(); } private Font getFont(int style) { Device device = Display.getDefault(); switch (style) { case SWT.BOLD: return new Font(device, getFontData(style)); case SWT.ITALIC: return new Font(device, getFontData(style)); case SWT.BOLD | SWT.ITALIC: return new Font(device, getFontData(style)); default: return font; } } private FontData[] getFontData(int style) { FontData[] fontDatas = font.getFontData(); for (int i = 0; i < fontDatas.length; i++) { fontDatas[i].setStyle(style); } return fontDatas; } private List<StyleRange> calculateTermsStyleRange(char[] source, char[] target, TextStyle style) { int sourceOffset = 0; int sourceCount = source.length; int targetOffset = 0, targetCount = target.length; char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); List<StyleRange> rangeList = new ArrayList<StyleRange>(); for (int i = sourceOffset; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first) ; } /* Found first character, now look at the rest of v2 */ if (i <= max) { List<StyleRange> tempList = new ArrayList<StyleRange>(); int start = i; int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end; j++, k++) { Matcher matcher = PlaceHolderEditModeBuilder.PATTERN.matcher(source[j] + ""); if (matcher.matches()) { StyleRange range = new StyleRange(style); range.start = start; range.length = j - start; start = j + 1; k--; end++; if (end > sourceCount) { break; } tempList.add(range); continue; } if (source[j] != target[k]) { break; } } if (j == end) { /* Found whole string. */ StyleRange range = new StyleRange(style); range.start = start; range.length = j - start; rangeList.addAll(tempList); rangeList.add(range); } } } return rangeList; } }
16,380
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
HsMultiCellEditorControl.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/HsMultiCellEditorControl.java
/** * HsMultiCellEditorControl.java * * Version information : * * Date:2012-12-14 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.ts.core.bean.SingleWord; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.qa.RealTimeSpellCheckTrigger; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.config.CellConfigAttributes; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.data.convert.IDisplayConverter; import net.sourceforge.nattable.data.validate.IDataValidator; import net.sourceforge.nattable.edit.EditConfigAttributes; import net.sourceforge.nattable.edit.ICellEditHandler; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.style.CellStyleProxy; import net.sourceforge.nattable.style.DisplayMode; import net.sourceforge.nattable.style.IStyle; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Rectangle; /** * @author Jason * @version * @since JDK1.6 */ public class HsMultiCellEditorControl { private static RealTimeSpellCheckTrigger spellTrigger; /** 当点以如下标点结尾时,触发实时拼写检查 robert */ private static final String ENDREGEX = "[ ,.;!?,。;!?]"; public static void activeSourceAndTargetCell(XLIFFEditorImplWithNatTable xliffEditor) { if (xliffEditor == null) { return; } int[] selectedRowIndexs = xliffEditor.getSelectedRows(); if (selectedRowIndexs.length == 0) { return; } Arrays.sort(selectedRowIndexs); int rowIndex = selectedRowIndexs[selectedRowIndexs.length - 1]; if (!xliffEditor.isHorizontalLayout()) { rowIndex = rowIndex * 2; // source index } NatTable natTable = xliffEditor.getTable(); IConfigRegistry configRegistry = natTable.getConfigRegistry(); ViewportLayer vLayer = LayerUtil.getLayer(natTable, ViewportLayer.class); int rowPosition = vLayer.getRowPositionByIndex(rowIndex); rowPosition += 1; if (rowPosition < 1) { return; } int columnIndex = xliffEditor.getSrcColumnIndex(); HsMultiCellEditor srcCellEditor = activeCell(vLayer, xliffEditor, configRegistry, columnIndex, rowIndex, rowPosition, NatTableConstant.SOURCE); if (srcCellEditor == null) { return; } if (!xliffEditor.isHorizontalLayout()) { rowIndex = rowIndex + 1; // target rowPosition = vLayer.getRowPositionByIndex(rowIndex); rowPosition += 1; if (rowPosition < 1) { return; } } columnIndex = xliffEditor.getTgtColumnIndex(); HsMultiCellEditor tgtCellEditor = activeCell(vLayer, xliffEditor, configRegistry, columnIndex, rowIndex, rowPosition, NatTableConstant.TARGET); if (tgtCellEditor == null) { return; } HsMultiActiveCellEditor.activateCellEditors(srcCellEditor, tgtCellEditor, natTable); // 目标文本段一进入焦点就进行一次拼写检查 robert 2013-01-22 // UNDO 这里错误单词提示并没有修改颜色。 String tgtLang = xliffEditor.getTgtColumnName(); spellTrigger = RealTimeSpellCheckTrigger.getInstance(); if (spellTrigger != null && spellTrigger.checkSpellAvailable(tgtLang)) { tgtTextFirstRealTimeSpellCheck(tgtLang, tgtCellEditor); tgtTextRealTimeSpellCheck(tgtLang, tgtCellEditor); } List<String> terms = xliffEditor.getTermsCache().get(selectedRowIndexs[0]); if (terms != null && terms.size() > 0) { srcCellEditor.highlightedTerms(terms); } } /** * 当一个文本段初次获取焦点时,实时进行拼写检查,<div style='color:red'>该方法与{@link tgtTextRealTimeSpellCheck} 类似</div> */ private static void tgtTextFirstRealTimeSpellCheck(final String tgtLang, HsMultiCellEditor targetEditor) { final StyledTextCellEditor tgtEditor = targetEditor.getCellEditor(); final StyledText text = tgtEditor.getSegmentViewer().getTextWidget(); if (tgtLang == null) { return; } String tgtText = text.getText(); if (tgtText == null || "".equals(tgtText.trim())) { return; } List<SingleWord> errorWordList = new LinkedList<SingleWord>(); errorWordList = spellTrigger.getErrorWords(tgtText, tgtLang); if (errorWordList != null && errorWordList.size() > 0) { targetEditor.highLightedErrorWord(tgtText, errorWordList); } else { targetEditor.refreshErrorWordsStyle(null); } } /** * 当文本处于正在编辑时,实时进行拼写检查,<div style='color:red'>该方法与{@link #tgtTextFirstRealTimeSpellCheck} 类似</div> */ private static void tgtTextRealTimeSpellCheck(final String tgtLang, final HsMultiCellEditor targetEditor) { final StyledTextCellEditor tgtEditor = targetEditor.getCellEditor(); final StyledText text = tgtEditor.getSegmentViewer().getTextWidget(); if (tgtLang == null) { return; } text.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String tgtText = text.getText(); if (tgtText.isEmpty()) { return; } String endStr = tgtText.substring(tgtText.length() - 1, tgtText.length()); if (endStr.matches(ENDREGEX)) { List<SingleWord> errorWordList = new LinkedList<SingleWord>(); errorWordList = spellTrigger.getErrorWords(tgtText, tgtLang); if (errorWordList != null && errorWordList.size() > 0) { targetEditor.highLightedErrorWord(tgtText, errorWordList); } else { targetEditor.refreshErrorWordsStyle(null); } } } }); } private static HsMultiCellEditor activeCell(ViewportLayer vLayer, XLIFFEditorImplWithNatTable xliffEditor, IConfigRegistry configRegistry, int columnIndex, int rowIndex, int rowPosition, String cellType) { NatTable natTable = xliffEditor.getTable(); int columnPosition = vLayer.getColumnPositionByIndex(columnIndex); LayerCell cell = natTable.getCellByPosition(columnPosition, rowPosition); if (cell == null) { return null; } Rectangle cellBounds = cell.getBounds(); List<String> configLabels = cell.getConfigLabels().getLabels(); if (!xliffEditor.isHorizontalLayout()) { if (cellType.equals(NatTableConstant.SOURCE)) { configLabels.remove(XLIFFEditorImplWithNatTable.TARGET_EDIT_CELL_LABEL); } else if (cellType.equals(NatTableConstant.TARGET)) { configLabels.remove(XLIFFEditorImplWithNatTable.SOURCE_EDIT_CELL_LABEL); } } ILayer layer = cell.getLayer(); Object originalCanonicalValue = cell.getDataValue(); IDisplayConverter displayConverter = configRegistry.getConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, DisplayMode.EDIT, configLabels); IStyle cellStyle = new CellStyleProxy(configRegistry, DisplayMode.EDIT, configLabels); IDataValidator dataValidator = configRegistry.getConfigAttribute(EditConfigAttributes.DATA_VALIDATOR, DisplayMode.EDIT, configLabels); Rectangle editorBounds = layer.getLayerPainter().adjustCellBounds( new Rectangle(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height)); int cellStartY = cellBounds.y; int cellEndY = cellStartY + cellBounds.height; Rectangle clientArea = natTable.getClientAreaProvider().getClientArea(); int clientAreaEndY = clientArea.y + clientArea.height; if (cellEndY > clientAreaEndY) { editorBounds.height = clientAreaEndY - cellStartY; } StyledTextCellEditor cellEditor = (StyledTextCellEditor) configRegistry.getConfigAttribute( EditConfigAttributes.CELL_EDITOR, DisplayMode.EDIT, configLabels); ICellEditHandler editHandler = new HsMultiCellEditorHandler(cellEditor, layer); HsMultiCellEditor hsCellEditor = new HsMultiCellEditor(cellType, cellEditor, editHandler, columnPosition, rowPosition, columnIndex, rowIndex, dataValidator, originalCanonicalValue, displayConverter, cellStyle, editorBounds); return hsCellEditor; } }
8,581
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XLIFFEditorActionHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/XLIFFEditorActionHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import net.heartsome.cat.common.ui.listener.PartAdapter2; import net.heartsome.cat.ts.ui.innertag.SegmentViewer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.MixUndoBean; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.dialog.FindReplaceDialog; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.ColumnSearchStrategy; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.DefaultCellSearchStrategy; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.IOperationHistory; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.commands.operations.OperationHistoryFactory; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.Event; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IPageListener; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.internal.ide.IDEWorkbenchMessages; import org.eclipse.ui.internal.ide.IIDEHelpContextIds; /** * Handles the redirection of the global actions Cut, Copy, Paste, Delete, Select All, Find, Undo and Redo to either the * current XLIFF editor or the part's supplied action handler. * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * <p> * Example usage: * * <pre> * actionHandler = new XLIFFEditorActionHandler(this.getEditorSite().getActionBars()); * actionHandler.addTextViewer(textCellEditor1); * actionHandler.setSelectAllAction(selectAllAction); * </pre> * * </p> * @noextend This class is not intended to be subclassed by clients. * @author weachy * @version * @since JDK1.5 * @see org.eclipse.ui.actions.TextActionHandler */ @SuppressWarnings("restriction") public class XLIFFEditorActionHandler { private CutActionHandler textCutAction = new CutActionHandler(); private CopyActionHandler textCopyAction = new CopyActionHandler(); private PasteActionHandler textPasteAction = new PasteActionHandler(); private DeleteActionHandler textDeleteAction = new DeleteActionHandler(); private SelectAllActionHandler textSelectAllAction = new SelectAllActionHandler(); private UndoActionHandler textUndoAction = new UndoActionHandler(); private RedoActionHandler textRedoAction = new RedoActionHandler(); private FindReplaceActionHandler textFindReplaceAction = new FindReplaceActionHandler(); private IActionBars actionBar; private MixUndoBean undoBean = new MixUndoBean(); /** * Creates a <code>StyledText</code> control action handler for the global Cut, Copy, Paste, Delete, and Select All * of the action bar. * @param actionBar * the action bar to register global action handlers for Cut, Copy, Paste, Delete, and Select All */ public XLIFFEditorActionHandler(IActionBars actionBar) { this.actionBar = actionBar; IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { final PartAdapter2 partListener2 = new PartAdapter2() { @Override public void partBroughtToTop(IWorkbenchPartReference partRef) { if ("net.heartsome.cat.ts.ui.xliffeditor.nattable.editor".equals(partRef.getId())) { XLIFFEditorActionHandler.this.actionBar.setGlobalActionHandler(ActionFactory.FIND.getId(), textFindReplaceAction); textFindReplaceAction.updateEnabledState(); XLIFFEditorActionHandler.this.actionBar.updateActionBars(); } } }; IWorkbenchPage page = window.getActivePage(); if (page != null) { page.addPartListener(partListener2); } else { window.addPageListener(new IPageListener() { public void pageOpened(IWorkbenchPage page) { page.addPartListener(partListener2); } public void pageClosed(IWorkbenchPage page) { page.addPartListener(partListener2); } public void pageActivated(IWorkbenchPage page) { } }); } } } private IAction deleteAction; private IAction cutAction; private IAction copyAction; private IAction pasteAction; private IAction selectAllAction; private IAction undoAction; private IAction redoAction; private IAction findReplaceAction; private IPropertyChangeListener cutActionListener = new PropertyChangeListener(textCutAction); private IPropertyChangeListener copyActionListener = new PropertyChangeListener(textCopyAction); private IPropertyChangeListener pasteActionListener = new PropertyChangeListener(textPasteAction); private IPropertyChangeListener deleteActionListener = new PropertyChangeListener(textDeleteAction); private IPropertyChangeListener selectAllActionListener = new PropertyChangeListener(textSelectAllAction); private IPropertyChangeListener undoActionListener = new PropertyChangeListener(textUndoAction); private IPropertyChangeListener redoActionListener = new PropertyChangeListener(textRedoAction); private IPropertyChangeListener findReplaceActionListener = new PropertyChangeListener(textFindReplaceAction); /** 封装StyledText,提供撤销/重做管理器的组件. */ private SegmentViewer viewer; private class PropertyChangeListener implements IPropertyChangeListener { private IAction actionHandler; protected PropertyChangeListener(IAction actionHandler) { super(); this.actionHandler = actionHandler; } public void propertyChange(PropertyChangeEvent event) { if (viewer != null) { return; } if (event.getProperty().equals(IAction.ENABLED)) { Boolean bool = (Boolean) event.getNewValue(); actionHandler.setEnabled(bool.booleanValue()); } } } private class CutActionHandler extends Action { protected CutActionHandler() { super(IDEWorkbenchMessages.Cut); setId("XLIFFEditorCutActionHandler");//$NON-NLS-1$ setEnabled(false); PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IIDEHelpContextIds.TEXT_CUT_ACTION); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { viewer.doOperation(ITextOperationTarget.CUT); updateActionsEnableState(); return; } if (cutAction != null) { cutAction.runWithEvent(event); return; } } /** * Update state. */ public void updateEnabledState() { if (viewer != null && !viewer.getTextWidget().isDisposed()) { setEnabled(viewer.canDoOperation(ITextOperationTarget.CUT)); return; } if (cutAction != null) { setEnabled(cutAction.isEnabled()); return; } setEnabled(false); } } /** * 撤销处理 * @author Leakey * @version * @since JDK1.6 */ private class UndoActionHandler extends Action { protected UndoActionHandler() { super("UNDO");//$NON-NLS-1$ setId("XLIFFEditorUndoActionHandler");//$NON-NLS-1$ setEnabled(true); } @Override public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); // 先保存在撤销,除非以后取消两种模式,否则不要删除此判断 if (viewer.canDoOperation(ITextOperationTarget.UNDO)) { HsMultiActiveCellEditor.commit(true); } IOperationHistory history = OperationHistoryFactory.getOperationHistory(); IUndoContext undoContext = (IUndoContext) xliffEditor.getTable().getData(IUndoContext.class.getName()); if (history.canUndo(undoContext)) { try { history.undo(undoContext, null, null); undoBean.setCrosseStep(undoBean.getCrosseStep() + 1); } catch (ExecutionException e) { e.printStackTrace(); } } XLIFFEditorImplWithNatTable.getCurrent().redraw(); updateActionsEnableState(); return; } if (undoAction != null) { undoAction.runWithEvent(event); return; } } } /** * 重做处理 * @author Leakey * @version * @since JDK1.6 */ private class RedoActionHandler extends Action { protected RedoActionHandler() { super("REDO");//$NON-NLS-1$ setId("XLIFFEditorRedoActionHandler");//$NON-NLS-1$ setEnabled(true); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { // 如果跨越焦点撤销,则先撤销非焦点 try { IOperationHistory history = OperationHistoryFactory.getOperationHistory(); IUndoContext undoContext = (IUndoContext) XLIFFEditorImplWithNatTable.getCurrent().getTable() .getData(IUndoContext.class.getName()); history.redo(undoContext, null, null); // int crossSegment = undoBean.getCrosseStep(); // if (crossSegment > 0) { // history.redo(undoContext, null, null); // undoBean.setCrosseStep(crossSegment - 1); // undoBean.setSaveStatus(-1); // } else if (undoBean.getSaveStatus() == -1) { // XLIFFEditorImplWithNatTable.getCurrent().jumpToRow(undoBean.getUnSaveRow()); // viewer.setText(undoBean.getUnSaveText()); // undoBean.setCrosseStep(0); // undoBean.setSaveStatus(0); // } else { // viewer.doOperation(ITextOperationTarget.REDO); // } } catch (ExecutionException e) { e.printStackTrace(); } System.out.println(undoBean.getCrosseStep()); updateActionsEnableState(); return; } if (redoAction != null) { redoAction.runWithEvent(event); return; } } } private class CopyActionHandler extends Action { protected CopyActionHandler() { super(IDEWorkbenchMessages.Copy); setId("XLIFFEditorCopyActionHandler");//$NON-NLS-1$ setEnabled(false); PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IIDEHelpContextIds.TEXT_COPY_ACTION); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { viewer.doOperation(ITextOperationTarget.COPY); updateActionsEnableState(); return; } if (copyAction != null) { copyAction.runWithEvent(event); return; } } /** * Update the state. */ public void updateEnabledState() { if (viewer != null && !viewer.getTextWidget().isDisposed()) { setEnabled(viewer.canDoOperation(ITextOperationTarget.COPY)); return; } if (copyAction != null) { setEnabled(copyAction.isEnabled()); return; } setEnabled(false); } } private class PasteActionHandler extends Action { protected PasteActionHandler() { super(IDEWorkbenchMessages.Paste); setId("XLIFFEditorPasteActionHandler");//$NON-NLS-1$ setEnabled(false); PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IIDEHelpContextIds.TEXT_PASTE_ACTION); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { viewer.doOperation(ITextOperationTarget.PASTE); updateActionsEnableState(); return; } } /** * Update the state */ public void updateEnabledState() { if (viewer != null && !viewer.getTextWidget().isDisposed()) { setEnabled(viewer.canDoOperation(ITextOperationTarget.PASTE)); return; } if (pasteAction != null) { setEnabled(pasteAction.isEnabled()); return; } setEnabled(false); } } private class DeleteActionHandler extends Action { protected DeleteActionHandler() { super(IDEWorkbenchMessages.Delete); setId("TextDeleteActionHandler");//$NON-NLS-1$ setEnabled(false); PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IIDEHelpContextIds.TEXT_DELETE_ACTION); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { StyledTextCellEditor editor = HsMultiActiveCellEditor.getFocusCellEditor(); boolean isSrc = false; if (editor != null && editor.getCellType().equals(NatTableConstant.SOURCE)) { isSrc = true; } StyledText styledText = viewer.getTextWidget(); String text = styledText.getText(); String selectionText = styledText.getSelectionText(); // 当选择源文时,要判断是否是删除所有源文 if (isSrc) { if (selectionText != null && text != null && text.equals(selectionText)) { MessageDialog.openInformation(viewer.getTextWidget().getShell(), Messages.getString("editor.XLIFFEditorActionHandler.msgTitle"), Messages.getString("editor.XLIFFEditorActionHandler.msg")); return; } } viewer.doOperation(ITextOperationTarget.DELETE); updateActionsEnableState(); return; } if (deleteAction != null) { deleteAction.runWithEvent(event); return; } } /** * Update state. */ public void updateEnabledState() { if (viewer != null && !viewer.getTextWidget().isDisposed()) { setEnabled(viewer.canDoOperation(ITextOperationTarget.DELETE)); return; } if (deleteAction != null) { setEnabled(deleteAction.isEnabled()); return; } setEnabled(false); } } private class SelectAllActionHandler extends Action { protected SelectAllActionHandler() { super(IDEWorkbenchMessages.TextAction_selectAll); setId("TextSelectAllActionHandler");//$NON-NLS-1$ setEnabled(false); PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IIDEHelpContextIds.TEXT_SELECT_ALL_ACTION); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { viewer.doOperation(ITextOperationTarget.SELECT_ALL); updateActionsEnableState(); return; } if (selectAllAction != null) { selectAllAction.runWithEvent(event); return; } } /** * Update the state. */ public void updateEnabledState() { if (viewer != null && !viewer.getTextWidget().isDisposed()) { setEnabled(viewer.canDoOperation(ITextOperationTarget.SELECT_ALL)); return; } if (selectAllAction != null) { setEnabled(selectAllAction.isEnabled()); return; } setEnabled(false); } } private class FindReplaceActionHandler extends Action { protected FindReplaceActionHandler() { super("FindReplace"); setId("TextFindReplaceActionHandler");//$NON-NLS-1$ setEnabled(false); } private FindReplaceDialog searchDialog; public void runWithEvent(Event event) { XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor != null) { String selectionText = editor.getSelectPureText(); if (searchDialog == null) { searchDialog = FindReplaceDialog.createDialog(editor.getEditorSite().getShell()); } NatTable natTable = editor.getTable(); int srcColumnIndex = editor.getSrcColumnIndex(); int[] columnPositions = { LayerUtil.getColumnPositionByIndex(natTable, srcColumnIndex) }; // 默认查询 source ColumnSearchStrategy searchStrategy = new ColumnSearchStrategy(columnPositions, editor); searchDialog.setSearchStrategy(searchStrategy, new DefaultCellSearchStrategy()); searchDialog.open(); // ICellEditor iCellEditor = ActiveCellEditor.getCellEditor(); // String selectionText = ""; // if (iCellEditor != null) { // if (iCellEditor instanceof StyledTextCellEditor) { // StyledTextCellEditor cellEditor = (StyledTextCellEditor) // iCellEditor; // StyledText styledText = // cellEditor.getSegmentViewer().getTextWidget(); // Point p = styledText.getSelection(); // if (p != null) { // if (p.x != p.y) { // // selectionText = cellEditor.getSelectedOriginalText(); // // 只获取纯文本,清除标记 // selectionText = cellEditor.getSelectedPureText(); // // 将换行符替换为空 // selectionText = selectionText.replaceAll("\n", ""); // } // } // } // // } searchDialog.setSearchText(selectionText != null ? selectionText : ""); updateEnabledState(); return; } if (findReplaceAction != null) { findReplaceAction.runWithEvent(event); return; } } /** * Update the state. */ public void updateEnabledState() { XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor != null) { setEnabled(true); return; } if (selectAllAction != null) { setEnabled(selectAllAction.isEnabled()); return; } setEnabled(false); } } /** * Add a <code>Text</code> control to the handler so that the Cut, Copy, Paste, Delete, Undo, Redo and Select All * actions are redirected to it when active. * @param viewer * the inline <code>Text</code> control */ public void addTextViewer(SegmentViewer viewer) { if (viewer == null) { return; } this.viewer = viewer; StyledText textControl = viewer.getTextWidget(); // 移除 StyledText 默认绑定的 Delete 键。解决“按下 Delete 键后会删除两次”的 Bug。 textControl.setKeyBinding(SWT.DEL, SWT.NULL); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateActionsEnableState(); } }); textControl.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateActionsEnableState(); } }); actionBar.setGlobalActionHandler(ActionFactory.CUT.getId(), textCutAction); actionBar.setGlobalActionHandler(ActionFactory.COPY.getId(), textCopyAction); actionBar.setGlobalActionHandler(ActionFactory.PASTE.getId(), textPasteAction); actionBar.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), textSelectAllAction); actionBar.setGlobalActionHandler(ActionFactory.DELETE.getId(), textDeleteAction); actionBar.setGlobalActionHandler(ActionFactory.UNDO.getId(), textUndoAction); actionBar.setGlobalActionHandler(ActionFactory.REDO.getId(), textRedoAction); if (textControl.isFocusControl()) { updateActionsEnableState(); } else { actionBar.updateActionBars(); } } public void updateGlobalActionHandler() { actionBar.setGlobalActionHandler(ActionFactory.CUT.getId(), textCutAction); actionBar.setGlobalActionHandler(ActionFactory.COPY.getId(), textCopyAction); actionBar.setGlobalActionHandler(ActionFactory.PASTE.getId(), textPasteAction); actionBar.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), textSelectAllAction); actionBar.setGlobalActionHandler(ActionFactory.DELETE.getId(), textDeleteAction); actionBar.setGlobalActionHandler(ActionFactory.UNDO.getId(), textUndoAction); actionBar.setGlobalActionHandler(ActionFactory.REDO.getId(), textRedoAction); if (viewer != null && viewer.getTextWidget().isFocusControl()) { updateActionsEnableState(); } else { actionBar.updateActionBars(); } } /** * Dispose of this action handler */ public void dispose() { setCutAction(null); setCopyAction(null); setPasteAction(null); setSelectAllAction(null); setDeleteAction(null); setUndoAction(null); } /** * Removes a <code>Text</code> control from the handler so that the Cut, Copy, Paste, Delete, and Select All actions * are no longer redirected to it when active. * @param textControl * the inline <code>Text</code> control */ public void removeTextViewer() { if (viewer == null) { return; } viewer = null; updateActionsEnableState(); } /** * Set the default <code>IAction</code> handler for the Copy action. This <code>IAction</code> is run only if no * active inline text control. * @param action * the <code>IAction</code> to run for the Copy action, or <code>null</code> if not interested. */ public void setCopyAction(IAction action) { if (copyAction == action) { return; } if (copyAction != null) { copyAction.removePropertyChangeListener(copyActionListener); } copyAction = action; if (copyAction != null) { copyAction.addPropertyChangeListener(copyActionListener); } textCopyAction.updateEnabledState(); } /** * Set the default <code>IAction</code> handler for the Cut action. This <code>IAction</code> is run only if no * active inline text control. * @param action * the <code>IAction</code> to run for the Cut action, or <code>null</code> if not interested. */ public void setCutAction(IAction action) { if (cutAction == action) { return; } if (cutAction != null) { cutAction.removePropertyChangeListener(cutActionListener); } cutAction = action; if (cutAction != null) { cutAction.addPropertyChangeListener(cutActionListener); } textCutAction.updateEnabledState(); } /** * Set the default <code>IAction</code> handler for the Undo action. This <code>IAction</code> is run only if no * active inline text control. * @param action * the <code>IAction</code> to run for the Undo action, or <code>null</code> if not interested. */ public void setUndoAction(IAction action) { if (undoAction == action) { return; } if (undoAction != null) { undoAction.removePropertyChangeListener(undoActionListener); } undoAction = action; if (undoAction != null) { undoAction.addPropertyChangeListener(undoActionListener); } } public void setRedoAction(IAction action) { if (redoAction == action) { return; } if (redoAction != null) { redoAction.removePropertyChangeListener(redoActionListener); } redoAction = action; if (redoAction != null) { redoAction.addPropertyChangeListener(redoActionListener); } } /** * Set the default <code>IAction</code> handler for the Paste action. This <code>IAction</code> is run only if no * active inline text control. * @param action * the <code>IAction</code> to run for the Paste action, or <code>null</code> if not interested. */ public void setPasteAction(IAction action) { if (pasteAction == action) { return; } if (pasteAction != null) { pasteAction.removePropertyChangeListener(pasteActionListener); } pasteAction = action; if (pasteAction != null) { pasteAction.addPropertyChangeListener(pasteActionListener); } textPasteAction.updateEnabledState(); } /** * Set the default <code>IAction</code> handler for the Select All action. This <code>IAction</code> is run only if * no active inline text control. * @param action * the <code>IAction</code> to run for the Select All action, or <code>null</code> if not interested. */ public void setSelectAllAction(IAction action) { if (selectAllAction == action) { return; } if (selectAllAction != null) { selectAllAction.removePropertyChangeListener(selectAllActionListener); } selectAllAction = action; if (selectAllAction != null) { selectAllAction.addPropertyChangeListener(selectAllActionListener); } textSelectAllAction.updateEnabledState(); } /** * Set the default <code>IAction</code> handler for the Delete action. This <code>IAction</code> is run only if no * active inline text control. * @param action * the <code>IAction</code> to run for the Delete action, or <code>null</code> if not interested. */ public void setDeleteAction(IAction action) { if (deleteAction == action) { return; } if (deleteAction != null) { deleteAction.removePropertyChangeListener(deleteActionListener); } deleteAction = action; if (deleteAction != null) { deleteAction.addPropertyChangeListener(deleteActionListener); } textDeleteAction.updateEnabledState(); } /** * Set the default <code>IAction</code> handler for the Find/Replcae action. This <code>IAction</code> is run only * if no active xliffeditor. * @param action * the <code>IAction</code> to run for the Find/Replcae action, or <code>null</code> if not interested. */ public void setFindReplaceAction(IAction action) { if (findReplaceAction == action) { return; } if (findReplaceAction != null) { findReplaceAction.removePropertyChangeListener(findReplaceActionListener); } findReplaceAction = action; if (findReplaceAction != null) { findReplaceAction.addPropertyChangeListener(findReplaceActionListener); } textFindReplaceAction.updateEnabledState(); } /** * Update the enable state of the Cut, Copy, Paste, Delete, Undo, Redo and Select All action handlers */ public void updateActionsEnableState() { textCutAction.updateEnabledState(); textCopyAction.updateEnabledState(); textPasteAction.updateEnabledState(); textSelectAllAction.updateEnabledState(); textDeleteAction.updateEnabledState(); actionBar.updateActionBars(); } }
25,208
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XLIFFEditorStatusLineItemWithProgressBar.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/XLIFFEditorStatusLineItemWithProgressBar.java
/** * XLIFFEditorStatusLineItemWithProgressBar.java * * Version information : * * Date:Mar 5, 2012 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.action.StatusLineLayoutData; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; /** * @author Jason * @version * @since JDK1.6 */ public class XLIFFEditorStatusLineItemWithProgressBar extends XLIFFEditorStatusLineItem { // private ProgressBar progressBar; private int progressValue; private Label label; // private String defaultMessage; public XLIFFEditorStatusLineItemWithProgressBar(String id, String defaultMessage) { super(id, defaultMessage); // this.defaultMessage = defaultMessage; } public void fill(Composite parent) { super.fill(parent); Composite container = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(1, false); gl.marginWidth = 0; gl.marginHeight = 0; gl.marginTop = 0; gl.marginRight = 0; gl.marginBottom = 0; container.setLayout(gl); // progressBar = new ProgressBar(container, SWT.SMOOTH); // GridData gdPprogressBar = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); // gdPprogressBar.heightHint = 16; // gdPprogressBar.widthHint = 130; // progressBar.setLayoutData(gdPprogressBar); // progressBar.setMinimum(0); // 最小值 // progressBar.setMaximum(100);// 最大值 // progressBar.setSelection(progressValue); // progressBar.setToolTipText(defaultMessage); GC gc = new GC(statusLine); int widthHint = gc.textExtent("100%").x; // int height = gc.textExtent("100%").y; gc.dispose(); label = new Label(container, SWT.NONE); GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1); gd.widthHint = widthHint; label.setLayoutData(gd); label.setText(progressValue + "%"); StatusLineLayoutData data = new StatusLineLayoutData(); container.setLayoutData(data); } public void setProgressValue(int value) { Assert.isLegal(value >= 0 && value <= 100); this.progressValue = value; if (label != null && !label.isDisposed()) { label.setText(value + "%"); // progressBar.setSelection(value); label.getParent().layout(); } } }
2,917
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Test.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/editor/Test.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.editor; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; public class Test extends Dialog { /** * Create the dialog. * @param parentShell */ public Test(Shell parentShell) { super(parentShell); } /** * Create contents of the dialog. * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); container.setLayout(new GridLayout(1, false)); Label lblThisIsA = new Label(container, SWT.NONE); lblThisIsA.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1)); lblThisIsA.setText("this is a test"); return container; } /** * Create contents of the button bar. * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return new Point(450, 300); } }
1,574
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XliffEditorGUIHelper.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/painter/XliffEditorGUIHelper.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.painter; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.ts.ui.xliffeditor.nattable.Activator; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; /** * 获取状态图片的工具类 * @author Leakey,weachy * @version * @since JDK1.5 */ public class XliffEditorGUIHelper { private static final String FILE_SEPARATER = System.getProperty("file.separator"); public enum ImageName { // APPROVE("approve"), DISAPPROVE("disapprove"), EDITNOTE("editnote"), REMOVENOTE("removenote"), FINAL("final"), // NEEDS_ADAPTATION( // "needs-adaptation"), NEEDS_L10N("needs-l10n"), NEEDS_REVIEW_ADAPTATION("needs-review-adaptation"), // NEEDS_REVIEW_L10N( // "needs-review-l10n"), NEEDS_REVIEW_TRANSLATION("needs-review-translation"), NEEDS_TRANSLATION( // "needs-translation"), NEW("new"), SIGNED_OFF("signed-off"), TRANSLATED("translated"), SPLITPOINT( // "splitPoint"); APPROVE("approved"), TRANSLATED("translated"), HAS_NOTE("note"), DONT_ADDDB("not-sent-db"), HAS_QUESTION( "questioning"), DRAFT("draft"), LOCKED("locked"),SINGED_OFF("sign-off"),SPLITPOINT("cut-point"),EMPTY("not-translated"); private final String value; private ImageName(String value) { this.value = value; } public static ImageName getItem(String value) { ImageName[] imageNames = values(); for (ImageName imageName : imageNames) { if (imageName.value.equals(value)) { return imageName; } } return null; } } /** 存放图片的路径数组. */ private static final String[] IMAGE_DIRS = new String[] { "images" + FILE_SEPARATER + "state"+FILE_SEPARATER }; /** 图片的后缀数组. */ private static final String[] IMAGE_EXTENSIONS = new String[] { ".png" }; /** 所有图片的Map. */ private static Map<ImageName, Image> images = new HashMap<ImageName, Image>(); /** * 得到图片 * @param ImageName * 图片名 * @return 图片; */ public static Image getImage(ImageName imageName) { return images.get(imageName); } /** * 根据给定的图片文件名(不带后缀)创建图片对象 * @param ImageName * 图片名 * @return 图片; */ private static Image createImage(ImageName imageName) { ImageDescriptor imageDescriptor = getImageDescriptor(imageName.value); if (imageDescriptor != null) { return imageDescriptor.createImage(); } return null; } /** * 得到图片描述符 * @param imageName * 图片名 * @return 图片描述符; */ private static ImageDescriptor getImageDescriptor(String imageName) { for (String dir : IMAGE_DIRS) { for (String ext : IMAGE_EXTENSIONS) { ImageDescriptor imageDescriptor = Activator.getImageDescriptor(dir + imageName + ext); if (imageDescriptor != null) { return imageDescriptor; } } } return null; } static { // 初始化 ImageName[] imageNames = ImageName.values(); for (ImageName imageName : imageNames) { images.put(imageName, createImage(imageName)); } } }
3,101
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
StatusPainter.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/painter/StatusPainter.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.painter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.ui.util.TmUtils; import net.heartsome.cat.ts.ui.xliffeditor.nattable.painter.XliffEditorGUIHelper.ImageName; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.data.IRowDataProvider; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.painter.cell.CellPainterWrapper; import net.sourceforge.nattable.style.CellStyleAttributes; import net.sourceforge.nattable.style.CellStyleUtil; import net.sourceforge.nattable.style.IStyle; import net.sourceforge.nattable.util.GUIHelper; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; /** * TU状态Painter * @author Leakey * @version * @since JDK1.5 */ public class StatusPainter extends CellPainterWrapper { /** 是否画背景. */ private final boolean paintBg; /** bodyDataProvider. */ private IRowDataProvider<TransUnitBean> bodyDataProvider; /** * @param bodyDataProvider * 数据提供者 */ public StatusPainter(IRowDataProvider<TransUnitBean> bodyDataProvider) { this.paintBg = true; this.bodyDataProvider = bodyDataProvider; } @Override public int getPreferredHeight(LayerCell cell, GC gc, IConfigRegistry configRegistry) { return 0; } /** * 重绘操作 */ @Override public void paintCell(LayerCell cell, GC gc, Rectangle bounds, IConfigRegistry configRegistry) { List<Map<Integer, Image>> images = getImages(cell, configRegistry); Rectangle cellBounds = cell.getBounds(); IStyle cellStyle = CellStyleUtil.getCellStyle(cell, configRegistry); if (paintBg) { Color originalBackground = gc.getBackground(); Color originalForeground = gc.getForeground(); Color backgroundColor = CellStyleUtil.getCellStyle(cell, configRegistry).getAttributeValue( CellStyleAttributes.BACKGROUND_COLOR); if (backgroundColor != null) { gc.setBackground(backgroundColor); gc.fillRectangle(bounds); } super.paintCell(cell, gc, bounds, configRegistry); if (machQuality != null) { Font oldFont = gc.getFont(); Font font = cellStyle.getAttributeValue(CellStyleAttributes.FONT); gc.setFont(font); if (cellBackground != null) { gc.setBackground(cellBackground); gc.setForeground(GUIHelper.COLOR_BLACK); } gc.drawText(machQuality, cellBounds.x + 15 + CellStyleUtil.getHorizontalAlignmentPadding(cellStyle, bounds, 15), bounds.y + CellStyleUtil.getVerticalAlignmentPadding(cellStyle, bounds, 15)); gc.setFont(oldFont); } gc.setForeground(originalForeground); gc.setBackground(originalBackground); cellBackground = null; } if (images != null) { int x = 0; for (Map<Integer, Image> imageMap : images) { Iterator<Integer> ps = imageMap.keySet().iterator(); if (ps.hasNext()) { int p = ps.next(); Image image = imageMap.get(p); if (image == null) { continue; } if (x == 0) { // 第一张图片的水平位置以cell的水平位置为准 x = cellBounds.x; } else { // 累加显示过图片的宽度以确定下一张图片的水平位置 x = cellBounds.x + 20; x += 16 * (p - 1); } // TODO 没有考虑对齐方式 if (p - 1 == 0) { // 第一张图片的水平位置要加上HorizontalAligmentPadding的宽度和VerticalAlignmentPadding的高度 gc.drawImage(image, x + CellStyleUtil.getHorizontalAlignmentPadding(cellStyle, bounds, 16), bounds.y + CellStyleUtil.getVerticalAlignmentPadding(cellStyle, bounds, 16)); } else { gc.drawImage(image, x, bounds.y + CellStyleUtil.getVerticalAlignmentPadding(cellStyle, bounds, 16)); } } } } } private Color cellBackground; private String machQuality; /** * 通过LayerCell得到行号确定所要得到的TU对象,通过TU对象的各种属性确定其状态图片 * @param cell * @param configRegistry * @return ; */ protected List<Map<Integer, Image>> getImages(LayerCell cell, IConfigRegistry configRegistry) { List<Map<Integer, Image>> images = new ArrayList<Map<Integer, Image>>(); int index = cell.getLayer().getRowIndexByPosition(cell.getRowPosition()); TransUnitBean tu = bodyDataProvider.getRowObject(index); String matchType = tu.getTgtProps().get("hs:matchType"); machQuality = tu.getTgtProps().get("hs:quality"); if (matchType != null && machQuality != null) { if (machQuality.endsWith("%")) { machQuality = machQuality.substring(0, machQuality.lastIndexOf("%")); } cellBackground = TmUtils.getMatchTypeColor(matchType, machQuality); } String approved = null; String translate = null; String state = null; String sendToTm = null; String needReview = null; int noteSize = 0; if (tu != null && tu.getTuProps() != null) { approved = tu.getTuProps().get("approved"); sendToTm = tu.getTuProps().get("hs:send-to-tm"); translate = tu.getTuProps().get("translate"); needReview = tu.getTuProps().get("hs:needs-review"); if (tu.getTgtProps() != null) { state = tu.getTgtProps().get("state"); } if (tu.getNotes() != null) { noteSize = tu.getNotes().size(); } } if (translate != null && "no".equals(translate)) { // 已锁定 addImage(images, XliffEditorGUIHelper.getImage(ImageName.LOCKED), 1); } else if (state != null && "signed-off".equals(state)) { // 已签发 addImage(images, XliffEditorGUIHelper.getImage(ImageName.SINGED_OFF), 1); } else if (approved != null && "yes".equals(approved)) { // 已批准 addImage(images, XliffEditorGUIHelper.getImage(ImageName.APPROVE), 1); } else if (state != null && "translated".equals(state)) { // 已翻译 addImage(images, XliffEditorGUIHelper.getImage(ImageName.TRANSLATED), 1); } else if (state != null && "new".equals(state)) { // 草稿 addImage(images, XliffEditorGUIHelper.getImage(ImageName.DRAFT), 1); } else { addImage(images, XliffEditorGUIHelper.getImage(ImageName.EMPTY), 1); } if (sendToTm != null && ("no").equals(sendToTm)) { addImage(images, XliffEditorGUIHelper.getImage(ImageName.DONT_ADDDB), 2); } if (needReview != null && "yes".equals(needReview)) { addImage(images, XliffEditorGUIHelper.getImage(ImageName.HAS_QUESTION), 3); } if (noteSize > 0) { addImage(images, XliffEditorGUIHelper.getImage(ImageName.HAS_NOTE), 4); } return images; } /** * 添加图片(过滤null的Image对象) * @param images * @param image */ private void addImage(List<Map<Integer, Image>> images, Image image, int position) { if (image != null) { Map<Integer, Image> tempMap = new HashMap<Integer, Image>(); tempMap.put(position, image); images.add(tempMap); } } }
7,028
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LineNumberPainter.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/painter/LineNumberPainter.java
/** * LineNumberPainter.java * * Version information : * * Date:Mar 1, 2012 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.painter; import java.util.List; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.painter.cell.TextPainter; import net.sourceforge.nattable.util.GUIHelper; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; /** * @author Jason * @version * @since JDK1.6 */ public class LineNumberPainter extends TextPainter { public LineNumberPainter() { super(true, false); } @Override public int getPreferredHeight(LayerCell cell, GC gc, IConfigRegistry configRegistry) { return 0; } public void paintCell(LayerCell cell, GC gc, Rectangle bounds, IConfigRegistry configRegistry) { Rectangle cellBounds = cell.getBounds(); // Color backgroundColor = CellStyleUtil.getCellStyle(cell, // configRegistry).getAttributeValue(CellStyleAttributes.BACKGROUND_COLOR); // if (backgroundColor != null) { Color originalBackground = gc.getBackground(); gc.setBackground(GUIHelper.COLOR_WIDGET_BACKGROUND); gc.fillRectangle(bounds); gc.setBackground(originalBackground); // } if (checkSplit(cell, configRegistry)) { // Color originalBackground = gc.getBackground(); // gc.setBackground(GUIHelper.COLOR_RED); // gc.fillRectangle(cellBounds); // gc.setBackground(originalBackground); // gc.setBackgroundPattern(new Pattern(Display.getCurrent(), // XliffEditorGUIHelper.getImage(XliffEditorGUIHelper.ImageName.SPLITPOINT))); Image image = XliffEditorGUIHelper.getImage(XliffEditorGUIHelper.ImageName.SPLITPOINT); gc.drawImage(image, cellBounds.width / 2 - image.getBounds().width / 2, cellBounds.y + cellBounds.height / 2 - image.getBounds().height / 2); // gc.setBackgroundPattern(null); // // } // else { } super.paintCell(cell, gc, bounds, configRegistry); } /** * 通过LayerCell得到行号确定所要得到的TU对象,通过TU对象的各种属性确定其状态图片 * @param cell * @param configRegistry * @return ; */ protected boolean checkSplit(LayerCell cell, IConfigRegistry configRegistry) { int index = cell.getLayer().getRowIndexByPosition(cell.getRowPosition()); // 添加分割点的图标,--robert XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor != null) { if (!editor.isHorizontalLayout()) { index = index / 2; } String rowId = editor.getXLFHandler().getRowId(index); List<String> splitPoints = editor.getSplitXliffPoints(); if (splitPoints.indexOf(rowId) != -1) { return true; } } return false; } }
3,443
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
RemoveAllTagsOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/RemoveAllTagsOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.HashMap; import java.util.List; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; public class RemoveAllTagsOperation extends AbstractOperation { private XLFHandler handler; private List<String> rowIds; private HashMap<String, String> map; private NatTable table; public RemoveAllTagsOperation(String label, NatTable table, XLFHandler handler, List<String> rowIds) { super(label); IUndoContext context = (IUndoContext) table.getData(IUndoContext.class.getName()); addContext(context); this.table = table; this.handler = handler; this.rowIds = rowIds; } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { map = handler.removeAllTags(rowIds); refreshNatTable(); return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { handler.resetRemoveAllTags(map); refreshNatTable(); return Status.OK_STATUS; } private void refreshNatTable() { if (XLIFFEditorImplWithNatTable.getCurrent() != null) { XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); xliffEditor.autoResize(); xliffEditor.refresh(); } } }
1,913
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
UpdateDataOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/UpdateDataOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import net.heartsome.cat.ts.ui.innertag.ISegmentViewer; import net.heartsome.cat.ts.ui.xliffeditor.nattable.UpdateDataBean; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.AutoResizeCurrentRowsCommand; import net.heartsome.cat.ts.ui.xliffeditor.nattable.handler.UpdateDataAndAutoResizeCommand; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.layer.DataLayer; import net.sourceforge.nattable.layer.event.CellVisualChangeEvent; import net.sourceforge.nattable.selection.command.SelectCellCommand; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; public class UpdateDataOperation extends AbstractOperation { private final Object oldValue; private final DataLayer dataLayer; private final UpdateDataAndAutoResizeCommand command; private final NatTable table; private final ViewportLayer viewportLayer; public UpdateDataOperation(NatTable table, UpdateDataAndAutoResizeCommand command) { this(table, LayerUtil.getLayer(table, DataLayer.class), command); } public UpdateDataOperation(NatTable table, DataLayer dataLayer, UpdateDataAndAutoResizeCommand command) { super("Typing"); IUndoContext undoContext = (IUndoContext) table.getData(IUndoContext.class.getName()); addContext(undoContext); Object currentValue = dataLayer.getDataProvider().getDataValue(command.getColumnPosition(), command.getRowPosition()); // Object currentValue = dataLayer.getDataValueByPosition(command2.getColumnPosition(), command2.getRowPosition()); oldValue = currentValue == null ? new UpdateDataBean() : new UpdateDataBean((String) currentValue, null, null); this.dataLayer = dataLayer; this.command = command; this.table = table; viewportLayer = LayerUtil.getLayer(table, ViewportLayer.class); } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { Object newValue = command.getNewValue() == null ? new UpdateDataBean() : command.getNewValue(); if (((UpdateDataBean) newValue).getText().equals(((UpdateDataBean) oldValue).getText())) { // 值相同,则取消操作 int currentRow = command.getRowPosition() + 1 /* 列头占一行 */; // 修改行在当前一屏显示的几行中的相对位置 table.doCommand(new AutoResizeCurrentRowsCommand(table, new int[] { currentRow }, table.getConfigRegistry())); return Status.CANCEL_STATUS; } return refreshNatTable(newValue, false); } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return refreshNatTable(command.getNewValue(), true); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return refreshNatTable(oldValue, true); } /** * 更新 NatTable 的 UI * @param value * 单元格保存的值 * @param move * 是否移动单元格到指定区域; */ private IStatus refreshNatTable(Object value, boolean move) { if (table == null || table.isDisposed()) { return Status.CANCEL_STATUS; } int rowIndex = command.getRowPosition(); int columnIndex = command.getColumnPosition(); int columnPosition = viewportLayer.getColumnPositionByIndex(columnIndex); int rowPosition = viewportLayer.getRowPositionByIndex(rowIndex); // 实质上 DataLayer 层的 index 和 position 是一致的,此方法可以对范围判断 if (rowIndex == -1 || columnIndex == -1) { return Status.CANCEL_STATUS; } // 修改值并刷新 UI。 dataLayer.getDataProvider().setDataValue(columnIndex, rowIndex, value); dataLayer.fireLayerEvent(new CellVisualChangeEvent(dataLayer, columnPosition, rowPosition)); int currentRow = rowPosition + 1 /* 列头占一行 */; // 修改行在当前一屏显示的几行中的相对位置 table.doCommand(new AutoResizeCurrentRowsCommand(table, new int[] { currentRow }, table.getConfigRegistry())); int selectedRow = XLIFFEditorImplWithNatTable.getCurrent().getSelectedRows()[0]; if (value instanceof UpdateDataBean & rowIndex == selectedRow) { UpdateDataBean bean = (UpdateDataBean) value; StyledTextCellEditor sourceCellEditor = HsMultiActiveCellEditor.getSourceStyledEditor(); StyledTextCellEditor targetCellEditor = HsMultiActiveCellEditor.getTargetStyledEditor(); if(sourceCellEditor != null && sourceCellEditor.getRowIndex() == rowIndex && sourceCellEditor.getColumnIndex() == columnIndex){ ISegmentViewer segviewer = sourceCellEditor.getSegmentViewer(); if (segviewer != null) { segviewer.setText(bean.getText()); } } else if (targetCellEditor != null && targetCellEditor.getRowIndex() == rowIndex && targetCellEditor.getColumnIndex() == columnIndex){ ISegmentViewer segviewer = targetCellEditor.getSegmentViewer(); if (segviewer != null) { segviewer.setText(bean.getText()); } } } // 先记录下可见区域的范围 int originRowPosition = viewportLayer.getOriginRowPosition(); int rowCount = viewportLayer.getRowCount(); // 总行数 int row = LayerUtil.convertRowPosition(dataLayer, rowPosition, viewportLayer); // 此操作会自动调整选中单元格进入可见区域 if (move) { // 定位到屏幕第三行的位置 if (rowPosition < originRowPosition || rowPosition > originRowPosition + rowCount) { HsMultiActiveCellEditor.commit(true); viewportLayer.doCommand(new SelectCellCommand(viewportLayer, columnPosition, row, false, false)); HsMultiCellEditorControl.activeSourceAndTargetCell(XLIFFEditorImplWithNatTable.getCurrent()); } else { XLIFFEditorImplWithNatTable.getCurrent().jumpToRow(rowIndex); } } return Status.OK_STATUS; } }
6,470
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NeedsReviewOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/NeedsReviewOperation.java
/** * HasQuestionOperation.java * * Version information : * * Date:Mar 1, 2012 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.file.XLFHandler; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; /** * @author Jason * @version * @since JDK1.6 */ public class NeedsReviewOperation extends AbstractOperation { private List<String> rowIdList; private NatTable table; private XLFHandler handler; private String state; private Map<String, String> oldState; public NeedsReviewOperation(String label, NatTable natTable, List<String> rowIdList, XLFHandler handler, String state) { super(label); IUndoContext context = (IUndoContext) natTable.getData(IUndoContext.class.getName()); addContext(context); this.table = natTable; this.rowIdList = rowIdList; this.handler = handler; this.state = state; this.oldState = handler.getTuPropValue(rowIdList, "hs:needs-review"); } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (rowIdList != null && rowIdList.size() > 0) { if("yes".equals(state)){ handler.changeTuPropValue(rowIdList, "hs:needs-review", state); }else{ handler.deleteTuProp(rowIdList, "hs:needs-review"); } table.redraw(); } return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (oldState != null && oldState.size() > 0) { handler.changeTuPropValue(oldState, "hs:needs-review"); table.redraw(); } return Status.OK_STATUS; } }
2,675
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MergeSegmentOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/MergeSegmentOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.HashMap; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.selection.command.SelectCellCommand; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; /** * 给合并文本段添加撤销与重做功能 * @author robert 2012-11-06 */ public class MergeSegmentOperation extends AbstractOperation { private XLIFFEditorImplWithNatTable xliffEditor; private XLFHandler handler; /** 要进行合并的所有文本段的 rowId 的集合 */ private List<String> rowIdList; private Map<String, String> oldSegFragMap; public MergeSegmentOperation(String label, XLIFFEditorImplWithNatTable xliffEditor, XLFHandler handler, List<String> rowIdList) { super(label); this.xliffEditor = xliffEditor; NatTable table = xliffEditor.getTable(); IUndoContext context = (IUndoContext) table.getData(IUndoContext.class.getName()); addContext(context); this.rowIdList = rowIdList; this.handler = handler; oldSegFragMap = new HashMap<String, String>(); } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { // 先获取合并前所有文本段的 content HsMultiActiveCellEditor.commit(true); for(String rowId : rowIdList){ oldSegFragMap.put(rowId, handler.getTUFragByRowId(rowId)); } for (int i = rowIdList.size() - 2; i >= 0; i--) { handler.mergeSegment(rowIdList.get(i), rowIdList.get(i + 1)); } // Bug #2373:选择全部文本段合并后,无显示内容 // xliffEditor.refresh(); // 合并文本段后自动调整大小 xliffEditor.autoResizeNotColumn(); xliffEditor.jumpToRow(rowIdList.get(0));//[13-04-24]:austen 定位 xliffEditor.refresh(); xliffEditor.updateStatusLine(); //[13-04-24]R8中无显示模式,合并文本段后定位不准猜测是由其引起的。故删除--> 见 readmine #2982 return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { handler.resetMergeSegment(oldSegFragMap); xliffEditor.autoResizeNotColumn(); return Status.OK_STATUS; } }
3,084
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
UpdateSegmentsOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/UpdateSegmentsOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.MessageDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UpdateSegmentsOperation extends AbstractOperation { /** 日志 */ Logger LOGGER = LoggerFactory.getLogger(UpdateSegmentsOperation.class); /** XLIFF 编辑器 */ private final XLIFFEditorImplWithNatTable xliffEditor; /** NatTable */ private final NatTable table; /** XLIFF 处理类 */ private final XLFHandler handler; /** 缓存的未修改前的文本段 */ private final Map<String, String> segmentCache; /** 做修改的行的 ID 集合 */ private final List<String> rowIds; /** Key:修改的行的 Id;value:新值 */ private Map<String, String> map; /** 新值 */ private String newValue; private String matchType; private String quality; /** 是否需要批准文本段 */ private final boolean approved; /** * 修改文本段的操作 * @param xliffEditor * XLIFF 编辑器 * @param handler * XLIFF 文件的处理类 * @param map * Key:修改的行的 Id;value:新值 * @param columnIndex * 列索引 * @param approved * 是否需要批准文本段 */ public UpdateSegmentsOperation(XLIFFEditorImplWithNatTable xliffEditor, XLFHandler handler, Map<String, String> map, int columnIndex, boolean approved, String matchType, String quality) { this(xliffEditor, handler, new ArrayList<String>(map.keySet()), columnIndex, approved, matchType, quality); this.map = map; } /** * 修改文本段的操作 * @param xliffEditor * XLIFF 编辑器 * @param handler * XLIFF 文件的处理类 * @param rowIds * 做修改的行的 ID 集合 * @param columnIndex * 列索引 * @param newValue * 新值 * @param approved * 是否需要批准文本段 */ public UpdateSegmentsOperation(XLIFFEditorImplWithNatTable xliffEditor, XLFHandler handler, List<String> rowIds, int columnIndex, String newValue, boolean approved, String matchType, String quality) { this(xliffEditor, handler, rowIds, columnIndex, approved, matchType, quality); this.newValue = newValue; } private UpdateSegmentsOperation(XLIFFEditorImplWithNatTable xliffEditor, XLFHandler handler, List<String> rowIds, int column, boolean approved, String matchType, String quality) { super("Update Segments"); this.xliffEditor = xliffEditor; this.table = xliffEditor.getTable(); IUndoContext undoContext = (IUndoContext) table.getData(IUndoContext.class.getName()); addContext(undoContext); // 绑定上下文 this.handler = handler; this.rowIds = rowIds; this.approved = approved; segmentCache = handler.getTuNodes(rowIds); // 缓存未修改前的文本段 this.matchType = matchType; this.quality = quality; } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { // updateCellEditor(); Assert.isNotNull(rowIds, Messages.getString("undoable.UpdateSegmentsOperation.msg1")); if (rowIds.size() == 0 || segmentCache == null || segmentCache.size() == 0) { return Status.CANCEL_STATUS; } if (newValue != null) { handler.changeTgtTextValue(rowIds, newValue, matchType, quality); } else if (map != null) { handler.changeTgtTextValue(map, matchType, quality); } else { return Status.CANCEL_STATUS; } if (approved) { // 批准文本段 List<String> rowids = handler.approveTransUnits(rowIds, true); if (rowids.size() > 0) { boolean res = MessageDialog.openQuestion(table.getShell(), null, MessageFormat.format( Messages.getString("undoable.UpdateSegmentsOperation.msg2"), rowIds.size())); if (res) { handler.approveTransUnits(rowIds, true, false); } } } int[] selectedRowIndexs = xliffEditor.getSelectedRows(); // 修改 if (!xliffEditor.isHorizontalLayout()) { int[] temp = new int[selectedRowIndexs.length * 2]; int j = 0; for (int i = 0; i < selectedRowIndexs.length; i++) { int sel = selectedRowIndexs[i] + 1; temp[j++] = sel * 2; temp[j++] = sel * 2 + 1; } // table.doCommand(new AutoResizeCurrentRowsCommand(table, temp, table.getConfigRegistry())); } else { int[] temp = new int[selectedRowIndexs.length]; int j = 0; for (int i = 0; i < selectedRowIndexs.length; i++) { int sel = selectedRowIndexs[i] + 1; temp[j++] = sel; } // table.doCommand(new AutoResizeCurrentRowsCommand(table, temp, table.getConfigRegistry())); // HsMultiActiveCellEditor.recalculateCellsBounds(); } table.redraw(); return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if(table == null || table.isDisposed()){ return Status.CANCEL_STATUS; } return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { Assert.isNotNull(segmentCache, Messages.getString("undoable.UpdateSegmentsOperation.msg3")); if(table == null || table.isDisposed()){ return Status.CANCEL_STATUS; } handler.resetTuNodes(segmentCache); // 重置为缓存的未修改前的文本段 xliffEditor.refresh(); return Status.OK_STATUS; } // 同步修改 Cell Editor 中的值,暂时保留 // /** // * 修改单元格编辑器中的文本。 // * @param newValue // * @return ; // */ // private boolean updateCellEditor() { // int rowIndex = ActiveCellEditor.getRowIndex(); // if (rowIndex == -1) { // return false; // } // ICellEditor cellEditor = ActiveCellEditor.getCellEditor(); // if (cellEditor == null) { // return false; // } // if (cellEditor instanceof StyledTextCellEditor) { // StyledTextCellEditor editor = (StyledTextCellEditor) cellEditor; // if (!editor.isClosed()) { // String rowId = handler.getRowId(rowIndex); // if (newValue != null && rowIds.contains(rowId)) { // editor.setCanonicalValue(newValue); // return true; // } else if (map != null) { // editor.setCanonicalValue(map.get(rowId)); // return true; // } // } // } // return false; // } }
6,949
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SplitSegmentOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/SplitSegmentOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.Arrays; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.ActiveCellRegion; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.event.RowSelectionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; public class SplitSegmentOperation extends AbstractOperation { private XLIFFEditorImplWithNatTable xliffEditor; private XLFHandler handler; private int offset; private String tuFragment; private int rowIndex; private String rowId; public SplitSegmentOperation(String label, XLIFFEditorImplWithNatTable xliffEditor, XLFHandler handler, int rowIndex, int offset) { super(label); this.xliffEditor = xliffEditor; IUndoContext context = (IUndoContext) xliffEditor.getTable().getData(IUndoContext.class.getName()); addContext(context); this.handler = handler; this.offset = offset; this.rowIndex = rowIndex; this.rowId = handler.getRowId(rowIndex); } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { tuFragment = handler.splitSegment(rowId, offset); refreshNatTable(); xliffEditor.jumpToRow(rowId + "-1"); xliffEditor.refresh(); return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { handler.resetSplitSegment(rowId, tuFragment); refreshNatTable(); xliffEditor.jumpToRow(rowId); xliffEditor.refresh(); return Status.OK_STATUS; } private void refreshNatTable() { SelectionLayer selectionLayer = LayerUtil.getLayer(xliffEditor.getTable(), SelectionLayer.class); int rowPosition = selectionLayer.getRowPositionByIndex(rowIndex); selectionLayer.fireLayerEvent(new RowSelectionEvent(selectionLayer, Arrays.asList(new Integer[] { rowPosition, rowPosition + 1 }))); xliffEditor.autoResizeNotColumn(); ActiveCellRegion.setActiveCellRegion(null); } }
2,644
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LockOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/LockOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.List; import net.heartsome.cat.ts.core.file.XLFHandler; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; public class LockOperation extends AbstractOperation { private List<String> rowIdList; private NatTable table; private XLFHandler handler; private boolean lock; /** * * @param label * @param natTable * @param rowIdList * @param handler * @param lock */ public LockOperation(String label, NatTable natTable, List<String> rowIdList, XLFHandler handler, boolean lock) { super(label); IUndoContext context = (IUndoContext) natTable.getData(IUndoContext.class.getName()); addContext(context); this.table = natTable; this.rowIdList = rowIdList; this.handler = handler; this.lock = lock; } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { changeTransUnitBeanProperties(this.lock); return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { changeTransUnitBeanProperties(!this.lock); return Status.OK_STATUS; } /** * 设置TU对象的属性以及Target的属性 * @param tu * @param tuProps * @param tgtProps * ; */ private void changeTransUnitBeanProperties(boolean lock) { if (rowIdList == null) { handler.lockAllTransUnits(lock); } else { handler.lockTransUnits(rowIdList, lock); } table.redraw(); } }
1,994
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SendTOTmOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/SendTOTmOperation.java
/** * SendTOTmOperation.java * * Version information : * * Date:Mar 1, 2012 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.file.XLFHandler; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; /** * @author Jason * @version * @since JDK1.6 */ public class SendTOTmOperation extends AbstractOperation { private List<String> rowIdList; private XLFHandler handler; private Map<String, String> oldState; private NatTable table; private String state; public SendTOTmOperation(String label, NatTable natTable, List<String> rowIdList, XLFHandler handler, String state) { super(label); IUndoContext context = (IUndoContext) natTable.getData(IUndoContext.class.getName()); addContext(context); this.table = natTable; this.rowIdList = rowIdList; this.handler = handler; this.state = state; this.oldState = handler.getTuPropValue(rowIdList, "hs:send-to-tm"); } /** * (non-Javadoc) * @see org.eclipse.core.commands.operations.AbstractOperation#execute(org.eclipse.core.runtime.IProgressMonitor, * org.eclipse.core.runtime.IAdaptable) */ @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (rowIdList != null && rowIdList.size() > 0) { if(state.equals("no")){ handler.changeTuPropValue(rowIdList, "hs:send-to-tm", state); }else{ handler.deleteTuProp(rowIdList, "hs:send-to-tm"); } table.redraw(); } return Status.OK_STATUS; } /** * (non-Javadoc) * @see org.eclipse.core.commands.operations.AbstractOperation#redo(org.eclipse.core.runtime.IProgressMonitor, * org.eclipse.core.runtime.IAdaptable) */ @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } /** * (non-Javadoc) * @see org.eclipse.core.commands.operations.AbstractOperation#undo(org.eclipse.core.runtime.IProgressMonitor, * org.eclipse.core.runtime.IAdaptable) */ @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (oldState != null && oldState.size() > 0) { handler.changeTuPropValue(oldState, "hs:send-to-tm"); table.redraw(); } return Status.OK_STATUS; } }
3,207
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DeleteAltTransOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/DeleteAltTransOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.viewers.StructuredSelection; public class DeleteAltTransOperation extends AbstractOperation { private final XLIFFEditorImplWithNatTable xliffEditor; private final XLFHandler handler; private final List<String> rowIds; private final Map<String, String> segmentCache; /** * “批准”操作 * @param natTable * NatTable对象 * @param rowIdList * RowId集合 * @param handler * XLFHandler对象 * @param approve * true:批准,false:取消批准 */ public DeleteAltTransOperation(XLIFFEditorImplWithNatTable xliffEditor, XLFHandler handler, List<String> rowIds) { super("Delete alt-trans"); IUndoContext context = (IUndoContext) xliffEditor.getTable().getData(IUndoContext.class.getName()); addContext(context); this.xliffEditor = xliffEditor; this.handler = handler; this.rowIds = rowIds; segmentCache = handler.getTuNodes(rowIds); } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { handler.deleteAltTrans(rowIds); refreshViews(); return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { handler.resetTuNodes(segmentCache); refreshViews(); return Status.OK_STATUS; } /** * 刷新其他视图。 ; */ private void refreshViews() { ArrayList<Integer> rowList = new ArrayList<Integer>(); int[] rows = xliffEditor.getSelectedRows(); for (int i : rows) { rowList.add(i); } StructuredSelection selection = new StructuredSelection(rowList); xliffEditor.getSite().getSelectionProvider().setSelection(selection); } }
2,463
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
StateOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/StateOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.file.XLFHandler; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; public class StateOperation extends AbstractOperation { private List<String> rowIdList; private NatTable table; private XLFHandler handler; private String state; private Map<String, String> oldState; /** * “修改状态“操作 * @param label * 操作名 * @param natTable * NatTable对象 * @param rowIdList * RowId集合 * @param handler * XLFHandler对象 * @param state * 状态值(Target节点的state属性的值) */ public StateOperation(String label, NatTable natTable, List<String> rowIdList, XLFHandler handler, String state) { super(label); IUndoContext context = (IUndoContext) natTable.getData(IUndoContext.class.getName()); addContext(context); this.table = natTable; this.rowIdList = rowIdList; this.handler = handler; this.state = state; this.oldState = handler.getTgtPropValue(rowIdList, "state"); } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (rowIdList != null && rowIdList.size() > 0) { handler.changeTgtPropValue(rowIdList, "state", state); if(state.equals("translated") || state.equals("new")){ //切换到已翻译或草稿状态 handler.deleteTuProp(rowIdList, "approved"); } if(state.equals("signed-off")){ handler.changeTuPropValue(rowIdList, "approved", "yes"); } table.redraw(); } return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (oldState != null && oldState.size() > 0) { handler.changeTgtPropValue(oldState, "state"); table.redraw(); } return Status.OK_STATUS; } }
2,403
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ApproveOperation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/undoable/ApproveOperation.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.undoable; import java.util.List; import net.heartsome.cat.ts.core.file.XLFHandler; import net.sourceforge.nattable.NatTable; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.MessageDialog; /** * 此类未使用,因此未做国际化 * @author peason * @version * @since JDK1.6 */ public class ApproveOperation extends AbstractOperation { private List<String> rowIdList; private NatTable table; private XLFHandler handler; private boolean approve; /** * “批准”操作 * @param label * 操作名,标识 * @param natTable * NatTable对象 * @param rowIdList * RowId集合 * @param handler * XLFHandler对象 * @param approve * true:批准,false:取消批准 */ public ApproveOperation(String label, NatTable natTable, List<String> rowIdList, XLFHandler handler, boolean approve) { super(label); IUndoContext context = (IUndoContext) natTable.getData(IUndoContext.class.getName()); addContext(context); this.table = natTable; this.rowIdList = rowIdList; this.handler = handler; this.approve = approve; } @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { changeTransUnitBeanProperties(this.approve); return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return execute(monitor, info); } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { changeTransUnitBeanProperties(!this.approve); return Status.OK_STATUS; } /** * 设置TU对象的属性以及Target的属性 * @param approve * true:批准,false:取消批准; */ private void changeTransUnitBeanProperties(boolean approve) { List<String> rowIds; if (rowIdList == null) { rowIds = handler.approveAllTransUnits(approve); } else { rowIds = handler.approveTransUnits(rowIdList, approve); } if (rowIds.size() > 0) { String message; if (rowIdList != null && rowIdList.size() == 1) { message = "当前翻译的长度不在允许范围内。是否仍要批准?"; } else { message = "有 " + rowIds.size() + " 个翻译的长度不在允许范围内。是否仍要批准?"; } boolean res = MessageDialog.openQuestion(table.getShell(), null, message); if (res) { handler.approveTransUnits(rowIds, approve, false); } } table.redraw(); } }
2,869
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
RowSelectionProvider.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/selection/RowSelectionProvider.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.selection; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.ActiveCellRegion; import net.sourceforge.nattable.layer.ILayerListener; import net.sourceforge.nattable.layer.event.ILayerEvent; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.command.SelectRowsCommand; import net.sourceforge.nattable.selection.event.ISelectionEvent; import net.sourceforge.nattable.util.ObjectUtils; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; public class RowSelectionProvider implements ISelectionProvider, ILayerListener { private SelectionLayer selectionLayer; private final boolean fullySelectedRowsOnly; private Set<ISelectionChangedListener> listeners = new HashSet<ISelectionChangedListener>(); public RowSelectionProvider(SelectionLayer selectionLayer) { this(selectionLayer, true); } public RowSelectionProvider(SelectionLayer selectionLayer, boolean fullySelectedRowsOnly) { this.selectionLayer = selectionLayer; this.fullySelectedRowsOnly = fullySelectedRowsOnly; selectionLayer.addLayerListener(this); } public void addSelectionChangedListener(ISelectionChangedListener listener) { listeners.add(listener); } public ISelection getSelection() { int[] rowPositions = selectionLayer.getFullySelectedRowPositions(); if (rowPositions.length > 0) { Arrays.sort(rowPositions); int rowPosition = rowPositions[rowPositions.length - 1]; int rowIndex = selectionLayer.getRowIndexByPosition(rowPosition); return new StructuredSelection(rowIndex); } return new StructuredSelection(); } public void removeSelectionChangedListener(ISelectionChangedListener listener) { listeners.remove(listener); } @SuppressWarnings("unchecked") public void setSelection(ISelection selection) { if (selectionLayer != null && selection instanceof IStructuredSelection) { selectionLayer.clear(); List<Integer> rowIndexs = ((IStructuredSelection) selection).toList(); Set<Integer> rowPositions = new HashSet<Integer>(); for (Integer rowIndex : rowIndexs) { int rowPosition = selectionLayer.getRowPositionByIndex(rowIndex); rowPositions.add(Integer.valueOf(rowPosition)); } selectionLayer.doCommand(new SelectRowsCommand(selectionLayer, 0, ObjectUtils.asIntArray(rowPositions), false, true)); } } private int currentRowPosition = -1; public void handleLayerEvent(ILayerEvent event) { if (event instanceof ISelectionEvent) { int[] rowPositions = selectionLayer.getFullySelectedRowPositions(); if (fullySelectedRowsOnly && rowPositions.length == 0) { ActiveCellRegion.setActiveCellRegion(null); return; } Arrays.sort(rowPositions); int rowPosition = rowPositions[rowPositions.length - 1]; if(rowPosition == currentRowPosition){ return; } currentRowPosition = rowPosition; int rowIndex = selectionLayer.getRowIndexByPosition(rowPosition); ISelection selection = new StructuredSelection(rowIndex); SelectionChangedEvent e = new SelectionChangedEvent(this, selection); for (ISelectionChangedListener listener : listeners) { listener.selectionChanged(e); } } } }
3,578
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
HorizontalRowSelectionModel.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/selection/HorizontalRowSelectionModel.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.selection; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import net.sourceforge.nattable.coordinate.Range; import net.sourceforge.nattable.selection.ISelectionModel; import net.sourceforge.nattable.selection.SelectionLayer; import org.eclipse.swt.graphics.Rectangle; /** * 水平布局下使用的选中行模型 * @author weachy * @version * @since JDK1.5 * @param <R> */ public class HorizontalRowSelectionModel implements ISelectionModel { private final SelectionLayer selectionLayer; private Rectangle lastSelectedRange; // *live* reference to last range parameter used in addSelection(range) private Set<Integer> selectedRows; // Key: rowId, Value: rowIndexes private Set<Integer> lastSelectedRowIds; private final ReadWriteLock selectionsLock; public ReadWriteLock getSelectionsLock() { return selectionsLock; } public HorizontalRowSelectionModel(SelectionLayer selectionLayer) { this.selectionLayer = selectionLayer; selectedRows = new HashSet<Integer>(); selectionsLock = new ReentrantReadWriteLock(); } public void clearSelection() { selectionsLock.writeLock().lock(); try { selectedRows.clear(); } finally { selectionsLock.writeLock().unlock(); } } public boolean isColumnPositionSelected(int columnPosition) { return !isEmpty(); } public int[] getSelectedColumns() { if (!isEmpty()) { selectionsLock.readLock().lock(); try { int columnCount = selectionLayer.getColumnCount(); int[] columns = new int[columnCount]; for (int i = 0; i < columnCount; i++) { columns[i] = i; } return columns; } finally { selectionsLock.readLock().unlock(); } } return new int[] {}; } public void addSelection(int columnPosition, int rowPosition) { selectionsLock.writeLock().lock(); try { // Serializable rowId = getRowIdByPosition(rowPosition); if (rowPosition != -1) { selectedRows.add(rowPosition); } } finally { selectionsLock.writeLock().unlock(); } } public void addSelection(Rectangle range) { selectionsLock.writeLock().lock(); try { if (range == lastSelectedRange) { // Unselect all previously selected rowIds if (lastSelectedRowIds != null) { for (Serializable rowId : lastSelectedRowIds) { selectedRows.remove(rowId); } } } int rowPosition = range.y; int length = range.height; int[] rowIndexs = new int[length]; Set<Integer> rowsToSelect = new HashSet<Integer>(); for (int i = 0; i < rowIndexs.length; i++) { rowsToSelect.add(rowPosition + i); } selectedRows.addAll(rowsToSelect); if (range == lastSelectedRange) { lastSelectedRowIds = rowsToSelect; } else { lastSelectedRowIds = null; } lastSelectedRange = range; } finally { selectionsLock.writeLock().unlock(); } } public int[] getFullySelectedColumns(int fullySelectedColumnRowCount) { selectionsLock.readLock().lock(); try { if (isColumnFullySelected(0, fullySelectedColumnRowCount)) { return getSelectedColumns(); } } finally { selectionsLock.readLock().unlock(); } return new int[] {}; } /** * 得到被整行选中的所有行 * @see net.sourceforge.nattable.selection.ISelectionModel#getFullySelectedRows(int) */ public int[] getFullySelectedRows(int rowWidth) { selectionsLock.readLock().lock(); try { int[] selectedRowPositions = new int[selectedRows.size()]; int i = 0; for (int selectedRow : selectedRows) { if (selectedRow > -1) { selectedRowPositions[i++] = selectedRow; } } return selectedRowPositions; } finally { selectionsLock.readLock().unlock(); } } /** * 得到选中行的个数 * @see net.sourceforge.nattable.selection.ISelectionModel#getSelectedRowCount() */ public int getSelectedRowCount() { selectionsLock.readLock().lock(); try { return selectedRows.size(); } finally { selectionsLock.readLock().unlock(); } } /** * 得到所有选中行 * @see net.sourceforge.nattable.selection.ISelectionModel#getSelectedRows() */ public Set<Range> getSelectedRows() { Set<Range> selectedRowRanges = new HashSet<Range>(); selectionsLock.readLock().lock(); try { for (int selectedRow : selectedRows) { if (selectedRow > -1) { selectedRowRanges.add(new Range(selectedRow, selectedRow + 1)); } } } finally { selectionsLock.readLock().unlock(); } return selectedRowRanges; } public List<Rectangle> getSelections() { List<Rectangle> selectionRectangles = new ArrayList<Rectangle>(); selectionsLock.readLock().lock(); try { int width = selectionLayer.getColumnCount(); for (int selectedRow : selectedRows) { if (selectedRow > -1) { selectionRectangles.add(new Rectangle(0, selectedRow, width, 1)); } } } finally { selectionsLock.readLock().unlock(); } return selectionRectangles; } public boolean isCellPositionSelected(int columnPosition, int rowPosition) { return isRowPositionSelected(rowPosition); } public boolean isColumnFullySelected(int columnPosition, int fullySelectedColumnRowCount) { selectionsLock.readLock().lock(); try { return selectedRows.size() == fullySelectedColumnRowCount; } finally { selectionsLock.readLock().unlock(); } } public boolean isEmpty() { selectionsLock.readLock().lock(); try { return selectedRows.isEmpty(); } finally { selectionsLock.readLock().unlock(); } } public boolean isRowFullySelected(int rowPosition, int rowWidth) { return isRowPositionSelected(rowPosition); } public boolean isRowPositionSelected(int rowPosition) { selectionsLock.readLock().lock(); try { return selectedRows.contains(rowPosition); } finally { selectionsLock.readLock().unlock(); } } public void removeSelection(Rectangle removedSelection) { selectionsLock.writeLock().lock(); try { for (int rowPosition = removedSelection.y; rowPosition < removedSelection.y + removedSelection.height; rowPosition++) { removeSelection(0, rowPosition); } } finally { selectionsLock.writeLock().unlock(); } } public void removeSelection(int columnPosition, int rowPosition) { selectionsLock.writeLock().lock(); try { selectedRows.remove(rowPosition); } finally { selectionsLock.writeLock().unlock(); } } }
6,541
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IRowIdAccessor.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/selection/IRowIdAccessor.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.selection; import java.io.Serializable; import java.util.ArrayList; import java.util.Set; /** * rowId存取器 * @author weachy * @version * @since JDK1.5 */ public interface IRowIdAccessor { /** * 获取指定行的RowId * @param rowPosition * 行的位置 * @return RowId; */ Serializable getRowIdByPosition(int rowPosition); /** * 获取指定范围的多行的RowId集合 * @param rowPosition * 起始行的位置 * @param length * 行个数 * @return RowId集合; */ Set<? extends Serializable> getRowIdsByPositionRange(int rowPosition, int length); /** * 得到当前所有显示行的RowId集合 * @return 当前所有显示行的RowId集合; */ ArrayList<? extends Serializable> getRowIds(); }
834
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
VerticalRowSelectionModel.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/selection/VerticalRowSelectionModel.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.selection; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.sourceforge.nattable.coordinate.Range; import net.sourceforge.nattable.selection.ISelectionModel; import net.sourceforge.nattable.selection.SelectionLayer; import org.eclipse.swt.graphics.Rectangle; /** * 垂直布局下使用的选中行模型 * @author weachy * @version * @since JDK1.5 * @param <R> */ public class VerticalRowSelectionModel<R> implements ISelectionModel { private final SelectionLayer selectionLayer; private final IRowIdAccessor rowIdAccessor; private Rectangle lastSelectedRange; // *live* reference to last range parameter used in addSelection(range) private Set<Serializable> selectedRows; // Key: rowId, Value: rowIndexes private Set<? extends Serializable> lastSelectedRowIds; private final ReadWriteLock selectionsLock; public ReadWriteLock getSelectionsLock() { return selectionsLock; } public VerticalRowSelectionModel(SelectionLayer selectionLayer, IRowIdAccessor rowIdAccessor) { this.selectionLayer = selectionLayer; this.rowIdAccessor = rowIdAccessor; selectedRows = new HashSet<Serializable>(); selectionsLock = new ReentrantReadWriteLock(); } public void clearSelection() { selectionsLock.writeLock().lock(); try { selectedRows.clear(); } finally { selectionsLock.writeLock().unlock(); } } public boolean isColumnPositionSelected(int columnPosition) { return !isEmpty(); } public int[] getSelectedColumns() { if (!isEmpty()) { selectionsLock.readLock().lock(); try { int columnCount = selectionLayer.getColumnCount(); int[] columns = new int[columnCount]; for (int i = 0; i < columnCount; i++) { columns[i] = i; } return columns; } finally { selectionsLock.readLock().unlock(); } } return new int[] {}; } public void addSelection(int columnPosition, int rowPosition) { selectionsLock.writeLock().lock(); try { Serializable rowId = getRowIdByPosition(rowPosition); if (rowId != null) { selectedRows.add(rowId); } } finally { selectionsLock.writeLock().unlock(); } } @SuppressWarnings("unchecked") public void addSelection(Rectangle range) { selectionsLock.writeLock().lock(); try { if (range == lastSelectedRange) { // Unselect all previously selected rowIds if (lastSelectedRowIds != null) { for (Serializable rowId : lastSelectedRowIds) { selectedRows.remove(rowId); } } } int rowPosition = range.y / VerticalNatTableConfig.ROW_SPAN; int end = (int) Math.ceil((range.y + range.height) * 1.0 / VerticalNatTableConfig.ROW_SPAN); int length = end - range.y / VerticalNatTableConfig.ROW_SPAN; Set<Serializable> rowsToSelect = (Set<Serializable>) rowIdAccessor.getRowIdsByPositionRange(rowPosition, length); selectedRows.addAll(rowsToSelect); if (range == lastSelectedRange) { lastSelectedRowIds = rowsToSelect; } else { lastSelectedRowIds = null; } lastSelectedRange = range; } finally { selectionsLock.writeLock().unlock(); } } public int[] getFullySelectedColumns(int fullySelectedColumnRowCount) { selectionsLock.readLock().lock(); try { if (isColumnFullySelected(0, fullySelectedColumnRowCount)) { return getSelectedColumns(); } } finally { selectionsLock.readLock().unlock(); } return new int[] {}; } /** * 得到被整行选中的所有行 * @see net.sourceforge.nattable.selection.ISelectionModel#getFullySelectedRows(int) */ public int[] getFullySelectedRows(int rowWidth) { selectionsLock.readLock().lock(); try { int[] selectedRowPositions = new int[selectedRows.size()]; int i = 0; for (Serializable selectedRow : selectedRows) { int rowPosition = rowIdAccessor.getRowIds().indexOf(selectedRow); if (rowPosition > -1) { selectedRowPositions[i++] = rowPosition; } } return selectedRowPositions; } finally { selectionsLock.readLock().unlock(); } } /** * 得到选中行的个数 * @see net.sourceforge.nattable.selection.ISelectionModel#getSelectedRowCount() */ public int getSelectedRowCount() { selectionsLock.readLock().lock(); try { return selectedRows.size() * VerticalNatTableConfig.ROW_SPAN; } finally { selectionsLock.readLock().unlock(); } } /** * 得到所有选中行 * @see net.sourceforge.nattable.selection.ISelectionModel#getSelectedRows() */ public Set<Range> getSelectedRows() { Set<Range> selectedRowRanges = new HashSet<Range>(); selectionsLock.readLock().lock(); try { for (Serializable selectedRow : selectedRows) { int rowPosition = rowIdAccessor.getRowIds().indexOf(selectedRow) * VerticalNatTableConfig.ROW_SPAN; if (rowPosition > -1) { for (int j = rowPosition; j < VerticalNatTableConfig.ROW_SPAN; j++) { selectedRowRanges.add(new Range(rowPosition, rowPosition + 1)); } } } } finally { selectionsLock.readLock().unlock(); } return selectedRowRanges; } public List<Rectangle> getSelections() { List<Rectangle> selectionRectangles = new ArrayList<Rectangle>(); selectionsLock.readLock().lock(); try { int width = selectionLayer.getColumnCount(); for (Serializable selectedRow : selectedRows) { int rowPosition = rowIdAccessor.getRowIds().indexOf(selectedRow) * VerticalNatTableConfig.ROW_SPAN; if (rowPosition > -1) { for (int j = rowPosition; j < VerticalNatTableConfig.ROW_SPAN; j++) { selectionRectangles.add(new Rectangle(0, rowPosition, width, 1)); } } } } finally { selectionsLock.readLock().unlock(); } return selectionRectangles; } public boolean isCellPositionSelected(int columnPosition, int rowPosition) { return isRowPositionSelected(rowPosition); } public boolean isColumnFullySelected(int columnPosition, int fullySelectedColumnRowCount) { selectionsLock.readLock().lock(); try { return selectedRows.size() == fullySelectedColumnRowCount; } finally { selectionsLock.readLock().unlock(); } } public boolean isEmpty() { selectionsLock.readLock().lock(); try { return selectedRows.isEmpty(); } finally { selectionsLock.readLock().unlock(); } } public boolean isRowFullySelected(int rowPosition, int rowWidth) { return isRowPositionSelected(rowPosition); } public boolean isRowPositionSelected(int rowPosition) { selectionsLock.readLock().lock(); try { Serializable rowId = getRowIdByPosition(rowPosition); return selectedRows.contains(rowId); } finally { selectionsLock.readLock().unlock(); } } public void removeSelection(Rectangle removedSelection) { selectionsLock.writeLock().lock(); try { for (int rowPosition = removedSelection.y; rowPosition < removedSelection.y + removedSelection.height; rowPosition++) { removeSelection(0, rowPosition); } } finally { selectionsLock.writeLock().unlock(); } } public void removeSelection(int columnPosition, int rowPosition) { selectionsLock.writeLock().lock(); try { Serializable rowId = getRowIdByPosition(rowPosition); selectedRows.remove(rowId); } finally { selectionsLock.writeLock().unlock(); } } /** * 通过行的位置得到行对应的翻译单元的Id * @param rowPosition * 行的相对位置,从0开始 * @return 行对应的翻译单元的Id; */ private Serializable getRowIdByPosition(int rowPosition) { return rowIdAccessor.getRowIdByPosition(rowPosition / VerticalNatTableConfig.ROW_SPAN); } }
7,822
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
KeyEditAction.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/actions/KeyEditAction.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.actions; import java.util.Arrays; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.NatTableConstant; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.coordinate.PositionCoordinate; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.command.SelectCellCommand; import net.sourceforge.nattable.ui.action.IKeyAction; import net.sourceforge.nattable.ui.matcher.LetterOrDigitKeyEventMatcher; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; /** * 按下字母键、数字键、F2,触发单元格进入编辑模式 * @author weachy * @version * @since JDK1.5 */ public class KeyEditAction implements IKeyAction { public void run(NatTable natTable, KeyEvent event) { Character character = null; if (LetterOrDigitKeyEventMatcher.isLetterOrDigit(event.character) || event.character == ' ') { character = Character.valueOf(event.character); } if (character != null) { int[] selectedRowIndexs = XLIFFEditorImplWithNatTable.getCurrent().getSelectedRows(); if (selectedRowIndexs.length == 0) { return; } Arrays.sort(selectedRowIndexs); int rowIndex = selectedRowIndexs[selectedRowIndexs.length - 1]; ViewportLayer viewportLayer = LayerUtil.getLayer(natTable, ViewportLayer.class); SelectionLayer selectionLayer = LayerUtil.getLayer(natTable, SelectionLayer.class); // 先记录下可见区域的范围 int originRowPosition = viewportLayer.getOriginRowPosition(); int rowCount = viewportLayer.getRowCount(); // 总行数 XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (!editor.isHorizontalLayout()) { rowIndex = rowIndex * 2; } if (rowIndex < originRowPosition || rowIndex > originRowPosition + rowCount || HsMultiActiveCellEditor.getTargetEditor() == null) { HsMultiActiveCellEditor.commit(true); PositionCoordinate p = selectionLayer.getLastSelectedCellPosition(); if (!editor.isHorizontalLayout()) { natTable.doCommand(new SelectCellCommand(selectionLayer, editor.getTgtColumnIndex(), p.rowPosition / 2 * 2, false, false)); } else { if (p.columnPosition != editor.getSrcColumnIndex() && p.columnPosition != editor.getTgtColumnIndex()) { p.columnPosition = editor.getTgtColumnIndex(); } natTable.doCommand(new SelectCellCommand(selectionLayer, p.columnPosition, p.rowPosition, false, false)); } HsMultiCellEditorControl.activeSourceAndTargetCell(editor); StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getFocusCellEditor(); if (cellEditor != null && cellEditor.getCellType().equals(NatTableConstant.TARGET)) { cellEditor.insertCanonicalValue(character); } } } else if ((event.character == SWT.CR) && event.stateMask == SWT.NONE) { HsMultiActiveCellEditor.commit(true); SelectionLayer selectionLayer = LayerUtil.getLayer(natTable, SelectionLayer.class); PositionCoordinate p = selectionLayer.getLastSelectedCellPosition(); XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (!editor.isHorizontalLayout()) { natTable.doCommand(new SelectCellCommand(selectionLayer, editor.getTgtColumnIndex(), p.rowPosition / 2 * 2, false, false)); } else { if (p.columnPosition != editor.getSrcColumnIndex() && p.columnPosition != editor.getTgtColumnIndex()) { p.columnPosition = editor.getTgtColumnIndex(); } natTable.doCommand(new SelectCellCommand(selectionLayer, p.columnPosition, p.rowPosition, false, false)); } HsMultiCellEditorControl.activeSourceAndTargetCell(editor); } } }
4,178
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MouseEditAction.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/actions/MouseEditAction.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.actions; import java.util.Vector; import net.heartsome.cat.ts.core.bean.NoteBean; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.heartsome.cat.ts.ui.xliffeditor.nattable.dialog.UpdateNoteDialog; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.painter.XliffEditorGUIHelper; import net.heartsome.cat.ts.ui.xliffeditor.nattable.painter.XliffEditorGUIHelper.ImageName; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.selection.command.SelectCellCommand; import net.sourceforge.nattable.style.CellStyleUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import com.ximpleware.NavException; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * 当进入编辑模式后,刷新删除光标后内容和删除标记前内容的 Command * @author peason * @version * @since JDK1.6 */ public class MouseEditAction extends net.sourceforge.nattable.edit.action.MouseEditAction { public void run(NatTable natTable, MouseEvent event) { XLIFFEditorImplWithNatTable xliffEditor = XLIFFEditorImplWithNatTable.getCurrent(); if (xliffEditor == null) { return; } int columnPosition = natTable.getColumnPositionByX(event.x); int rowPosition = natTable.getRowPositionByY(event.y); boolean withShiftMask = (event.stateMask & SWT.SHIFT) != 0; boolean withCtrlMask = (event.stateMask & SWT.CTRL) != 0; if (!xliffEditor.isHorizontalLayout() && rowPosition != HsMultiActiveCellEditor.targetRowPosition && (rowPosition != HsMultiActiveCellEditor.sourceRowPosition || columnPosition != xliffEditor .getSrcColumnIndex())) { HsMultiActiveCellEditor.commit(true); natTable.doCommand(new SelectCellCommand(natTable, columnPosition, rowPosition, withShiftMask, withCtrlMask)); if (columnPosition == xliffEditor.getTgtColumnIndex()) { HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } } else if (rowPosition != HsMultiActiveCellEditor.targetRowPosition || columnPosition != xliffEditor.getSrcColumnIndex() || columnPosition != xliffEditor.getTgtColumnIndex()) { HsMultiActiveCellEditor.commit(true); natTable.doCommand(new SelectCellCommand(natTable, columnPosition, rowPosition, withShiftMask, withCtrlMask)); if (columnPosition == xliffEditor.getSrcColumnIndex() || columnPosition == xliffEditor.getTgtColumnIndex()) { HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor); } } // 点击批注图片时打开编辑批注对话框 Image image = XliffEditorGUIHelper.getImage(ImageName.HAS_NOTE); // int columnPosition = natTable.getColumnPositionByX(event.x); // int rowPosition = natTable.getRowPositionByY(event.y); LayerCell cell = natTable.getCellByPosition(columnPosition, rowPosition); Rectangle imageBounds = image.getBounds(); if (cell == null) { return; } Rectangle cellBounds = cell.getBounds(); int x = cellBounds.x + imageBounds.width * 3 + 20; int y = cellBounds.y + CellStyleUtil.getVerticalAlignmentPadding( CellStyleUtil.getCellStyle(cell, natTable.getConfigRegistry()), cellBounds, imageBounds.height); if (columnPosition == xliffEditor.getStatusColumnIndex() && event.x >= x && event.x <= (x + imageBounds.width) && event.y >= y && event.y <= (y + imageBounds.height)) { if ((xliffEditor.isHorizontalLayout() && columnPosition == 2) || (!xliffEditor.isHorizontalLayout() && columnPosition == 1)) { Vector<NoteBean> noteBeans = null; try { int rowIndex = natTable.getRowIndexByPosition(rowPosition); if (!xliffEditor.isHorizontalLayout()) { rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; } noteBeans = xliffEditor.getXLFHandler().getNotes(xliffEditor.getXLFHandler().getRowId(rowIndex)); if (noteBeans != null && noteBeans.size() > 0) { UpdateNoteDialog dialog = new UpdateNoteDialog(xliffEditor.getSite().getShell(), xliffEditor, rowIndex); dialog.open(); } } catch (NavException e) { e.printStackTrace(); } catch (XPathParseException e) { e.printStackTrace(); } catch (XPathEvalException e) { e.printStackTrace(); } } } } }
4,676
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PopupMenuAction.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/actions/PopupMenuAction.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.actions; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.action.AbstractMouseSelectionAction; import net.sourceforge.nattable.selection.command.SelectCellCommand; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.widgets.Menu; public class PopupMenuAction extends AbstractMouseSelectionAction { private SelectionLayer selectionLayer; private Menu menu; public PopupMenuAction(Menu menu) { this.menu = menu; } @Override public void run(NatTable natTable, MouseEvent event) { // ActiveCellEditor.commit(); // 执行弹出菜单前先关闭编辑模式的单元格 super.run(natTable, event); if (selectionLayer == null) { selectionLayer = LayerUtil.getLayer(natTable, SelectionLayer.class); } int rowIndex = natTable.getRowIndexByPosition(getGridRowPosition()); XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if(!editor.isHorizontalLayout()){ rowIndex = rowIndex / 2; } // 如果该行已经选中的了,直接显示出右键菜单。 if (!isSelected(rowIndex)) { HsMultiActiveCellEditor.commit(true); natTable.doCommand(new SelectCellCommand(natTable, getGridColumnPosition(), getGridRowPosition(), isWithShiftMask(), isWithControlMask())); HsMultiCellEditorControl.activeSourceAndTargetCell(editor); } menu.setData(event.data); menu.setVisible(true); } /** * 是否选中了该行 * @param rowIndex * 行索引 * @return 是否选中; */ private boolean isSelected(int rowIndex) { int[] selectedRows = selectionLayer.getFullySelectedRowPositions(); for (int row : selectedRows) { if (row == rowIndex) { return true; } } return false; } }
2,168
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XliffEditorDataProvider.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/dataprovider/XliffEditorDataProvider.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.dataprovider; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.UpdateDataBean; import net.sourceforge.nattable.data.IColumnAccessor; import net.sourceforge.nattable.data.IRowDataProvider; public class XliffEditorDataProvider<T> implements IRowDataProvider<T> { private XLFHandler handler; private static final int CACHE_SIZE = 200; public XLFHandler getHandler() { return handler; } private IColumnAccessor<T> columnAccessor; public XliffEditorDataProvider(XLFHandler handler, IColumnAccessor<T> columnAccessor) { this.handler = handler; this.columnAccessor = columnAccessor; } @SuppressWarnings("unchecked") public T getRowObject(final int rowIndex) { T obj = (T) handler.getCacheMap().get(rowIndex); if (obj == null) { obj = (T) handler.getTransUnit(rowIndex); cache(rowIndex, obj); // 缓存操作 } return obj; } /** * 缓存当前页 * @param key * @param value * ; */ private void cache(final int key, T value) { if (handler.getCacheMap().size() > CACHE_SIZE) { // 清空缓存 handler.resetCache(); } else { handler.getCacheMap().put(key, (TransUnitBean) value); } } public int indexOfRowObject(T rowObject) { // TODO 暂时用不到,无实现 return 0; } public int getColumnCount() { return columnAccessor.getColumnCount(); } public Object getDataValue(int columnIndex, int rowIndex) { if (columnIndex == 0) { return rowIndex + 1; } else if (columnIndex == 1) { // 获取Source列的值 // T obj = (T) handler.getCacheMap().get(rowIndex); // if (obj != null) { // return ((TransUnitBean) obj).getSrcContent(); // } else { // String rowId = handler.getRowId(rowIndex); // return handler.getSrcContent(rowId); // } T obj = getRowObject(rowIndex); if (obj != null) { return ((TransUnitBean) obj).getSrcContent(); } else { return null; } } else if (columnIndex == 3) { // 获取Target列的值 // T obj = (T) handler.getCacheMap().get(rowIndex); // if (obj != null) { // return ((TransUnitBean) obj).getTgtContent(); // } else { // String rowId = handler.getRowId(rowIndex); // return handler.getTgtContent(rowId); // } T obj = getRowObject(rowIndex); if (obj != null) { return ((TransUnitBean) obj).getTgtContent(); } else { return null; } } else { return columnAccessor.getDataValue(getRowObject(rowIndex), columnIndex); } } public int getRowCount() { return handler.countEditableTransUnit(); } public void setDataValue(int columnIndex, int rowIndex, Object newValue) { if (columnIndex == 1) { // 修改Source列 setSrcValue(rowIndex, newValue); } if (columnIndex == 3) { // 修改Target列 setTgtValue(rowIndex, newValue); } } protected void setSrcValue(int rowIndex, Object newValue) { handler.changeSrcTextValue(handler.getRowId(rowIndex), ((UpdateDataBean) newValue).getText()); } protected void setTgtValue(int rowIndex, Object newValue) { UpdateDataBean bean = (UpdateDataBean) newValue; handler.changeTgtTextValue(handler.getRowId(rowIndex), bean.getText(), bean.getMatchType(), bean.getQuality()); } }
3,303
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
VerticalLayerBodyDataProvider.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/dataprovider/VerticalLayerBodyDataProvider.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.dataprovider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; import net.sourceforge.nattable.data.IColumnAccessor; import net.sourceforge.nattable.data.ISpanningDataProvider; import net.sourceforge.nattable.layer.cell.DataCell; public class VerticalLayerBodyDataProvider<T> extends XliffEditorDataProvider<T> implements ISpanningDataProvider { private static final Logger LOGGER = LoggerFactory.getLogger(XLIFFEditorImplWithNatTable.class); public VerticalLayerBodyDataProvider(XLFHandler handler, IColumnAccessor<T> columnAccessor) { super(handler, columnAccessor); } @Override public Object getDataValue(int columnIndex, int rowIndex) { if (columnIndex == VerticalNatTableConfig.ID_COL_INDEX) { // ID 列 if (rowIndex % VerticalNatTableConfig.ROW_SPAN == 0) { // 第一列要显示ID的地方 return rowIndex / VerticalNatTableConfig.ROW_SPAN + 1; } } else if (columnIndex == VerticalNatTableConfig.STATUS_COL_INDEX) { // 状态列 return "flag"; } else { // Source和Target列 if (VerticalNatTableConfig.isSource(columnIndex, rowIndex)) { return ((TransUnitBean) getRowObject(rowIndex)).getSrcContent(); } else if (VerticalNatTableConfig.isTarget(columnIndex, rowIndex)) { return ((TransUnitBean) getRowObject(rowIndex)).getTgtContent(); } } return null; } @Override public int getRowCount() { return super.getRowCount() * VerticalNatTableConfig.ROW_SPAN; } @Override public void setDataValue(int columnIndex, int rowIndex, Object newValue) { if (columnIndex != VerticalNatTableConfig.SOURCE_COL_INDEX) { LOGGER.debug(Messages.getString("dataprovider.VerticalLayerBodyDataProvider.logger1")); } if (rowIndex % 2 == 0) { setSrcValue(rowIndex / VerticalNatTableConfig.ROW_SPAN, newValue); } else { setTgtValue(rowIndex / VerticalNatTableConfig.ROW_SPAN, newValue); } } @Override public T getRowObject(int rowIndex) { return super.getRowObject(rowIndex / VerticalNatTableConfig.ROW_SPAN); } @Override public int indexOfRowObject(T rowObject) { // TODO 暂时用不到,无实现 // LOGGER.debug("此方法尚未实现。"); return 0; } public DataCell getCellByPosition(int columnPosition, int rowPosition) { int rowSpan = 1; // TODO 用索引来判断 Position,可能会有问题 if (columnPosition == VerticalNatTableConfig.ID_COL_INDEX || columnPosition == VerticalNatTableConfig.STATUS_COL_INDEX) { rowSpan = VerticalNatTableConfig.ROW_SPAN; rowPosition = rowPosition / VerticalNatTableConfig.ROW_SPAN * VerticalNatTableConfig.ROW_SPAN; } return new DataCell(columnPosition, rowPosition, 1, rowSpan); } }
3,042
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
UnexpectedTypeExcetion.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/exception/UnexpectedTypeExcetion.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.exception; /** * 在程序中遇到了非预期的类型时抛出此异常。如重写 NatTabel 的 paintControl 方法中,预期 NatTable 的直接底层布局为 CompositeLayer,如果不是,则抛出异常。 * @author cheney * @since JDK1.6 */ public class UnexpectedTypeExcetion extends RuntimeException { /** serialVersionUID. */ private static final long serialVersionUID = 1875863249595095139L; /** * 构建一个无详细信息的 UnexpectedTypeExcetion。 */ public UnexpectedTypeExcetion() { super(); } /** * 构建一个有详细说明的 UnexpectedTypeExcetion。 * @param s * 描述异常的信息说明。 */ public UnexpectedTypeExcetion(String s) { super(s); } /** * 构建一个包含详细说明和堆栈的 UnexpectedTypeExcetion。 * @param message * 描述异常的信息说明。 * @param cause * 堆栈信息。 */ public UnexpectedTypeExcetion(String message, Throwable cause) { super(message, cause); } /** * 构建一个包含堆栈的 UnexpectedTypeExcetion。 * @param cause * 堆栈信息。 */ public UnexpectedTypeExcetion(Throwable cause) { super(cause); } }
1,259
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DeleteToEndOrToTagPropertyTester.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/propertyTester/DeleteToEndOrToTagPropertyTester.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester; import org.eclipse.core.expressions.PropertyTester; /** * 删除光标后内容和删除标记前内容的 test * @author peason * @version * @since JDK1.6 */ public class DeleteToEndOrToTagPropertyTester extends PropertyTester { public static final String PROPERTY_NAMESPACE = "DeleteContent"; public static final String PROPERTY_ENABLED = "enabled"; public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { // boolean enabled = false; // IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); // if (window != null) { // IWorkbenchPage page = window.getActivePage(); // if (page != null) { // IEditorPart editor = page.getActiveEditor(); // if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { // ICellEditor iCellEditor = ActiveCellEditor.getCellEditor(); // if (iCellEditor != null) { // if (iCellEditor instanceof StyledTextCellEditor) { // StyledTextCellEditor cellEditor = (StyledTextCellEditor) iCellEditor; // if (!cellEditor.isClosed()) { // String type = cellEditor.getCellType(); // // 只能删除目标文本 // if (type.equals(NatTableConstant.TARGET)) { // enabled = true; // } // } // } // } // } // } // } return true; } }
1,402
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XLIFFEditorSelectionPropertyTester.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/propertyTester/XLIFFEditorSelectionPropertyTester.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester; import java.util.List; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * 验证 XLIFF 编辑器选中状态的类 * @author peason * @version * @since JDK1.6 */ public class XLIFFEditorSelectionPropertyTester extends PropertyTester { public static final String PROPERTY_NAMESPACE = "xliffEditor"; public static final String PROPERTY_ENABLED = "selectionCount"; public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { // boolean enabled = false; // IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); // if (window != null) { // IWorkbenchPage page = window.getActivePage(); // if (page != null) { // IEditorPart editor = page.getActiveEditor(); // if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { // XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; // if (xliffEditor != null && xliffEditor.getTable() != null) { // List<String> selectedRowIds = xliffEditor.getSelectedRowIds(); // enabled = (selectedRowIds != null && selectedRowIds.size() > 0); // } // } // } // } // // return enabled; return true; } }
1,496
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SignOffPropertyTester.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/propertyTester/SignOffPropertyTester.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * 签发的 test * @author peason * @version * @since JDK1.6 */ public class SignOffPropertyTester extends PropertyTester { public static final String PROPERTY_NAMESPACE = "signedOff"; public static final String PROPERTY_ENABLED = "enabled"; public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { // IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); // if (window != null) { // IWorkbenchPage page = window.getActivePage(); // if (page != null) { // IEditorPart editor = page.getActiveEditor(); // if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { // XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; // if (xliffEditor != null && xliffEditor.getTable() != null) { // long l = System.currentTimeMillis(); // XLFHandler handler = xliffEditor.getXLFHandler(); // List<String> selectedRowIds = xliffEditor.getSelectedRowIds(); // if (selectedRowIds != null && selectedRowIds.size() > 0) { // boolean isLock = true; // boolean isDraft = true; // for (String rowId : selectedRowIds) { // if (!handler.isDraft(rowId) && isDraft) { // isDraft = false; // if (!isLock) { // break; // } // } // if (!handler.isLocked(rowId) && isLock) { // isLock = false; // if (!isDraft) { // break; // } // } // } // if (isLock || isDraft) { // return false; // } // final Map<String, List<String>> tmpGroup = RowIdUtil.groupRowIdByFileName(selectedRowIds); // boolean hasNullTgt = true; // group: // for (Entry<String, List<String>> entry : tmpGroup.entrySet()) { // List<String> lstRowIdList = entry.getValue(); // for (String rowId : lstRowIdList) { // String tgtText = handler.getTgtContent(rowId); // if (tgtText != null && !tgtText.equals("") && hasNullTgt) { // hasNullTgt = false; // break group; // } // } // } // if (hasNullTgt) { // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // return false; // } // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // return true; // } // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // } // } // } // } // return false; return true; } }
3,045
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
UnTranslatedPropertyTester.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/propertyTester/UnTranslatedPropertyTester.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester; import java.util.List; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.swt.custom.StyledText; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * 未翻译的 test * @author peason * @version * @since JDK1.6 */ public class UnTranslatedPropertyTester extends PropertyTester { public static final String PROPERTY_NAMESPACE = "untranslated"; public static final String PROPERTY_ENABLED = "enabled"; public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { // boolean enabled = false; // IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); // if (window != null) { // IWorkbenchPage page = window.getActivePage(); // if (page != null) { // IEditorPart editor = page.getActiveEditor(); // if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { // XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; // if (xliffEditor != null && xliffEditor.getTable() != null) { // long l = System.currentTimeMillis(); // enabled = true; // XLFHandler handler = xliffEditor.getXLFHandler(); // List<String> selectedRowIds = xliffEditor.getSelectedRowIds(); // if (selectedRowIds != null && selectedRowIds.size() > 0) { // boolean isLock = true; // for (String rowId : selectedRowIds) { // if (!handler.isEmptyTranslation(rowId)) { // enabled = false; // break; // } // if (!handler.isLocked(rowId)) { // isLock = false; // } // } // enabled = enabled && !isLock; // if (!enabled) { // StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getTargetStyledEditor(); // if (cellEditor != null && !cellEditor.isApprovedOrLocked()) { // StyledText styledText = cellEditor.getSegmentViewer().getTextWidget(); // if (styledText != null) { // String text = styledText.getText(); // if (text != null && !text.equals("")) { // enabled = true; // } // } // } // // } // } // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // } // } // } // } // return enabled; return true; } }
2,736
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddSegmentToTMPropertyTester.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/propertyTester/AddSegmentToTMPropertyTester.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.swt.custom.StyledText; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * 完成翻译,批准,草稿的 test * @author peason * @version * @since JDK1.6 */ public class AddSegmentToTMPropertyTester extends PropertyTester { public static final String PROPERTY_NAMESPACE = "table"; public static final String PROPERTY_ENABLED = "enabled"; public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { // boolean enabled = false; // IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); // if (window != null) { // IWorkbenchPage page = window.getActivePage(); // if (page != null) { // IEditorPart editor = page.getActiveEditor(); // if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { // XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; // if (xliffEditor != null && xliffEditor.getTable() != null) { // long l = System.currentTimeMillis(); // XLFHandler handler = xliffEditor.getXLFHandler(); // List<String> selectedRowIds = xliffEditor.getSelectedRowIds(); // if (selectedRowIds != null && selectedRowIds.size() > 0) { // final Map<String, List<String>> tmpGroup = RowIdUtil.groupRowIdByFileName(selectedRowIds); // boolean hasNullTgt = true; // group: for (Entry<String, List<String>> entry : tmpGroup.entrySet()) { // List<String> lstRowIdList = entry.getValue(); // for (String rowId : lstRowIdList) { // String tgtText = handler.getTgtContent(rowId); // if (tgtText != null && !tgtText.equals("") && hasNullTgt) { // hasNullTgt = false; // break group; // } // } // } // boolean isLock = true; // for (String rowId : selectedRowIds) { // if (!handler.isLocked(rowId)) { // isLock = false; // } // } // enabled = !hasNullTgt && !isLock; // // if (!enabled) { // StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getTargetStyledEditor(); // if (cellEditor != null && !cellEditor.isApprovedOrLocked()) { // StyledText styledText = cellEditor.getSegmentViewer().getTextWidget(); // if (styledText != null) { // String text = styledText.getText(); // if (text != null && !text.equals("")) { // enabled = true; // } // } // } // } // } // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // } // } // } // } // // return enabled; return true; } }
3,264
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CellRegion.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/coordinate/CellRegion.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate; import net.sourceforge.nattable.coordinate.PositionCoordinate; import org.eclipse.jface.text.IRegion; public class CellRegion { public CellRegion(PositionCoordinate positionCoordinate, IRegion region) { this.positionCoordinate = positionCoordinate; this.region = region; } private PositionCoordinate positionCoordinate; private IRegion region; public void setPositionCoordinate(PositionCoordinate positionCoordinate) { this.positionCoordinate = positionCoordinate; } public PositionCoordinate getPositionCoordinate() { return positionCoordinate; } public void setRegion(IRegion region) { this.region = region; } public IRegion getRegion() { return region; } @Override public boolean equals(Object obj) { if (!(obj instanceof PositionCoordinate)) { return false; } CellRegion coordinate = (CellRegion) obj; try { return this.positionCoordinate.equals(coordinate.positionCoordinate) && this.region.equals(coordinate.region); } catch (Exception e) { return false; } } @Override public String toString() { return positionCoordinate.toString() + " | " + region.toString(); } }
1,214
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ActiveCellRegion.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/coordinate/ActiveCellRegion.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate; public class ActiveCellRegion { private static CellRegion activeCellRegion; public static synchronized CellRegion getActiveCellRegion() { return activeCellRegion; } public static synchronized void setActiveCellRegion(CellRegion region) { activeCellRegion = region; } }
356
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FindReplaceDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/dialog/FindReplaceDialog.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.dialog; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import net.heartsome.cat.common.ui.listener.PartAdapter; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.bean.XliffEditorParameter; import net.heartsome.cat.ts.ui.xliffeditor.nattable.Activator; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.Messages; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.command.FindReplaceCommand; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.ActiveCellRegion; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.CellRegion; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.event.FindReplaceEvent; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.ColumnSearchStrategy; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.ICellSearchStrategy; import net.sourceforge.nattable.NatTable; import net.sourceforge.nattable.coordinate.PositionCoordinate; import net.sourceforge.nattable.layer.DataLayer; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.ILayerListener; import net.sourceforge.nattable.layer.event.ILayerEvent; import net.sourceforge.nattable.selection.SelectionLayer; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 查找对话框 * @author weachy * @version * @since JDK1.5 */ public class FindReplaceDialog extends Dialog { private static final Logger LOGGER = LoggerFactory.getLogger(FindReplaceDialog.class); public static boolean isOpen = false; private Combo cmbFind; /** */ private Combo cmbReplace; /** 查找 */ private Button findButton; /** 查找下一个 */ private Button findNextButton; /** 替换 */ private Button replaceButton; /** 替换全部 */ private Button replaceAllButton; /** 大小写敏感按钮 */ private Button caseSensitiveButton; /** 状态信息 */ private Label statusLabel; /** 循环查找 */ /** burke 修改find/replace界面框 注释 */ // private Button wrapSearchButton; /** 正向查找按钮 */ private Button forwardButton; /** 反向向查找按钮 */ private Button backwardButton; /** 查找源语言按钮 */ private Button sourceButton; /** 查找目标语言按钮 */ private Button targetButton; /** 搜索策略 */ private ColumnSearchStrategy searchStrategy; /** 比较器 */ private ICellSearchStrategy cellSearchStrategy; /** 匹配整词 */ private Button wholeWordButton; /** 模糊搜索 */ /** burke 修改find/replace界面框 注释 */ // private Button fuzzySearchButton; /** 正则表达式 */ private Button regExButton; private String msg = Messages.getString("dialog.FindReplaceDialog.status1"); private final int HISTORY_SIZE = 5; private List<String> lstFindHistory; private List<String> lstReplaceHistory; IPartListener partListener = new PartAdapter() { @Override public void partActivated(IWorkbenchPart part) { clearActiveCellRegion(part); } public void partOpened(IWorkbenchPart part) { clearActiveCellRegion(part); }; private void clearActiveCellRegion(IWorkbenchPart part) { if (part instanceof XLIFFEditorImplWithNatTable) { CellRegion cellRegion = ActiveCellRegion.getActiveCellRegion(); if (cellRegion == null) { return; } ILayer layer = cellRegion.getPositionCoordinate().getLayer(); NatTable table = ((XLIFFEditorImplWithNatTable) part).getTable(); ILayer layer1 = LayerUtil.getLayer(table, layer.getClass()); if (!layer.equals(layer1)) { ActiveCellRegion.setActiveCellRegion(null); // 清空查找结果 } } } }; private FindReplaceDialog(Shell shell) { super(shell); setShellStyle(getShellStyle() ^ SWT.APPLICATION_MODAL | SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE); setBlockOnOpen(false); isOpen = true; PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().addPartListener(partListener); lstFindHistory = new ArrayList<String>(HISTORY_SIZE - 1); lstReplaceHistory = new ArrayList<String>(HISTORY_SIZE - 1); } public static FindReplaceDialog createDialog(Shell shell) { return new FindReplaceDialog(shell); } public void setSearchStrategy(ColumnSearchStrategy searchStrategy, ICellSearchStrategy cellSearchStrategy) { this.searchStrategy = searchStrategy; this.cellSearchStrategy = cellSearchStrategy; // ActiveCellRegion.setActiveCellRegion(null); } @Override public void create() { super.create(); isOpen = true; getShell().setText(Messages.getString("dialog.FindReplaceDialog.Title")); updateCombo(cmbFind, lstFindHistory); updateCombo(cmbReplace, lstReplaceHistory); // 打开了查找替换框后,判断查找输入框中是否存在查找替换内容,判断查找,查找下一个,替换,替换所有按钮的可用性 setEnable(); } @Override protected boolean isResizable() { return true; } protected Point getInitialSize() { // Point initialSize = super.getInitialSize(); // Point minSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT); // if (initialSize.x < minSize.x) // return minSize; // return initialSize; return new Point(350, 435); } protected IDialogSettings getDialogBoundsSettings() { String sectionName = getClass().getName() + "_dialogBounds"; //$NON-NLS-1$ IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(sectionName); if (section == null) section = settings.addNewSection(sectionName); return section; } @Override public boolean close() { ActiveCellRegion.setActiveCellRegion(null); // 清空查找结果 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().removePartListener(partListener); isOpen = false; writeDialogSettings(); return super.close(); } @Override protected void buttonPressed(int buttonID) { if (buttonID == IDialogConstants.CLOSE_ID) { close(); } } @Override protected Control createDialogArea(Composite parent) { return super.createDialogArea(parent); } @Override protected Control createContents(final Composite parent) { final Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, true)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(composite); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(createInputPanel(composite)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(createConfigPanel(composite)); Composite buttonPanel = createButtonSection(composite); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.BOTTOM).grab(true, false).applyTo(buttonPanel); Composite statusBar = createStatusAndCloseButton(composite); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.BOTTOM).grab(true, false).applyTo(statusBar); readDialogSettings(); return composite; } /** * Creates the options configuration section of the find replace dialog. * @param parent * the parent composite * @return the options configuration section */ private Composite createConfigPanel(Composite parent) { Composite panel = new Composite(parent, SWT.NONE); panel.setLayout(new GridLayout(1, true)); Composite rangePanel = createRangePanel(panel); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(rangePanel); Composite optionPanel = createOptionsPanel(panel); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(optionPanel); return panel; } private Composite createButtonSection(Composite composite) { Composite panel = new Composite(composite, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = -2; // this is intended panel.setLayout(layout); findButton = createButton(panel, IDialogConstants.CLIENT_ID, Messages.getString("dialog.FindReplaceDialog.findButton"), false); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.BOTTOM).grab(false, false).hint(95, SWT.DEFAULT) .applyTo(findButton); findButton.setEnabled(false); findButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doFind(); updateFindHistory(); } }); findNextButton = createButton(panel, IDialogConstants.CLIENT_ID, Messages.getString("dialog.FindReplaceDialog.findNextButton"), false); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.BOTTOM).grab(false, false).hint(95, SWT.DEFAULT) .applyTo(findNextButton); findNextButton.setEnabled(false); findNextButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doFindNext(); updateFindHistory(); } }); replaceButton = createButton(panel, IDialogConstants.CLIENT_ID, Messages.getString("dialog.FindReplaceDialog.replaceButton"), false); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.BOTTOM).grab(false, false).hint(95, SWT.DEFAULT) .applyTo(replaceButton); replaceButton.setEnabled(false); replaceButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doReplace(); updateFindAndReplaceHistory(); } }); replaceAllButton = createButton(panel, IDialogConstants.CLIENT_ID, Messages.getString("dialog.FindReplaceDialog.replaceAllButton"), false); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.BOTTOM).grab(false, false).hint(95, SWT.DEFAULT) .applyTo(replaceAllButton); replaceAllButton.setEnabled(false); replaceAllButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { doReplaceAll(); updateFindAndReplaceHistory(); } }); getShell().setDefaultButton(findNextButton); // 设置默认按钮 return panel; } /** * Creates the status and close section of the dialog. * @param parent * the parent composite * @return the status and close button */ private Composite createStatusAndCloseButton(Composite parent) { statusLabel = new Label(parent, SWT.LEFT); statusLabel.setForeground(statusLabel.getDisplay().getSystemColor(SWT.COLOR_RED)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(statusLabel); Composite panel = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(0, false); layout.marginWidth = 0; layout.marginHeight = 0; panel.setLayout(layout); panel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Button closeButton = createButton(panel, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, false); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.BOTTOM).grab(true, false).hint(90, SWT.DEFAULT) .applyTo(closeButton); return parent; } private Composite createInputPanel(final Composite composite) { final Composite row = new Composite(composite, SWT.NONE); row.setLayout(new GridLayout(2, false)); final Label findLabel = new Label(row, SWT.NONE); findLabel.setText(Messages.getString("dialog.FindReplaceDialog.findLabel")); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(findLabel); cmbFind = new Combo(row, SWT.DROP_DOWN | SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(cmbFind); cmbFind.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { /* * boolean enabled = findText.getText().length() > 0; findButton.setEnabled(enabled); * findNextButton.setEnabled(enabled); replaceAllButton.setEnabled(!sourceButton.getSelection() && * enabled); if (!enabled) { replaceButton.setEnabled(false); } */ setEnable(); } }); cmbFind.addSelectionListener(new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent e) { if (findButton.isEnabled()) { doFindNext(); } } }); Label replaceWithLabel = new Label(row, SWT.NONE); replaceWithLabel.setText(Messages.getString("dialog.FindReplaceDialog.replaceWithLabel")); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(replaceWithLabel); cmbReplace = new Combo(row, SWT.DROP_DOWN | SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(cmbReplace); return row; } /** * 范围面板 * @param composite * @return ; */ private Composite createRangePanel(Composite composite) { final Composite row = new Composite(composite, SWT.NONE); row.setLayout(new GridLayout(2, true)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(row); final Group directionGroup = new Group(row, SWT.SHADOW_ETCHED_IN); directionGroup.setText(Messages.getString("dialog.FindReplaceDialog.directionGroup")); directionGroup.setLayout(new GridLayout(1, true)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(directionGroup); forwardButton = new Button(directionGroup, SWT.RADIO); forwardButton.setText(Messages.getString("dialog.FindReplaceDialog.forwardButton")); forwardButton.setSelection(true); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).applyTo(forwardButton); backwardButton = new Button(directionGroup, SWT.RADIO); backwardButton.setText(Messages.getString("dialog.FindReplaceDialog.backwardButton")); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).applyTo(backwardButton); final Group rangeGroup = new Group(row, SWT.SHADOW_ETCHED_IN); rangeGroup.setText(Messages.getString("dialog.FindReplaceDialog.rangeGroup")); rangeGroup.setLayout(new GridLayout(1, true)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(rangeGroup); /** 搜索范围:源语言 */ sourceButton = new Button(rangeGroup, SWT.RADIO); sourceButton.setText(Messages.getString("dialog.FindReplaceDialog.sourceButton")); sourceButton.setSelection(true); sourceButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor != null) { replaceButton.setEnabled(false); replaceAllButton.setEnabled(false); } } }); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).applyTo(sourceButton); targetButton = new Button(rangeGroup, SWT.RADIO); targetButton.setText(Messages.getString("dialog.FindReplaceDialog.targetButton")); targetButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor != null) { boolean enabled = cmbFind.getText().length() > 0; replaceAllButton.setEnabled(enabled); } } }); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).applyTo(targetButton); return row; } private Composite createOptionsPanel(final Composite composite) { final Group optionsGroup = new Group(composite, SWT.SHADOW_ETCHED_IN); optionsGroup.setText(Messages.getString("dialog.FindReplaceDialog.optionsGroup")); final GridLayout gridLayout = new GridLayout(2, true); optionsGroup.setLayout(gridLayout); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(optionsGroup); // optionsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); caseSensitiveButton = new Button(optionsGroup, SWT.CHECK); caseSensitiveButton.setText(Messages.getString("dialog.FindReplaceDialog.caseSensitiveButton")); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).applyTo(caseSensitiveButton); /** burke 修改find/replace界面框 注释 */ /* * wrapSearchButton = new Button(optionsGroup, SWT.CHECK); wrapSearchButton.setText("&Wrap Search"); * wrapSearchButton.setSelection(true); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, * false).applyTo(wrapSearchButton); */ wholeWordButton = new Button(optionsGroup, SWT.CHECK); wholeWordButton.setText(Messages.getString("dialog.FindReplaceDialog.wholeWordButton")); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).applyTo(wholeWordButton); /** burke 修改find/replace界面框 注释 */ /* * fuzzySearchButton = new Button(optionsGroup, SWT.CHECK); fuzzySearchButton.setText("Fu&zzy Search"); * GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).applyTo(fuzzySearchButton); */ regExButton = new Button(optionsGroup, SWT.CHECK); regExButton.setText(Messages.getString("dialog.FindReplaceDialog.regExButton")); regExButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (regExButton.getSelection()) { wholeWordButton.setEnabled(false); /** burke 修改find/replace界面框 注释 */ // fuzzySearchButton.setEnabled(false); } else { wholeWordButton.setEnabled(true); /** burke 修改find/replace界面框 注释 */ // fuzzySearchButton.setEnabled(true); } } }); GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(false, false).span(2, 1).applyTo(regExButton); return optionsGroup; } private CellRegion searchResultCellRegion = null; private CellRegion find(final int startingRowPosition, final int startOffset) { // 查找前选提交编辑模式的单元格 BusyIndicator.showWhile(super.getShell().getDisplay(), new Runnable() { public void run() { XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor == null) { return; } NatTable natTable = editor.getTable(); searchResultCellRegion = null; statusLabel.setText(""); boolean searchForward = forwardButton.getSelection(); boolean searchSource = sourceButton.getSelection(); boolean caseSensitive = caseSensitiveButton.getSelection(); /** burke 修改find/replace界面框 注释 使得find/replace默认为循环查找 */ // boolean wrapSearch = wrapSearchButton.getSelection(); boolean wrapSearch = true; boolean wholeWord = wholeWordButton.getEnabled() && wholeWordButton.getSelection(); boolean regExSearch = regExButton.getEnabled() && regExButton.getSelection(); /** burke 修改find/replace界面框 注释 */ // boolean fuzzySearch = fuzzySearchButton.getSelection(); if (searchSource) { int columnPosition = LayerUtil.getColumnPositionByIndex(natTable, editor.getSrcColumnIndex()); searchStrategy.setColumnPositions(new int[] { columnPosition }); } else { int columnPosition = LayerUtil.getColumnPositionByIndex(natTable, editor.getTgtColumnIndex()); searchStrategy.setColumnPositions(new int[] { columnPosition }); } searchStrategy.setStartingRowPosition(startingRowPosition); cellSearchStrategy.init(searchForward, caseSensitive, wholeWord, regExSearch, startOffset); final FindReplaceCommand command = new FindReplaceCommand(cmbFind.getText(), natTable, searchStrategy, cellSearchStrategy); final ILayerListener searchEventListener = initSearchEventListener(); command.setSearchEventListener(searchEventListener); try { // Fire command natTable.doCommand(command); // 如果未找到 if (searchResultCellRegion == null) { if (wrapSearch) { if (forwardButton.getSelection()) { int rowPositionFlag = 0; // 解决垂直布局执行查找下一个或者替换所有时,如果没有匹配,界面会卡住一会儿并且后台会报异常的问题 if (!editor.isHorizontalLayout()) { rowPositionFlag = 1; } if (startingRowPosition > rowPositionFlag) { int rowPosition = 0; // 默认从第一行(索引为 0)开始 if (!editor.isHorizontalLayout()) { // 如果是垂直布局并且是 if (!sourceButton.getSelection()) { rowPosition = 1; } } find(rowPosition, 0); } else { refreshMsgAndTable(); } } else { DataLayer dataLayer = LayerUtil.getLayer(natTable, DataLayer.class); int lastRowPosition = dataLayer.getRowCount() - 1; SelectionLayer selectionLayer = LayerUtil.getLayer(natTable, SelectionLayer.class); lastRowPosition = LayerUtil.convertRowPosition(dataLayer, lastRowPosition, selectionLayer); if (startingRowPosition < lastRowPosition) { find(lastRowPosition, -1); } else { refreshMsgAndTable(); } } } else { refreshMsgAndTable(); } } } finally { command.getContext().removeLayerListener(searchEventListener); } } private ILayerListener initSearchEventListener() { // Register event listener final ILayerListener searchEventListener = new ILayerListener() { public void handleLayerEvent(ILayerEvent event) { if (event instanceof FindReplaceEvent) { FindReplaceEvent searchEvent = (FindReplaceEvent) event; searchResultCellRegion = searchEvent.getCellRegion(); if (searchResultCellRegion != null) { ActiveCellRegion.setActiveCellRegion(searchResultCellRegion); } } } }; return searchEventListener; } }); return searchResultCellRegion; } private boolean doFind() { CellRegion cellRegion; XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor == null) { return false; } if (forwardButton.getSelection()) { if (editor.isHorizontalLayout()) { cellRegion = find(0, 0); } else { // 解决在垂直布局查找 Source 时,如果 Source 没有匹配而 Target 有匹配,会找到 Target 中的匹配文本 if (sourceButton.getSelection()) { cellRegion = find(0, 0); } else { cellRegion = find(1, 0); } } } else { NatTable natTable = editor.getTable(); int sourceRowPosition = natTable.getRowCount() - 1; int row = LayerUtil.getLowerLayerRowPosition(natTable, sourceRowPosition, SelectionLayer.class); if (!editor.isHorizontalLayout()) { row *= VerticalNatTableConfig.ROW_SPAN; if (!sourceButton.getSelection()) { row++; } } cellRegion = find(row, -1); } replaceButton.setEnabled(!sourceButton.getSelection() && cellRegion != null); if (cellRegion == null) { refreshMsgAndTable(); } return cellRegion != null; } /** * 查找下一个 ; * @return */ private boolean doFindNext() { XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor == null) { return false; } int[] selectedRows = editor.getSelectedRows(); int startingRowPosition; if (selectedRows.length > 0) { Arrays.sort(selectedRows); if (forwardButton.getSelection()) { startingRowPosition = selectedRows[selectedRows.length - 1] /* 最大行数 */; // 从当前选中行中最大的行开始找。 } else { startingRowPosition = selectedRows[0] /* 最小行数 */; // 从当前选中行中最大的行开始找。 } if (!editor.isHorizontalLayout()) { startingRowPosition *= VerticalNatTableConfig.ROW_SPAN; if (!sourceButton.getSelection()) { startingRowPosition++; } } int startOffset; CellRegion cellRegion = ActiveCellRegion.getActiveCellRegion(); if (cellRegion == null || cellRegion.getPositionCoordinate().getRowPosition() != startingRowPosition) { // 起始行不一致 if (forwardButton.getSelection()) { startOffset = 0; } else { startOffset = -1; } } else { PositionCoordinate coordinate = cellRegion.getPositionCoordinate(); int columnIndex = coordinate.getLayer().getColumnIndexByPosition(coordinate.getColumnPosition()); // 得到上次查找的列 if (columnIndex != (sourceButton.getSelection() ? editor.getSrcColumnIndex() : editor .getTgtColumnIndex())) {// 如果所查找的列改变了,赋为初始值 if (forwardButton.getSelection()) { startOffset = 0; } else { startOffset = -1; } } else { if (forwardButton.getSelection()) { startOffset = cellRegion.getRegion().getOffset() + cellRegion.getRegion().getLength(); } else { startOffset = cellRegion.getRegion().getOffset() - 1; if (startOffset == -1) { // 解决在垂直布局时,选择向后查找在查找到某一行后会返回到最后一行继续查找的问题。 if (editor.isHorizontalLayout()) { startingRowPosition--; } else { startingRowPosition -= 2; } } } } } cellRegion = find(startingRowPosition, startOffset); replaceButton.setEnabled(!sourceButton.getSelection() && cellRegion != null); if (cellRegion == null) { refreshMsgAndTable(); } return cellRegion != null; } else { return doFind(); } } /** * 替换 ; */ private void doReplace() { CellRegion activeCellRegion = ActiveCellRegion.getActiveCellRegion(); if (activeCellRegion == null) { return; } StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getTargetStyledEditor(); if(cellEditor != null){ StyledText text = cellEditor.getSegmentViewer().getTextWidget(); String sleText = text.getSelectionText(); String findStr = cmbFind.getText(); if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) { findStr = findStr.replaceAll("\\n", Constants.LINE_SEPARATOR_CHARACTER + "\n"); findStr = findStr.replaceAll("\\t", Constants.TAB_CHARACTER + "\u200B"); findStr = findStr.replaceAll(" ", Constants.SPACE_CHARACTER + "\u200B"); } if( sleText != null && sleText.toLowerCase().equals(findStr.toLowerCase())){ Point p = text.getSelection(); text.replaceTextRange(p.x, p.y - p.x, cmbReplace.getText()); } } } /** * 替换全部 ; */ private void doReplaceAll() { XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); if (editor == null) { return; } CellRegion cellRegion = null; if (editor.isHorizontalLayout()) { cellRegion = find(0, 0); } else { cellRegion = find(1, 0); } if (cellRegion == null) { // 无查找结果 return; } boolean forward = forwardButton.getSelection(); if(!forward){ forwardButton.setSelection(true); } int firstRowPosition = cellRegion.getPositionCoordinate().getRowPosition(); HashMap<String, String> segments = new HashMap<String, String>(); int count = 0; String findStr = cmbFind.getText(); String replaceStr = cmbReplace.getText(); do { PositionCoordinate coordinate = cellRegion.getPositionCoordinate(); int rowPosition = coordinate.rowPosition; int columnPosition = coordinate.columnPosition; int rowIndex = coordinate.getLayer().getRowIndexByPosition(rowPosition); if (!editor.isHorizontalLayout()) { rowIndex = rowIndex / VerticalNatTableConfig.ROW_SPAN; } // 判断锁定 TransUnitBean transUnit = editor.getRowTransUnitBean(rowIndex); String translate = transUnit.getTuProps().get("translate"); if (translate != null && "no".equalsIgnoreCase(translate)) { rowPosition++; cellRegion = find(rowPosition, 0); continue; } String cellValue = (String) coordinate.getLayer().getDataValueByPosition(columnPosition, rowPosition); StringBuffer cellValueBf = new StringBuffer(cellValue); int start = cellValue.toUpperCase().indexOf(findStr.toUpperCase()); while (start != -1) { cellValueBf.replace(start, start + findStr.length(), replaceStr); start = cellValueBf.indexOf(findStr, start); count++; } segments.put(editor.getXLFHandler().getRowId(rowIndex), cellValueBf.toString()); rowPosition++; if(!editor.isHorizontalLayout()){ rowPosition++; } cellRegion = find(rowPosition, 0); } while (cellRegion.getPositionCoordinate().getRowPosition() != firstRowPosition); if(!forward){ forwardButton.setSelection(false); backwardButton.setSelection(true); } int columnIndex = 0; if (sourceButton.getSelection()) { columnIndex = editor.getSrcColumnIndex(); } else { columnIndex = editor.getTgtColumnIndex(); } try { editor.updateSegments(segments, columnIndex, null, null); } catch (ExecutionException e) { LOGGER.error(Messages.getString("dialog.FindReplaceDialog.logger1"), e); } String msg = Messages.getString("dialog.FindReplaceDialog.status3"); statusLabel.setText(MessageFormat.format(msg, count)); ActiveCellRegion.setActiveCellRegion(null); } /** * 刷新提示信息和 Nattable */ private void refreshMsgAndTable() { // 更换条件查找,当查找不到结果时,清除之前标记的红色文本 ActiveCellRegion.setActiveCellRegion(null); statusLabel.setText(msg); XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); editor.setFocus(); if (editor != null) { editor.refresh(); } } // private String replaceText(String initValue, String text, String replaceText, List<IRegion> regions) { // IInnerTagFactory innerTagFactory = new XliffInnerTagFactory(initValue, new PlaceHolderNormalModeBuilder()); // List<InnerTagBean> innerTagBeans = innerTagFactory.getInnerTagBeans(); // int wave = 0; // StringBuffer sb = new StringBuffer(initValue); // // 解决向后查找替换时替换位置会出现错误的问题。 // if (!forwardButton.getSelection()) { // Collections.reverse(regions); // } // StringBuffer sbText = new StringBuffer(text); // for (IRegion region : regions) { // // 由于可能含有标记,因此先找到 region 的实际位置 // int caretOffset = region.getOffset() + wave; // int offset = caretOffset; // Matcher matcher = PATTERN.matcher(sbText); // int index = 0; // while (matcher.find()) { // String placeHolder = matcher.group(); // int start = matcher.start(); // if (start >= offset) { // break; // } // caretOffset += innerTagBeans.get(index++).getContent().replaceAll("&amp;", "&").length() - placeHolder.length(); // } // sb.replace(caretOffset, caretOffset + region.getLength(), replaceText); // int start = region.getOffset() + wave; // sbText.replace(start, start + region.getLength(), replaceText); // wave += replaceText.length() - region.getLength(); // } // return sb.toString(); // } /** * 通过每次打开查找替换框或者修改查找框中内容,判断查找,查找下一个,替换,替换所有按钮的可用性 修改查找替换BUG时添加 burke */ private void setEnable() { boolean enabled = cmbFind.getText().length() > 0; findButton.setEnabled(enabled); findNextButton.setEnabled(enabled); replaceAllButton.setEnabled(!sourceButton.getSelection() && enabled); if (!enabled) { replaceButton.setEnabled(false); } } public void setSearchText(String text) { if (cmbFind != null && !cmbFind.isDisposed()) { if (!text.equals("")) { cmbFind.setText(text); } else if (lstFindHistory != null && lstFindHistory.size() > 0){ cmbFind.setText(lstFindHistory.get(0)); } cmbFind.setSelection(new Point(0, cmbFind.getText().length())); } } private void readDialogSettings() { IDialogSettings ids = getDialogSettings(); boolean blnDirection = ids.getBoolean("nattable.FindReplaceDialog.direction"); forwardButton.setSelection(!blnDirection); backwardButton.setSelection(blnDirection); boolean blnRange = ids.getBoolean("nattable.FindReplaceDialog.range"); sourceButton.setSelection(!blnRange); targetButton.setSelection(blnRange); caseSensitiveButton.setSelection(ids.getBoolean("nattable.FindReplaceDialog.caseSensitive")); wholeWordButton.setSelection(ids.getBoolean("nattable.FindReplaceDialog.wholeWord")); regExButton.setSelection(ids.getBoolean("nattable.FindReplaceDialog.regEx")); String[] arrFindHistory = ids.getArray("nattable.FindReplaceDialog.findHistory"); if (arrFindHistory != null) { lstFindHistory.clear(); for (int i = 0; i < arrFindHistory.length; i++) { lstFindHistory.add(arrFindHistory[i]); } } String[] arrReplaceHistory = ids.getArray("nattable.FindReplaceDialog.replaceHistory"); if (arrReplaceHistory != null) { lstReplaceHistory.clear(); for (int i = 0; i < arrReplaceHistory.length; i++) { lstReplaceHistory.add(arrReplaceHistory[i]); } } } private void writeDialogSettings() { IDialogSettings ids = getDialogSettings(); ids.put("nattable.FindReplaceDialog.direction", backwardButton.getSelection()); ids.put("nattable.FindReplaceDialog.range", targetButton.getSelection()); ids.put("nattable.FindReplaceDialog.caseSensitive", caseSensitiveButton.getSelection()); ids.put("nattable.FindReplaceDialog.wholeWord", wholeWordButton.getSelection()); ids.put("nattable.FindReplaceDialog.regEx", regExButton.getSelection()); if (okToUse(cmbFind)) { String findString = cmbFind.getText(); if (findString.length() > 0) { lstFindHistory.add(0, findString); } writeHistory(lstFindHistory, ids, "nattable.FindReplaceDialog.findHistory"); } if (okToUse(cmbReplace)) { String replaceString = cmbReplace.getText(); if (replaceString.length() > 0) { lstReplaceHistory.add(0, replaceString); } writeHistory(lstReplaceHistory, ids, "nattable.FindReplaceDialog.replaceHistory"); } } /** * Writes the given history into the given dialog store. * * @param history the history * @param settings the dialog settings * @param sectionName the section name * @since 3.2 */ private void writeHistory(List<String> history, IDialogSettings settings, String sectionName) { int itemCount= history.size(); Set<String> distinctItems= new HashSet<String>(itemCount); for (int i= 0; i < itemCount; i++) { String item= (String)history.get(i); if (distinctItems.contains(item)) { history.remove(i--); itemCount--; } else { distinctItems.add(item); } } while (history.size() > 8) { history.remove(8); } String[] names= new String[history.size()]; history.toArray(names); settings.put(sectionName, names); } private IDialogSettings getDialogSettings() { IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings fDialogSettings = settings.getSection(getClass().getName()); if (fDialogSettings == null) fDialogSettings = settings.addNewSection(getClass().getName()); return fDialogSettings; } /** * Updates the given combo with the given content. * @param combo * combo to be updated * @param content * to be put into the combo */ private void updateCombo(Combo combo, List<String> content) { combo.removeAll(); for (int i = 0; i < content.size(); i++) { combo.add(content.get(i)); } } /** * Returns <code>true</code> if control can be used. * @param control * the control to be checked * @return <code>true</code> if control can be used */ private boolean okToUse(Control control) { return control != null && !control.isDisposed(); } /** * Called after executed find/replace action to update the history. */ private void updateFindAndReplaceHistory() { updateFindHistory(); if (okToUse(cmbReplace)) { updateHistory(cmbReplace, lstReplaceHistory); } } /** * Called after executed find action to update the history. */ private void updateFindHistory() { if (okToUse(cmbFind)) { updateHistory(cmbFind, lstFindHistory); } } /** * Updates the combo with the history. * @param combo * to be updated * @param history * to be put into the combo */ private void updateHistory(Combo combo, List<String> history) { String findString = combo.getText(); int index = history.indexOf(findString); if (index != 0) { if (index != -1) { history.remove(index); } history.add(0, findString); Point selection = combo.getSelection(); updateCombo(combo, history); combo.setText(findString); combo.setSelection(selection); } } }
37,859
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FindReplaceCommand.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/command/FindReplaceCommand.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.command; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.ICellSearchStrategy; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.ISearchStrategy; import net.sourceforge.nattable.command.ILayerCommand; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.ILayerListener; public class FindReplaceCommand implements ILayerCommand { private ILayer context; private final ISearchStrategy searchStrategy; private final String searchText; private final ICellSearchStrategy cellSearchStrategy; private ILayerListener searchEventListener; public FindReplaceCommand(ILayer layer, ISearchStrategy searchStrategy, ICellSearchStrategy cellSearchStrategy) { this(null, layer, searchStrategy, cellSearchStrategy); } public FindReplaceCommand(String searchText, ILayer layer, ISearchStrategy searchStrategy, ICellSearchStrategy cellSearchStrategy) { this.context = layer; this.searchStrategy = searchStrategy; this.searchText = searchText; this.cellSearchStrategy = cellSearchStrategy; } protected FindReplaceCommand(FindReplaceCommand command) { this.context = command.context; this.searchStrategy = command.searchStrategy; this.searchText = command.searchText; this.cellSearchStrategy = command.cellSearchStrategy; this.searchEventListener = command.searchEventListener; } public ILayer getContext() { return context; } public ISearchStrategy getSearchStrategy() { return searchStrategy; } public String getSearchText() { return searchText; } public ILayerListener getSearchEventListener() { return searchEventListener; } public void setSearchEventListener(ILayerListener listener) { this.searchEventListener = listener; } public ICellSearchStrategy getCellSearchStrategy() { return cellSearchStrategy; } public boolean convertToTargetLayer(ILayer targetLayer) { context = targetLayer; return true; } public FindReplaceCommand cloneCommand() { return new FindReplaceCommand(this); } }
2,081
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FindReplaceCommandHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/command/FindReplaceCommandHandler.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.command; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.bean.XliffEditorParameter; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiCellEditorControl; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.layer.LayerUtil; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.CellRegion; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.event.FindReplaceEvent; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.DefaultCellSearchStrategy; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.ICellSearchStrategy; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy.ISearchStrategy; import net.sourceforge.nattable.command.ILayerCommandHandler; import net.sourceforge.nattable.coordinate.PositionCoordinate; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.selection.SelectionLayer; import net.sourceforge.nattable.selection.command.SelectCellCommand; import net.sourceforge.nattable.viewport.ViewportLayer; import org.eclipse.jface.text.IRegion; public class FindReplaceCommandHandler implements ILayerCommandHandler<FindReplaceCommand> { private final SelectionLayer selectionLayer; private CellRegion searchResultCellRegion; public FindReplaceCommandHandler(SelectionLayer selectionLayer) { this.selectionLayer = selectionLayer; } public Class<FindReplaceCommand> getCommandClass() { return FindReplaceCommand.class; }; public boolean doCommand(ILayer targetLayer, FindReplaceCommand findReplaceCommand) { findReplaceCommand.convertToTargetLayer(targetLayer); ISearchStrategy searchStrategy = findReplaceCommand.getSearchStrategy(); if (findReplaceCommand.getSearchEventListener() != null) { selectionLayer.addLayerListener(findReplaceCommand.getSearchEventListener()); } PositionCoordinate anchor = selectionLayer.getSelectionAnchor(); if (anchor.columnPosition < 0 || anchor.rowPosition < 0) { anchor = new PositionCoordinate(selectionLayer, 0, 0); } searchStrategy.setContextLayer(targetLayer); Object dataValueToFind = null; if ((dataValueToFind = findReplaceCommand.getSearchText()) == null) { dataValueToFind = selectionLayer.getDataValueByPosition(anchor.columnPosition, anchor.rowPosition); } ICellSearchStrategy cellSearchStrategy = findReplaceCommand.getCellSearchStrategy(); searchStrategy.setCellSearchStrategy(cellSearchStrategy); DefaultCellSearchStrategy defaultCellSearchStrategy = null; if (cellSearchStrategy instanceof DefaultCellSearchStrategy) { defaultCellSearchStrategy = (DefaultCellSearchStrategy) cellSearchStrategy; } searchResultCellRegion = searchStrategy.executeSearch(dataValueToFind); if (searchResultCellRegion != null) { PositionCoordinate searchResultCellCoordinate = searchResultCellRegion.getPositionCoordinate(); int rowPosition = searchResultCellCoordinate.rowPosition; XLIFFEditorImplWithNatTable editor = XLIFFEditorImplWithNatTable.getCurrent(); ViewportLayer viewportLayer = LayerUtil.getLayer(editor.getTable(), ViewportLayer.class); HsMultiActiveCellEditor.commit(true); if (!editor.isHorizontalLayout()) { viewportLayer.doCommand(new SelectCellCommand(selectionLayer, searchResultCellCoordinate.columnPosition, rowPosition / 2 * 2, false, false)); } else { viewportLayer.doCommand(new SelectCellCommand(selectionLayer, searchResultCellCoordinate.columnPosition, rowPosition, false, false)); } HsMultiCellEditorControl.activeSourceAndTargetCell(editor); HsMultiActiveCellEditor.setCellEditorForceFocusByIndex(searchResultCellCoordinate.columnPosition, rowPosition); StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getFocusCellEditor(); if (cellEditor != null) { String dataValue = cellEditor.getSegmentViewer().getDocument().get(); if (dataValue != null) { int startOffset = -1; if (defaultCellSearchStrategy != null) { startOffset = defaultCellSearchStrategy.getStartOffset(); } defaultCellSearchStrategy.setStartOffset(startOffset); String findString = dataValueToFind.toString(); if (XliffEditorParameter.getInstance().isShowNonpirnttingCharacter()) { findString = findString.replaceAll("\\n", Constants.LINE_SEPARATOR_CHARACTER + "\n"); findString = findString.replaceAll("\\t", Constants.TAB_CHARACTER + "\u200B"); findString = findString.replaceAll(" ", Constants.SPACE_CHARACTER + "\u200B"); } IRegion region = defaultCellSearchStrategy.executeSearch(findString, dataValue); if (region != null) { HsMultiActiveCellEditor.setSelectionText(cellEditor, region.getOffset(), region.getLength()); } defaultCellSearchStrategy.setStartOffset(-1); } } } selectionLayer.fireLayerEvent(new FindReplaceEvent(searchResultCellRegion)); if (findReplaceCommand.getSearchEventListener() != null) { selectionLayer.removeLayerListener(findReplaceCommand.getSearchEventListener()); } return true; } }
5,353
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultCellSearchStrategy.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/strategy/DefaultCellSearchStrategy.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy; import net.heartsome.cat.common.ui.utils.InnerTagUtil; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.FindReplaceDocumentAdapter; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Position; /** * The comparator will base its comparison on the display value of a cell. The display value is assumed to be a string. */ public class DefaultCellSearchStrategy implements ICellSearchStrategy { public DefaultCellSearchStrategy() { } private boolean searchForward = true; private int startOffset = 0; private boolean caseSensitive; private boolean wholeWord; private boolean regExSearch; /** burke 修改find/replace界面修改 不需要fuzzySearch*/ //private boolean fuzzySearch; public IRegion executeSearch(String findValue, String dataValue) { // 如果查找的字符和单元格中的数据长度为 0,,则直接返回没有找到。 if (findValue == null || findValue.length() == 0 || dataValue == null || dataValue.length() == 0) { return null; } Document doc = new Document(dataValue); FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(doc); IRegion region; try { if (startOffset == -1) { if (searchForward) { startOffset = 0; } else { startOffset = adapter.length() - 1; } } region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch); while (region != null) { boolean inTag = false; for (int i = region.getOffset(); i < region.getOffset() + region.getLength(); i++) { Position tagRange = InnerTagUtil.getStyledTagRange(dataValue, i); if (tagRange != null) { if (searchForward) { if (tagRange.getOffset() + tagRange.getLength() == dataValue.length()) { return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。 } startOffset = tagRange.getOffset() + tagRange.getLength(); } else { if (tagRange.offset == 0) { return null; // 如果句首是一个标记,则直接返回 null,会继续查找上一个文本段。 } startOffset = tagRange.getOffset() - 1; } inTag = true; break; } } if (inTag) { region = adapter.find(startOffset, findValue, searchForward, caseSensitive, wholeWord, regExSearch); } else { break; } } return region; } catch (BadLocationException e) { return null; } } public boolean isCaseSensitive() { return caseSensitive; } public boolean isWholeWord() { return wholeWord; } public boolean isRegExSearch() { return regExSearch; } /** burke 修改find/replace界面修改 不需要fuzzySearch*/ /*public boolean isFuzzySearch() { return fuzzySearch; }*/ public boolean isSearchForward() { return searchForward; } public int getStartOffset() { return startOffset; } public void setStartOffset(int startOffset) { this.startOffset = startOffset; } /** burke 修改find/replace界面修改 不需要fuzzySearch*/ /*public void init(boolean searchForward, boolean caseSensitive, boolean wholeWord, boolean regExSearch, boolean fuzzySearch, int startOffset) {*/ public void init(boolean searchForward, boolean caseSensitive, boolean wholeWord, boolean regExSearch, int startOffset) { this.searchForward = searchForward; this.caseSensitive = caseSensitive; this.wholeWord = wholeWord; this.regExSearch = regExSearch; /** burke 修改find/replace界面修改 不需要fuzzySearch*/ //this.fuzzySearch = fuzzySearch; this.startOffset = startOffset; } }
3,730
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ICellSearchStrategy.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/strategy/ICellSearchStrategy.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy; import org.eclipse.jface.text.IRegion; public interface ICellSearchStrategy { IRegion executeSearch(String firstValue, String secondValue); /** burke 修改find/replace界面框 修改 不需要fuzzySearch*/ //void init(boolean searchForward, boolean caseSensitive, boolean wholeWord, boolean regExSearch, boolean fuzzySearch, int startOffset); void init(boolean searchForward, boolean caseSensitive, boolean wholeWord, boolean regExSearch, int startOffset); boolean isSearchForward(); }
569
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ISearchStrategy.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/strategy/ISearchStrategy.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.CellRegion; import net.sourceforge.nattable.layer.ILayer; public interface ISearchStrategy { CellRegion executeSearch(Object valueToMatch); void setContextLayer(ILayer contextLayer); ILayer getContextLayer(); ICellSearchStrategy getCellSearchStrategy(); void setCellSearchStrategy(ICellSearchStrategy cellSearchStrategy); }
493
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ColumnSearchStrategy.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/strategy/ColumnSearchStrategy.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.CellRegion; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.coordinate.PositionCoordinate; import net.sourceforge.nattable.layer.ILayer; public class ColumnSearchStrategy implements ISearchStrategy { private ILayer contextLayer; private int[] columnPositions; private int startingRowPosition; private final XLIFFEditorImplWithNatTable xliffEditor; private final IConfigRegistry configRegistry; private ICellSearchStrategy cellSearchStrategy; private boolean isHorizontalLayout; public ColumnSearchStrategy(int[] columnPositions, XLIFFEditorImplWithNatTable xliffEditor) { this(columnPositions, 0, xliffEditor); } public ColumnSearchStrategy(int[] columnPositions, int startingRowPosition, XLIFFEditorImplWithNatTable xliffEditor) { this.columnPositions = columnPositions; this.startingRowPosition = startingRowPosition; this.xliffEditor = xliffEditor; this.configRegistry = xliffEditor.getTable().getConfigRegistry(); } public CellRegion executeSearch(Object valueToMatch) { return CellDisplayValueSearchUtil.findCell(getContextLayer(), configRegistry, getColumnCellsToSearch(getContextLayer()), valueToMatch, getCellSearchStrategy()); } public void setStartingRowPosition(int startingRowPosition) { this.startingRowPosition = startingRowPosition; } public void setColumnPositions(int[] columnPositions) { this.columnPositions = columnPositions; isHorizontalLayout = xliffEditor.isHorizontalLayout(); } protected PositionCoordinate[] getColumnCellsToSearch(ILayer contextLayer) { List<PositionCoordinate> cellsToSearch = new ArrayList<PositionCoordinate>(); int rowPosition = startingRowPosition; // See how many rows we can add, depends on where the search is starting from final int rowCount = contextLayer.getRowCount(); int height = rowCount; boolean searchForward = getCellSearchStrategy().isSearchForward(); if (searchForward) { height = height - startingRowPosition; } else { height = startingRowPosition; } for (int columnIndex = 0; columnIndex < columnPositions.length; columnIndex++) { final int startingColumnPosition = columnPositions[columnIndex]; if (!searchForward) { cellsToSearch.addAll(CellDisplayValueSearchUtil.getDescendingCellCoordinates(getContextLayer(), startingColumnPosition, rowPosition, 1, height, isHorizontalLayout)); rowPosition = rowCount - 1; } else { cellsToSearch.addAll(CellDisplayValueSearchUtil.getCellCoordinates(getContextLayer(), startingColumnPosition, rowPosition, 1, height, isHorizontalLayout)); rowPosition = 0; } height = rowCount; // After first column is set, start the next column from the top } return cellsToSearch.toArray(new PositionCoordinate[0]); } public ILayer getContextLayer() { return contextLayer; } public void setContextLayer(ILayer contextLayer) { this.contextLayer = contextLayer; } public ICellSearchStrategy getCellSearchStrategy() { return cellSearchStrategy; } public void setCellSearchStrategy(ICellSearchStrategy cellSearchStrategy) { this.cellSearchStrategy = cellSearchStrategy; } }
3,513
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CellDisplayValueSearchUtil.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/strategy/CellDisplayValueSearchUtil.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.strategy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.heartsome.cat.ts.ui.xliffeditor.nattable.config.VerticalNatTableConfig; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.TagDisplayConverter; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.CellRegion; import net.sourceforge.nattable.config.CellConfigAttributes; import net.sourceforge.nattable.config.IConfigRegistry; import net.sourceforge.nattable.coordinate.PositionCoordinate; import net.sourceforge.nattable.data.convert.IDisplayConverter; import net.sourceforge.nattable.layer.ILayer; import net.sourceforge.nattable.layer.cell.LayerCell; import net.sourceforge.nattable.style.DisplayMode; import org.eclipse.jface.text.IRegion; public class CellDisplayValueSearchUtil { static List<PositionCoordinate> getCellCoordinates(ILayer contextLayer, int startingColumnPosition, int startingRowPosition, int width, int height, boolean isHorizontalLayout) { if (!isHorizontalLayout) { height = (int) Math.ceil(height * 1.0 / VerticalNatTableConfig.ROW_SPAN); } List<PositionCoordinate> coordinates = new ArrayList<PositionCoordinate>(); for (int columnPosition = 0; columnPosition < width; columnPosition++) { for (int rowPosition = 0; rowPosition < height; rowPosition++) { PositionCoordinate coordinate = new PositionCoordinate(contextLayer, startingColumnPosition, startingRowPosition); coordinates.add(coordinate); startingRowPosition += isHorizontalLayout ? 1 : VerticalNatTableConfig.ROW_SPAN; } startingColumnPosition++; } return coordinates; } static List<PositionCoordinate> getDescendingCellCoordinates(ILayer contextLayer, int startingColumnPosition, int startingRowPosition, int width, int height, boolean isHorizontalLayout) { if (!isHorizontalLayout) { width = width / VerticalNatTableConfig.ROW_SPAN; } List<PositionCoordinate> coordinates = new ArrayList<PositionCoordinate>(); for (int columnPosition = width; columnPosition >= 0 && startingColumnPosition >= 0; columnPosition--) { for (int rowPosition = height; rowPosition >= 0 && startingRowPosition >= 0; rowPosition--) { PositionCoordinate coordinate = new PositionCoordinate(contextLayer, startingColumnPosition, startingRowPosition); coordinates.add(coordinate); startingRowPosition -= isHorizontalLayout ? 1 : VerticalNatTableConfig.ROW_SPAN; } startingColumnPosition--; } return coordinates; } static CellRegion findCell(final ILayer layer, final IConfigRegistry configRegistry, final PositionCoordinate[] cellsToSearch, final Object valueToMatch, final ICellSearchStrategy cellSearchStrategy) { final List<PositionCoordinate> cellCoordinates = Arrays.asList(cellsToSearch); // Find cell CellRegion targetCoordinate = null; String stringValue = valueToMatch.toString(); final IDisplayConverter displayConverter = configRegistry .getConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, DisplayMode.NORMAL, XLIFFEditorImplWithNatTable.SOURCE_EDIT_CELL_LABEL); for (int cellIndex = 0; cellIndex < cellCoordinates.size(); cellIndex++) { final PositionCoordinate cellCoordinate = cellCoordinates.get(cellIndex); final int columnPosition = cellCoordinate.columnPosition; final int rowPosition = cellCoordinate.rowPosition; // Convert cell's data if (displayConverter instanceof TagDisplayConverter) { LayerCell cell = new LayerCell(cellCoordinate.getLayer(), cellCoordinate.getColumnPosition(), cellCoordinate.getRowPosition()); ((TagDisplayConverter) displayConverter).setCell(cell); } final Object dataValue = displayConverter.canonicalToDisplayValue(layer.getDataValueByPosition( columnPosition, rowPosition)); // Compare with valueToMatch if (dataValue instanceof String) { String dataValueString = dataValue.toString(); IRegion region; if ((region = cellSearchStrategy.executeSearch(stringValue, dataValueString)) != null) { targetCoordinate = new CellRegion(cellCoordinate, region); break; } ((DefaultCellSearchStrategy)cellSearchStrategy).setStartOffset(-1); } } return targetCoordinate; } }
4,369
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FindReplaceEvent.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/search/event/FindReplaceEvent.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.search.event; import net.heartsome.cat.ts.ui.xliffeditor.nattable.search.coordinate.CellRegion; import net.sourceforge.nattable.layer.event.AbstractContextFreeEvent; public class FindReplaceEvent extends AbstractContextFreeEvent { private final CellRegion cellRegion; public FindReplaceEvent(CellRegion cellRegion) { this.cellRegion = cellRegion; } public CellRegion getCellRegion() { return cellRegion; } public FindReplaceEvent cloneEvent() { return new FindReplaceEvent(cellRegion); } }
562
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AutomaticQATrigger.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/qa/AutomaticQATrigger.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.qa; import net.heartsome.cat.ts.core.file.XLFHandler; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SafeRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 自动品质检查的扩展触发类 * @author robert 2012-??-?? */ public class AutomaticQATrigger { private static final Logger LOGGER = LoggerFactory.getLogger(AutomaticQATrigger.class); private IAutomaticQA autoQA; private static final String CONSTANT_automaticQA_EXTENSION_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.extension.automaticQA"; public AutomaticQATrigger(XLFHandler handler) { runExtension(); if (checkAutoQA()) { autoQA.setInitData(handler); } } /** * 开始进行自动品质检查 * * @param isAddToDb * 若为true,则是入库操作,若false,则为批准操作 */ public String beginAutoQa(boolean isAddToDb, String rowId, boolean needInitQAResultViewer) { if (!checkAutoQA()) { return ""; } return autoQA.beginAutoQa(isAddToDb, rowId, needInitQAResultViewer); } public boolean checkAutoQA() { if (autoQA == null) { return false; } return true; } public void bringQAResultViewerToTop(){ autoQA.bringQAResultViewerToTop(); } public void informQAEndFlag(){ autoQA.informQAEndFlag(); } /** * 加载自动品质检查的扩展 */ private void runExtension() { IConfigurationElement[] config = Platform.getExtensionRegistry() .getConfigurationElementsFor(CONSTANT_automaticQA_EXTENSION_ID); try { for (IConfigurationElement e : config) { final Object o = e.createExecutableExtension("class"); if (o instanceof IAutomaticQA) { ISafeRunnable runnable = new ISafeRunnable() { public void handleException(Throwable exception) { exception.printStackTrace(); } public void run() throws Exception { autoQA = (IAutomaticQA) o; } }; SafeRunner.run(runnable); } } } catch (CoreException e) { LOGGER.error("", e); e.printStackTrace(); } } }
2,242
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
RealTimeSpellCheckTrigger.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/qa/RealTimeSpellCheckTrigger.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.qa; import java.util.List; import net.heartsome.cat.ts.core.bean.SingleWord; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SafeRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * nattable 编辑界面实时检查触发类 * @author robert 2013-01-21 */ public class RealTimeSpellCheckTrigger { private static RealTimeSpellCheckTrigger instance = null; private IRealTimeSpellCheck realTimeSpell; /** 这是实时检查的扩展点 id */ private static final String CONSTANT_realTimeSpell_extentionId = "net.heartsome.cat.ts.ui.xliffeditor.nattable.extension.realTimeSpellCheck"; private static final Logger LOGGER = LoggerFactory.getLogger(RealTimeSpellCheckTrigger.class.getName()); private RealTimeSpellCheckTrigger(){ if (realTimeSpell == null) { runExtension(); } if (realTimeSpell == null) { // TODO ... } } public static RealTimeSpellCheckTrigger getInstance(){ if (instance == null) { instance = new RealTimeSpellCheckTrigger(); } return instance; } /** * 检查拼写检查是否可用,分为四种情况,<br> * 1、Spell 实例是否为空,由 trigger 类控制<br> * 2、系统是否选择勾选实时检查。<br> * 3、当前拼写检查器是否支持当前语种的拼写检查。<br> * 4、拼写检查器是否运行错误,或者配置错误。<br> * @return */ public boolean checkSpellAvailable(String language){ if (realTimeSpell == null) { return false; } if (!realTimeSpell.checkLangAvailable(language)) { return false; } return true; } /** * 获取错误的单词 * @param text * @param targetLanguage * @return */ public List<SingleWord> getErrorWords(String tgtText, String targetLanguage){ return realTimeSpell.getErrorWords(tgtText, targetLanguage); } /** * 加哉实时拼写检查 ; */ private void runExtension() { IConfigurationElement[] config = Platform.getExtensionRegistry() .getConfigurationElementsFor(CONSTANT_realTimeSpell_extentionId); try { for (IConfigurationElement e : config) { final Object o = e.createExecutableExtension("class"); if (o instanceof IRealTimeSpellCheck) { ISafeRunnable runnable = new ISafeRunnable() { public void handleException(Throwable exception) { exception.printStackTrace(); } public void run() throws Exception { realTimeSpell = (IRealTimeSpellCheck) o; } }; SafeRunner.run(runnable); } } } catch (CoreException e) { LOGGER.error("", e); e.printStackTrace(); } } }
2,793
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IRealTimeSpellCheck.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/qa/IRealTimeSpellCheck.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.qa; import java.util.List; import net.heartsome.cat.ts.core.bean.SingleWord; /** * 实时检查的接口 * @author robert 2013-01-21 */ public interface IRealTimeSpellCheck { /** * 根据传入的文本段以及语种,获取错误的单词 * @param tgtText ,这是获取的带标记的目标文本段 */ List<SingleWord> getErrorWords(String tgtText, String language); /** * 根据传入的语言,检查当前拼写检查器是否支持 * @param language * @return */ boolean checkLangAvailable(String language); }
604
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IAutomaticQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/qa/IAutomaticQA.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.qa; import net.heartsome.cat.ts.core.file.XLFHandler; /** * 自动品质检查的接口 * @author robert 2012-05-16 */ public interface IAutomaticQA { /** * 开始自动品质检查 * @param isAddToDb * @param rowId * @return */ public String beginAutoQa(boolean isAddToDb, String rowId, boolean needInitQAResultViewer); public void setInitData(XLFHandler handler); /** * 激活品质检查视图 */ public void bringQAResultViewerToTop(); /** 通知本次品质检查已经结束 */ public void informQAEndFlag(); }
596
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/resource/Messages.java
package net.heartsome.cat.ts.ui.xliffeditor.nattable.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 国际化工具类 * @author peason * @version * @since JDK1.6 */ public class Messages { private static final String BUNDLE_NAME = "net.heartsome.cat.ts.ui.xliffeditor.nattable.resource.nattable"; private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); public static String getString(String key) { try { return BUNDLE.getString(key); } catch (MissingResourceException e) { return key; } } }
591
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImageConstant.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/resource/ImageConstant.java
/** * ImageConstant.java * * Version information : * * Date:Mar 15, 2012 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.xliffeditor.nattable.resource; /** * @author Jason * @version * @since JDK1.6 */ public final class ImageConstant { // XLIFFEDITOR右键菜单 public final static String TU_STATE_SEARCHTM = "images/state/search-tm.png"; public final static String TU_STATE_SEARCHTB = "images/state/search-tb.png"; public final static String TU_STATE_ADDNOTE = "images/state/add-note.png"; public final static String TU_STATE_EDITNOTE = "images/state/edit-note.png"; public final static String TU_STATE_DELETENOTE = "images/edit/delete note.png"; // delete segment translation public final static String TU_STATE_DELETETRANS = "images/edit/delete translation.png"; /** 工具栏->改变布局的水平布局图片路径 */ public final static String TOOL_LAYOUT_HORIZONTAL = "images/tool/horizontal.png"; /** 工具栏->改变布局的垂直布局图片路径 */ public final static String TOOL_LAYOUT_VERTICAL = "images/tool/vertical.png"; public final static String WEB_SEARCH = "images/websearch/websearch16.png"; }
1,682
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.lockrepeat/src/net/heartsome/cat/ts/lockrepeat/Activator.java
package net.heartsome.cat.ts.lockrepeat; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "net.heartsome.cat.ts.lockrepeat"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given * plug-in relative path * * @param path the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } }
1,384
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LockRepeatedSegmentDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.lockrepeat/src/net/heartsome/cat/ts/lockrepeat/dialog/LockRepeatedSegmentDialog.java
package net.heartsome.cat.ts.lockrepeat.dialog; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.lockrepeat.Activator; import net.heartsome.cat.ts.lockrepeat.resource.ImageConstant; import net.heartsome.cat.ts.lockrepeat.resource.Messages; import net.heartsome.cat.ts.ui.composite.DialogLogoCmp; import org.eclipse.core.resources.IFile; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; /** * 锁定重复文本段对话框 * @author weachy * @version * @since JDK1.5 */ public class LockRepeatedSegmentDialog extends Dialog { /** XLIFF 文件 */ private List<IFile> xliffFiles; /** 文件列表 */ private TableViewer tableViewer; /** 对话框标题 */ private String title; /** 锁定内部重复 */ private Button btnLockInnerRepeat; /** 锁定外部100%匹配 */ private Button btnLockTM100; /** 锁定外部101%匹配 */ private Button btnLockTM101; private Image logoImage = Activator.getImageDescriptor(ImageConstant.TRANSLATE_LOCKREPEATED_LOGO).createImage(); public LockRepeatedSegmentDialog(Shell parentShell, List<IFile> xliffFiles, String title) { super(parentShell); this.xliffFiles = xliffFiles; this.title = title; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(title); } @Override protected boolean isResizable() { return false; } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); Button btnOK = getButton(IDialogConstants.OK_ID); btnOK.setText(Messages.getString("dialog.LockRepeatedSegmentDialog.ok")); Button cancelBtn = getButton(IDialogConstants.CANCEL_ID); cancelBtn.setText(Messages.getString("dialog.LockRepeatedSegmentDialog.cancel")); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true); parentData.widthHint = 600; parentData.heightHint = 350; tparent.setLayoutData(parentData); GridLayoutFactory.fillDefaults().extendedMargins(-1, -1, -1, 8).numColumns(1).applyTo(tparent); createLogoArea(tparent); createFileDataGroup(tparent); return parent; } /** * 显示图片区 * @param parent */ public void createLogoArea(Composite parent) { new DialogLogoCmp(parent, SWT.NONE, title, Messages.getString("dialog.LockRepeatedSegmentResultDialog.desc"), logoImage); } /** * @param parent */ public void createFileDataGroup(Composite parent) { Composite parentCmp = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(9, 9, 0, 0).numColumns(1).applyTo(parentCmp); GridDataFactory.fillDefaults().grab(true, true).applyTo(parentCmp); tableViewer = new TableViewer(parentCmp, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); final Table table = tableViewer.getTable(); GridData tableData = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH); tableData.heightHint = 50; table.setLayoutData(tableData); table.setLinesVisible(true); table.setHeaderVisible(true); String[] columnNames = new String[] { Messages.getString("dialog.LockRepeatedSegmentDialog.columnNames1"), Messages.getString("dialog.LockRepeatedSegmentDialog.columnNames2") }; int[] columnAlignments = new int[] { SWT.LEFT, SWT.LEFT }; for (int i = 0; i < columnNames.length; i++) { TableColumn tableColumn = new TableColumn(table, columnAlignments[i]); tableColumn.setText(columnNames[i]); tableColumn.setWidth(50); } tableViewer.setLabelProvider(new TableViewerLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.setInput(getTableData()); // 让列表列宽动态变化 table.addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { final Table table = ((Table) event.widget); final TableColumn[] columns = table.getColumns(); event.widget.getDisplay().syncExec(new Runnable() { public void run() { double[] columnWidths = new double[] { 0.1, 0.8 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); tableViewer.getTable().setFocus(); btnLockInnerRepeat = new Button(parentCmp, SWT.CHECK); btnLockInnerRepeat.setText(Messages.getString("dialog.LockRepeatedSegmentDialog.btnLockInnerRepeat")); btnLockInnerRepeat.setSelection(true); btnLockTM100 = new Button(parentCmp, SWT.CHECK); btnLockTM100.setText(Messages.getString("dialog.LockRepeatedSegmentDialog.btnLockTM100")); btnLockTM100.setSelection(true); if (CommonFunction.checkEdition("U")) { btnLockTM101 = new Button(parentCmp, SWT.CHECK); btnLockTM101.setText(Messages.getString("dialog.LockRepeatedSegmentDialog.btnLockTM101")); btnLockTM101.setSelection(true); } } @Override protected void okPressed() { lockInnerRepeatedSegment = btnLockInnerRepeat.getSelection(); lockTM100Segment = btnLockTM100.getSelection(); if (CommonFunction.checkEdition("U")) { lockTM101Segment = btnLockTM101.getSelection(); } else { lockTM101Segment = false; } super.okPressed(); } private boolean lockInnerRepeatedSegment; private boolean lockTM100Segment; private boolean lockTM101Segment; /** * 是否锁定内部重复文本段 * @return ; */ public boolean isLockInnerRepeatedSegment() { return lockInnerRepeatedSegment; } /** * 是否锁定记忆库完全匹配 * @return ; */ public boolean isLockTM100Segment() { return lockTM100Segment; } /** * 是否锁定记忆库上下文匹配 * @return ; */ public boolean isLockTM101Segment() { return lockTM101Segment; } /** * 获取tableViewer的填充内容 * @return */ public String[][] getTableData() { ArrayList<String[]> tableDataList = new ArrayList<String[]>(); for (int i = 0; i < xliffFiles.size(); i++) { String[] tableInfo = new String[] { "" + (i + 1), xliffFiles.get(i).getFullPath().toOSString() }; tableDataList.add(tableInfo); } return tableDataList.toArray(new String[][] {}); } /** * tableViewer的标签提供器 */ class TableViewerLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof String[]) { String[] array = (String[]) element; return array[columnIndex]; } return null; } } @Override public boolean close() { if(logoImage != null && !logoImage.isDisposed()){ logoImage.dispose(); } return super.close(); } }
7,628
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LockRepeatedSegmentResultDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.lockrepeat/src/net/heartsome/cat/ts/lockrepeat/dialog/LockRepeatedSegmentResultDialog.java
/** * PreTranslationResultDialog.java * * Version information : * * Date:Oct 20, 2011 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.lockrepeat.dialog; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.lockrepeat.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; /** * 锁定重复文本段结果对话框 * @author weachy * @version * @since JDK1.5 */ public class LockRepeatedSegmentResultDialog extends Dialog { private TableViewer tableViewer; private List<IFile> filesPath; private Map<String, Integer> lockedInnerRepeatedResault; private Map<String, Integer> lockedFullMatchResult; private Map<String, Integer> lockedContextResult; private Map<String, Integer> tuNumResult; /** * Create the dialog. * @param parentShell */ public LockRepeatedSegmentResultDialog(Shell parentShell, List<IFile> filesPath) { super(parentShell); this.filesPath = filesPath; lockedInnerRepeatedResault = Collections.EMPTY_MAP; lockedFullMatchResult = Collections.EMPTY_MAP; lockedContextResult = Collections.EMPTY_MAP; tuNumResult = Collections.EMPTY_MAP; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("dialog.LockRepeatedSegmentResultDialog.title")); } /** * Create contents of the dialog. * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); container.setLayout(new GridLayout(1, false)); Composite composite = new Composite(container, SWT.NONE); GridLayout gl_composite = new GridLayout(1, false); gl_composite.verticalSpacing = 0; gl_composite.marginWidth = 0; gl_composite.marginHeight = 0; composite.setLayout(gl_composite); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); tableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL); Table table = tableViewer.getTable(); GridData tableGd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); tableGd.heightHint = 220; table.setLayoutData(tableGd); table.setLinesVisible(true); table.setHeaderVisible(true); String[] clmnTitles = new String[] { Messages.getString("dialog.LockRepeatedSegmentResultDialog.clmnTitles1"), Messages.getString("dialog.LockRepeatedSegmentResultDialog.clmnTitles2"), Messages.getString("dialog.LockRepeatedSegmentResultDialog.clmnTitles3"), Messages.getString("dialog.LockRepeatedSegmentResultDialog.clmnTitles4"), Messages.getString("dialog.LockRepeatedSegmentResultDialog.clmnTitles5"), Messages.getString("dialog.LockRepeatedSegmentResultDialog.clmnTitles6") }; int[] clmnBounds = { 60, 200, 100, 110, 110, 110 }; for (int i = 0; i < clmnTitles.length; i++) { createTableViewerColumn(tableViewer, clmnTitles[i], clmnBounds[i], i); } tableViewer.setLabelProvider(new TableViewerLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.setInput(this.getTableViewerInput()); return container; } /** * Create contents of the button bar. * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT); } private String[][] getTableViewerInput() { List<String[]> rows = new ArrayList<String[]>(); int i = 1; for (IFile iFile : filesPath) { String workspacePath = iFile.getFullPath().toOSString(); String xlfPath = ResourceUtils.iFileToOSPath(iFile); Object tmp = tuNumResult.get(xlfPath); String tuSum = tmp == null ? "0" : tmp.toString(); tmp = lockedInnerRepeatedResault.get(xlfPath); String lockedInnerRepeatedNum = tmp == null ? "0" : tmp.toString(); tmp = lockedFullMatchResult.get(xlfPath); String lockedFullMatchNum = tmp == null ? "0" : tmp.toString(); tmp = lockedContextResult.get(xlfPath); String lockedContextMatchNum = tmp == null ? "0" : tmp.toString(); String[] row = new String[] { String.valueOf(i++), workspacePath, tuSum, lockedInnerRepeatedNum, lockedContextMatchNum, lockedFullMatchNum }; rows.add(row); } return rows.toArray(new String[][] {}); } /** * 设置TableViewer 列属性 * @param viewer * @param title * 列标题 * @param bound * 列宽 * @param colNumber * 列序号 * @return {@link TableViewerColumn}; */ private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) { final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize); final TableColumn column = viewerColumn.getColumn(); column.setText(title); column.setWidth(bound); column.setResizable(true); column.setMoveable(true); return viewerColumn; } /** * tableViewer的标签提供器 * @author Jason */ class TableViewerLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof String[]) { String[] array = (String[]) element; return array[columnIndex]; } return null; } } /** * @param tableViewer * the tableViewer to set */ public void setTableViewer(TableViewer tableViewer) { this.tableViewer = tableViewer; } /** * @param lockedInnerRepeatedResault * the lockedInnerRepeatedResault to set; */ public void setLockedInnerRepeatedResault(Map<String, Integer> lockedInnerRepeatedResault) { this.lockedInnerRepeatedResault = lockedInnerRepeatedResault; } /** * @param lockedFullMatchResult * the lockedFullMatchResult to set */ public void setLockedFullMatchResult(Map<String, Integer> lockedFullMatchResult) { this.lockedFullMatchResult = lockedFullMatchResult; } /** * @param lockedContextResult * the lockedContextResult to set */ public void setLockedContextResult(Map<String, Integer> lockedContextResult) { this.lockedContextResult = lockedContextResult; } /** * @param tuNumResult * the tuNumResult to set */ public void setTuNumResult(Map<String, Integer> tuNumResult) { this.tuNumResult = tuNumResult; } public int getLockedContextResult(String filePath){ if(null ==this.lockedContextResult || this.lockedContextResult.isEmpty() ){ return -1; } return this.lockedContextResult.get(filePath); } public int getLockedFullMatchResult(String filePath){ if(null ==this.lockedFullMatchResult || this.lockedFullMatchResult.isEmpty() ){ return -1; } return this.lockedFullMatchResult.get(filePath); } public int getLockedInnerRepeatedResault(String filePath){ if(null ==this.lockedInnerRepeatedResault || this.lockedInnerRepeatedResault.isEmpty()){ return -1; } return this.lockedInnerRepeatedResault.get(filePath); } }
8,577
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LockRepeatedSegmentHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.lockrepeat/src/net/heartsome/cat/ts/lockrepeat/handler/LockRepeatedSegmentHandler.java
package net.heartsome.cat.ts.lockrepeat.handler; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.common.core.Constant; import net.heartsome.cat.common.file.XLFValidator; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.common.ui.handlers.AbstractSelectProjectFilesHandler; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.lockrepeat.dialog.LockRepeatedSegmentDialog; import net.heartsome.cat.ts.lockrepeat.dialog.LockRepeatedSegmentResultDialog; import net.heartsome.cat.ts.lockrepeat.resource.Messages; import net.heartsome.cat.ts.tm.match.TmMatcher; import net.heartsome.cat.ts.ui.util.MultiFilesOper; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 锁定重复文本段 (修改者:robert 2012-03-24) * @author weachy * @version * @since JDK1.5 */ public class LockRepeatedSegmentHandler extends AbstractSelectProjectFilesHandler { private static final Logger LOGGER = LoggerFactory.getLogger(LockRepeatedSegmentHandler.class); private static final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; private IWorkbenchWindow window; /** 标识某文件是否被锁定 */ private boolean isLocked; private List<IFile> list = new ArrayList<IFile>(); private XLIFFEditorImplWithNatTable nattable; /** 在针对非编辑器打开文件的情况下,是否单个处理 */ private boolean continuee; private XLIFFEditorImplWithNatTable singleNattable; /** 记忆库操作类,用来查询记忆库的数据 */ private TmMatcher tmMatcher; private IProject curProject; /** 是否退出操作 */ private boolean isCancel; /** * 是否内部重复锁定 */ private boolean isLockInnerRepeatedSegment; /** * 是否完全匹配锁定 */ private boolean isLockTM100Segment; /** * 是否上下文锁定 */ private boolean isLockTM101Segment; @Override public Object execute(final ExecutionEvent event, final List<IFile> iFileList) { list = iFileList; tmMatcher = new TmMatcher(); isCancel = false; continuee = true; isLocked = false; if (list == null || list.isEmpty()) { if (list.size() == 0) { MessageDialog.openInformation(shell, Messages.getString("translation.LockRepeatedSegmentHandler.msgTitle"), Messages.getString("translation.LockRepeatedSegmentHandler.msg1")); return null; } return null; } try { window = HandlerUtil.getActiveWorkbenchWindowChecked(event); } catch (ExecutionException e1) { LOGGER.error("", e1); e1.printStackTrace(); } // 首先验证是否是合并打开的文件 --robert if (isEditor) { IEditorReference[] editorRefe = window.getActivePage().findEditors(new FileEditorInput(list.get(0)), XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); if (editorRefe.length <= 0) { return null; } nattable = (XLIFFEditorImplWithNatTable) editorRefe[0].getEditor(true); // 针对合并打开 if (nattable.isMultiFile()) { list = ResourceUtils.filesToIFiles(nattable.getMultiFileList()); } } // 添加验证 peason List<IFile> lstFiles = new ArrayList<IFile>(); XLFValidator.resetFlag(); for (IFile iFile : list) { if (!XLFValidator.validateXliffFile(iFile)) { lstFiles.add(iFile); } } XLFValidator.resetFlag(); if (!(list instanceof ArrayList)) { list = new ArrayList<IFile>(list); } list.removeAll(lstFiles); if (list.size() == 0) { return null; } CommonFunction.removeRepeateSelect(list); final LockRepeatedSegmentDialog dialog = new LockRepeatedSegmentDialog(shell, list, Messages.getString("translation.LockRepeatedSegmentHandler.dialog")); if (dialog.open() == LockRepeatedSegmentDialog.OK) { isLockInnerRepeatedSegment =dialog.isLockInnerRepeatedSegment(); isLockTM100Segment =dialog.isLockTM100Segment(); isLockTM101Segment=dialog.isLockTM101Segment(); if (!dialog.isLockInnerRepeatedSegment() && !dialog.isLockTM100Segment() && !dialog.isLockTM101Segment()) { // “锁定内部”、“锁定100%”、“锁定101%”都未选中。 return null; } if (!isEditor) { // 如果针对单个文件, 先验证是否有合并打开的 MultiFilesOper oper = new MultiFilesOper(list.get(0).getProject(), (ArrayList<IFile>) list); // 如果有合并打开的文件,那么将这种转换成针对编辑器的方式处理 if (oper.validExist()) { final IFile multiTempIFile = oper.getMultiFilesTempIFile(true); IEditorReference[] editorRefe = window.getActivePage().findEditors( new FileEditorInput(multiTempIFile), XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); // 如果这几个文件没有合并打开, if (editorRefe.length > 0) { nattable = (XLIFFEditorImplWithNatTable) editorRefe[0].getEditor(true); continuee = false; } } } // 开始进行处理 IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { int totalWork = dialog.isLockInnerRepeatedSegment() ? list.size() : 0; totalWork = (dialog.isLockTM100Segment() || dialog.isLockTM101Segment()) ? totalWork * 2 : totalWork; monitor.beginTask(Messages.getString("translation.LockRepeatedSegmentHandler.task1"), totalWork); // 修改结果显示为是否成功 final LockRepeatedSegmentResultDialog lrsrd = new LockRepeatedSegmentResultDialog(shell, list); // 是否进行外部匹配 boolean checkTM = false; curProject = list.get(0).getProject(); // 锁定外部完全匹配与外部上下文匹配 if ((dialog.isLockTM100Segment() || dialog.isLockTM101Segment())) { // 如果是针对编辑器,那么将里面的文件进行统一处理 if (isEditor) { LockTMSegment lts = lockTMSegmentOFEditor(list, dialog.isLockTM100Segment(), dialog.isLockTM101Segment(), monitor); // 用户指定退出操作 if (lts == null && isCancel) { return; } lrsrd.setLockedFullMatchResult(lts.getLockedFullMatchResult()); lrsrd.setLockedContextResult(lts.getLockedContextResult()); lrsrd.setTuNumResult(lts.getTuNumResult()); checkTM = true; } else { if (continuee) { Map<String, Integer> lockedFullMatchResultMap = new HashMap<String, Integer>(); Map<String, Integer> lockedContextMatchResultMap = new HashMap<String, Integer>(); Map<String, Integer> lockedTuNumResultMap = new HashMap<String, Integer>(); for (int i = 0; i < list.size(); i++) { IFile iFile = list.get(i); LockTMSegment lts = lockTMSegment(Arrays.asList(iFile), dialog.isLockTM100Segment(), dialog.isLockTM101Segment(), monitor); if (lts == null && isCancel) { return; } // 返回的为空,是解析异常的文件被删除了。 if (lts != null) { lockedFullMatchResultMap.putAll(lts.getLockedFullMatchResult()); lockedContextMatchResultMap.putAll(lts.getLockedContextResult()); lockedTuNumResultMap.putAll(lts.getTuNumResult()); } else { i--; } } lrsrd.setLockedFullMatchResult(lockedFullMatchResultMap); lrsrd.setLockedContextResult(lockedContextMatchResultMap); lrsrd.setTuNumResult(lockedTuNumResultMap); checkTM = true; } else { LockTMSegment lts = lockTMSegmentOFEditor(list, dialog.isLockTM100Segment(), dialog.isLockTM101Segment(), monitor); if (lts == null && isCancel) { return; } lrsrd.setLockedFullMatchResult(lts.getLockedFullMatchResult()); lrsrd.setLockedContextResult(lts.getLockedContextResult()); lrsrd.setTuNumResult(lts.getTuNumResult()); checkTM = true; } } } // 锁定内部重复 if (dialog.isLockInnerRepeatedSegment()) { SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, list.size(), SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); HashMap<String, Integer> lockedInnerRepeatedResault = new HashMap<String, Integer>(); HashMap<String, Integer> tuNumResult = null; if (!checkTM) { tuNumResult = new HashMap<String, Integer>(); } Map<String, int[]> resMap = lockInnerRepeatedSegment(list, subMonitor, checkTM); for (IFile iFile : list) { String filePath = ResourceUtils.iFileToOSPath(iFile); int[] res = resMap.get(filePath); if (!checkTM) { int countTU = res[0]; tuNumResult.put(filePath, countTU); } int countLockedInnerRepeatedSegment = res[1]; lockedInnerRepeatedResault.put(filePath, countLockedInnerRepeatedSegment); } lrsrd.setLockedInnerRepeatedResault(lockedInnerRepeatedResault); if (!checkTM) { lrsrd.setTuNumResult(tuNumResult); } } Display.getDefault().asyncExec(new Runnable() { public void run() { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; xliffEditor.reloadXliff(); } // lrsrd.open(); if(hasWrongResults(list, lrsrd)){ MessageDialog.openInformation(shell, Messages.getString("translation.LockRepeatedSegmentHandler.msgTitle"), Messages.getString("dialog.LockRepeatedSegmentResultDialog.locksuccesful")); }else{ MessageDialog.openInformation(shell, Messages.getString("translation.LockRepeatedSegmentHandler.msgTitle"), Messages.getString("dialog.LockRepeatedSegmentResultDialog.locksuccesful")); } lrsrd.close(); HsMultiActiveCellEditor.refrushCellsEditAbility(); } }); } finally { monitor.done(); } } }; try { new ProgressMonitorDialog(shell).run(true, true, runnable); } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 专门处理以 nattble 形式打开的文件 * @param iFileList * @param isLockTM100Segment * @param isLockTM101Segment * @param monitor * @return ; */ private LockTMSegment lockTMSegmentOFEditor(List<IFile> iFileList, boolean isLockTM100Segment, boolean isLockTM101Segment, IProgressMonitor monitor) { XLFHandler xlfHandler = nattable.getXLFHandler(); SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, iFileList.size(), SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); subMonitor.beginTask("", 10); subMonitor.setTaskName(Messages.getString("translation.LockRepeatedSegmentHandler.task2")); // 解析文件,占 1/10,这里是直接获取编辑器的XLFHandler,故不需解析 if (!monitorWork(subMonitor, 1)) { return null; } List<String> filesPath = ResourceUtils.IFilesToOsPath(iFileList); LockTMSegment lts = new LockTMSegment(xlfHandler, tmMatcher, filesPath, curProject); lts.setLockedContextMatch(isLockTM101Segment); lts.setLockedFullMatch(isLockTM100Segment); // 查记忆库并锁定,占剩下的 9/10。 IProgressMonitor subSubMonitor = new SubProgressMonitor(monitor, 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); if (!lts.executeTranslation(subSubMonitor)) { subSubMonitor.done(); subMonitor.done(); isCancel = true; return null; } subSubMonitor.done(); subMonitor.done(); if (nattable != null) { Display.getDefault().syncExec(new Runnable() { public void run() { nattable.getTable().redraw(); } }); } Map<String, List<String>> needLockRowIdMap = lts.getNeedLockRowIdMap(); if (needLockRowIdMap.size() > 0) { lockTU(xlfHandler, needLockRowIdMap); } return lts; } private LockTMSegment lockTMSegment(final List<IFile> iFileList, boolean isLockTM100Segment, boolean isLockTM101Segment, IProgressMonitor monitor) { SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, iFileList.size(), SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); subMonitor.beginTask("", 10); subMonitor.setTaskName(Messages.getString("translation.LockRepeatedSegmentHandler.task2")); XLFHandler xlfHandler = null; singleNattable = null; Display.getDefault().syncExec(new Runnable() { public void run() { IEditorReference[] editorRefer = window.getActivePage().findEditors( new FileEditorInput(iFileList.get(0)), XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); if (editorRefer.length > 0) { singleNattable = ((XLIFFEditorImplWithNatTable) editorRefer[0].getEditor(true)); } } }); if (singleNattable != null) { xlfHandler = singleNattable.getXLFHandler(); } if (xlfHandler == null) { xlfHandler = new XLFHandler(); for (final IFile iFile : iFileList) { File file = iFile.getLocation().toFile(); try { Map<String, Object> resultMap = xlfHandler.openFile(file); if (resultMap == null || Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap .get(Constant.RETURNVALUE_RESULT)) { // 打开文件失败。 Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openInformation(shell, Messages .getString("translation.LockRepeatedSegmentHandler.msgTitle"), MessageFormat .format(Messages.getString("translation.LockRepeatedSegmentHandler.msg2"), iFile.getLocation().toOSString())); } }); list.remove(iFile); return null; } } catch (Exception e) { LOGGER.error("", e); e.printStackTrace(); } if (!monitorWork(monitor, 1)) { return null; } } } else { subMonitor.worked(1); } List<String> filesPath = ResourceUtils.IFilesToOsPath(iFileList); LockTMSegment lts = new LockTMSegment(xlfHandler, tmMatcher, filesPath, curProject); lts.setLockedContextMatch(isLockTM101Segment); lts.setLockedFullMatch(isLockTM100Segment); // 查记忆库并锁定,占剩下的 9/10。 SubProgressMonitor subSubMonitor = new SubProgressMonitor(subMonitor, 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); if (!lts.executeTranslation(subSubMonitor)) { isCancel = true; subSubMonitor.done(); subMonitor.done(); return null; } subSubMonitor.done(); subMonitor.done(); if (singleNattable != null) { Display.getDefault().syncExec(new Runnable() { public void run() { singleNattable.getTable().redraw(); } }); } Map<String, List<String>> needLockRowIdMap = lts.getNeedLockRowIdMap(); if (needLockRowIdMap.size() > 0) { lockTU(xlfHandler, needLockRowIdMap); } return lts; } /** * 概据内部匹配结果,锁定文本段。 * @param xlfHandler * @param rowIdMap */ private void lockTU(final XLFHandler xlfHandler, Map<String, List<String>> rowIdMap) { Iterator<Entry<String, List<String>>> it = rowIdMap.entrySet().iterator(); while (it.hasNext()) { isLocked = false; final Entry<String, List<String>> rowIdsEntry = it.next(); final String fileLC = rowIdsEntry.getKey(); // 查看该文件是否打开,若打开,则获editor的handler,若未打开,则直接使用当前handler final IEditorInput input = new FileEditorInput(ResourceUtils.fileToIFile(fileLC)); final IEditorReference[] editorRefes = window.getActivePage().getEditorReferences(); Display.getDefault().syncExec(new Runnable() { public void run() { for (int i = 0; i < editorRefes.length; i++) { if (XLIFF_EDITOR_ID.equals(editorRefes[i].getId())) { // 先判断打开单个文件的情况 XLIFFEditorImplWithNatTable nattable = (XLIFFEditorImplWithNatTable) (editorRefes[i] .getEditor(true)); if (!nattable.isMultiFile()) { if (nattable.getEditorInput().equals(input)) { nattable.getXLFHandler().lockTransUnits(rowIdsEntry.getValue(), true); isLocked = true; nattable.getTable().redraw(); } } else { // 这是合并打开的情况 if (nattable.getMultiFileList().indexOf(new File(fileLC)) >= 0) { nattable.getXLFHandler().lockTransUnits(rowIdsEntry.getValue(), true); isLocked = true; nattable.getTable().redraw(); } ; } } } // 如果未被锁定(当前文件没有打开),就调用当前XLFHandler去锁定所有文本段 if (!isLocked) { xlfHandler.lockTransUnits(rowIdsEntry.getValue(), true); } } }); } } /** * 锁定内部重复文本段 * @param iFile * @param monitor * @return ; */ private Map<String, int[]> lockInnerRepeatedSegment(List<IFile> iFileList, IProgressMonitor monitor, boolean checkTM) { Map<String, int[]> repeatedMap = new HashMap<String, int[]>(); final XLFHandler handler = new XLFHandler(); Map<String, Integer> lockedSizeMap = new HashMap<String, Integer>(); monitor.beginTask(Messages.getString("translation.LockRepeatedSegmentHandler.task3"), iFileList.size() * 3); List<IFile> removeiFileList = new ArrayList<IFile>(); for (final IFile iFile : iFileList) { File file = iFile.getLocation().toFile(); try { Map<String, Object> resultMap = handler.openFile(file); if (resultMap == null || Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap .get(Constant.RETURNVALUE_RESULT)) { // 打开文件失败。 Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openInformation(shell, Messages .getString("translation.LockRepeatedSegmentHandler.msgTitle"), MessageFormat .format(Messages.getString("translation.LockRepeatedSegmentHandler.msg2"), iFile .getLocation().toOSString())); } }); removeiFileList.add(iFile); repeatedMap.put(file.getPath(), new int[] { 0, 0 }); } } catch (Exception e) { LOGGER.error("", e); e.printStackTrace(); } lockedSizeMap.put(iFile.getLocation().toOSString(), 0); if (!monitorWork(monitor, 1)) { return null; } } Map<String, ArrayList<String>> languages = handler.getLanguages(); for (Entry<String, ArrayList<String>> entry : languages.entrySet()) { String srcLanguage = entry.getKey(); for (String tgtLanguage : entry.getValue()) { ArrayList<String> rowIds = handler.getRepeatedSegmentExceptFirstOne(srcLanguage, tgtLanguage); // 将所有的RowId进行按文件名排序 Map<String, List<String>> lockedRowidsMap = RowIdUtil.groupRowIdByFileName(rowIds); // 将锁定的文件本个数添加到map中 for (String rowId : rowIds) { String fileLC = RowIdUtil.getFileNameByRowId(rowId); lockedSizeMap.put(fileLC, lockedSizeMap.get(fileLC) + 1); } if (!monitorWork(monitor, iFileList.size())) { isCancel = true; return null; } lockTU(handler, lockedRowidsMap); } } // 如果没有进行外部匹配,那么就必须获取每个文件的TU节点数量 for (IFile iFile : iFileList) { if (removeiFileList.indexOf(iFile) >= 0) { continue; } String iFileLc = iFile.getLocation().toOSString(); repeatedMap.put(iFileLc, new int[] { checkTM ? -1 : handler.countTransUnit(iFileLc), lockedSizeMap.get(iFileLc) }); if (!monitorWork(monitor, 1)) { isCancel = true; return null; } } monitor.done(); return repeatedMap; } @Override public String[] getLegalFileExtensions() { return CommonFunction.xlfExtesionArray; } /** * 进度条前进管理方法,如果返回false,则表示退出操作 * @param monitor * @param interval * @return */ private boolean monitorWork(IProgressMonitor monitor, int interval) { if (monitor.isCanceled()) { isCancel = true; monitor.done(); return false; } monitor.worked(interval); return true; } /** * 修改重复锁定结果是否有错误 * @param iFileList * @param lrsrd ; */ private boolean hasWrongResults(List<IFile> iFileList ,LockRepeatedSegmentResultDialog lrsrd){ for(IFile iFile :iFileList ){ String filePath = ResourceUtils.iFileToOSPath(iFile); //上下文匹配结果 int lockedContextResult = lrsrd.getLockedContextResult(filePath); if(-1 ==lockedContextResult && isLockTM101Segment ){ return true; } // 内部重复 int lockedInnerRepeatedResault = lrsrd.getLockedInnerRepeatedResault(filePath); if(-1 ==lockedInnerRepeatedResault && isLockInnerRepeatedSegment ){ return true; } // 全部匹配 int lockedFullMatchResult = lrsrd.getLockedFullMatchResult(filePath); if(-1 ==lockedFullMatchResult && isLockTM100Segment ){ return true; } } return false; } }
22,321
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LockTMSegment.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.lockrepeat/src/net/heartsome/cat/ts/lockrepeat/handler/LockTMSegment.java
/** * PreTranslation.java * * Version information : * * Date:Dec 13, 2011 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.lockrepeat.handler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.heartsome.cat.common.bean.TranslationUnitAnalysisResult; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.lockrepeat.resource.Messages; import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean; import net.heartsome.cat.ts.tm.match.TmMatcher; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 锁定重复之锁定外部重复 * @author robert 2012-05-08 * @version * @since JDK1.6 */ public class LockTMSegment { public static final Logger logger = LoggerFactory.getLogger(LockTMSegment.class); private boolean isLockedContextMatch = true; // 是否需要锁定上下文匹配 private boolean isLockedFullMatch = true; // 是否需要锁定完全匹配 private XLFHandler xlfHandler; // 项目中的XLIFF文件解析 private TmMatcher tmMatcher; private TransUnitInfo2TranslationBean tuInfoBean = null; /** 上下文个数 */ private int contextSize; private List<String> xlfFiles; // 项目中的XLIFF文件路径,绝对路径 private IProject curProject; private final String SRCLANG = "source-language"; private final String TAGLANG = "target-language"; private final String XPATH_ALL_TU = "/xliff/file/body/descendant::trans-unit[source/text()!='' or source/*]"; private final String XP_FILE = "/xliff/file"; private static final int CONSTANT_ONE = 1; private Map<String, Integer> tuNumResult; private Map<String, Integer> lockedFullMatchResult; private Map<String, Integer> lockedContextResult; /** 要进行锁定的文本段的rowId */ private Map<String, List<String>> needLockRowIdMap; public LockTMSegment(XLFHandler xlfHandler, TmMatcher tmMatcher, List<String> xlfFiles, IProject curProject) { this.xlfHandler = xlfHandler; this.xlfFiles = xlfFiles; this.tmMatcher = tmMatcher; this.curProject = curProject; lockedFullMatchResult = new HashMap<String, Integer>(); lockedContextResult = new HashMap<String, Integer>(); tuNumResult = new HashMap<String, Integer>(); needLockRowIdMap = new HashMap<String, List<String>>(); //只查询一个数据,并且最低匹配为100 this.tmMatcher.setCustomeMatchParameters(1, 100); contextSize = tmMatcher.getContextSize(); } /** * 根据构建参数执行预翻译 ; * @return false:标识用户点击退出按钮,不再执行 */ public boolean executeTranslation(IProgressMonitor monitor) { if (monitor == null) { monitor = new NullProgressMonitor(); } if (monitor != null && monitor.isCanceled()) { throw new OperationCanceledException(); } //首先获取所有文件的tu节点的总数 int allTuSize = 0; for (String xlfPath : xlfFiles) { int curTuSize = xlfHandler.getNodeCount(xlfPath, XPATH_ALL_TU); //初始化结果集 tuNumResult.put(xlfPath, curTuSize); if (lockedFullMatchResult.get(xlfPath) == null) { lockedFullMatchResult.put(xlfPath, 0); } if (lockedContextResult.get(xlfPath) == null) { lockedContextResult.put(xlfPath, 0); } if (needLockRowIdMap.get(xlfPath) == null) { needLockRowIdMap.put(xlfPath, new ArrayList<String>()); } allTuSize += curTuSize; } monitor.beginTask(Messages.getString("translation.LockTMSegment.task1"), allTuSize); boolean canTmMatch = tmMatcher.checkTmMatcher(curProject); if (!canTmMatch) { monitorWork(monitor, allTuSize); return true; } Map<String, String> srcTextMap = null; for (String xlfPath : xlfFiles) { int fileNodeSum = xlfHandler.getNodeCount(xlfPath, XP_FILE); for (int fileNodeIdx = CONSTANT_ONE; fileNodeIdx <= fileNodeSum; fileNodeIdx++) { String source_lan = xlfHandler.getNodeAttribute(xlfPath, "/xliff/file[" + fileNodeIdx + "]", SRCLANG); String target_lan = xlfHandler.getNodeAttribute(xlfPath, "/xliff/file[" + fileNodeIdx + "]", TAGLANG); if (source_lan == null || source_lan.equals("")) { continue; } if (target_lan == null || target_lan.equals("")) { continue; } //获取每一个tu节点的相关信息 int curFileNodeTuSize = xlfHandler.getNodeCount(xlfPath, "/xliff/file[" + fileNodeIdx + "]/body/descendant::trans-unit[source/text()!='' or source/*]"); for (int tuNodeIdx = CONSTANT_ONE; tuNodeIdx <= curFileNodeTuSize; tuNodeIdx++) { String tuXpath = "/xliff/file[" + fileNodeIdx + "]/descendant::trans-unit[" + tuNodeIdx + "]"; srcTextMap = xlfHandler.getTUsrcText(xlfPath, tuXpath, contextSize); if (srcTextMap == null || srcTextMap.size() < 0 ) { return true; } searchTmAndLockTu(xlfPath, source_lan, target_lan, srcTextMap); if (!monitorWork(monitor, allTuSize)) { return false; } } } } return true; } /** * 查询数据库的匹配并且锁定文本段 * @param xlfPath * @param source_lan * @param target_lan * @param srcTextMap */ private void searchTmAndLockTu(String xlfPath, String source_lan, String target_lan, Map<String, String> srcTextMap) { tuInfoBean = new TransUnitInfo2TranslationBean(); String srcContent = srcTextMap.get("content"); if (srcContent == null || "".equals(srcContent)) { return; } tuInfoBean.setNextContext(srcTextMap.get("nextHash")); tuInfoBean.setPreContext(srcTextMap.get("preHash")); tuInfoBean.setSrcFullText(srcContent); tuInfoBean.setSrcLanguage(source_lan); tuInfoBean.setSrcPureText(srcTextMap.get("pureText")); tuInfoBean.setTgtLangugage(target_lan); int a = 1; List<TranslationUnitAnalysisResult> tmResult = tmMatcher.analysTranslationUnit(curProject, tuInfoBean); if (tmResult != null && tmResult.size() > 0) { int similarity = tmResult.get(0).getSimilarity(); if (isLockedContextMatch && similarity == 101) { xlfHandler.lockTransUnit(xlfPath, "no"); Integer lockedNum = lockedContextResult.get(xlfPath); if (lockedNum == null) { lockedContextResult.put(xlfPath, 1); } else { lockedContextResult.put(xlfPath, lockedNum + 1); } needLockRowIdMap.get(xlfPath).add(srcTextMap.get("rowId")); } else if (isLockedFullMatch && similarity == 100) { xlfHandler.lockTransUnit(xlfPath, "no"); Integer lockedNum = lockedFullMatchResult.get(xlfPath); if (lockedNum == null) { lockedFullMatchResult.put(xlfPath, 1); } else { lockedFullMatchResult.put(xlfPath, lockedNum + 1); } needLockRowIdMap.get(xlfPath).add(srcTextMap.get("rowId")); } a ++; } } /** * 设置是否锁定上下文匹配,即101%匹配 * @param isLockedContextMatch * the isLocaledContextMatch to set */ public void setLockedContextMatch(boolean isLockedContextMatch) { this.isLockedContextMatch = isLockedContextMatch; } /** * 设置是否锁定完全匹配,即100%匹配 * @param isLockedFullMatch * the isLocaledFullMatch to set */ public void setLockedFullMatch(boolean isLockedFullMatch) { this.isLockedFullMatch = isLockedFullMatch; } /** @return the lockedFullMatchResult */ public Map<String, Integer> getLockedFullMatchResult() { return lockedFullMatchResult; } /** @return the lockedContextResult */ public Map<String, Integer> getLockedContextResult() { return lockedContextResult; } /** @return the tuNumResult */ public Map<String, Integer> getTuNumResult() { return tuNumResult; } public Map<String, List<String>> getNeedLockRowIdMap() { return needLockRowIdMap; } public boolean monitorWork(IProgressMonitor monitor, int stepValue){ if (monitor.isCanceled()) { return false; } monitor.worked(stepValue); return true; } }
8,510
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.lockrepeat/src/net/heartsome/cat/ts/lockrepeat/resource/Messages.java
package net.heartsome.cat.ts.lockrepeat.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 国际化工具类 * @author peason * @version * @since JDK1.6 */ public class Messages { private static final String BUNDLE_NAME = "net.heartsome.cat.ts.lockrepeat.resource.message"; private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); public static String getString(String key) { try { return BUNDLE.getString(key); } catch (MissingResourceException e) { return key; } } }
564
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImageConstant.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.lockrepeat/src/net/heartsome/cat/ts/lockrepeat/resource/ImageConstant.java
/** * ImageConstant.java * * Version information : * * Date:Mar 15, 2012 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.lockrepeat.resource; /** * 图片路径工具类 * @author peason * @version * @since JDK1.6 */ public final class ImageConstant { /** 锁定重复文本段对话框的LOGO*/ public final static String TRANSLATE_LOCKREPEATED_LOGO = "images/translate/lock-repeated-logo.png"; }
944
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z