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
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.term/src/net/heartsome/cat/ts/ui/term/Activator.java
package net.heartsome.cat.ts.ui.term; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.ImageData; 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.ui.term"; //$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; } /** * 提供一个图片文件对插件的相对路径,返回该图片的描述信息。 * @param path * 图片资源对插件的相对路径。 * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } /** * 提供一个图片文件对插件的相对路径,返回该图片被伸缩变换为16*16像素的描述信息。 * @param path * the path * @return the icon descriptor */ public static ImageDescriptor getIconDescriptor(String path) { ImageDescriptor image = getImageDescriptor(path); ImageData data = image.getImageData(); data = data.scaledTo(16, 16); image = ImageDescriptor.createFromImageData(data); return image; } }
1,926
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImageConstants.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.term/src/net/heartsome/cat/ts/ui/term/ImageConstants.java
/** * ImageConstants.java * * Version information : * * Date:2012-5-2 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.term; /** * @author jason * @version * @since JDK1.6 */ public interface ImageConstants { /** 接受术语 */ String ACCPTE_TERM = "images/term-view/addmatchedterm.png"; String ADD_TERM = "images/translate/add-term.png"; String EDIT_TERM = "images/translate/edit-term.png"; String DELETE_TERM = "images/translate/delete-term.png"; }
994
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CellRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.term/src/net/heartsome/cat/ts/ui/term/view/CellRenderer.java
/** * CellRenderer.java * * Version information : * * Date:2012-10-18 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.term.view; import net.heartsome.cat.ts.ui.grid.XGridCellRenderer; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.nebula.widgets.grid.IInternalWidget; import org.eclipse.nebula.widgets.grid.internal.BranchRenderer; import org.eclipse.nebula.widgets.grid.internal.CheckBoxRenderer; import org.eclipse.nebula.widgets.grid.internal.TextUtils; import org.eclipse.nebula.widgets.grid.internal.ToggleRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; /** * @author Jason * @version * @since JDK1.6 */ public class CellRenderer extends XGridCellRenderer { private int insideMargin = 3; int treeIndent = 20; private ToggleRenderer toggleRenderer; private BranchRenderer branchRenderer; private CheckBoxRenderer checkRenderer; /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); boolean drawAsSelected = isSelected(); boolean drawBackground = true; if (isCellSelected()) { drawAsSelected = true;// (!isCellFocus()); } if (drawAsSelected) { // gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLACK)); gc.setBackground((Color) item.getParent().getData("selectedBgColor")); } else { if (item.getParent().isEnabled()) { Color back = item.getBackground(getColumn()); if (back != null) { gc.setBackground(back); } else { drawBackground = false; } } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } // gc.setForeground(item.getForeground(getColumn())); } if (drawBackground) gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height); int x = leftMargin; if (isTree()) { boolean renderBranches = item.getParent().getTreeLinesVisible(); if (renderBranches) { branchRenderer.setBranches(getBranches(item)); branchRenderer.setIndent(treeIndent); branchRenderer.setBounds(getBounds().x + x, getBounds().y, getToggleIndent(item), getBounds().height + 1); // Take into account border } x += getToggleIndent(item); toggleRenderer.setExpanded(item.isExpanded()); toggleRenderer.setHover(getHoverDetail().equals("toggle")); toggleRenderer.setLocation(getBounds().x + x, (getBounds().height - toggleRenderer.getBounds().height) / 2 + getBounds().y); if (item.hasChildren()) toggleRenderer.paint(gc, null); if (renderBranches) { branchRenderer.setToggleBounds(toggleRenderer.getBounds()); branchRenderer.paint(gc, null); } x += toggleRenderer.getBounds().width + insideMargin; } if (isCheck()) { checkRenderer.setChecked(item.getChecked(getColumn())); checkRenderer.setGrayed(item.getGrayed(getColumn())); if (!item.getParent().isEnabled()) { checkRenderer.setGrayed(true); } checkRenderer.setHover(getHoverDetail().equals("check")); if (isCenteredCheckBoxOnly(item)) { // Special logic if this column only has a checkbox and is centered checkRenderer.setBounds(getBounds().x + ((getBounds().width - checkRenderer.getBounds().width) / 2), (getBounds().height - checkRenderer.getBounds().height) / 2 + getBounds().y, checkRenderer.getBounds().width, checkRenderer.getBounds().height); } else { checkRenderer.setBounds(getBounds().x + x, (getBounds().height - checkRenderer.getBounds().height) / 2 + getBounds().y, checkRenderer.getBounds().width, checkRenderer.getBounds().height); x += checkRenderer.getBounds().width + insideMargin; } checkRenderer.paint(gc, null); } Image image = item.getImage(getColumn()); if (image != null) { int y = getBounds().y; y += (getBounds().height - image.getBounds().height) / 2; gc.drawImage(image, getBounds().x + x, y); x += image.getBounds().width + insideMargin; } if (drawAsSelected) { // gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT)); } else { gc.setForeground(item.getForeground(getColumn())); } if (!isWordWrap()) { int width = getBounds().width - x - rightMargin; String text = TextUtils.getShortString(gc, item.getText(getColumn()), width); if (getAlignment() == SWT.RIGHT) { int len = gc.stringExtent(text).x; if (len < width) { x += width - len; } } else if (getAlignment() == SWT.CENTER) { int len = gc.stringExtent(text).x; if (len < width) { x += (width - len) / 2; } } gc.drawString(text, getBounds().x + x, getBounds().y + textTopMargin + topMargin, true); } else { TextLayout layout = getTextLayout(gc, item, getColumn(), true, true); try { int y = getBounds().y + textTopMargin + topMargin; y += getVerticalAlignmentAdjustment(layout.getBounds().height, getBounds().height); if (item.getParent().isAutoHeight()) { int textHeight = topMargin + textTopMargin; // fix Bug #3116 库匹配面板--显示的匹配有截断 by Jason // for (int cnt = 0; cnt < layout.getLineCount(); cnt++) // textHeight += layout.getLineBounds(cnt).height; textHeight += layout.getBounds().height; Object obj = item.getData("itemHeight"); if (getColumn() != item.getParent().getColumnCount() - 1) { if (obj != null) { int heigth = (Integer) obj; textHeight = Math.max(textHeight, heigth); } item.setData("itemHeight", textHeight); } else { int heigth = (Integer) obj; textHeight = Math.max(textHeight, heigth); if (textHeight != item.getHeight()) { item.setHeight(textHeight); } item.setData("itemHeight", null); } } x = getBounds().x + leftMargin; if (copyEnable != null) { // Point selection = copyEnable.getSelectionRange(getColumn(), getRow() - 1 ); Point selection = copyEnable.getSelectionRange(getColumn(), item); if (selection == null || selection.x == selection.y) { layout.draw(gc, x, y); } else { int start = Math.max(0, selection.x); int end = Math.min(layout.getText().length(), selection.y); layout.draw(gc, x, y, start, end - 1, getDisplay() .getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT), getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); attachInnertTagStyle(gc, layout, true); } } else { layout.draw(gc, x, y); } } finally { layout.dispose(); } } if (item.getParent().getLinesVisible()) { if (isCellSelected()) { // XXX: should be user definable? gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } else { gc.setForeground(item.getParent().getLineColor()); } gc.drawLine(getBounds().x, getBounds().y + getBounds().height, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); } if (isCellFocus()) { Rectangle focusRect = new Rectangle(getBounds().x, getBounds().y, getBounds().width - 1, getBounds().height); // gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND)); gc.drawRectangle(focusRect); if (isFocus()) { focusRect.x++; focusRect.width -= 2; focusRect.y++; focusRect.height -= 2; gc.drawRectangle(focusRect); } } } /** * Calculates the sequence of branch lines which should be rendered for the provided item * @param item * @return an array of integers composed using the constants in {@link BranchRenderer} */ private int[] getBranches(GridItem item) { int[] branches = new int[item.getLevel() + 1]; GridItem[] roots = item.getParent().getRootItems(); // Is this a node or a leaf? if (item.getParentItem() == null) { // Add descender if not last item if (!item.isExpanded() && roots[roots.length - 1].equals(item)) { if (item.hasChildren()) branches[item.getLevel()] = BranchRenderer.LAST_ROOT; else branches[item.getLevel()] = BranchRenderer.SMALL_L; } else { if (item.hasChildren()) branches[item.getLevel()] = BranchRenderer.ROOT; else branches[item.getLevel()] = BranchRenderer.SMALL_T; } } else if (item.hasChildren()) if (item.isExpanded()) branches[item.getLevel()] = BranchRenderer.NODE; else branches[item.getLevel()] = BranchRenderer.NONE; else branches[item.getLevel()] = BranchRenderer.LEAF; // Branch for current item GridItem parent = item.getParentItem(); if (parent == null) return branches; // Are there siblings below this item? if (parent.indexOf(item) < parent.getItemCount() - 1) branches[item.getLevel() - 1] = BranchRenderer.T; // Is the next node a root? else if (parent.getParentItem() == null && !parent.equals(roots[roots.length - 1])) branches[item.getLevel() - 1] = BranchRenderer.T; // This must be the last element at this level else branches[item.getLevel() - 1] = BranchRenderer.L; Grid grid = item.getParent(); item = parent; parent = item.getParentItem(); // Branches for parent items while (item.getLevel() > 0) { if (parent.indexOf(item) == parent.getItemCount() - 1) { if (parent.getParentItem() == null && !grid.getRootItem(grid.getRootItemCount() - 1).equals(parent)) branches[item.getLevel() - 1] = BranchRenderer.I; else branches[item.getLevel() - 1] = BranchRenderer.NONE; } else branches[item.getLevel() - 1] = BranchRenderer.I; item = parent; parent = item.getParentItem(); } // item should be null at this point return branches; } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); int x = 0; x += leftMargin; if (isTree()) { x += getToggleIndent(item); x += toggleRenderer.getBounds().width + insideMargin; } if (isCheck()) { x += checkRenderer.getBounds().width + insideMargin; } int y = 0; Image image = item.getImage(getColumn()); if (image != null) { y = topMargin + image.getBounds().height + bottomMargin; x += image.getBounds().width + insideMargin; } // MOPR-DND // MOPR: replaced this code (to get correct preferred height for cells // in word-wrap columns) // // x += gc.stringExtent(item.getText(column)).x + rightMargin; // // y = Math.max(y,topMargin + gc.getFontMetrics().getHeight() + // bottomMargin); // // with this code: int textHeight = 0; if (!isWordWrap()) { x += gc.textExtent(item.getText(getColumn())).x + rightMargin; textHeight = topMargin + textTopMargin + gc.getFontMetrics().getHeight() + textBottomMargin + bottomMargin; } else { int plainTextWidth; if (wHint == SWT.DEFAULT) plainTextWidth = getBounds().width - x - rightMargin; else plainTextWidth = wHint - x - rightMargin; TextLayout currTextLayout = new TextLayout(gc.getDevice()); currTextLayout.setFont(gc.getFont()); currTextLayout.setText(item.getText(getColumn())); currTextLayout.setAlignment(getAlignment()); currTextLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth); x += plainTextWidth + rightMargin; textHeight += topMargin + textTopMargin; for (int cnt = 0; cnt < currTextLayout.getLineCount(); cnt++) textHeight += currTextLayout.getLineBounds(cnt).height; textHeight += textBottomMargin + bottomMargin; currTextLayout.dispose(); } y = Math.max(y, textHeight); return new Point(x, y); } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { GridItem item = (GridItem) value; if (isCheck()) { if (event == IInternalWidget.MouseMove) { if (overCheck(item, point)) { setHoverDetail("check"); return true; } } if (event == IInternalWidget.LeftMouseButtonDown) { if (overCheck(item, point)) { if (!item.getCheckable(getColumn())) { return false; } item.setChecked(getColumn(), !item.getChecked(getColumn())); item.getParent().redraw(); item.fireCheckEvent(getColumn()); return true; } } } if (isTree() && item.hasChildren()) { if (event == IInternalWidget.MouseMove) { if (overToggle(item, point)) { setHoverDetail("toggle"); return true; } } if (event == IInternalWidget.LeftMouseButtonDown) { if (overToggle(item, point)) { item.setExpanded(!item.isExpanded()); item.getParent().redraw(); if (item.isExpanded()) { item.fireEvent(SWT.Expand); } else { item.fireEvent(SWT.Collapse); } return true; } } } return false; } private boolean overCheck(GridItem item, Point point) { if (isCenteredCheckBoxOnly(item)) { point = new Point(point.x, point.y); point.x -= getBounds().x; point.y -= getBounds().y; Rectangle checkBounds = new Rectangle(0, 0, 0, 0); checkBounds.x = (getBounds().width - checkRenderer.getBounds().width) / 2; checkBounds.y = ((getBounds().height - checkRenderer.getBounds().height) / 2); checkBounds.width = checkRenderer.getBounds().width; checkBounds.height = checkRenderer.getBounds().height; return checkBounds.contains(point); } else { point = new Point(point.x, point.y); point.x -= getBounds().x; point.y -= getBounds().y; int x = leftMargin; if (isTree()) { x += getToggleIndent(item); x += toggleRenderer.getSize().x + insideMargin; } if (point.x >= x && point.x < (x + checkRenderer.getSize().x)) { int yStart = ((getBounds().height - checkRenderer.getBounds().height) / 2); if (point.y >= yStart && point.y < yStart + checkRenderer.getSize().y) { return true; } } return false; } } private int getToggleIndent(GridItem item) { return item.getLevel() * treeIndent; } private boolean overToggle(GridItem item, Point point) { point = new Point(point.x, point.y); point.x -= getBounds().x - 1; point.y -= getBounds().y - 1; int x = leftMargin; x += getToggleIndent(item); if (point.x >= x && point.x < (x + toggleRenderer.getSize().x)) { // return true; int yStart = ((getBounds().height - toggleRenderer.getBounds().height) / 2); if (point.y >= yStart && point.y < yStart + toggleRenderer.getSize().y) { return true; } } return false; } /** * {@inheritDoc} */ public void setTree(boolean tree) { super.setTree(tree); if (tree) { toggleRenderer = new ToggleRenderer(); toggleRenderer.setDisplay(getDisplay()); branchRenderer = new BranchRenderer(); branchRenderer.setDisplay(getDisplay()); } } /** * {@inheritDoc} */ public void setCheck(boolean check) { super.setCheck(check); if (check) { checkRenderer = new CheckBoxRenderer(); checkRenderer.setDisplay(getDisplay()); } else { checkRenderer = null; } } /** * {@inheritDoc} */ public Rectangle getTextBounds(GridItem item, boolean preferred) { int x = leftMargin; if (isTree()) { x += getToggleIndent(item); x += toggleRenderer.getBounds().width + insideMargin; } if (isCheck()) { x += checkRenderer.getBounds().width + insideMargin; } Image image = item.getImage(getColumn()); if (image != null) { x += image.getBounds().width + insideMargin; } Rectangle bounds = new Rectangle(x, topMargin + textTopMargin, 0, 0); GC gc = new GC(item.getParent()); gc.setFont(item.getFont(getColumn())); Point size = gc.stringExtent(item.getText(getColumn())); bounds.height = size.y; if (preferred) { bounds.width = size.x - 1; } else { bounds.width = getBounds().width - x - rightMargin; } gc.dispose(); return bounds; } private boolean isCenteredCheckBoxOnly(GridItem item) { return !isTree() && item.getImage(getColumn()) == null && item.getText(getColumn()).equals("") && getAlignment() == SWT.CENTER; } }
16,894
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TermViewerBodyMenu.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.term/src/net/heartsome/cat/ts/ui/term/view/TermViewerBodyMenu.java
/** * MatchViewerMenuManager.java * * Version information : * * Date:2013-3-28 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.term.view; import java.sql.SQLException; import java.util.List; import net.heartsome.cat.common.bean.DatabaseModelBean; import net.heartsome.cat.database.DBOperator; import net.heartsome.cat.database.service.DatabaseService; import net.heartsome.cat.ts.core.file.ProjectConfiger; import net.heartsome.cat.ts.core.file.ProjectConfigerFactory; import net.heartsome.cat.ts.tb.importer.TbImporter; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.term.Activator; import net.heartsome.cat.ts.ui.term.ImageConstants; import net.heartsome.cat.ts.ui.term.dialog.AddTermToTBDialog; import net.heartsome.cat.ts.ui.term.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jason * @version * @since JDK1.6 */ class TermViewerBodyMenu { private static final Logger logger = LoggerFactory.getLogger(TermViewerBodyMenu.class); private Menu bodyMenu; private TerminologyViewPart termView; AddTermAction addAction; DeleteTermAction deleteAction; EditTermAction editAction; public TermViewerBodyMenu(TerminologyViewPart termView) { this.termView = termView; } public Menu getBodyMenu() { return this.bodyMenu; } public void createMenu(Action[] addActions) { MenuManager menuMgr = new MenuManager(); bodyMenu = menuMgr.createContextMenu(this.termView.getGridTable()); bodyMenu.addListener(SWT.Show, new Listener() { public void handleEvent(Event event) { updateActionsState(); } }); if (null != addActions && addActions.length != 0) { for (Action action : addActions) { if (null != action) { menuMgr.add(action); } } } addAction = new AddTermAction(); menuMgr.add(addAction); editAction = new EditTermAction(); menuMgr.add(editAction); deleteAction = new DeleteTermAction(); menuMgr.add(deleteAction); } void updateActionsState() { addAction.updateEnabledState(); deleteAction.updateEnabledState(); editAction.updateActionsState(); } class EditTermAction extends Action { public EditTermAction() { setText(Messages.getString("view.TerminologyViewPart.menu.editterm")); setToolTipText(Messages.getString("view.TerminologyViewPart.menu.editterm")); setImageDescriptor(Activator.getImageDescriptor(ImageConstants.EDIT_TERM)); } @Override public void run() { editTerm(); refreshResources(getCurentProject()); } void updateActionsState() { IProject curentProject = getCurentProject(); GridItem selectItem = getSelectItem(); if (curentProject != null && null != selectItem) { setEnabled(true); } else { setEnabled(false); } } } class DeleteTermAction extends Action { public DeleteTermAction() { setText(Messages.getString("view.TerminologyViewPart.menu.deleteterm")); setToolTipText(Messages.getString("view.TerminologyViewPart.menu.deleteterm")); setImageDescriptor(Activator.getImageDescriptor(ImageConstants.DELETE_TERM)); } @Override public void run() { deleteSelectTerm(); refreshResources(getCurentProject()); } public void updateEnabledState() { IProject curentProject = getCurentProject(); GridItem selectItem = getSelectItem(); if (curentProject != null && null != selectItem) { setEnabled(true); } else { setEnabled(false); } } }; class AddTermAction extends Action { public AddTermAction() { setText(Messages.getString("view.TerminologyViewPart.menu.addterm")); setToolTipText(Messages.getString("view.TerminologyViewPart.menu.addterm")); setImageDescriptor(Activator.getImageDescriptor(ImageConstants.ADD_TERM)); } @Override public void run() { addTerm(); } public void updateEnabledState() { if (getCurentProject() == null) { setEnabled(false); } else { setEnabled(true); } } }; void refreshResources(IProject project) { this.termView.refresh(); try { project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { logger.error("refresh " + project.getName() + "error", e); } } IProject getCurentProject() { IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor(); if (null == activeEditor) { return null; } if (activeEditor instanceof IXliffEditor) { IFile file = ((FileEditorInput) activeEditor.getEditorInput()).getFile(); return file.getProject(); } return null; } DBOperator getDbOperator(IProject project) { if (null == project) { return null; } ProjectConfiger projectConfiger = ProjectConfigerFactory.getProjectConfiger(project); List<DatabaseModelBean> termBaseDbs = projectConfiger.getTermBaseDbs(true); if (null == termBaseDbs || termBaseDbs.isEmpty()) { return null; } return DatabaseService.getDBOperator(termBaseDbs.get(0).toDbMetaData()); } GridItem getSelectItem() { GridItem[] selection = this.termView.getGridTable().getSelection(); if (null == selection || selection.length == 0) { return null; } return selection[0]; } String getSrcLang() { return this.termView.srcLang; } String getTgtLang() { return this.termView.tgtLang; } void deleteSelectTerm() { IProject project = getCurentProject(); if (null == project) { // show some msg here return; } DBOperator dbOperator = getDbOperator(project); if (null == dbOperator) { // show error msg here MessageDialog.openInformation(this.termView.getSite().getShell(), Messages.getString("handler.AddTermToTBHandler.msgTitle"), Messages.getString("handler.AddTermToTBHandler.msg")); return; } GridItem selectItem = getSelectItem(); if (null == selectItem) { // show some msg here return; } try { dbOperator.start(); dbOperator.beginTransaction(); Object id = selectItem.getData("DBID"); if (id instanceof String) { String termId = (String) id; dbOperator.deleteTermEntry(termId, getSrcLang(), getTgtLang()); } dbOperator.commit(); } catch (SQLException e) { MessageDialog.openInformation(this.termView.getSite().getShell(), Messages.getString("view.TerminologyViewPart.action.msg"), Messages.getString("view.TerminologyViewPart.action.deleteFailed")); try { dbOperator.rollBack(); } catch (SQLException e1) { logger.error("RollBack error",e); } logger.error("execute sql error",e); } catch (ClassNotFoundException e) { logger.error("data base driver not found",e); } finally { if (null != dbOperator) { try { dbOperator.end(); } catch (SQLException e) { logger.error("",e); } } } } void addTerm() { IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if (editor instanceof IXliffEditor) { IXliffEditor xliffEditor = (IXliffEditor) editor; IFile file = ((FileEditorInput) editor.getEditorInput()).getFile(); TbImporter.getInstance().setProject(file.getProject()); if (!TbImporter.getInstance().checkImporter()) { MessageDialog.openInformation(editor.getSite().getShell(), Messages.getString("handler.AddTermToTBHandler.msgTitle"), Messages.getString("handler.AddTermToTBHandler.msg")); return; } StringBuffer srcTerm = new StringBuffer(); StringBuffer tgtTerm = new StringBuffer(); String srcAllText = xliffEditor.getRowTransUnitBean(xliffEditor.getSelectedRows()[0]).getSrcText(); xliffEditor.getSelectSrcOrTgtPureText(srcTerm, tgtTerm); AddTermToTBDialog dialog = AddTermToTBDialog.getInstance(editor.getSite().getShell(), srcTerm.toString() .trim(), tgtTerm.toString().trim(), AddTermToTBDialog.ADD_TYPE); dialog.setProject(file.getProject()); dialog.setSrcLang(xliffEditor.getSrcColumnName()); dialog.setTgtLang(xliffEditor.getTgtColumnName()); dialog.setSrcAllText(srcAllText); dialog.open(); } } void editTerm() { IProject curentProject = getCurentProject(); DBOperator dbOperator = getDbOperator(curentProject); try { if (dbOperator.getConnection() == null) { dbOperator.start(); } GridItem selectItem = getSelectItem(); String srcTerm = selectItem.getText(1); String tgtTerm = selectItem.getText(2); String properValue = selectItem.getText(3); AddTermToTBDialog dialog = AddTermToTBDialog.getInstance(this.termView.getSite().getShell(), srcTerm .toString().trim(), tgtTerm.toString().trim(), AddTermToTBDialog.EDIT_TYPE); dialog.setProject(curentProject); dialog.setSrcLang(getSrcLang()); dialog.setTgtLang(getTgtLang()); dialog.setPropertyValue(properValue); dialog.setDbOperator(dbOperator); Object id = selectItem.getData("DBID"); int open = dialog.open(); if (Dialog.OK == open) { if (id instanceof String) { String termId = (String) id; dbOperator.beginTransaction(); dbOperator.deleteTermEntry(termId, getSrcLang(), getTgtLang()); } dbOperator.commit(); } } catch (Exception e) { MessageDialog.openInformation(this.termView.getSite().getShell(), Messages.getString("view.TerminologyViewPart.action.msg"), Messages.getString("view.TerminologyViewPart.action.editFailed")); try { dbOperator.rollBack(); } catch (SQLException e1) { logger.error("RollBack error", e); } logger.error("", e); } finally { try { dbOperator.end(); } catch (SQLException e) { logger.error("", e); } } } }
11,070
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TerminologyViewPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.term/src/net/heartsome/cat/ts/ui/term/view/TerminologyViewPart.java
/** * TerminologyViewPart.java * * Version information : * * Date:Jan 27, 2010 * * Copyright notice : */ package net.heartsome.cat.ts.ui.term.view; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Vector; import net.heartsome.cat.common.core.Constant; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.common.locale.LocaleService; import net.heartsome.cat.common.ui.listener.PartAdapter2; import net.heartsome.cat.database.bean.TBPreferenceConstants; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.tb.match.TbMatcher; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.grid.GridCopyEnable; import net.heartsome.cat.ts.ui.term.Activator; import net.heartsome.cat.ts.ui.term.ImageConstants; import net.heartsome.cat.ts.ui.term.resource.Messages; import net.heartsome.cat.ts.ui.view.ITermViewPart; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; 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.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IMemento; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.ViewPart; /** * 术语视图 * @author stone,Weachy,robert 2011-12-22(实现术语的查询,填充) * @version * @since JDK1.5 */ public class TerminologyViewPart extends ViewPart implements ISelectionListener, ITermViewPart { /** 常量,视图ID。 */ public static final String ID = "net.heartsome.cat.ts.ui.term.view.termView"; /** 源语言 */ String srcLang; /** 目标语言 */ String tgtLang; /** 源语言列 */ private GridColumn srcTableColumn; /** 目标语言列 */ private GridColumn tgtTableColumn; /** 插入术语。 */ private Action firstAction; /** 项目的配置文件的路径 */ private String curProConfigPath = ""; private IXliffEditor tempEditor; /** 当前行的索引 */ private int rowIndex; private Composite parent; private Grid gridTable; private GridCopyEnable copyEnable; private CLabel tipLabel; private Image tipLabelImage; private TbMatcher matcher = new TbMatcher(); private CellRenderer idColumnCellRenderer = new CellRenderer(); private CellRenderer srcColumnCellRenderer = new CellRenderer(); private CellRenderer tgtColumnCellRenderer = new CellRenderer(); private CellRenderer propColumnCellRenderer = new CellRenderer(); private Color selectedBgColor; private FontPropertyChangeListener fontChangeListener = new FontPropertyChangeListener(); public TerminologyViewPart() { JFaceResources.getFontRegistry().addListener(fontChangeListener); selectedBgColor = new Color(Display.getDefault(), 210, 210, 240); tipLabelImage = Activator.getImageDescriptor("images/status/Loading.png").createImage(); } @Override public void init(IViewSite site, IMemento memento) throws PartInitException { init(site); final IWorkbenchPage page = site.getPage(); page.addPostSelectionListener(this); page.addPartListener(new PartAdapter2() { @Override public void partClosed(IWorkbenchPartReference partRef) { if (gridTable == null || gridTable.isDisposed()) { page.removePartListener(this); // 关闭视图后,移除此监听 } else { if ("net.heartsome.cat.ts.ui.xliffeditor.nattable.editor".equals(partRef.getId())) { IEditorReference[] editorReferences = page.getEditorReferences(); if (editorReferences.length == 0) { // 所有编辑器全部关闭的情况下。 matcher.clearResources(); firstAction.setEnabled(false); copyEnable.resetSelection(); gridTable.removeAll(); } } } } }); site.getActionBars().getStatusLineManager() .setMessage(Messages.getString("view.TerminologyViewPart.statusLine")); } /** * 创建控件。 * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { this.parent = parent; createAction(); GridLayout parentGl = new GridLayout(1, false); parentGl.marginWidth = 0; parentGl.marginHeight = 0; parent.setLayout(parentGl); final Composite contentPanel = new Composite(parent, SWT.NONE); GridLayout secondPageCompositeGl = new GridLayout(1, false); secondPageCompositeGl.marginBottom = -1; secondPageCompositeGl.marginLeft = -1; secondPageCompositeGl.marginRight = -1; secondPageCompositeGl.marginTop = -1; secondPageCompositeGl.marginWidth = 0; secondPageCompositeGl.marginHeight = 0; contentPanel.setLayout(secondPageCompositeGl); contentPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); contentPanel.setLayout(secondPageCompositeGl); contentPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // firstPageComposite = new Composite(contentPanel, SWT.NONE); // firstPageComposite.setLayout(new GridLayout(1, false)); // secondPageComposite = new Composite(contentPanel, SWT.NONE); // GridLayout secondPageCompositeGl = new GridLayout(1, false); // secondPageCompositeGl.marginBottom = -1; // secondPageCompositeGl.marginLeft = -1; // secondPageCompositeGl.marginRight = -1; // secondPageCompositeGl.marginTop = -1; // secondPageCompositeGl.marginWidth = 0; // secondPageCompositeGl.marginHeight = 0; // secondPageComposite.setLayout(secondPageCompositeGl); // secondPageComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); gridTable = new Grid(contentPanel, SWT.BORDER | SWT.V_SCROLL); gridTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); gridTable.setHeaderVisible(true); gridTable.setAutoHeight(true); gridTable.setRowsResizeable(true); gridTable.setData("selectedBgColor", selectedBgColor); final GridColumn idItem = new GridColumn(gridTable, SWT.NONE); idItem.setText(Messages.getString("view.TerminologyViewPart.idItem")); idColumnCellRenderer.setFont(JFaceResources.getFont(Constants.MATCH_VIEWER_TEXT_FONT)); idColumnCellRenderer.setVerticalAlignment(SWT.CENTER); idItem.setCellRenderer(idColumnCellRenderer); idItem.setWordWrap(true); srcTableColumn = new GridColumn(gridTable, SWT.NONE); srcTableColumn.setText(Messages.getString("view.TerminologyViewPart.srcTableColumn")); srcColumnCellRenderer.setFont(JFaceResources.getFont(Constants.MATCH_VIEWER_TEXT_FONT)); srcTableColumn.setCellRenderer(srcColumnCellRenderer); srcTableColumn.setWordWrap(true); tgtTableColumn = new GridColumn(gridTable, SWT.NONE); tgtTableColumn.setText(Messages.getString("view.TerminologyViewPart.tgtTableColumn")); tgtColumnCellRenderer.setFont(JFaceResources.getFont(Constants.MATCH_VIEWER_TEXT_FONT)); tgtTableColumn.setCellRenderer(tgtColumnCellRenderer); tgtTableColumn.setWordWrap(true); final GridColumn propertyColumn = new GridColumn(gridTable, SWT.NONE); propertyColumn.setText(Messages.getString("view.TerminologyViewPart.propertyColumn")); propColumnCellRenderer.setFont(JFaceResources.getFont(Constants.MATCH_VIEWER_TEXT_FONT)); propertyColumn.setCellRenderer(propColumnCellRenderer); propertyColumn.setWordWrap(true); copyEnable = new GridCopyEnable(gridTable); srcColumnCellRenderer.setCopyEnable(copyEnable); tgtColumnCellRenderer.setCopyEnable(copyEnable); // 设置列宽按比例 contentPanel.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { Rectangle area = contentPanel.getClientArea(); Point preferredSize = gridTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); int width = area.width; // - 2 * gridTable.getBorderWidth(); if (preferredSize.y > area.height + gridTable.getHeaderHeight()) { Point vBarSize = gridTable.getVerticalBar().getSize(); width -= vBarSize.x; } gridTable.setSize(area.width, area.height); width -= 45; idItem.setWidth(45); srcTableColumn.setWidth((int) (width * 0.4)); tgtTableColumn.setWidth((int) (width * 0.4)); propertyColumn.setWidth((int) (width * 0.2)); } }); Composite statusComposite = new Composite(contentPanel, SWT.NONE); GridLayout statusComptGridLayout = new GridLayout(2, false); statusComptGridLayout.marginBottom = -1; statusComptGridLayout.marginLeft = -1; statusComptGridLayout.marginRight = -1; statusComptGridLayout.marginTop = -1; statusComptGridLayout.marginWidth = 0; statusComptGridLayout.marginHeight = 0; statusComposite.setLayout(statusComptGridLayout); statusComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); tipLabel = new CLabel(statusComposite, SWT.NONE); tipLabel.setAlignment(SWT.LEFT); CLabel label = new CLabel(statusComposite, SWT.None); GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd.heightHint = 20; label.setLayoutData(gd); gridTable.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { selectItem(); } }); gridTable.addListener(SWT.MouseDoubleClick, new Listener() { public void handleEvent(Event event) { firstAction.run(); } }); initHookMenu(); } private void initHookMenu() { TermViewerBodyMenu bodyMenuManager = new TermViewerBodyMenu(this); Action[] action = new Action[1]; action[0]=firstAction; bodyMenuManager.createMenu(action); getGridTable().setMenu(bodyMenuManager.getBodyMenu()); } public void selectItem() { if (gridTable.getSelection().length <= 0) { firstAction.setEnabled(false); } else { firstAction.setEnabled(true); } } /** * 创建视图工具栏的按钮。 */ private void createAction() { firstAction = new Action() { @Override public void run() { if (rowIndex < 0) { return; } if (tempEditor == null || rowIndex < 0) { return; } TransUnitBean transUnit = tempEditor.getRowTransUnitBean(rowIndex); Hashtable<String, String> tuProp = transUnit.getTuProps(); if (tuProp != null) { String translate = tuProp.get("translate"); if (translate != null && translate.equalsIgnoreCase("no")) { MessageDialog.openInformation(getSite().getShell(), Messages.getString("view.TerminologyViewPart.msgTitle"), Messages.getString("view.TerminologyViewPart.msg1")); return; } } String tarTerm = ""; GridItem[] items = gridTable.getSelection(); if (items.length <= 0) { return; } else { tarTerm = items[0].getText(2); } try { tempEditor.insertCell(rowIndex, tempEditor.getTgtColumnIndex(), tarTerm); // tempEditor.setFocus(); // 焦点给回编辑器 } catch (ExecutionException e) { if (Constant.RUNNING_MODE == Constant.MODE_DEBUG) { e.printStackTrace(); } MessageDialog.openInformation(parent.getShell(), Messages.getString("view.TerminologyViewPart.msgTitle"), Messages.getString("view.TerminologyViewPart.msg2") + e.getMessage()); } } }; firstAction.setText(Messages.getString("view.TerminologyViewPart.menu.inserttermtarget")); firstAction.setImageDescriptor(Activator.getIconDescriptor(ImageConstants.ACCPTE_TERM)); firstAction.setToolTipText(Messages.getString("view.TerminologyViewPart.firstAction")); firstAction.setEnabled(false); //getViewSite().getActionBars().getToolBarManager().add(firstAction); } public void acceptTermByIndex(int index) { if (index < 0 || index + 1 > gridTable.getItemCount()) { return; } gridTable.select(index); firstAction.run(); } /** * 获得焦点。 * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { gridTable.setFocus(); } /** * 监听来自IHSEditor的选中改变事件。 * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IWorkbenchPart part, ISelection selection) { // UNDO 每次启动程序后,术语匹配面板无法识别出术语。 2012-06-21 if (part == null || selection == null) { return; } if (part instanceof IXliffEditor) { if (!part.equals(tempEditor)) { IXliffEditor editor = (IXliffEditor) part; tempEditor = editor; tempEditor = (IXliffEditor) part; FileEditorInput input = (FileEditorInput) getSite().getPage().getActiveEditor().getEditorInput(); IProject currProject = input.getFile().getProject(); matcher.setCurrentProject(currProject); } } else { firstAction.setEnabled(false); return; } if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) { firstAction.setEnabled(false); return; } IStructuredSelection structuredSelecion = (IStructuredSelection) selection; Object object = structuredSelecion.getFirstElement(); if (object instanceof Integer) { rowIndex = (Integer) object; IXliffEditor editor = (IXliffEditor) part; TransUnitBean bean = editor.getRowTransUnitBean(rowIndex);// handler.getTransUnit(rowId); String pureText = bean.getSrcText(); srcLang = bean.getSrcLang(); tgtLang = bean.getTgtLang(); tgtLang = tgtLang == null || tgtLang.equals("") ? editor.getTgtColumnName() : tgtLang; srcLang = srcLang == null || "".equals(srcLang) ? editor.getSrcColumnName() : srcLang; if (srcLang == null || "".equals(srcLang) || tgtLang == null || "".equals(tgtLang)) { return; } Language srcLangL = LocaleService.getLanguageConfiger().getLanguageByCode(srcLang); Language tgtLangL = LocaleService.getLanguageConfiger().getLanguageByCode(tgtLang); if (srcLangL.isBidi() || tgtLangL.isBidi()) { gridTable.setOrientation(SWT.RIGHT_TO_LEFT); } else { gridTable.setOrientation(SWT.LEFT_TO_RIGHT); } srcTableColumn.setText(srcLang); tgtTableColumn.setText(tgtLang); loadData(pureText, srcLang, tgtLang, true); } } /** * 销毁视图时被调用,移出监听器。 * @see org.eclipse.ui.part.WorkbenchPart#dispose() */ @Override public void dispose() { getSite().getPage().removePostSelectionListener(this); this.tempEditor = null; matcher.clearResources(); JFaceResources.getFontRegistry().removeListener(fontChangeListener); if (selectedBgColor != null && !selectedBgColor.isDisposed()) { selectedBgColor.dispose(); } if (tipLabelImage != null && !tipLabelImage.isDisposed()) { tipLabelImage.dispose(); } super.dispose(); } private TermSearchThread currentThread; /** * 获取tableViewer的填充内容 robert * @return */ private void loadData(String pureText, String srcLang, String tgtLang, boolean isSort) { copyEnable.resetSelection(); gridTable.removeAll(); if (currentThread != null) { currentThread.interrupt(); currentThread.setStop(true); } currentThread = new TermSearchThread(pureText, srcLang, tgtLang, isSort); currentThread.start(); } class TermSearchThread extends Thread { private String pureText; private String srcLanguage; private String targetLanguage; private boolean isSort; private boolean stop; TermSearchThread(String pureText, String srcLang, String tgtLang, boolean isSort) { this.pureText = pureText; this.srcLanguage = srcLang; this.targetLanguage = tgtLang; this.isSort = isSort; this.stop = false; } public void setStop(boolean stop) { this.stop = stop; } @Override public void run() { updateStatusInfo(Messages.getString("view.TerminologyViewPart.processInfo")); Vector<Hashtable<String, String>> terms = matcher.serachTransUnitTerms(pureText, srcLanguage, targetLanguage, isSort); if (stop) { updateStatusInfo(""); return; } updateUI(pureText, terms); } private void updateUI(final String pureText, final Vector<Hashtable<String, String>> terms) { Display.getDefault().asyncExec(new Runnable() { public void run() { List<String> temp = new ArrayList<String>(); for (int i = 0; i < terms.size(); i++) { GridItem item = new GridItem(gridTable, SWT.NONE); item.setData("DBID", terms.get(i).get("tuid")); item.setText(0, (i + 1) + ""); item.setText(1, terms.get(i).get("srcWord")); item.setText(2, terms.get(i).get("tgtWord")); item.setText(3, terms.get(i).get("property") == null ? "" : terms.get(i).get("property")); temp.add(terms.get(i).get("srcWord")); } if (terms.size() > 0) { firstAction.setEnabled(true); gridTable.select(0); }else{ firstAction.setEnabled(false); } updateStatusInfo(""); tempEditor.highlightedTerms(rowIndex, getHighlightWord(pureText, temp)); } }); } private List<String> getHighlightWord(String pureText, List<String> temp) { boolean b = PlatformUI.getPreferenceStore().getBoolean(TBPreferenceConstants.TB_CASE_SENSITIVE); if (!b) { return temp; } List<String> rs = new ArrayList<String>(); String ignoreCaseMathText = null; for (String word : temp) { ignoreCaseMathText = getIgnoreCaseMathText(pureText, word); if (null != ignoreCaseMathText) { rs.add(ignoreCaseMathText); } } return rs; } private String getIgnoreCaseMathText(String src, String contanStr) { String temp = src.toUpperCase(Locale.US); contanStr = contanStr.toUpperCase(Locale.US); int index = temp.indexOf(contanStr); if (index < 0) { return null; } else { return src.substring(index, index + contanStr.length()); } } /** * 更新状态信息 * @param content * ; */ private void updateStatusInfo(final String content) { Display.getDefault().syncExec(new Runnable() { public void run() { if (content != null && content.length() != 0) { setProcessMessage(tipLabelImage, content, ""); } else { setProcessMessage(null, content, ""); } } }); } }; public void refresh() { // FIXME when the program started ,select nothing.tempEditor is null. if (null == tempEditor) { return; } TransUnitBean bean = tempEditor.getRowTransUnitBean(rowIndex);// handler.getTransUnit(rowId); String pureText = bean.getSrcText(); String srcLang = bean.getSrcLang(); String tgtLang = bean.getTgtLang(); tgtLang = tgtLang == null || tgtLang.equals("") ? tempEditor.getTgtColumnName() : tgtLang; srcLang = srcLang == null || "".equals(srcLang) ? tempEditor.getSrcColumnName() : srcLang; loadData(pureText, srcLang, tgtLang, true); } /** * tableViewer的标签提供器 * @author robert */ 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; } } // public TermOperator getTermOper() { // return termOper; // } public String getCurProConfigPath() { return curProConfigPath; } public Grid getGridTable() { return gridTable; } class FontPropertyChangeListener implements IPropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { if (gridTable == null || gridTable.isDisposed()) { return; } String property = event.getProperty(); if (Constants.MATCH_VIEWER_TEXT_FONT.equals(property)) { Font font = JFaceResources.getFont(Constants.MATCH_VIEWER_TEXT_FONT); idColumnCellRenderer.setFont(font); srcColumnCellRenderer.setFont(font); tgtColumnCellRenderer.setFont(font); propColumnCellRenderer.setFont(font); gridTable.redraw(); } } } private void setProcessMessage(Image image, String message, String tooltip) { if (image != null && !image.isDisposed()) { tipLabel.setImage(image); } else { tipLabel.setImage(null); } tipLabel.setText(message); tipLabel.setToolTipText(tooltip); tipLabel.pack(); } IXliffEditor getXliffEditor() { return tempEditor; } }
21,585
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddTermToTBDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.term/src/net/heartsome/cat/ts/ui/term/dialog/AddTermToTBDialog.java
package net.heartsome.cat.ts.ui.term.dialog; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.common.core.exception.ImportException; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.database.Constants; import net.heartsome.cat.database.DBOperator; import net.heartsome.cat.database.service.DatabaseService; import net.heartsome.cat.ts.core.file.ProjectConfiger; import net.heartsome.cat.ts.core.file.ProjectConfigerFactory; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.tb.importer.TbImporter; import net.heartsome.cat.ts.tb.importer.extension.ITbImporter; import net.heartsome.cat.ts.ui.composite.LanguageLabelProvider; import net.heartsome.cat.ts.ui.term.resource.Messages; import net.heartsome.cat.ts.ui.term.view.TerminologyViewPart; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.nebula.jface.tablecomboviewer.TableComboViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; 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.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.PlatformUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ximpleware.NavException; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * 添加术语到术语库对话框 * @author peason * @version * @since JDK1.6 */ public class AddTermToTBDialog extends TrayDialog { private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class.getName()); public static final int EDIT_TYPE = 0; public static final int ADD_TYPE = 1; private static int TYPE = -1; /** 源语言 */ private String srcLang; /** 目标语言 */ private String tgtLang; /** 源术语 */ private String srcText; /** 目标术语 */ private String tgtText; /** 选中行的源文本,用于术语匹配 */ private String srcAllText; /** 文件所属的 project 对象 */ private IProject project; /** 源语言下拉框 */ private TableComboViewer cmbSrcLang; /** 目标语言下拉框 */ private TableComboViewer cmbTgtLang; private static AddTermToTBDialog instance; /** 源术语文本框 */ public Text txtSrc; /** 目标术语文本框 */ public Text txtTgt; private Text txtProperty; private String propertyValue; public String getPropertyValue() { return this.propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } /** * 由于添加术语到术语库中的源术语和目标术语通过快捷键方式填充,因此使用单例模式, 保证填充术语时是对同一个对话框进行操作 * @param parentShell * @param srcText * @param tgtText * @return ; */ public static synchronized AddTermToTBDialog getInstance(Shell parentShell, String srcText, String tgtText, int type) { if (instance == null) { instance = new AddTermToTBDialog(parentShell, srcText, tgtText); } else { // 重新选择源或目标后,对话框中相应的值也要改变 instance.srcText = srcText; instance.tgtText = tgtText; instance.initProperty(); } TYPE = type; return instance; } /** * 私有构造方法 * @param parentShell * @param srcText * 源术语 * @param tgtText * 目标术语 */ private AddTermToTBDialog(Shell parentShell, String srcText, String tgtText) { super(parentShell); this.srcText = srcText; this.tgtText = tgtText; setShellStyle(getShellStyle() & ~SWT.APPLICATION_MODAL); setHelpAvailable(true); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("dialog.AddTermToTBDialog.title")); } /** * 添加帮助按钮 robert 2012-09-06 */ @Override protected Control createHelpControl(Composite parent) { // ROBERTHELP 添加术语 String language = CommonFunction.getSystemLanguage(); final String helpUrl = MessageFormat.format( "/net.heartsome.cat.ts.ui.help/html/{0}/ch05s04.html#add-terminology", language); Image helpImage = JFaceResources.getImage(DLG_IMG_HELP); ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS); ((GridLayout) parent.getLayout()).numColumns++; toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND); toolBar.setCursor(cursor); toolBar.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { cursor.dispose(); } }); ToolItem helpItem = new ToolItem(toolBar, SWT.NONE); helpItem.setImage(helpImage); helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$ helpItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl); } }); return toolBar; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridLayoutFactory.swtDefaults().extendedMargins(5, 5, 10, 0).numColumns(2).equalWidth(true).applyTo(tparent); GridData parentData = new GridData(GridData.FILL_BOTH); tparent.setLayoutData(parentData); Composite cmpTerm = new Composite(tparent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(cmpTerm); GridDataFactory.swtDefaults().applyTo(cmpTerm); Label lblSource = new Label(cmpTerm, SWT.NONE); lblSource.setText(Messages.getString("dialog.AddTermToTBDialog.lblSource")); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblSource); txtSrc = new Text(cmpTerm, SWT.BORDER); GridData txtData = new GridData(); // 解决在 Windows 下文本框高度太小的问题 txtData.widthHint = 290; txtSrc.setLayoutData(txtData); Label lblTarget = new Label(cmpTerm, SWT.NONE); lblTarget.setText(Messages.getString("dialog.AddTermToTBDialog.lblTarget")); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblTarget); txtTgt = new Text(cmpTerm, SWT.BORDER); txtTgt.setLayoutData(txtData); Composite cmpLang = new Composite(tparent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(cmpLang); GridDataFactory.fillDefaults().applyTo(cmpLang); Label lblSrcLang = new Label(cmpLang, SWT.NONE); lblSrcLang.setText(Messages.getString("dialog.AddTermToTBDialog.lblSrcLang")); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblSrcLang); cmbSrcLang = new TableComboViewer(cmpLang, SWT.READ_ONLY | SWT.BORDER); cmbSrcLang.getTableCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); cmbSrcLang.setContentProvider(new ArrayContentProvider()); Label lblTgtLang = new Label(cmpLang, SWT.NONE); lblTgtLang.setText(Messages.getString("dialog.AddTermToTBDialog.lblTgtLang")); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblTgtLang); cmbTgtLang = new TableComboViewer(cmpLang, SWT.READ_ONLY | SWT.BORDER); cmbTgtLang.getTableCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); cmbTgtLang.setContentProvider(new ArrayContentProvider()); Composite cmpProperty = new Composite(tparent, SWT.None); GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(cmpProperty); GridDataFactory.fillDefaults().span(2, 1).applyTo(cmpProperty); Label lblProperty = new Label(cmpProperty, SWT.None); lblProperty.setText(Messages.getString("dialog.AddTermToTBDialog.lblProperty")); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblProperty); txtProperty = new Text(cmpProperty, SWT.BORDER); txtProperty.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); initProperty(); tparent.computeSize(SWT.DEFAULT, SWT.DEFAULT); return tparent; } /** * 初始化各个控件的值 ; */ public void initProperty() { if (srcText != null && !srcText.equals("")) { txtSrc.setText(srcText); txtSrc.setSelection(0, srcText.length()); txtSrc.setFocus(); } if (tgtText != null && !tgtText.equals("")) { txtTgt.setText(tgtText); txtTgt.setSelection(0, tgtText.length()); txtTgt.setFocus(); } if(getPropertyValue()!=null){ txtProperty.setText(getPropertyValue()); } ProjectConfiger projectConfig = ProjectConfigerFactory.getProjectConfiger(project); List<Language> rsLstSrcLangs = new ArrayList<Language>(); List<Language> rsLstTgtLangs = null; try { rsLstSrcLangs.add(projectConfig.getSourceLanguage()); rsLstTgtLangs = projectConfig.getTargetlanguages(); } catch (XPathParseException e) { LOGGER.error(Messages.getString("dialog.AddTermToTBDialog.logger"), e); } catch (NavException e) { LOGGER.error(Messages.getString("dialog.AddTermToTBDialog.logger"), e); } catch (XPathEvalException e) { LOGGER.error(Messages.getString("dialog.AddTermToTBDialog.logger"), e); } ArrayList<String> lstTgtLangs = new ArrayList<String>(); if (rsLstTgtLangs != null) { for (Language lang : rsLstTgtLangs) { lstTgtLangs.add(lang.getCode()); } } cmbSrcLang.setLabelProvider(new LanguageLabelProvider()); cmbSrcLang.setInput(rsLstSrcLangs); cmbSrcLang.getTableCombo().select(0); cmbTgtLang.setLabelProvider(new LanguageLabelProvider()); cmbTgtLang.setInput(rsLstTgtLangs); if (tgtLang != null) { cmbTgtLang.getTableCombo().select(lstTgtLangs.indexOf(tgtLang)); } } /** * 获取源语言 * @return ; */ public String getSrcLang() { return srcLang; } /** * 设置源语言 * @param srcLang * 源语言 */ public void setSrcLang(String srcLang) { this.srcLang = srcLang; } /** * 获取目标语言 * @return ; */ public String getTgtLang() { return tgtLang; } /** * 设置目标语言 * @param tgtLang * 目标语言 */ public void setTgtLang(String tgtLang) { this.tgtLang = tgtLang; } /** * 获取 IProject 对象 * @return ; */ public IProject getProject() { return project; } /** * 设置 IProject 对象 * @param project * ; */ public void setProject(IProject project) { this.project = project; } /** * 获取选中行的源文本 * @return ; */ public String getSrcAllText() { return srcAllText; } /** * 设置选中行的源文本 * @param srcAllText * ; */ public void setSrcAllText(String srcAllText) { this.srcAllText = srcAllText; } @Override protected void okPressed() { String srcTerm = cleanString(txtSrc.getText()); String tgtTerm = cleanString(txtTgt.getText()); if (srcTerm == null || srcTerm.equals("")) { MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.msg1")); return; } if (tgtTerm == null || tgtTerm.equals("")) { MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.msg2")); return; } // 添加空格不可入库的判断,--robert 2012-11-19 if (srcTerm.length() > 0 && srcTerm.trim().equals("")) { MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.addTip1")); return; } if (tgtTerm.length() > 0 && tgtTerm.trim().equals("")) { MessageDialog.openInformation(getShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.addTip2")); return; } srcTerm = srcTerm.trim(); tgtTerm = tgtTerm.trim(); XLFHandler handler = new XLFHandler(); IStructuredSelection srcSelected = (IStructuredSelection) cmbSrcLang.getSelection(); Language srcSelectedLang = (Language) srcSelected.getFirstElement(); String srcLang = srcSelectedLang.getCode(); IStructuredSelection tgtSelection = (IStructuredSelection) cmbTgtLang.getSelection(); Language tgtSelectedLang = (Language) tgtSelection.getFirstElement(); String tgtLang = tgtSelectedLang.getCode(); String strTBX = handler.generateTBXWithString(srcLang, tgtLang, srcTerm, tgtTerm, txtProperty.getText()); TbImporter importer = TbImporter.getInstance(); importer.setProject(project); int state = -1; try { if (TYPE == EDIT_TYPE) { if (null != this.dbOperator) { state = DatabaseService.importTbxWithString(strTBX, null, this.dbOperator, Constants.IMPORT_MODEL_ALWAYSADD, srcLang); if(state!=1){ return; } } } else if (TYPE == ADD_TYPE) { state = importer.executeImport(strTBX, srcLang, null); if(state == ITbImporter.IMPORT_STATE_FAILED){ MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), Messages.getString("dialog.AddTermToTBDialog.msg3")); importer.clearResources(); return; } } } catch (ImportException e) { final String msg = e.getMessage(); Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.getString("dialog.AddTermToTBDialog.msgTitle"), msg); } }); return; } importer.clearResources(); TerminologyViewPart view = (TerminologyViewPart) PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage().findView(TerminologyViewPart.ID); if (view != null) { view.refresh(); } setReturnCode(OK); if (TYPE == ADD_TYPE) { try { project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { LOGGER.error("", e); } } close(); } private DBOperator dbOperator; public void setDbOperator(DBOperator dbOperator) { this.dbOperator = dbOperator; } /** * 当关闭对话框时,单例对象要置空,否则再次打开对话框时会报异常 * @see org.eclipse.jface.dialogs.Dialog#close() */ @Override public boolean close() { boolean blnClose = super.close(); instance = null; return blnClose; } public static String cleanString(String string) { string = string.replaceAll("&", "&amp;"); string = string.replaceAll("<", "&lt;"); string = string.replaceAll(">", "&gt;"); // string = string.replaceAll("\"", "&quot;"); // 这里的 引号是不用转义的。--robert 2012-10-26 return string; } }
15,577
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddTermToTBHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.term/src/net/heartsome/cat/ts/ui/term/handler/AddTermToTBHandler.java
package net.heartsome.cat.ts.ui.term.handler; import net.heartsome.cat.ts.tb.importer.TbImporter; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.term.dialog.AddTermToTBDialog; import net.heartsome.cat.ts.ui.term.resource.Messages; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.part.FileEditorInput; /** * 添加术语到术语库的 Handler * @author peason * @version * @since JDK1.6 */ public class AddTermToTBHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (editor instanceof IXliffEditor) { IXliffEditor xliffEditor = (IXliffEditor) editor; IFile file = ((FileEditorInput) editor.getEditorInput()).getFile(); // ProjectConfiger projectConfig = ProjectConfigerFactory.getProjectConfiger(file.getProject()); // List<DatabaseModelBean> lstDatabase = projectConfig.getTermBaseDbs(true); TbImporter.getInstance().setProject(file.getProject()); if (!TbImporter.getInstance().checkImporter()) { MessageDialog.openInformation(HandlerUtil.getActiveShell(event), Messages.getString("handler.AddTermToTBHandler.msgTitle"), Messages.getString("handler.AddTermToTBHandler.msg")); return null; } StringBuffer srcTerm = new StringBuffer(); StringBuffer tgtTerm = new StringBuffer(); String srcAllText = xliffEditor.getRowTransUnitBean(xliffEditor.getSelectedRows()[0]).getSrcText(); xliffEditor.getSelectSrcOrTgtPureText(srcTerm, tgtTerm); AddTermToTBDialog dialog = AddTermToTBDialog.getInstance(editor.getSite().getShell(), srcTerm.toString().trim(), tgtTerm.toString().trim(),AddTermToTBDialog.ADD_TYPE); dialog.setProject(file.getProject()); dialog.setSrcLang(xliffEditor.getSrcColumnName()); dialog.setTgtLang(xliffEditor.getTgtColumnName()); dialog.setSrcAllText(srcAllText); dialog.open(); } return null; } }
2,252
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.term/src/net/heartsome/cat/ts/ui/term/resource/Messages.java
package net.heartsome.cat.ts.ui.term.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.term.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; } } }
558
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.importproject/src/net/heartsome/cat/ts/importproject/Activator.java
package net.heartsome.cat.ts.importproject; 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.importproject"; //$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,390
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ResourceTree.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.importproject/src/net/heartsome/cat/ts/importproject/widgiet/ResourceTree.java
package net.heartsome.cat.ts.importproject.widgiet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Tree; /** * 显示带有项目,项目文件的 树 * @author robert 2013-03-06 */ public class ResourceTree extends CheckboxTreeViewer implements ICheckStateListener, IDoubleClickListener{ private Tree tree; /** 当前树的内容提供者 */ private ITreeContentProvider contentProvider; /** 当前树的标签提供者 */ private ILabelProvider labelProvider; /** 保存半选中状态的节点 */ private Set<Object> grayStoreSet = new HashSet<Object>(); private ProjectResource[] root; public ResourceTree(Composite parent, ITreeContentProvider contentProvider, ILabelProvider labelProvider) { super(parent); this.contentProvider = contentProvider; this.labelProvider = labelProvider; tree = this.getTree(); tree.setLayoutData(new GridData(GridData.FILL_BOTH)); this.setLabelProvider(this.labelProvider); this.setContentProvider(this.contentProvider); this.addCheckStateListener(this); this.addDoubleClickListener(this); } public void setRoot(ProjectResource[] root) { this.root = root; } /** * 设置选择全部 */ public void setCheckedAll(boolean checkState){ for(ProjectResource projRoot : root){ setSubtreeChecked(projRoot, checkState); } // 让缓存全部删除 setGrayedElements(new Object[0]); grayStoreSet.clear(); } /** * 获取所有的节点 * @return */ public List<ProjectResource> getAllElement(){ List<ProjectResource> allElements = new ArrayList<ProjectResource>(); for(ProjectResource proRoot : root){ allElements.add(proRoot); Object[] objArray = contentProvider.getChildren(proRoot); for(Object obj : objArray){ if (obj instanceof ProjectResource) { ProjectResource childProResource = (ProjectResource) obj; allElements.add(childProResource); getAllElementImpl(childProResource, allElements); } } } return allElements; } private void getAllElementImpl(ProjectResource parentProjRes, List<ProjectResource> allElements){ for(Object obj : contentProvider.getChildren(parentProjRes)){ if (obj instanceof ProjectResource) { ProjectResource childProResource = (ProjectResource) obj; allElements.add(childProResource); getAllElementImpl(childProResource, allElements); } } } /** * 设置所有子节点是否选中 * @param element 要选中与否的 节点 * @param state 当前节点是否要选中 */ private void setAllChildCheck(Object element, boolean state){ setSubtreeChecked(element, state); setAllChildCheckImp(element, state); } private void setAllChildCheckImp(Object element, boolean state){ Object[] childList = contentProvider.getChildren(element); if (childList == null) { return; } for(Object childElement : childList){ if (getGrayed(childElement)) { grayStoreSet.remove(childElement); } setAllChildCheckImp(childElement, state); } } /** * 双击事件,若双击,自动展开该文件夹 */ public void doubleClick(final DoubleClickEvent event) { BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { public void run() { ISelection selection = event.getSelection(); IStructuredSelection struSelection = (IStructuredSelection) selection; Object obj = struSelection.getFirstElement(); if (getExpandedState(obj)) { collapseToLevel(obj, 1); }else { expandToLevel(obj, 1); } } }); } public void checkStateChanged(final CheckStateChangedEvent event) { BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { public void run() { Object element = event.getElement(); if (getChecked(element)) { setAllChildCheck(element, true); // 让父文件夹处于半选中状态 Object parent = contentProvider.getParent(element); while(parent != null){ if (!getChecked(parent)) { grayStoreSet.add(parent); } parent = contentProvider.getParent(parent); } }else { if (getGrayed(element)) { grayStoreSet.remove(element); } setAllChildCheck(element, false); Object parent = contentProvider.getParent(element); while(parent != null){ if (hasCheckedChildren(parent)) { grayStoreSet.add(parent); }else { if (getGrayed(parent)) { grayStoreSet.remove(parent); } setChecked(parent, false); } parent = contentProvider.getParent(parent); } } setGrayedElements(new Object[0]); setGrayedElements(grayStoreSet.toArray()); for (Object obj : grayStoreSet) { setChecked(obj, true); } } }); } /** * 判断当前父目录是否有子文件或子文件夹被选中 * @param parent * @return */ private boolean hasCheckedChildren(Object parent){ Object[] childArray = contentProvider.getChildren(parent); if (childArray == null || childArray.length <= 0) { return false; } for(Object child : childArray){ if (getChecked(child)) { return true; } if (hasCheckedChildren(child)) { return true; } } return false; } }
5,858
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ProjectResource.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.importproject/src/net/heartsome/cat/ts/importproject/widgiet/ProjectResource.java
package net.heartsome.cat.ts.importproject.widgiet; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.ui.internal.wizards.datatransfer.ILeveledImportStructureProvider; import net.heartsome.cat.common.core.Constant; import net.heartsome.cat.ts.importproject.wizards.ImportProjectWizardPage2.ProjectRecord; /** * 这是树的内容类 * @author robert */ @SuppressWarnings("restriction") public class ProjectResource { private Object element; private ProjectResource parent; private ProjectRecord proRecord; private boolean isFolder; /** 是否是项目 */ private boolean isProject; private List<ProjectResource> childrenList; private String projectName; /** 项目是否重复 */ private boolean isProjectRepeat; /** 当前节点是否重复 */ private boolean isElementRepeat; private IWorkspaceRoot root; private ILeveledImportStructureProvider structureProvider; /** 标识当前重复的节点是不是需要覆盖已经存在的文件 */ private boolean needCover; /** 设置过滤文件的条件 */ private Set<String> FILE_FILTER = new HashSet<String>(); /** * 该构造函数主要是针对项目用的 * @param entry * @param proRecord */ public ProjectResource(Object entry, ProjectRecord proRecord, ILeveledImportStructureProvider structureProvider){ this.element = entry; this.proRecord = proRecord; this.projectName = this.proRecord.getProjectName(); this.structureProvider = structureProvider; // 备注,下面这四个初始化的方法,位置不能更换。 root = ResourcesPlugin.getWorkspace().getRoot(); isProject = true; initIsProjectRepeat(); initData(); initChildren(); } /** * 该构造函数主要针对项目下的文件夹或者文件 * @param entry * @param parent * @param projectName * @param isProjectRepeat * @param structureProvider */ public ProjectResource(Object entry, ProjectResource parent, String projectName, boolean isProjectRepeat, ILeveledImportStructureProvider structureProvider){ this.element = entry; this.parent = parent; this.projectName = projectName; this.isProjectRepeat = isProjectRepeat; this.structureProvider = structureProvider; // 备注,下面这四个初始化的方法,位置不能更换。 root = ResourcesPlugin.getWorkspace().getRoot(); isProject = false; initIsElementRepeat(); initData(); initChildren(); } /** * 初始化相关数据 */ private void initData(){ isFolder = structureProvider.isFolder(element); needCover = !isElementRepeat; FILE_FILTER.add(".project"); FILE_FILTER.add(Constant.FILE_CONFIG); FILE_FILTER.add(".TEMP"); } @SuppressWarnings("unchecked") private void initChildren(){ childrenList = new ArrayList<ProjectResource>(); if (isFolder()) { List<Object> childrenObjList = structureProvider.getChildren(element); if (childrenObjList == null || childrenObjList.size() <= 0) { return; } for(Object curObj : childrenObjList){ String fileName = structureProvider.getLabel(curObj); if (FILE_FILTER.contains(fileName)) { continue; } childrenList.add(new ProjectResource(curObj, this, projectName, isProjectRepeat, structureProvider)); } } } /** * 初始化项目是否重复 */ private void initIsProjectRepeat(){ isElementRepeat = isProjectRepeat = root.getLocation().append(projectName).toFile().exists(); } /** * 初始化当前节点是否重复 */ private void initIsElementRepeat(){ // 如果项目名称不重复,那么里面的内容也不会重复的。 if (isProjectRepeat) { // UNDO 这里要注意下,当项目文件与根目录文件不相符时,这里是否合法?我猜是不能的。 isElementRepeat = root.getLocation().append(structureProvider.getFullPath(element)).toFile().exists(); }else { isElementRepeat = false; } } public String getLabel(){ if (proRecord != null) { return projectName; }else { return structureProvider.getLabel(element); } } /** * 将 needCover 属性恢复默认 */ public void restoreNeedCoverDefault(){ needCover = !isElementRepeat; } /** * 获取项目下 .config 文件的输入流 * <div style='color:red'>备注: 该方法只针对项目进行调用</div> * @return */ @SuppressWarnings("unchecked") public InputStream getConfigFileContent(){ if (!isProject) { return null; } InputStream stream = null; List<Object> childrenObjList = structureProvider.getChildren(element); for(Object curObj : childrenObjList){ String fileName = structureProvider.getLabel(curObj); if (Constant.FILE_CONFIG.contains(fileName)) { stream = structureProvider.getContents(curObj); } } return stream; } /** * 是否有孩子节点 * @return */ public boolean hasChildren(){ return structureProvider.isFolder(element); } public boolean isProjectRepeat() { return isProjectRepeat; } public boolean isElementRepeat() { return isElementRepeat; } /** * 是否是文件夹 * @return */ public boolean isFolder(){ return isFolder; } public List<ProjectResource> getChildren(){ return childrenList; } public ProjectRecord getProRecord() { return proRecord; } public ProjectResource getParent(){ return parent; } public String getProjectName() { return projectName; } public boolean isNeedCover() { return needCover; } public void setNeedCover(boolean needCover) { this.needCover = needCover; } public InputStream getInputStream(){ if (isFolder) { return null; } return structureProvider.getContents(element); } public boolean isProject() { return isProject; } }
5,863
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImportProjectHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.importproject/src/net/heartsome/cat/ts/importproject/handler/ImportProjectHandler.java
package net.heartsome.cat.ts.importproject.handler; import java.text.MessageFormat; import net.heartsome.cat.common.ui.wizard.TSWizardDialog; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.importproject.wizards.ImportProjectWizard; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; 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.Control; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; /** * 导入项目的 Handler * @author peason * @version * @since JDK1.6 */ public class ImportProjectHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event); ImportProjectWizard wizard = new ImportProjectWizard(); TSWizardDialog dialog = new TSWizardDialog(window.getShell(), wizard){ /** * 添加帮助按钮 * robert 2012-09-06 */ @Override protected Control createHelpControl(Composite parent) { // ROBERTHELP 导入项目 String language = CommonFunction.getSystemLanguage(); final String helpUrl = MessageFormat.format( "/net.heartsome.cat.ts.ui.help/html/{0}/ch07s03.html#import-project", language); Image helpImage = JFaceResources.getImage(DLG_IMG_HELP); ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS); ((GridLayout) parent.getLayout()).numColumns++; toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND); toolBar.setCursor(cursor); toolBar.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { cursor.dispose(); } }); ToolItem helpItem = new ToolItem(toolBar, SWT.NONE); helpItem.setImage(helpImage); helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$ helpItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl); } }); return toolBar; } }; dialog.setHelpAvailable(true); dialog.open(); return null; } }
2,943
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImportProjectWizardPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.importproject/src/net/heartsome/cat/ts/importproject/wizards/ImportProjectWizardPage.java
package net.heartsome.cat.ts.importproject.wizards; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import net.heartsome.cat.ts.importproject.Activator; import net.heartsome.cat.ts.importproject.resource.Messages; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; 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.OperationCanceledException; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.PixelConverter; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IColorProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.IOverwriteQuery; import org.eclipse.ui.internal.ide.IDEWorkbenchMessages; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; import org.eclipse.ui.internal.wizards.datatransfer.ArchiveFileManipulations; import org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages; import org.eclipse.ui.internal.wizards.datatransfer.ILeveledImportStructureProvider; import org.eclipse.ui.internal.wizards.datatransfer.TarEntry; import org.eclipse.ui.internal.wizards.datatransfer.TarException; import org.eclipse.ui.internal.wizards.datatransfer.TarFile; import org.eclipse.ui.internal.wizards.datatransfer.TarLeveledStructureProvider; import org.eclipse.ui.internal.wizards.datatransfer.ZipLeveledStructureProvider; import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider; import org.eclipse.ui.wizards.datatransfer.ImportOperation; @SuppressWarnings("restriction") public class ImportProjectWizardPage extends WizardPage implements IOverwriteQuery { /** * The name of the folder containing metadata information for the workspace. */ public static final String METADATA_FOLDER = ".metadata"; //$NON-NLS-1$ /** * The import structure provider. * * @since 3.4 */ private ILeveledImportStructureProvider structureProvider; /** * @since 3.5 * */ private final class ProjectLabelProvider extends LabelProvider implements IColorProvider{ public String getText(Object element) { return ((ProjectRecord) element).getProjectLabel(); } public Color getBackground(Object element) { return null; } public Color getForeground(Object element) { ProjectRecord projectRecord = (ProjectRecord) element; if(projectRecord.hasConflicts) return getShell().getDisplay().getSystemColor(SWT.COLOR_GRAY); return null; } } /** * Class declared public only for test suite. * */ public class ProjectRecord { File projectSystemFile; Object projectArchiveFile; String projectName; Object parent; int level; boolean hasConflicts; IProjectDescription description; /** * Create a record for a project based on the info in the file. * * @param file */ ProjectRecord(File file) { projectSystemFile = file; setProjectName(); } /** * @param file * The Object representing the .project file * @param parent * The parent folder of the .project file * @param level * The number of levels deep in the provider the file is */ ProjectRecord(Object file, Object parent, int level) { this.projectArchiveFile = file; this.parent = parent; this.level = level; setProjectName(); } /** * Set the name of the project based on the projectFile. */ private void setProjectName() { try { if (projectArchiveFile != null) { InputStream stream = structureProvider .getContents(projectArchiveFile); // If we can get a description pull the name from there if (stream == null) { if (projectArchiveFile instanceof ZipEntry) { IPath path = new Path( ((ZipEntry) projectArchiveFile).getName()); projectName = path.segment(path.segmentCount() - 2); } else if (projectArchiveFile instanceof TarEntry) { IPath path = new Path( ((TarEntry) projectArchiveFile).getName()); projectName = path.segment(path.segmentCount() - 2); } } else { description = IDEWorkbenchPlugin.getPluginWorkspace() .loadProjectDescription(stream); stream.close(); projectName = description.getName(); } } // If we don't have the project name try again if (projectName == null) { IPath path = new Path(projectSystemFile.getPath()); // if the file is in the default location, use the directory // name as the project name if (isDefaultLocation(path)) { projectName = path.segment(path.segmentCount() - 2); description = IDEWorkbenchPlugin.getPluginWorkspace() .newProjectDescription(projectName); } else { description = IDEWorkbenchPlugin.getPluginWorkspace() .loadProjectDescription(path); projectName = description.getName(); } } } catch (CoreException e) { // no good couldn't get the name } catch (IOException e) { // no good couldn't get the name } } /** * Returns whether the given project description file path is in the * default location for a project * * @param path * The path to examine * @return Whether the given path is the default location for a project */ private boolean isDefaultLocation(IPath path) { // The project description file must at least be within the project, // which is within the workspace location if (path.segmentCount() < 2) return false; return path.removeLastSegments(2).toFile().equals( Platform.getLocation().toFile()); } /** * Get the name of the project * * @return String */ public String getProjectName() { return projectName; } /** * Gets the label to be used when rendering this project record in the * UI. * * @return String the label * @since 3.4 */ public String getProjectLabel() { if (description == null) return projectName; String path = projectSystemFile == null ? structureProvider .getLabel(parent) : projectSystemFile .getParent(); return NLS.bind( DataTransferMessages.WizardProjectsImportPage_projectLabel, projectName, path); } /** * @return Returns the hasConflicts. */ public boolean hasConflicts() { return hasConflicts; } } // dialog store id constants private final static String STORE_COPY_PROJECT_ID = "ImportProjectWizardPage.STORE_COPY_PROJECT_ID"; //$NON-NLS-1$ private final static String STORE_ARCHIVE_SELECTED = "ImportProjectWizardPage.STORE_ARCHIVE_SELECTED"; //$NON-NLS-1$ private CheckboxTreeViewer projectsList; private boolean copyFiles = true; private boolean lastCopyFiles = false; private ProjectRecord[] selectedProjects = new ProjectRecord[0]; // Keep track of the archive that we browsed to last time // the wizard was invoked. private static String previouslyBrowsedArchive = ""; //$NON-NLS-1$ private Label projectFromArchiveRadio; private Text archivePathField; private Button browseArchivesButton; private IProject[] wsProjects; // constant from WizardArchiveFileResourceImportPage1 private static final String[] FILE_IMPORT_MASK = { "*.zip", "*" }; //$NON-NLS-1$ //$NON-NLS-2$ // The initial path to set private String initialPath; // The last selected path to minimize searches private String lastPath; // The last time that the file or folder at the selected path was modified // to mimize searches private long lastModified; private IStructuredSelection currentSelection; /** * Creates a new project creation wizard page. * */ public ImportProjectWizardPage() { this("wizardImportProjectsPage", null, null); //$NON-NLS-1$ } /** * Create a new instance of the receiver. * * @param pageName */ public ImportProjectWizardPage(String pageName) { this(pageName,null, null); } /** * More (many more) parameters. * * @param pageName * @param initialPath * @param currentSelection * @since 3.5 */ public ImportProjectWizardPage(String pageName,String initialPath, IStructuredSelection currentSelection) { super(pageName); this.initialPath = initialPath; this.currentSelection = currentSelection; setPageComplete(false); setTitle(DataTransferMessages.WizardProjectsImportPage_ImportProjectsTitle); setDescription(Messages.getString("wizard.ImportProjectWizardPage.desc")); setImageDescriptor(Activator.getImageDescriptor("images/importProject_logo.png")); } /* * (non-Javadoc) * * @see * org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets * .Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite workArea = new Composite(parent, SWT.NONE); setControl(workArea); workArea.setLayout(new GridLayout()); workArea.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL)); createProjectsRoot(workArea); createProjectsList(workArea); restoreWidgetValues(); Dialog.applyDialogFont(workArea); } /** * Create the checkbox list for the found projects. * * @param workArea */ private void createProjectsList(Composite workArea) { Label title = new Label(workArea, SWT.NONE); title .setText(DataTransferMessages.WizardProjectsImportPage_ProjectsListTitle); Composite listComposite = new Composite(workArea, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.marginWidth = 0; layout.makeColumnsEqualWidth = false; listComposite.setLayout(layout); listComposite.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH)); projectsList = new CheckboxTreeViewer(listComposite, SWT.BORDER); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.widthHint = new PixelConverter(projectsList.getControl()).convertWidthInCharsToPixels(25); gridData.heightHint = new PixelConverter(projectsList.getControl()).convertHeightInCharsToPixels(10); projectsList.getControl().setLayoutData(gridData); projectsList.setContentProvider(new ITreeContentProvider() { /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java * .lang.Object) */ public Object[] getChildren(Object parentElement) { return null; } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.IStructuredContentProvider#getElements * (java.lang.Object) */ public Object[] getElements(Object inputElement) { return getProjectRecords(); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java * .lang.Object) */ public boolean hasChildren(Object element) { return false; } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ITreeContentProvider#getParent(java * .lang.Object) */ public Object getParent(Object element) { return null; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ public void dispose() { } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse * .jface.viewers.Viewer, java.lang.Object, java.lang.Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } }); projectsList.setLabelProvider(new ProjectLabelProvider()); projectsList.addCheckStateListener(new ICheckStateListener() { /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged * (org.eclipse.jface.viewers.CheckStateChangedEvent) */ public void checkStateChanged(CheckStateChangedEvent event) { ProjectRecord element = (ProjectRecord) event.getElement(); if(element.hasConflicts) { projectsList.setChecked(element, false); } setPageComplete(projectsList.getCheckedElements().length > 0); } }); projectsList.setInput(this); projectsList.setComparator(new ViewerComparator()); createSelectionButtons(listComposite); } /** * Create the selection buttons in the listComposite. * * @param listComposite */ private void createSelectionButtons(Composite listComposite) { Composite buttonsComposite = new Composite(listComposite, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginWidth = 0; layout.marginHeight = 0; buttonsComposite.setLayout(layout); buttonsComposite.setLayoutData(new GridData( GridData.VERTICAL_ALIGN_BEGINNING)); Button selectAll = new Button(buttonsComposite, SWT.PUSH); selectAll.setText(DataTransferMessages.DataTransfer_selectAll); selectAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { for (int i = 0; i < selectedProjects.length; i++) { if(selectedProjects[i].hasConflicts) projectsList.setChecked(selectedProjects[i], false); else projectsList.setChecked(selectedProjects[i], true); } setPageComplete(projectsList.getCheckedElements().length > 0); } }); Dialog.applyDialogFont(selectAll); setButtonLayoutData(selectAll); Button deselectAll = new Button(buttonsComposite, SWT.PUSH); deselectAll.setText(DataTransferMessages.DataTransfer_deselectAll); deselectAll.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse * .swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { projectsList.setCheckedElements(new Object[0]); setPageComplete(false); } }); Dialog.applyDialogFont(deselectAll); setButtonLayoutData(deselectAll); Button refresh = new Button(buttonsComposite, SWT.PUSH); refresh.setText(DataTransferMessages.DataTransfer_refresh); refresh.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse * .swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { updateProjectsList(archivePathField.getText().trim()); } }); Dialog.applyDialogFont(refresh); setButtonLayoutData(refresh); } /** * Create the area where you select the root directory for the projects. * * @param workArea * Composite */ private void createProjectsRoot(Composite workArea) { // project specification group Composite projectGroup = new Composite(workArea, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.makeColumnsEqualWidth = false; layout.marginWidth = 0; projectGroup.setLayout(layout); projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // new project from archive radio button projectFromArchiveRadio = new Label(projectGroup, SWT.None); projectFromArchiveRadio .setText(DataTransferMessages.WizardProjectsImportPage_ArchiveSelectTitle); // project location entry field archivePathField = new Text(projectGroup, SWT.BORDER); GridData archivePathData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); archivePathData.widthHint = new PixelConverter(archivePathField).convertWidthInCharsToPixels(25); archivePathField.setLayoutData(archivePathData); // browse button browseArchivesButton = new Button(projectGroup, SWT.PUSH); browseArchivesButton.setText(DataTransferMessages.DataTransfer_browse); setButtonLayoutData(browseArchivesButton); browseArchivesButton.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse * .swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { handleLocationArchiveButtonPressed(); } }); archivePathField.addTraverseListener(new TraverseListener() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.TraverseListener#keyTraversed(org.eclipse * .swt.events.TraverseEvent) */ public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_RETURN) { e.doit = false; updateProjectsList(archivePathField.getText().trim()); } } }); archivePathField.addFocusListener(new FocusAdapter() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt * .events.FocusEvent) */ public void focusLost(org.eclipse.swt.events.FocusEvent e) { updateProjectsList(archivePathField.getText().trim()); } }); } /* * (non-Javadoc) Method declared on IDialogPage. Set the focus on path * fields when page becomes visible. */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { this.archivePathField.setFocus(); } } /** * Update the list of projects based on path. Method declared public only * for test suite. * * @param path */ public void updateProjectsList(final String path) { // on an empty path empty selectedProjects if (path == null || path.length() == 0) { setMessage(Messages.getString("wizard.ImportProjectWizardPage.desc")); selectedProjects = new ProjectRecord[0]; projectsList.refresh(true); projectsList.setCheckedElements(selectedProjects); setPageComplete(projectsList.getCheckedElements().length > 0); lastPath = path; return; } final File directory = new File(path); long modified = directory.lastModified(); if (path.equals(lastPath) && lastModified == modified && lastCopyFiles == copyFiles) { // since the file/folder was not modified and the path did not // change, no refreshing is required return; } lastPath = path; lastModified = modified; lastCopyFiles = copyFiles; // We can't access the radio button from the inner class so get the // status beforehand final boolean dirSelected = false; try { getContainer().run(true, true, new IRunnableWithProgress() { /* * (non-Javadoc) * * @see * org.eclipse.jface.operation.IRunnableWithProgress#run(org * .eclipse.core.runtime.IProgressMonitor) */ @SuppressWarnings("rawtypes") public void run(IProgressMonitor monitor) { monitor .beginTask( DataTransferMessages.WizardProjectsImportPage_SearchingMessage, 100); selectedProjects = new ProjectRecord[0]; Collection files = new ArrayList(); monitor.worked(10); if (!dirSelected && ArchiveFileManipulations.isTarFile(path)) { TarFile sourceTarFile = getSpecifiedTarSourceFile(path); if (sourceTarFile == null) { return; } structureProvider = new TarLeveledStructureProvider( sourceTarFile); Object child = structureProvider.getRoot(); if (!collectProjectFilesFromProvider(files, child, 0, monitor)) { return; } Iterator filesIterator = files.iterator(); selectedProjects = new ProjectRecord[files.size()]; int index = 0; monitor.worked(50); monitor .subTask(DataTransferMessages.WizardProjectsImportPage_ProcessingMessage); while (filesIterator.hasNext()) { selectedProjects[index++] = (ProjectRecord) filesIterator .next(); } } else if (!dirSelected && ArchiveFileManipulations.isZipFile(path)) { ZipFile sourceFile = getSpecifiedZipSourceFile(path); if (sourceFile == null) { return; } structureProvider = new ZipLeveledStructureProvider( sourceFile); Object child = structureProvider.getRoot(); if (!collectProjectFilesFromProvider(files, child, 0, monitor)) { return; } Iterator filesIterator = files.iterator(); selectedProjects = new ProjectRecord[files.size()]; int index = 0; monitor.worked(50); monitor .subTask(DataTransferMessages.WizardProjectsImportPage_ProcessingMessage); while (filesIterator.hasNext()) { selectedProjects[index++] = (ProjectRecord) filesIterator .next(); } } else { monitor.worked(60); } monitor.done(); } }); } catch (InvocationTargetException e) { IDEWorkbenchPlugin.log(e.getMessage(), e); } catch (InterruptedException e) { // Nothing to do if the user interrupts. } projectsList.refresh(true); ProjectRecord[] projects = getProjectRecords(); boolean displayWarning = false; for (int i = 0; i < projects.length; i++) { if(projects[i].hasConflicts) { displayWarning = true; projectsList.setGrayed(projects[i], true); }else { projectsList.setChecked(projects[i], true); } } if (displayWarning) { setMessage( DataTransferMessages.WizardProjectsImportPage_projectsInWorkspace, WARNING); } else { setMessage(""); } setPageComplete(projectsList.getCheckedElements().length > 0); if(selectedProjects.length == 0) { setMessage( DataTransferMessages.WizardProjectsImportPage_noProjectsToImport, WARNING); } } /** * Answer a handle to the zip file currently specified as being the source. * Return null if this file does not exist or is not of valid format. */ private ZipFile getSpecifiedZipSourceFile(String fileName) { if (fileName.length() == 0) { return null; } try { return new ZipFile(fileName); } catch (ZipException e) { displayErrorDialog(DataTransferMessages.ZipImport_badFormat); } catch (IOException e) { displayErrorDialog(DataTransferMessages.ZipImport_couldNotRead); } archivePathField.setFocus(); return null; } /** * Answer a handle to the zip file currently specified as being the source. * Return null if this file does not exist or is not of valid format. */ private TarFile getSpecifiedTarSourceFile(String fileName) { if (fileName.length() == 0) { return null; } try { return new TarFile(fileName); } catch (TarException e) { displayErrorDialog(DataTransferMessages.TarImport_badFormat); } catch (IOException e) { displayErrorDialog(DataTransferMessages.ZipImport_couldNotRead); } archivePathField.setFocus(); return null; } /** * Display an error dialog with the specified message. * * @param message * the error message */ protected void displayErrorDialog(String message) { MessageDialog.open(MessageDialog.ERROR, getContainer().getShell(), getErrorDialogTitle(), message, SWT.SHEET); } /** * Get the title for an error dialog. Subclasses should override. */ protected String getErrorDialogTitle() { return IDEWorkbenchMessages.WizardExportPage_internalErrorTitle; } /** * Collect the list of .project files that are under directory into files. * * @param files * @param monitor * The monitor to report to * @return boolean <code>true</code> if the operation was completed. */ private boolean collectProjectFilesFromProvider(Collection files, Object entry, int level, IProgressMonitor monitor) { if (monitor.isCanceled()) { return false; } monitor.subTask(NLS.bind( DataTransferMessages.WizardProjectsImportPage_CheckingMessage, structureProvider.getLabel(entry))); List children = structureProvider.getChildren(entry); if (children == null) { children = new ArrayList(1); } Iterator childrenEnum = children.iterator(); while (childrenEnum.hasNext()) { Object child = childrenEnum.next(); if (structureProvider.isFolder(child)) { collectProjectFilesFromProvider(files, child, level + 1, monitor); } String elementLabel = structureProvider.getLabel(child); if (elementLabel.equals(IProjectDescription.DESCRIPTION_FILE_NAME)) { files.add(new ProjectRecord(child, entry, level)); } } return true; } /** * The browse button has been selected. Select the location. */ protected void handleLocationArchiveButtonPressed() { FileDialog dialog = new FileDialog(archivePathField.getShell(), SWT.SHEET); dialog.setFilterExtensions(FILE_IMPORT_MASK); dialog .setText(DataTransferMessages.WizardProjectsImportPage_SelectArchiveDialogTitle); String fileName = archivePathField.getText().trim(); if (fileName.length() == 0) { fileName = previouslyBrowsedArchive; } if (fileName.length() == 0) { dialog.setFilterPath(IDEWorkbenchPlugin.getPluginWorkspace() .getRoot().getLocation().toOSString()); } else { File path = new File(fileName).getParentFile(); if (path != null && path.exists()) { dialog.setFilterPath(path.toString()); } } String selectedArchive = dialog.open(); if (selectedArchive != null) { previouslyBrowsedArchive = selectedArchive; archivePathField.setText(previouslyBrowsedArchive); updateProjectsList(selectedArchive); } } /** * Create the selected projects * * @return boolean <code>true</code> if all project creations were * successful. */ public boolean createProjects() { saveWidgetValues(); final Object[] selected = projectsList.getCheckedElements(); createdProjects = new ArrayList(); WorkspaceModifyOperation op = new WorkspaceModifyOperation() { protected void execute(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("", selected.length); //$NON-NLS-1$ if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (int i = 0; i < selected.length; i++) { createExistingProject((ProjectRecord) selected[i], new SubProgressMonitor(monitor, 1)); } } finally { monitor.done(); } } }; // run the new project creation operation try { getContainer().run(true, true, op); } catch (InterruptedException e) { return false; } catch (InvocationTargetException e) { // one of the steps resulted in a core exception Throwable t = e.getTargetException(); String message = DataTransferMessages.WizardExternalProjectImportPage_errorMessage; IStatus status; if (t instanceof CoreException) { status = ((CoreException) t).getStatus(); } else { status = new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, 1, message, t); } ErrorDialog.openError(getShell(), message, null, status); return false; } ArchiveFileManipulations.closeStructureProvider(structureProvider, getShell()); return true; } List createdProjects; /** * Performs clean-up if the user cancels the wizard without doing anything */ public void performCancel() { ArchiveFileManipulations.closeStructureProvider(structureProvider, getShell()); } /** * Create the project described in record. If it is successful return true. * * @param record * @return boolean <code>true</code> if successful * @throws InterruptedException */ private boolean createExistingProject(final ProjectRecord record, IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { String projectName = record.getProjectName(); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IProject project = workspace.getRoot().getProject(projectName); createdProjects.add(project); if (record.description == null) { // error case record.description = workspace.newProjectDescription(projectName); IPath locationPath = new Path(record.projectSystemFile .getAbsolutePath()); // If it is under the root use the default location if (Platform.getLocation().isPrefixOf(locationPath)) { record.description.setLocation(null); } else { record.description.setLocation(locationPath); } } else { record.description.setName(projectName); } if (record.projectArchiveFile != null) { // import from archive List fileSystemObjects = structureProvider .getChildren(record.parent); structureProvider.setStrip(record.level); ImportOperation operation = new ImportOperation(project .getFullPath(), structureProvider.getRoot(), structureProvider, this, fileSystemObjects); operation.setContext(getShell()); operation.run(monitor); return true; } // import from file system File importSource = null; if (copyFiles) { // import project from location copying files - use default project // location for this workspace URI locationURI = record.description.getLocationURI(); // if location is null, project already exists in this location or // some error condition occured. if (locationURI != null) { // validate the location of the project being copied IStatus result = ResourcesPlugin.getWorkspace().validateProjectLocationURI(project, locationURI); if(!result.isOK()) throw new InvocationTargetException(new CoreException(result)); importSource = new File(locationURI); IProjectDescription desc = workspace .newProjectDescription(projectName); desc.setBuildSpec(record.description.getBuildSpec()); desc.setComment(record.description.getComment()); desc.setDynamicReferences(record.description .getDynamicReferences()); desc.setNatureIds(record.description.getNatureIds()); desc.setReferencedProjects(record.description .getReferencedProjects()); record.description = desc; } } try { monitor .beginTask( DataTransferMessages.WizardProjectsImportPage_CreateProjectsTask, 100); project.create(record.description, new SubProgressMonitor(monitor, 30)); project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor( monitor, 70)); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } // import operation to import project files if copy checkbox is selected if (copyFiles && importSource != null) { List filesToImport = FileSystemStructureProvider.INSTANCE .getChildren(importSource); ImportOperation operation = new ImportOperation(project .getFullPath(), importSource, FileSystemStructureProvider.INSTANCE, this, filesToImport); operation.setContext(getShell()); operation.setOverwriteResources(true); // need to overwrite // .project, .classpath // files operation.setCreateContainerStructure(false); operation.run(monitor); } return true; } /** * The <code>WizardDataTransfer</code> implementation of this * <code>IOverwriteQuery</code> method asks the user whether the existing * resource at the given path should be overwritten. * * @param pathString * @return the user's reply: one of <code>"YES"</code>, <code>"NO"</code>, * <code>"ALL"</code>, or <code>"CANCEL"</code> */ public String queryOverwrite(String pathString) { Path path = new Path(pathString); String messageString; // Break the message up if there is a file name and a directory // and there are at least 2 segments. if (path.getFileExtension() == null || path.segmentCount() < 2) { messageString = NLS.bind( IDEWorkbenchMessages.WizardDataTransfer_existsQuestion, pathString); } else { messageString = NLS .bind( IDEWorkbenchMessages.WizardDataTransfer_overwriteNameAndPathQuestion, path.lastSegment(), path.removeLastSegments(1) .toOSString()); } final MessageDialog dialog = new MessageDialog(getContainer() .getShell(), IDEWorkbenchMessages.Question, null, messageString, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.NO_TO_ALL_LABEL, IDialogConstants.CANCEL_LABEL }, 0) { protected int getShellStyle() { return super.getShellStyle() | SWT.SHEET; } }; String[] response = new String[] { YES, ALL, NO, NO_ALL, CANCEL }; // run in syncExec because callback is from an operation, // which is probably not running in the UI thread. getControl().getDisplay().syncExec(new Runnable() { public void run() { dialog.open(); } }); return dialog.getReturnCode() < 0 ? CANCEL : response[dialog .getReturnCode()]; } /** * Method used for test suite. * * @return CheckboxTreeViewer the viewer containing all the projects found */ public CheckboxTreeViewer getProjectsList() { return projectsList; } /** * Retrieve all the projects in the current workspace. * * @return IProject[] array of IProject in the current workspace */ private IProject[] getProjectsInWorkspace() { if (wsProjects == null) { wsProjects = IDEWorkbenchPlugin.getPluginWorkspace().getRoot() .getProjects(); } return wsProjects; } /** * Get the array of project records that can be imported from the * source workspace or archive, selected by the user. If a project with the * same name exists in both the source workspace and the current workspace, * then the hasConflicts flag would be set on that project record. * * Method declared public for test suite. * * @return ProjectRecord[] array of projects that can be imported into the * workspace */ public ProjectRecord[] getProjectRecords() { List projectRecords = new ArrayList(); for (int i = 0; i < selectedProjects.length; i++) { if ( (isProjectInWorkspacePath(selectedProjects[i].getProjectName()) && copyFiles)|| isProjectInWorkspace(selectedProjects[i].getProjectName())) { selectedProjects[i].hasConflicts = true; } projectRecords.add(selectedProjects[i]); } return (ProjectRecord[]) projectRecords .toArray(new ProjectRecord[projectRecords.size()]); } /** * Determine if there is a directory with the project name in the workspace path. * * @param projectName the name of the project * @return true if there is a directory with the same name of the imported project */ private boolean isProjectInWorkspacePath(String projectName){ final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IPath wsPath = workspace.getRoot().getLocation(); IPath localProjectPath = wsPath.append(projectName); return localProjectPath.toFile().exists(); } /** * Determine if the project with the given name is in the current workspace. * * @param projectName * String the project name to check * @return boolean true if the project with the given name is in this * workspace */ private boolean isProjectInWorkspace(String projectName) { if (projectName == null) { return false; } IProject[] workspaceProjects = getProjectsInWorkspace(); for (int i = 0; i < workspaceProjects.length; i++) { if (projectName.equals(workspaceProjects[i].getName())) { return true; } } return false; } /** * Use the dialog store to restore widget values to the values that they * held last time this wizard was used to completion, or alternatively, * if an initial path is specified, use it to select values. * * Method declared public only for use of tests. */ public void restoreWidgetValues() { // First, check to see if we have resore settings, and // take care of the checkbox IDialogSettings settings = getDialogSettings(); if (settings != null) { // checkbox copyFiles = settings.getBoolean(STORE_COPY_PROJECT_ID); lastCopyFiles = copyFiles; } // Third, if we do have an initial path, set the proper // path and radio buttons to the initial value. Move // cursor to the end of the path so user can see the // most relevant part (directory / archive name) else if (initialPath != null) { boolean dir = new File(initialPath).isDirectory(); if (!dir) { archivePathField.setText(initialPath); archivePathField.setSelection(initialPath.length()); } } } /** * Since Finish was pressed, write widget values to the dialog store so that * they will persist into the next invocation of this wizard page. * * Method declared public only for use of tests. */ public void saveWidgetValues() { IDialogSettings settings = getDialogSettings(); if (settings != null) { settings.put(STORE_COPY_PROJECT_ID, true); settings.put(STORE_ARCHIVE_SELECTED, true); } } }
38,179
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImportProjectWizard.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.importproject/src/net/heartsome/cat/ts/importproject/wizards/ImportProjectWizard.java
package net.heartsome.cat.ts.importproject.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IImportWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; import org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings("restriction") public class ImportProjectWizard extends Wizard implements IImportWizard { private static final String IMPORT_PROJECT_SECTION = "ImportProjectWizard";//$NON-NLS-1$ private Logger LOGGER = LoggerFactory.getLogger(ImportProjectWizard.class); // private ImportProjectWizardPage mainPage; private ImportProjectWizardPage2 mainPage; private IStructuredSelection currentSelection = null; private String initialPath = null; private boolean canFinish; /** * Constructor for ExternalProjectImportWizard. */ public ImportProjectWizard() { this(null); } /** * Constructor for ExternalProjectImportWizard. * * @param initialPath Default path for wizard to import * @since 3.5 */ public ImportProjectWizard(String initialPath) { super(); this.initialPath = initialPath; setWindowTitle(DataTransferMessages.DataTransfer_importTitle); setNeedsProgressMonitor(true); IDialogSettings workbenchSettings = IDEWorkbenchPlugin.getDefault() .getDialogSettings(); IDialogSettings wizardSettings = workbenchSettings .getSection(IMPORT_PROJECT_SECTION); if (wizardSettings == null) { wizardSettings = workbenchSettings .addNewSection(IMPORT_PROJECT_SECTION); } setDialogSettings(wizardSettings); } /* (non-Javadoc) * Method declared on IWizard. */ public void addPages() { super.addPages(); // mainPage = new ImportProjectWizardPage("wizardExternalProjectsPage", initialPath, currentSelection); //$NON-NLS-1$ mainPage = new ImportProjectWizardPage2("wizardExternalProjectsPage", initialPath, currentSelection); //$NON-NLS-1$ addPage(mainPage); } /* (non-Javadoc) * Method declared on IWorkbenchWizard. */ public void init(IWorkbench workbench, IStructuredSelection currentSelection) { setDefaultPageImageDescriptor( IDEWorkbenchPlugin.getIDEImageDescriptor("wizban/importproj_wiz.png")); //$NON-NLS-1$ this.currentSelection = currentSelection; } /* (non-Javadoc) * Method declared on IWizard. */ public boolean performCancel() { mainPage.performCancel(); return true; } /* (non-Javadoc) * Method declared on IWizard. */ public boolean performFinish() { final IRunnableWithProgress importProgress = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { canFinish = mainPage.createProjects(monitor); } }; try { Display.getDefault().syncExec(new Runnable() { public void run() { try { getContainer().run(true, true, importProgress); } catch (InvocationTargetException e) { e.printStackTrace(); LOGGER.error("",e); } catch (InterruptedException e) { e.printStackTrace(); LOGGER.error("",e); } } }); } catch (Exception e) { e.printStackTrace(); LOGGER.error("",e); } return canFinish; } }
3,807
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImportProjectWizardPage2.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.importproject/src/net/heartsome/cat/ts/importproject/wizards/ImportProjectWizardPage2.java
package net.heartsome.cat.ts.importproject.wizards; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import net.heartsome.cat.common.bean.DatabaseModelBean; import net.heartsome.cat.common.bean.ProjectInfoBean; import net.heartsome.cat.common.core.Constant; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.core.file.ProjectConfiger; import net.heartsome.cat.ts.core.file.ProjectConfigerFactory; import net.heartsome.cat.ts.core.file.ProjectConfigerUtil; import net.heartsome.cat.ts.importproject.Activator; import net.heartsome.cat.ts.importproject.resource.Messages; import net.heartsome.cat.ts.importproject.widgiet.ProjectResource; import net.heartsome.cat.ts.importproject.widgiet.ResourceTree; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; 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.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IColorProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.wizards.datatransfer.ArchiveFileManipulations; import org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages; import org.eclipse.ui.internal.wizards.datatransfer.ILeveledImportStructureProvider; import org.eclipse.ui.internal.wizards.datatransfer.TarEntry; import org.eclipse.ui.internal.wizards.datatransfer.TarException; import org.eclipse.ui.internal.wizards.datatransfer.TarFile; import org.eclipse.ui.internal.wizards.datatransfer.TarLeveledStructureProvider; import org.eclipse.ui.internal.wizards.datatransfer.ZipLeveledStructureProvider; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 导入项目新的需求设计 * @author robert 2013-02-27 */ public class ImportProjectWizardPage2 extends WizardPage implements Listener { private static final String[] FILE_IMPORT_MASK = { "*" + Constant.PROJECT_PACK_EXTENSSION, "*" }; private static final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; private static final String HTML_EDITOR_ID = "net.heartsome.cat.ts.ui.editor.HtmlBrowser"; /** 项目的图标 */ private Image projectImg; /** 文件夹的图标 */ private Image folderImg; /** hsXliff 文件的图标 */ private Image hsXLiffImg; /** html 的图标 */ private Image htmlImg; private Image defaultImg; private Map<String, Image> imgMap; private String previouslyBrowsedPath = ""; private Text filePathTxt; private Button browseBtn; /** 左边显示所有内容,包括项目,文件夹,文件的树 */ private ResourceTree selectElementTree; /** 右边显示左边选中要导入资源的重复文件或重复的文件夹 */ private ResourceTree repeatElementTree; private Button leftSelectAllBtn; private Button leftDisSelectAllBtn; private Button leftAllExpandBtn; private Button rightSelectAllBtn; private Button rightDisSelectAllBtn; private Button rightAllExpandBtn; private SelectProjectContentProvider selectContentProvider; private RepeatProjectContentProvider repeateContentProvider; /** 默认导入的资源,即这些资源是不会显示在资源树上的 */ private List<IResource> defaultImportItemList = new ArrayList<IResource>(); private ProjectRecord[] selectedProjects = new ProjectRecord[0]; @SuppressWarnings("restriction") private ILeveledImportStructureProvider structureProvider; // The last selected path to minimize searches private String lastPath; // The last time that the file or folder at the selected path was modified to mimize searches private long lastModified; private boolean copyFiles = true; private boolean lastCopyFiles = false; /** 左边资源树选择文件后,重复的资源 */ private Map<String, Set<ProjectResource>> checkedRepeatElementMap = new HashMap<String, Set<ProjectResource>>(); private IWorkspaceRoot root; private IWorkbenchPage page; /** 初始化时,所有的根项目 */ private ProjectResource[] rootProjectArray; private int totalWorkSum = 0; private boolean runContinue = false; private Map<IFile, IEditorPart> openedIfileMap; private final int INIT_TYPE = 0; private final int OTHER_TYPE = 1; private Logger LOGGER = LoggerFactory.getLogger(ImportProjectWizardPage2.class.getName()); @SuppressWarnings("restriction") protected ImportProjectWizardPage2(String pageName, String initialPath, IStructuredSelection currentSelection) { super(pageName); setTitle(DataTransferMessages.DataTransfer_importTitle); initData(); } private void initData() { root = ResourcesPlugin.getWorkspace().getRoot(); page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); projectImg = Activator.getImageDescriptor("images/prj_open.png").createImage(); folderImg = Activator.getImageDescriptor("images/folder.png").createImage(); hsXLiffImg = Activator.getImageDescriptor("images/hsxliff.png").createImage(); htmlImg = Activator.getImageDescriptor("images/html.png").createImage(); defaultImg = Activator.getImageDescriptor("images/file_obj.png").createImage(); imgMap = new HashMap<String, Image>(); } public void createControl(Composite parent) { GridDataFactory.fillDefaults().hint(800, 450).grab(true, true).applyTo(parent); Composite tparent = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().hint(600, 600).grab(true, true).applyTo(tparent); tparent.setLayout(new GridLayout()); initializeDialogUnits(parent); createBrowseBtn(tparent); createResourceTree(tparent); setControl(parent); setPageCompleteState(INIT_TYPE); setImageDescriptor(Activator.getImageDescriptor("images/importProject_logo.png")); } /** * 创建 浏览 文件按钮 * @param tparent */ private void createBrowseBtn(Composite tparent) { Composite btnCmp = new Composite(tparent, SWT.NONE); btnCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); btnCmp.setLayout(new GridLayout(3, false)); Label lbl = new Label(btnCmp, SWT.NONE); lbl.setText(Messages.getString("importProjectWizardPage.selectFileLbl")); filePathTxt = new Text(btnCmp, SWT.BORDER); filePathTxt.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseBtn = new Button(btnCmp, SWT.NONE); browseBtn.setText(Messages.getString("importProjectWizardPage.broswer")); browseBtn.addListener(SWT.Selection, this); } /** * 创建两颗显示资源树 */ private void createResourceTree(Composite tparent) { Composite resourceTreeCmp = new Composite(tparent, SWT.NONE); resourceTreeCmp.setLayoutData(new GridData(GridData.FILL_BOTH)); resourceTreeCmp.setLayout(new GridLayout(2, true)); Label leftLbl = new Label(resourceTreeCmp, SWT.NONE); leftLbl.setText(Messages.getString("importProjectWizardPage.projectOfImport")); Label rightLbl = new Label(resourceTreeCmp, SWT.NONE); rightLbl.setText(Messages.getString("importProjectWizardPage.repeatedContent")); // 定义两颗树 selectContentProvider = new SelectProjectContentProvider(); repeateContentProvider = new RepeatProjectContentProvider(); selectElementTree = new ResourceTree(resourceTreeCmp, selectContentProvider, new ProjectLabelProvider()); repeatElementTree = new ResourceTree(resourceTreeCmp, repeateContentProvider, new ProjectLabelProvider()); // 左边的按钮 Composite leftBtnCmp = new Composite(resourceTreeCmp, SWT.NONE); leftBtnCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayoutFactory.swtDefaults().margins(0, 0).numColumns(3).applyTo(leftBtnCmp); leftSelectAllBtn = new Button(leftBtnCmp, SWT.PUSH); leftSelectAllBtn.setText(Messages.getString("importProjectWizardPage.leftSelectAllBtn")); leftSelectAllBtn.addListener(SWT.Selection, this); setButtonLayoutData(leftSelectAllBtn); leftDisSelectAllBtn = new Button(leftBtnCmp, SWT.PUSH); leftDisSelectAllBtn.setText(Messages.getString("importProjectWizardPage.leftDisSelectAllBtn")); leftDisSelectAllBtn.addListener(SWT.Selection, this); setButtonLayoutData(leftDisSelectAllBtn); leftAllExpandBtn = new Button(leftBtnCmp, SWT.PUSH); leftAllExpandBtn.setText(Messages.getString("importProjectWizardPage.leftExpandAllBtn")); leftAllExpandBtn.addListener(SWT.Selection, this); setButtonLayoutData(leftAllExpandBtn); // 右边的按钮 Composite rightBtnCmp = new Composite(resourceTreeCmp, SWT.NONE); rightBtnCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayoutFactory.swtDefaults().margins(0, 0).numColumns(3).applyTo(rightBtnCmp); rightSelectAllBtn = new Button(rightBtnCmp, SWT.PUSH); rightSelectAllBtn.setText(Messages.getString("importProjectWizardPage.rightSelectAllBtn")); rightSelectAllBtn.addListener(SWT.Selection, this); setButtonLayoutData(rightSelectAllBtn); rightDisSelectAllBtn = new Button(rightBtnCmp, SWT.PUSH); rightDisSelectAllBtn.setText(Messages.getString("importProjectWizardPage.rightDisSelectAllBtn")); rightDisSelectAllBtn.addListener(SWT.Selection, this); setButtonLayoutData(rightDisSelectAllBtn); rightAllExpandBtn = new Button(rightBtnCmp, SWT.PUSH); rightAllExpandBtn.setText(Messages.getString("importProjectWizardPage.rightExpandAllBtn")); rightAllExpandBtn.addListener(SWT.Selection, this); setButtonLayoutData(rightAllExpandBtn); // 初始化两颗树的事件 initTreeListener(); selectElementTree.setInput(this); repeatElementTree.setInput(this); } public void handleEvent(Event event) { if (event.widget == browseBtn) { handleBrowseBtnPressed(); } else if (event.widget == leftSelectAllBtn) { // 执行全部选择(左边树) selectElementTreeBtnSelectFunction(true); } else if (event.widget == leftDisSelectAllBtn) { // 执行全部不选(右边树) selectElementTreeBtnSelectFunction(false); } else if (event.widget == leftAllExpandBtn) { selectElementTree.expandAll(); } else if (event.widget == rightSelectAllBtn) { // 执行全部选择(左边树) checkRepeatTreeBtnSelectFunction(true); } else if (event.widget == rightDisSelectAllBtn) { // 执行全部不选(右边树) checkRepeatTreeBtnSelectFunction(false); } else if (event.widget == rightAllExpandBtn) { repeatElementTree.expandAll(); } setPageCompleteState(OTHER_TYPE); } /** * 重复树点击选择所有以及所有不选择按钮时执行的方法 */ private void checkRepeatTreeBtnSelectFunction(final boolean checkState) { BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { public void run() { repeatElementTree.setCheckedAll(checkState); for (Object obj : repeatElementTree.getAllElement()) { if (obj instanceof ProjectResource) { ProjectResource proResourceElement = (ProjectResource) obj; proResourceElement.setNeedCover(repeatElementTree.getChecked(proResourceElement)); } } repeatElementTree.refresh(true); } }); } /** * 点击选择所有以及所有不选择按钮时执行的方法 * @param event */ private void selectElementTreeBtnSelectFunction(final boolean checkState) { checkedRepeatElementMap.clear(); selectElementTree.setCheckedAll(checkState); Object[] checkedElementArray = selectElementTree.getCheckedElements(); for (Object checkedElement : checkedElementArray) { if (checkedElement instanceof ProjectResource) { ProjectResource proResourceElement = (ProjectResource) checkedElement; String projectName = proResourceElement.getProjectName(); // 如果是重复的资源,那么添加到缓存中 if (proResourceElement.isProjectRepeat()) { if (checkedRepeatElementMap.containsKey(projectName)) { Set<ProjectResource> checkedElementSet = checkedRepeatElementMap.get(projectName); checkedElementSet.add(proResourceElement); checkedRepeatElementMap.put(projectName, checkedElementSet); } else { Set<ProjectResource> checkedElementSet = new HashSet<ProjectResource>(); checkedElementSet.add(proResourceElement); checkedRepeatElementMap.put(projectName, checkedElementSet); } } } } setNotCoverForNotcheckOfSelectTree(); repeatElementTree.refresh(); repeatElementTree.expandAll(); checkRepeatTreeBtnSelectFunction(true); } /** * 初始化两颗树的事件 */ private void initTreeListener() { selectElementTree.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(final CheckStateChangedEvent event) { BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { public void run() { selectElementTreeCheckFunction(event); setNotCoverForNotcheckOfSelectTree(); setPageCompleteState(OTHER_TYPE); } }); } }); repeatElementTree.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(final CheckStateChangedEvent event) { BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { public void run() { Object element = event.getElement(); if (element instanceof ProjectResource) { ProjectResource proResourceElement = (ProjectResource) element; if (repeatElementTree.getChecked(proResourceElement)) { proResourceElement.setNeedCover(true); } else { proResourceElement.setNeedCover(false); } // 处理所有的子文件或文件夹,以保存证他们都处于要覆盖状态 checkRepeatTreeChildCover(proResourceElement); // 处理当前节点的所有父节点 ProjectResource parentProRes = proResourceElement.getParent(); while (parentProRes != null) { parentProRes.setNeedCover(repeatElementTree.getChecked(parentProRes)); parentProRes = parentProRes.getParent(); } repeatElementTree.refresh(true); } setPageCompleteState(OTHER_TYPE); } }); } }); } /** * 左边树点击事件触发的方法 * @param event */ private void selectElementTreeCheckFunction(CheckStateChangedEvent event) { checkedRepeatElementMap.clear(); Object[] checkedElementArray = selectElementTree.getCheckedElements(); for (Object checkedElement : checkedElementArray) { if (checkedElement instanceof ProjectResource) { ProjectResource proResourceElement = (ProjectResource) checkedElement; String projectName = proResourceElement.getProjectName(); // 如果是重复的资源,那么添加到缓存中 if (proResourceElement.isProjectRepeat()) { if (checkedRepeatElementMap.containsKey(projectName)) { Set<ProjectResource> checkedElementSet = checkedRepeatElementMap.get(projectName); checkedElementSet.add(proResourceElement); checkedRepeatElementMap.put(projectName, checkedElementSet); } else { Set<ProjectResource> checkedElementSet = new HashSet<ProjectResource>(); checkedElementSet.add(proResourceElement); checkedRepeatElementMap.put(projectName, checkedElementSet); } } } } boolean noData = repeatElementTree.getTree().getItemCount() <= 0; repeatElementTree.refresh(); if (noData) { checkRepeatTreeBtnSelectFunction(true); repeatElementTree.expandAll(); } } /** * 将左边树中未选择的节点的 needCover 属性恢复默认状态 备注:主要是修改 一个属性同步的BUG : 全选左边树,再全选右边树,这时全不选左边树,这时所有属性 */ private void setNotCoverForNotcheckOfSelectTree() { for (ProjectResource proSourceElement : selectElementTree.getAllElement()) { if (!selectElementTree.getChecked(proSourceElement)) { proSourceElement.restoreNeedCoverDefault(); } } } /** * 重复树点击事件触发的方法,该方法主要是实现用户针对重复文件的覆盖选择操作 * @param event */ private void checkRepeatTreeChildCover(ProjectResource parentElemnt) { Object[] childArray = repeateContentProvider.getChildren(parentElemnt); if (childArray == null || childArray.length <= 0) { return; } for (Object childObj : childArray) { if (childObj instanceof ProjectResource) { ProjectResource proResourceChild = (ProjectResource) childObj; proResourceChild.setNeedCover(repeatElementTree.getChecked(proResourceChild)); checkRepeatTreeChildCover(proResourceChild); } } } protected void handleBrowseBtnPressed() { FileDialog dialog = new FileDialog(filePathTxt.getShell(), SWT.SHEET); dialog.setFilterExtensions(FILE_IMPORT_MASK); dialog.setText(Messages.getString("importProjectWizardPage.SelectArchiveDialogTitle")); String fileName = filePathTxt.getText().trim(); if (fileName.length() == 0) { fileName = previouslyBrowsedPath; } if (fileName.length() == 0) { // IDEWorkbenchPlugin.getPluginWorkspace() dialog.setFilterPath(ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString()); } else { File path = new File(fileName).getParentFile(); if (path != null && path.exists()) { dialog.setFilterPath(path.toString()); } } String selectedArchive = dialog.open(); if (selectedArchive != null) { previouslyBrowsedPath = selectedArchive; filePathTxt.setText(previouslyBrowsedPath); // 先择新的项目包时,清除重复树中的所有内容 checkedRepeatElementMap.clear(); repeatElementTree.refresh(true); updateProjectsList(selectedArchive); // 初始化时全部初始化 selectElementTree.expandAll(); selectElementTreeBtnSelectFunction(true); } } public void updateProjectsList(final String path) { if (path == null || path.length() == 0) { setMessage(Messages.getString("wizard.ImportProjectWizardPage.desc")); selectedProjects = new ProjectRecord[0]; setPageComplete(selectElementTree.getCheckedElements().length > 0); lastPath = path; return; } final File directory = new File(path); long modified = directory.lastModified(); if (path.equals(lastPath) && lastModified == modified && lastCopyFiles == copyFiles) { // since the file/folder was not modified and the path did not // change, no refreshing is required return; } lastPath = path; lastModified = modified; lastCopyFiles = copyFiles; // We can't access the radio button from the inner class so get the // status beforehand final boolean dirSelected = false; try { getContainer().run(true, true, new IRunnableWithProgress() { @SuppressWarnings({ "rawtypes", "restriction" }) public void run(IProgressMonitor monitor) { monitor.beginTask(Messages.getString("importProjectWizardPage.searchingMessage"), 100); selectedProjects = new ProjectRecord[0]; Collection files = new ArrayList(); monitor.worked(10); if (!dirSelected && ArchiveFileManipulations.isTarFile(path)) { TarFile sourceTarFile = getSpecifiedTarSourceFile(path); if (sourceTarFile == null) { return; } structureProvider = new TarLeveledStructureProvider(sourceTarFile); Object child = structureProvider.getRoot(); if (!collectProjectFilesFromProvider(files, child, 0, monitor)) { return; } Iterator filesIterator = files.iterator(); selectedProjects = new ProjectRecord[files.size()]; int index = 0; monitor.worked(50); monitor.subTask(Messages.getString("importProjectWizardPage.processingMessage")); while (filesIterator.hasNext()) { selectedProjects[index++] = (ProjectRecord) filesIterator.next(); } } else if (!dirSelected && ArchiveFileManipulations.isZipFile(path)) { ZipFile sourceFile = getSpecifiedZipSourceFile(path); if (sourceFile == null) { return; } structureProvider = new ZipLeveledStructureProvider(sourceFile); Object child = structureProvider.getRoot(); if (!collectProjectFilesFromProvider(files, child, 0, monitor)) { return; } Iterator filesIterator = files.iterator(); selectedProjects = new ProjectRecord[files.size()]; int index = 0; monitor.worked(50); monitor.subTask(Messages.getString("importProjectWizardPage.processingMessage")); while (filesIterator.hasNext()) { selectedProjects[index++] = (ProjectRecord) filesIterator.next(); } } else { monitor.worked(60); } monitor.done(); } }); } catch (InvocationTargetException e) { LOGGER.error(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } // 开始处理导入项目中的项目名称不合法的情况 String projectName = ""; StringBuffer errorProjectNameSB = new StringBuffer(); StringBuffer errorCharSB = new StringBuffer(); List<ProjectRecord> tempList = new ArrayList<ProjectRecord>(); boolean isError = false; for (int i = 0; i < selectedProjects.length; i++) { projectName = selectedProjects[i].getProjectName(); isError = false; for (int j = 0; j < Constant.RESOURCE_ERRORCHAR.length; j++) { if (projectName.indexOf(Constant.RESOURCE_ERRORCHAR[j]) != -1) { errorCharSB.append(Constant.RESOURCE_ERRORCHAR[j]); errorProjectNameSB.append(projectName + ", "); isError = true; } } if (!isError) { tempList.add(selectedProjects[i]); } } if (errorProjectNameSB.length() > 0) { final String errorTip = MessageFormat.format( Messages.getString("importProjectWizardPage.projectError"), new Object[] { errorProjectNameSB.toString().substring(0, errorProjectNameSB.toString().length() - 2), errorCharSB.toString() }); Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openWarning(getShell(), Messages.getString("importProject.all.dialog.warning"), errorTip); } }); } selectedProjects = tempList.toArray(new ProjectRecord[tempList.size()]); setPageComplete(selectElementTree.getCheckedElements().length > 0); selectElementTree.refresh(true); } public static void main(String[] args) { String[] a = new String[] { "1", "2", "3", "4" }; String[] b = new String[a.length]; for (int i = 0; i < 2; i++) { b[i] = a[i]; } a = b; System.out.println(a.length); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } @SuppressWarnings("restriction") private TarFile getSpecifiedTarSourceFile(String fileName) { if (fileName.length() == 0) { return null; } try { return new TarFile(fileName); } catch (TarException e) { displayErrorDialog(Messages.getString("importProjectWizardPage.dialog.badFormat")); } catch (IOException e) { displayErrorDialog(Messages.getString("importProjectWizardPage.dialog.couldNotRead")); } filePathTxt.setFocus(); return null; } /** * 获取左边树(选择项目资源树)的输入内容 * @return */ private ProjectResource[] getProjectResourceInput() { rootProjectArray = null; List<ProjectResource> proResourceList = new ArrayList<ProjectResource>(); for (int i = 0; i < selectedProjects.length; i++) { proResourceList.add(new ProjectResource(selectedProjects[i].getParent(), selectedProjects[i], structureProvider)); } rootProjectArray = (ProjectResource[]) proResourceList.toArray(new ProjectResource[proResourceList.size()]); selectElementTree.setRoot(rootProjectArray); return rootProjectArray; } /** * 获取右边树(重复项目资源)的输入内容,即获取重复的项目资源 * @return */ private ProjectResource[] getRepeateProResourceInput() { List<ProjectResource> proResourceList = new ArrayList<ProjectResource>(); for (ProjectResource proResource : rootProjectArray) { String projectName = proResource.getProjectName(); if (checkedRepeatElementMap.containsKey(projectName)) { proResourceList.add(proResource); } } ProjectResource[] root = (ProjectResource[]) proResourceList .toArray(new ProjectResource[proResourceList.size()]); repeatElementTree.setRoot(root); return root; } @SuppressWarnings({ "rawtypes", "unchecked" }) private boolean collectProjectFilesFromProvider(Collection files, Object entry, int level, IProgressMonitor monitor) { if (monitor.isCanceled()) { return false; } monitor.subTask(NLS.bind(Messages.getString("importProjectWizardPage.checkingMessage"), structureProvider.getLabel(entry))); List children = structureProvider.getChildren(entry); if (children == null) { children = new ArrayList(1); } Iterator childrenEnum = children.iterator(); while (childrenEnum.hasNext()) { Object child = childrenEnum.next(); if (structureProvider.isFolder(child)) { collectProjectFilesFromProvider(files, child, level + 1, monitor); } String elementLabel = structureProvider.getLabel(child); if (elementLabel.equals(IProjectDescription.DESCRIPTION_FILE_NAME)) { files.add(new ProjectRecord(child, entry, level)); } } return true; } private ZipFile getSpecifiedZipSourceFile(String fileName) { if (fileName.length() == 0) { return null; } try { return new ZipFile(fileName); } catch (ZipException e) { displayErrorDialog(Messages.getString("importProjectWizardPage.dialog.badFormat")); } catch (IOException e) { displayErrorDialog(Messages.getString("importProjectWizardPage.dialog.couldNotRead")); } filePathTxt.setFocus(); return null; } protected void displayErrorDialog(String message) { MessageDialog.openError(getShell(), Messages.getString("importProjectWizardPage.dialog.error"), message); } public void performCancel() { disposeImg(); } /** * 创建项目 * @return */ public boolean createProjects(IProgressMonitor monitor) { if (monitor == null) { monitor = new NullProgressMonitor(); } Display.getDefault().syncExec(new Runnable() { public void run() { for (ProjectResource projRoot : rootProjectArray) { if (selectElementTree.getChecked(projRoot)) { totalWorkSum++; } } } }); monitor.beginTask(Messages.getString("importProjectWizardPage.beginImportProj"), totalWorkSum); Display.getDefault().syncExec(new Runnable() { public void run() { openedIfileMap = getAllOpenedIFile(); } }); try { // 一个项目一个项目的进行相关处理 for (final ProjectResource projRoot : rootProjectArray) { // 如果当前项目未被选择。跳过继续执行 runContinue = false; Display.getDefault().syncExec(new Runnable() { public void run() { if (!selectElementTree.getChecked(projRoot)) { runContinue = true; } } }); if (runContinue) { continue; } monitor.setTaskName(MessageFormat.format( Messages.getString("importProjectWizardPage.beginImportProjName"), new Object[] { projRoot.getProjectName() })); final IProject newProject = root.getProject(projRoot.getProjectName()); if (!projRoot.isProjectRepeat()) { // 创建项目 newProject.create(null); if (!newProject.isOpen()) { newProject.open(null); } } IFile configIFile = newProject.getFile(Constant.FILE_CONFIG); ProjectConfigerUtil configUtil = null; if (configIFile.exists()) { configUtil = new ProjectConfigerUtil(newProject); configUtil.setDbMementos(); configUtil.clearConfig(); } final StringBuilder sb = new StringBuilder(); try { Display.getDefault().syncExec(new Runnable() { public void run() { try { createProjectImpl(projRoot, newProject); } catch (Exception e) { sb.append(Messages.getString("importProjectWizardPage.importFail")); LOGGER.error("",e); } } }); } finally { if (null != configUtil) { configUtil.restoreMementos(); } if(!sb.toString().isEmpty()){ monitor.done(); Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openWarning(getShell(), Messages.getString("importProject.all.dialog.warning"), Messages.getString("importProjectWizardPage.importFail")); } }); return false; } } createConfigFile(projRoot, newProject); createRequireFolder(newProject); resetConfigContent(newProject); monitor.worked(1); } } catch (Exception e) { e.printStackTrace(); monitor.done(); Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openWarning(getShell(), Messages.getString("importProject.all.dialog.warning"), Messages.getString("importProjectWizardPage.importFail")); } }); LOGGER.error(Messages.getString("importProjectWizardPage.LOGG.importEroor"), e); // disposeImg(); return false; } disposeImg(); monitor.done(); Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openInformation(getShell(), Messages.getString("importProject.all.dialog.info"), Messages.getString("importProjectWizardPage.importSuccess")); } }); return true; } /** * 创建 .config 文件夹 * @param projRoot * @param newProject */ private void createConfigFile(ProjectResource projRoot, IProject newProject) { try { IFile configIFile = newProject.getFile(Constant.FILE_CONFIG); if (!configIFile.exists()) { InputStream configStream = projRoot.getConfigFileContent(); configIFile.create(configStream, true, null); } } catch (Exception e) { e.printStackTrace(); LOGGER.error(Messages.getString("importProjectWizardPage.LOGG.importEroor"), e); } } public void resetConfigContent(IProject project) { ProjectConfiger projectConfig = ProjectConfigerFactory.getProjectConfiger(project); if (null == projectConfig) { return; } // FIX Bug#3709 导入项目时更新库--打开XLIFF文件时无法更新同名的记忆库/术语库 projectConfig.reloadConfig();// 重新加载一次数据,如果ProjectConfigerFactory缓存中含有导入项目的名称时,有bug ProjectInfoBean currentProjectConfig = projectConfig.getCurrentProjectConfig(); List<DatabaseModelBean> tmDb = currentProjectConfig.getTmDb(); int index = 0; for (DatabaseModelBean bean : tmDb) {// update tm config if ("SQLite".equals(bean.getDbType())) { resetSqliteTMNameAndPath(project, bean, index); index++; } } List<DatabaseModelBean> tbDb = currentProjectConfig.getTbDb(); index = 0; for (DatabaseModelBean bean : tbDb) {// update tb config if ("SQLite".equals(bean.getDbType())) { resetSqliteTBNameAndPath(project, bean, index); index++; } } projectConfig.updateProjectConfig(currentProjectConfig); try { project.refreshLocal(IResource.DEPTH_ZERO, null); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void resetSqliteTMNameAndPath(IProject project, DatabaseModelBean bean, int index) { IFolder folder = project.getFolder("TM"); if (!folder.exists()) { return; } String dbName = bean.getDbName(); IFile file = folder.getFile("Exported_" + index + "_" + dbName); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); String rootLocation = root.getLocation().toOSString(); String fileSeparator = System.getProperty("file.separator"); if (file.exists()) { bean.setDbName("Exported_" + index + "_" + dbName); } if (file.exists() || folder.getFile(dbName).exists()) { bean.setItlDBLocation(rootLocation + fileSeparator + project.getName() + fileSeparator + "TM"); } } private void resetSqliteTBNameAndPath(IProject project, DatabaseModelBean bean, int index) { IFolder folder = project.getFolder("TB"); if (!folder.exists()) { return; } String dbName = bean.getDbName(); IFile file = folder.getFile("Exported_" + index + "_" + dbName); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); String rootLocation = root.getLocation().toOSString(); String fileSeparator = System.getProperty("file.separator"); if (file.exists()) {// FIXME bean.setDbName("Exported_" + index + "_" + dbName); } if (file.exists() || folder.getFile(dbName).exists()) { bean.setItlDBLocation(rootLocation + fileSeparator + project.getName() + fileSeparator + "TB"); } } /** * 如果这几个必须的文件夹在项目中不存在,则创建。创建几个必须的文件夹,如下: Intermediate[Report, SKL], Source, Target, XLIFF 。 */ private void createRequireFolder(IProject newProject) { try { // 从上到下,先处理 Intermediate IFolder intermediateFolder = newProject.getFolder(Constant.FOLDER_INTERMEDDIATE); if (!intermediateFolder.exists()) { intermediateFolder.create(true, true, null); } // 再处理 Report IFolder reportFolder = intermediateFolder.getFolder(Constant.FOLDER_REPORT); if (!reportFolder.exists()) { reportFolder.create(true, true, null); } // 再处理 SKL IFolder sklFolder = intermediateFolder.getFolder(Constant.FOLDER_SKL); if (!sklFolder.exists()) { sklFolder.create(true, true, null); } // 再处理 source IFolder srcFolder = newProject.getFolder(Constant.FOLDER_SRC); if (!srcFolder.exists()) { srcFolder.create(true, true, null); } // 再处理 target IFolder tgtFolder = newProject.getFolder(Constant.FOLDER_TGT); if (!tgtFolder.exists()) { tgtFolder.create(true, true, null); } // 再处理 xliff IFolder xlfFolder = newProject.getFolder(Constant.FOLDER_XLIFF); if (!xlfFolder.exists()) { xlfFolder.create(true, true, null); } } catch (Exception e) { LOGGER.error(Messages.getString("importProjectWizardPage.LOGG.importEroor"), e); } } private void createProjectImpl(ProjectResource projRoot, IProject newProject) throws Exception { try { for (Object obj : selectContentProvider.getChildren(projRoot)) { if (obj instanceof ProjectResource) { ProjectResource proResource = (ProjectResource) obj; // 如果没有选中,那么不进行导入操作 if (!selectElementTree.getChecked(proResource)) { continue; } if (proResource.isFolder()) { // 如果是文件夹,则创建 IFolder childFolder = newProject.getFolder(proResource.getLabel()); if (!childFolder.exists()) { childFolder.create(true, true, null); } createCurProjectResource(proResource, childFolder); } else { // 如果是文件,则判断是否需要覆盖,若是,则直接覆盖 if (proResource.isNeedCover()) { IFile iFile = newProject.getFile(proResource.getLabel()); InputStream inputStream = proResource.getInputStream(); if (inputStream != null) { if (iFile.exists()) { closeOpenedFile(iFile); iFile.delete(true, null); } iFile.create(inputStream, true, null); } } } } } } catch (Exception e) { //disposeImg(); LOGGER.error(Messages.getString("importProjectWizardPage.LOGG.importEroor"), e); throw e; } } /** * 获取指定节点被选择的子节点 * @param parentResource * 树节点的父节点 * @param parentFolder * 项目空间的父文件夹 * @return */ private void createCurProjectResource(ProjectResource parentResource, IFolder parentContainer) throws Exception { if (parentResource == null || parentContainer == null) { return; } for (Object obj : selectContentProvider.getChildren(parentResource)) { if (obj instanceof ProjectResource) { ProjectResource proResource = (ProjectResource) obj; if (!selectElementTree.getChecked(proResource)) { continue; } // 如果是文件夹,如果没有创建,直接创建 if (proResource.isFolder()) { IFolder childFolder = parentContainer.getFolder(proResource.getLabel()); if (!childFolder.exists()) { childFolder.create(true, true, null); } createCurProjectResource(proResource, childFolder); } else { // 如果是文件,则判断是否需要覆盖,若是,则直接覆盖 if (proResource.isNeedCover()) { IFile iFile = parentContainer.getFile(proResource.getLabel()); InputStream inputStream = proResource.getInputStream(); if (inputStream != null) { if (iFile.exists()) { closeOpenedFile(iFile); iFile.delete(true, null); } iFile.create(inputStream, true, null); } } } } } } /** * 设置向导界面状态,以及相关提示信息 */ private void setPageCompleteState(int type) { if (INIT_TYPE == type) { setPageComplete(false); return; } String filepath = filePathTxt.getText().trim(); if (filepath.length() <= 0) { setErrorMessage(Messages.getString("importProjectWizardPage.selectImportFilePath")); setPageComplete(false); } else if (rootProjectArray.length == 0) { if (filepath.endsWith(Constant.PROJECT_PACK_EXTENSSION)) { // setErrorMessage(Messages.getString("importProjectWizardPage.selectImportFilePath")); setMessage(Messages.getString("importProjectWizardPage.noProjectsToImport"), WARNING); setPageComplete(false); } else { setErrorMessage(Messages.getString("importProjectWizardPage.selectRightImportFilePath")); setPageComplete(false); } } else { if (selectElementTree.getCheckedElements().length <= 0) { setErrorMessage(Messages.getString("importProjectWizardPage.selectImportProject")); setPageComplete(false); } else { if (repeatElementTree.getTree().getItemCount() > 0) { if (repeatElementTree.getCheckedElements().length <= 0) { setErrorMessage(null); setMessage(Messages.getString("importProjectWizardPage.selectNeedCoverFile")); setPageComplete(true); } else { setErrorMessage(null); setMessage(null); setPageComplete(true); } } else { setErrorMessage(null); setMessage(null); setPageComplete(true); } } } } /** * 当项目导入完成时,关闭已经打开的文件(针对通过编辑器打开,特别是 nattble 与 html 编辑器)  备注:这里特别要注意合并打开的情况。 */ private void closeOpenedFile(final IFile iFile) { Display.getDefault().syncExec(new Runnable() { public void run() { IEditorPart editor = openedIfileMap.get(iFile); if (editor == null) { return; } page.closeEditor(editor, true); } }); } /** * 获取所有已经被打开的文件 * @return */ private Map<IFile, IEditorPart> getAllOpenedIFile() { Map<IFile, IEditorPart> openedIfileMap = new HashMap<IFile, IEditorPart>(); IEditorReference[] referenceArray = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getEditorReferences(); for (IEditorReference reference : referenceArray) { IEditorPart editor = reference.getEditor(true); // 如果这是一个 nattable 编辑器 if (XLIFF_EDITOR_ID.equals(editor.getSite().getId())) { IXliffEditor xlfEditor = (IXliffEditor) editor; if (xlfEditor.isMultiFile()) { for (File file : xlfEditor.getMultiFileList()) { openedIfileMap.put(ResourceUtils.fileToIFile(file.getAbsolutePath()), editor); } } else { openedIfileMap.put(((FileEditorInput) editor.getEditorInput()).getFile(), editor); } } else { // 其他情况,直接将文件丢进去就行了 openedIfileMap.put(((FileEditorInput) editor.getEditorInput()).getFile(), editor); } } return openedIfileMap; } /** * 销毁图片资源 */ private void disposeImg() { if(null != projectImg && !projectImg.isDisposed()){ projectImg.dispose(); } if(null != folderImg&& !folderImg.isDisposed()){ folderImg.dispose(); } if(null !=hsXLiffImg && !hsXLiffImg.isDisposed() ){ hsXLiffImg.dispose(); } if(null !=htmlImg && !htmlImg.isDisposed()){ htmlImg.dispose(); } if(null !=defaultImg && !defaultImg.isDisposed()){ defaultImg.dispose(); } for (Entry<String, Image> entry : imgMap.entrySet()) { Image value = entry.getValue(); if(null != value && !value.isDisposed()){ value.dispose(); } } imgMap.clear(); } // ------------------------- 下面是几个 provider 以及项目的封装类 -------------------------// /** * 标签提供者 * @author robert */ private final class ProjectLabelProvider extends LabelProvider implements IColorProvider { public String getText(Object element) { if (element instanceof ProjectResource) { ProjectResource proResource = (ProjectResource) element; return proResource.getLabel(); } return null; } public Color getBackground(Object element) { return null; } public Color getForeground(Object element) { //  测试代码 // ProjectResource proResource = (ProjectResource) element; // if (proResource.isNeedCover()) { // return getShell().getDisplay().getSystemColor(SWT.COLOR_RED); // } return null; } @Override public Image getImage(Object element) { if (element instanceof ProjectResource) { ProjectResource proResource = (ProjectResource) element; String fileName = proResource.getLabel(); if (proResource.isProject()) { return projectImg; } else if (proResource.isFolder()) { return folderImg; } else if (fileName.endsWith(".hsxliff")) { return hsXLiffImg; } else if (fileName.endsWith(".html")) { return htmlImg; } else { int index = fileName.lastIndexOf("."); if (index != -1) { String extension = fileName.substring(index, fileName.length()); if (imgMap.containsKey(extension)) { return imgMap.get(extension); } Program program = Program.findProgram(extension); if (program != null) { ImageData imageData = program.getImageData(); if (imageData != null) { Image img = new Image(getShell().getDisplay(), imageData); imgMap.put(extension, img); return img; } } } } } return defaultImg; } } /** * 内容提供者 * @author robert */ private final class SelectProjectContentProvider implements ITreeContentProvider { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public Object[] getElements(Object inputElement) { return getProjectResourceInput(); } public Object[] getChildren(Object parentElement) { if (parentElement == null) { return new Object[0]; } return ((ProjectResource) parentElement).getChildren().toArray(); } public Object getParent(Object element) { if (element instanceof ProjectResource) { return ((ProjectResource) element).getParent(); } return null; } public boolean hasChildren(Object element) { return ((ProjectResource) element).hasChildren(); } } /** * 右边重复项目树的内容提供者 * @author robert */ private final class RepeatProjectContentProvider implements ITreeContentProvider { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public Object[] getElements(Object inputElement) { return getRepeateProResourceInput(); } public Object[] getChildren(Object parentElement) { if (parentElement == null) { return new Object[0]; } List<ProjectResource> childList = new ArrayList<ProjectResource>(); Object[] allChildren = selectContentProvider.getChildren(parentElement); for (Object obj : allChildren) { if (obj instanceof ProjectResource) { // 先查看该子节点在左边树中是否被选中 ProjectResource proResource = (ProjectResource) obj; String projectName = proResource.getProjectName(); if (checkedRepeatElementMap.get(projectName).contains(proResource)) { // 如果这是一个重复的资源,那么就显示在右边的重复内容树上面 if (proResource.isElementRepeat()) { childList.add(proResource); } } } } return childList.toArray(new ProjectResource[childList.size()]); } public Object getParent(Object element) { if (element instanceof ProjectResource) { return selectContentProvider.getParent(element); } return null; } public boolean hasChildren(Object element) { return selectContentProvider.hasChildren(element); } } /** * 项目记录 * @author robert 2013-03-08 */ public class ProjectRecord { File projectSystemFile; /** 项目的标识文件 .project */ Object projectArchiveFile; /** 项目名称 */ String projectName; /** 项目标识文件.project 的父文件夹 */ Object parent; int level; boolean hasConflicts; IProjectDescription description; /** * Create a record for a project based on the info in the file. * @param file */ ProjectRecord(File file) { projectSystemFile = file; setProjectName(); } /** * @param file * The Object representing the .project file * @param parent * The parent folder of the .project file * @param level * The number of levels deep in the provider the file is */ ProjectRecord(Object file, Object parent, int level) { this.projectArchiveFile = file; this.parent = parent; this.level = level; setProjectName(); } /** * Set the name of the project based on the projectFile. */ @SuppressWarnings("restriction") private void setProjectName() { try { if (projectArchiveFile != null) { InputStream stream = structureProvider.getContents(projectArchiveFile); // If we can get a description pull the name from there if (stream == null) { if (projectArchiveFile instanceof ZipEntry) { IPath path = new Path(((ZipEntry) projectArchiveFile).getName()); projectName = path.segment(path.segmentCount() - 2); } else if (projectArchiveFile instanceof TarEntry) { IPath path = new Path(((TarEntry) projectArchiveFile).getName()); projectName = path.segment(path.segmentCount() - 2); } } else { description = ResourcesPlugin.getWorkspace().loadProjectDescription(stream); stream.close(); projectName = description.getName(); } } // If we don't have the project name try again if (projectName == null) { IPath path = new Path(projectSystemFile.getPath()); // if the file is in the default location, use the directory // name as the project name if (isDefaultLocation(path)) { projectName = path.segment(path.segmentCount() - 2); description = ResourcesPlugin.getWorkspace().newProjectDescription(projectName); // IProject project = } else { description = ResourcesPlugin.getWorkspace().loadProjectDescription(path); projectName = description.getName(); } } } catch (CoreException e) { // no good couldn't get the name } catch (IOException e) { // no good couldn't get the name } } /** * Returns whether the given project description file path is in the default location for a project * @param path * The path to examine * @return Whether the given path is the default location for a project */ private boolean isDefaultLocation(IPath path) { // The project description file must at least be within the project, // which is within the workspace location if (path.segmentCount() < 2) return false; return path.removeLastSegments(2).toFile().equals(Platform.getLocation().toFile()); } /** * Get the name of the project * @return String */ public String getProjectName() { return projectName; } /** * Gets the label to be used when rendering this project record in the UI. * @return String the label * @since 3.4 */ public String getProjectLabel() { if (description == null) return projectName; String path = projectSystemFile == null ? structureProvider.getLabel(parent) : projectSystemFile .getParent(); return NLS.bind(Messages.getString("importProjectWizardPage.projectLabel"), projectName, path); } /** * @return Returns the hasConflicts. */ public boolean hasConflicts() { return hasConflicts; } public Object getParent() { return parent; } } }
50,421
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.importproject/src/net/heartsome/cat/ts/importproject/resource/Messages.java
package net.heartsome.cat.ts.importproject.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.importproject.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; } } }
570
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.bingtrans/src/net/heartsome/cat/ts/bingtrans/Activator.java
package net.heartsome.cat.ts.bingtrans; 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.bingtrans"; //$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; } /** * 提供一个图片文件对插件的相对路径,返回该图片的描述信息。 * @param path * 图片资源对插件的相对路径。 * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } }
1,423
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
BingTransUtils.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.bingtrans/src/net/heartsome/cat/ts/bingtrans/BingTransUtils.java
/** * GoogleTransUtils.java * * Version information : * * Date:2012-5-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.bingtrans; import com.memetix.mst.language.Language; /** * @author jason * @version * @since JDK1.6 */ public class BingTransUtils { /** 处理语言 */ public static Language processLanguage(String hsLanguageCode) { // 由于中文前缀一样,需针对中文特殊处理。 if (hsLanguageCode.equalsIgnoreCase("zh-CN")) { return Language.CHINESE_SIMPLIFIED; } if (hsLanguageCode.equalsIgnoreCase("zh-TW") || hsLanguageCode.equalsIgnoreCase("zh-HK")) { return Language.CHINESE_TRADITIONAL; } Language[] supportedLangs = Language.values(); for (Language lang : supportedLangs) { String code = lang.toString(); if (code.equals("")) { continue; } if (hsLanguageCode.startsWith(code) || code.startsWith(hsLanguageCode)) { return lang; } } return null; } }
1,468
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SimpleMatcherBingImpl.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.bingtrans/src/net/heartsome/cat/ts/bingtrans/SimpleMatcherBingImpl.java
/** * SimpleMatcherBingImpl.java * * Version information : * * Date:2012-5-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.bingtrans; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.bingtrans.bean.PrefrenceParameters; import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean; import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher; import com.memetix.mst.translate.Translate; /** * http://code.google.com/p/microsoft-translator-java-api/ * @author jason * @version * @since JDK1.6 */ public class SimpleMatcherBingImpl implements ISimpleMatcher { private PrefrenceParameters parameters = PrefrenceParameters.getInstance(); private String type = "Bing"; private String toolId = "Bing Translation"; private String origin = "Bing Translation"; /** * */ public SimpleMatcherBingImpl() { } /** * (non-Javadoc) * @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#getMatcherOrigin() */ public String getMatcherType() { return type; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#getMathcerToolId() */ public String getMathcerToolId() { return toolId; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#matchChecker() */ public boolean matchChecker() { if (!parameters.getState()) { return false; } if (parameters.isNeverAccess()) { return false; } return true; } // private boolean validator() { // try { // String result = Translate.execute("test", BingTransUtils.processLanguage("en-US"), // BingTransUtils.processLanguage("zh-CN")); // if (result.equals("测试")) { // return true; // } // } catch (Exception e) { // return false; // } // // return false; // } /** * (non-Javadoc) * @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#executeMatch(net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean) */ public String executeMatch(TransUnitInfo2TranslationBean tuInfo) { try { String srcText = tuInfo.getSrcPureText(); String srcLang = tuInfo.getSrcLanguage(); String tgtLang = tuInfo.getTgtLangugage(); String bingId = parameters.getId(); String bingKey = parameters.getKey(); Translate.setClientId(bingId); Translate.setClientSecret(bingKey); String result = Translate.execute(srcText, BingTransUtils.processLanguage(srcLang), BingTransUtils.processLanguage(tgtLang)); // 处理字符转义,有可能翻译的字符有一部分是转义了的,而另一部没有转义 //bug:3317 fixed by yule 2013-7-26 String resetSpecialString = TextUtil.resetSpecialString(result); result = TextUtil.cleanSpecialString(resetSpecialString); if (result != null) { return result; } } catch (Exception e) { return ""; } return ""; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#isSuportPreTrans() */ public boolean isSuportPreTrans() { if (parameters != null) { return parameters.isSuportPreTrans() && parameters.getState(); } return false; } /** * (non-Javadoc) * @see net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher#isOverwriteMatch() */ public boolean isOverwriteMatch() { return parameters.isAlwaysAccess(); } public String getMathcerOrigin() { return origin; } public static void main(String arg[]) { Translate.setClientId("Bing_Client_ID"); Translate.setClientSecret("tEIlN/kkAFGFaNve4Q3q85sB6QARrlf2pMyBkuIgTjs="); String result; try { result = Translate.execute( " Obey all safety messages that follow this symbol to avoid possible injury or death.", BingTransUtils.processLanguage("en-US"), BingTransUtils.processLanguage("zh-CN")); System.out.println(result); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4,356
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
BingPreferencePage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.bingtrans/src/net/heartsome/cat/ts/bingtrans/preference/BingPreferencePage.java
/** * BingPreferencePage.java * * Version information : * * Date:2012-5-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.bingtrans.preference; import net.heartsome.cat.ts.bingtrans.Activator; import net.heartsome.cat.ts.bingtrans.BingTransUtils; import net.heartsome.cat.ts.bingtrans.bean.IPreferenceConstant; import net.heartsome.cat.ts.bingtrans.resource.Messages; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.common.util.CommonFunction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Button; 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.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.memetix.mst.translate.Translate; /** * @author jason * @version * @since JDK1.6 */ public class BingPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private IPreferenceStore ps; private Text idText; private Text bingKeyText; private Label stateLabel; // accessibility widget private Button noRepeatAccessBtn; private Button alwaysAccessBtn; private Button manualAccessBtn; // preTranslation suport private Button suportPreTransBtn; private Image rightImage; private Image errorImage; private boolean state; /** * constructor */ public BingPreferencePage() { setPreferenceStore(Activator.getDefault().getPreferenceStore()); ps = getPreferenceStore(); state = ps.getBoolean(IPreferenceConstant.STATE); rightImage = Activator.getImageDescriptor("images/right.png").createImage(); errorImage = Activator.getImageDescriptor("images/error.png").createImage(); } /** * (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } // private Label label; /** * (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) */ protected Control createContents(Composite parent) { Composite tparent = new Composite(parent, SWT.NONE); tparent.setLayout(new GridLayout(1, false)); tparent.setLayoutData(new GridData(GridData.FILL_BOTH)); Group apiKeySettingGroup = new Group(tparent, SWT.NONE); apiKeySettingGroup.setText(Messages.getString("preference.BingPreferencePage.apiKeySettingGroup")); apiKeySettingGroup.setLayout(new GridLayout(1, false)); apiKeySettingGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); HsImageLabel lbKeySetting = new HsImageLabel(Messages.getString("preference.BingPreferencePage.lbKeySetting"), Activator.getImageDescriptor("images/trans_bing_key_32.png")); Composite com = lbKeySetting.createControl(apiKeySettingGroup); com.setLayout(new GridLayout(3, false)); Label lblId = new Label(com, SWT.NONE); lblId.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblId.setText(Messages.getString("preference.BingPreferencePage.lblId")); idText = new Text(com, SWT.BORDER); idText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); new Label(com, SWT.NONE); Label lblApiKey = new Label(com, SWT.NONE); lblApiKey.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblApiKey.setText(Messages.getString("preference.BingPreferencePage.lblApiKey")); bingKeyText = new Text(com, SWT.BORDER); bingKeyText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); stateLabel = new Label(com, SWT.NONE); new Label(com, SWT.NONE); Button validateKey = new Button(com, SWT.NONE); validateKey.setText(Messages.getString("preference.BingPreferencePage.validateKey")); validateKey.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String id = idText.getText(); String bingKey = bingKeyText.getText(); if (id == null || id.equals("")) { MessageDialog.openInformation(getShell(), Messages.getString("preference.BingPreferencePage.msgTitle"), Messages.getString("preference.BingPreferencePage.msg1")); return; } if (bingKey == null || bingKey.equals("")) { MessageDialog.openInformation(getShell(), Messages.getString("preference.BingPreferencePage.msgTitle"), Messages.getString("preference.BingPreferencePage.msg2")); return; } validator(); enableComponent(state); if (!state) { MessageDialog.openInformation(getShell(), Messages.getString("preference.BingPreferencePage.msgTitle"), Messages.getString("preference.BingPreferencePage.msg3")); return; } } }); new Label(com, SWT.NONE); new Label(com, SWT.NONE); Link link = new Link(com, SWT.NONE); link.setText("<a>" + Messages.getString("preference.BingPreferencePage.link") + "</a>"); link.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Program.launch("http://msdn.microsoft.com/en-us/library/hh454950.aspx"); } }); link.setToolTipText("http://msdn.microsoft.com/en-us/library/hh454950.aspx"); new Label(com, SWT.NONE); lbKeySetting.computeSize(); Group apiAccessibilityGroup = new Group(tparent, SWT.NONE); apiAccessibilityGroup.setLayout(new GridLayout(1, false)); apiAccessibilityGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); apiAccessibilityGroup.setText(Messages.getString("preference.BingPreferencePage.apiAccessibilityGroup")); HsImageLabel accessibility = new HsImageLabel( Messages.getString("preference.BingPreferencePage.accessibility"), Activator.getImageDescriptor("images/trans_bing_set_32.png")); Composite accessibilityComp = accessibility.createControl(apiAccessibilityGroup); accessibilityComp.setLayout(new GridLayout()); noRepeatAccessBtn = new Button(accessibilityComp, SWT.RADIO); noRepeatAccessBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); noRepeatAccessBtn.setText(Messages.getString("preference.BingPreferencePage.noRepeatAccessBtn")); noRepeatAccessBtn.setEnabled(false); noRepeatAccessBtn.setSelection(false); alwaysAccessBtn = new Button(accessibilityComp, SWT.RADIO); alwaysAccessBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); alwaysAccessBtn.setText(Messages.getString("preference.BingPreferencePage.alwaysAccessBtn")); alwaysAccessBtn.setEnabled(false); alwaysAccessBtn.setSelection(false); manualAccessBtn = new Button(accessibilityComp, SWT.RADIO); manualAccessBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); manualAccessBtn.setText(Messages.getString("preference.BingPreferencePage.neverAccessBtn")); manualAccessBtn.setEnabled(false); manualAccessBtn.setSelection(false); accessibility.computeSize(); if (CommonFunction.checkEdition("U")) { Group preTransGroup = new Group(tparent, SWT.NONE); preTransGroup.setLayout(new GridLayout(1, false)); preTransGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); preTransGroup.setText(Messages.getString("preference.BingPreferencePage.preTransGroup")); HsImageLabel preTrans = new HsImageLabel(Messages.getString("preference.BingPreferencePage.preTrans"), Activator.getImageDescriptor("images/trans_bing_trans_32.png")); Composite group = preTrans.createControl(preTransGroup); group.setLayout(new GridLayout()); suportPreTransBtn = new Button(group, SWT.CHECK); suportPreTransBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); suportPreTransBtn.setText(Messages.getString("preference.BingPreferencePage.suportPreTransBtn")); suportPreTransBtn.setEnabled(false); suportPreTransBtn.setSelection(false); preTrans.computeSize(); } setValues(false); return tparent; } private void enableComponent(boolean currentState) { alwaysAccessBtn.setEnabled(currentState); manualAccessBtn.setEnabled(currentState); noRepeatAccessBtn.setEnabled(currentState); if (CommonFunction.checkEdition("U")) { suportPreTransBtn.setEnabled(currentState); } if (currentState) { stateLabel.setImage(rightImage); boolean noRepeate = ps.getBoolean(IPreferenceConstant.NO_REPEATE_ACCESS); boolean always = ps.getBoolean(IPreferenceConstant.ALWAYS_ACCESS); boolean never = ps.getBoolean(IPreferenceConstant.MANUAL_ACCESS); if (!(noRepeate || always || never)) { noRepeate = ps.getDefaultBoolean(IPreferenceConstant.NO_REPEATE_ACCESS); always = ps.getDefaultBoolean(IPreferenceConstant.ALWAYS_ACCESS); never = ps.getDefaultBoolean(IPreferenceConstant.MANUAL_ACCESS); } alwaysAccessBtn.setSelection(always); manualAccessBtn.setSelection(never); noRepeatAccessBtn.setSelection(noRepeate); boolean preTrans = ps.getBoolean(IPreferenceConstant.PRETRANS_STATE); if (CommonFunction.checkEdition("U")) { suportPreTransBtn.setSelection(preTrans); } } else { stateLabel.setImage(errorImage); alwaysAccessBtn.setSelection(false); manualAccessBtn.setSelection(false); noRepeatAccessBtn.setSelection(false); if (CommonFunction.checkEdition("U")) { suportPreTransBtn.setSelection(false); } } // ps.setValue(IPreferenceConstant.STATE, currentState); // 记录当前通过了验证 } @Override protected void performDefaults() { setValues(true); } @Override protected void performApply() { super.performApply(); String id = idText.getText(); String bingKey = bingKeyText.getText(); if (id == null || id.equals("")) { state = false; enableComponent(state); } else if (bingKey == null || bingKey.equals("")) { state = false; enableComponent(state); } else { validator(); enableComponent(state); if (!state) { MessageDialog.openInformation(getShell(), Messages.getString("preference.BingPreferencePage.msgTitle"), Messages.getString("preference.BingPreferencePage.msg3")); } } } @Override public boolean performOk() { String id = idText.getText(); String key = bingKeyText.getText(); if (id == null || id.equals("")) { state = false; } else if (key == null || key.equals("")) { state = false; } else { validator(); } boolean always = alwaysAccessBtn.getSelection(); boolean manual = manualAccessBtn.getSelection(); ps.setValue(IPreferenceConstant.STATE, state); ps.setValue(IPreferenceConstant.ID, id); ps.setValue(IPreferenceConstant.KEY, key); ps.setValue(IPreferenceConstant.ALWAYS_ACCESS, always); ps.setValue(IPreferenceConstant.MANUAL_ACCESS, manual); boolean noRepeat = noRepeatAccessBtn.getSelection(); ps.setValue(IPreferenceConstant.NO_REPEATE_ACCESS, noRepeat); if (CommonFunction.checkEdition("U")) { boolean preTrans = suportPreTransBtn.getSelection(); ps.setValue(IPreferenceConstant.PRETRANS_STATE, preTrans); } return true; } /** @return the checkResult */ public boolean isCheckResult() { return state; } /** * @param checkResult * the checkResult to set */ public void setCheckResult(boolean checkResult) { this.state = checkResult; } private void validator() { BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { public void run() { String id = idText.getText(); String bingKey = bingKeyText.getText(); if (bingKey != null && !bingKey.trim().equals("") && id != null && !id.equals("")) { Translate.setClientId(id); Translate.setClientSecret(bingKey); try { String result = Translate.execute("test", BingTransUtils.processLanguage("en-US"), BingTransUtils.processLanguage("zh-CN")); if (result.equals("测试")) { state = true; } else { state = false; } } catch (Exception e) { state = false; } } else { state = false; } } }); } private void setValues(boolean blnIsApplyDefault) { if (blnIsApplyDefault) { this.state = ps.getDefaultBoolean(IPreferenceConstant.STATE); this.idText.setText(ps.getDefaultString(IPreferenceConstant.ID)); this.bingKeyText.setText(ps.getDefaultString(IPreferenceConstant.KEY)); enableComponent(state); // 根据需要是否禁用其他选项 } else { this.state = ps.getBoolean(IPreferenceConstant.STATE); enableComponent(state); this.idText.setText(ps.getString(IPreferenceConstant.ID)); this.bingKeyText.setText(ps.getString(IPreferenceConstant.KEY)); } } @Override public void dispose() { if (rightImage != null) { rightImage.dispose(); } if (errorImage != null) { errorImage.dispose(); } super.dispose(); } }
13,694
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
BingTransPreferenceInitializer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.bingtrans/src/net/heartsome/cat/ts/bingtrans/preference/BingTransPreferenceInitializer.java
/** * GooglTransPreferenceInitializer.java * * Version information : * * Date:2012-5-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.bingtrans.preference; import net.heartsome.cat.ts.bingtrans.Activator; import net.heartsome.cat.ts.bingtrans.bean.IPreferenceConstant; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; /** * @author jason * @version * @since JDK1.6 */ public class BingTransPreferenceInitializer extends AbstractPreferenceInitializer { /** (non-Javadoc) * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() */ @Override public void initializeDefaultPreferences() { IPreferenceStore ps = Activator.getDefault().getPreferenceStore(); ps.setDefault(IPreferenceConstant.STATE, false); ps.setDefault(IPreferenceConstant.ID, ""); ps.setDefault(IPreferenceConstant.KEY, ""); ps.setDefault(IPreferenceConstant.NO_REPEATE_ACCESS, true); ps.setDefault(IPreferenceConstant.ALWAYS_ACCESS, false); ps.setDefault(IPreferenceConstant.MANUAL_ACCESS, false); ps.setDefault(IPreferenceConstant.PRETRANS_STATE, false); } }
1,728
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PrefrenceParameters.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.bingtrans/src/net/heartsome/cat/ts/bingtrans/bean/PrefrenceParameters.java
/** * PrefrenceParameters.java * * Version information : * * Date:2012-5-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.bingtrans.bean; import net.heartsome.cat.ts.bingtrans.Activator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; /** * @author jason * @version * @since JDK1.6 */ public class PrefrenceParameters implements IPropertyChangeListener { private String id = ""; private String key = ""; private boolean state; private boolean isNoRepateAccess; private boolean isAlwaysAccess; private boolean isNeverAccess; private boolean isSuportPreTrans; private IPreferenceStore ps; private static PrefrenceParameters instance; public static PrefrenceParameters getInstance() { if (instance == null) { instance = new PrefrenceParameters(); } return instance; } private PrefrenceParameters() { ps = Activator.getDefault().getPreferenceStore(); ps.addPropertyChangeListener(this); loadPrefrence(); } private void loadPrefrence() { if (ps != null) { state = ps.getBoolean(IPreferenceConstant.STATE); key = ps.getString(IPreferenceConstant.KEY); id = ps.getString(IPreferenceConstant.ID); isNoRepateAccess = ps.getBoolean(IPreferenceConstant.NO_REPEATE_ACCESS); isAlwaysAccess = ps.getBoolean(IPreferenceConstant.ALWAYS_ACCESS); isNeverAccess = ps.getBoolean(IPreferenceConstant.MANUAL_ACCESS); isSuportPreTrans = ps.getBoolean(IPreferenceConstant.PRETRANS_STATE); } } public void propertyChange(PropertyChangeEvent event) { loadPrefrence(); } public String getId(){ return id; } /** * 获取当前Key true or false * @return ; */ public String getKey() { return key; } /** * 获取当前状态,true or false * @return ; */ public boolean getState() { return state; } /** * 返回访问API的策略, 没有指定访问策略则返回一个空串,如果有策略则返回对的首选项参数名称 * @return */ public String getAccessStrategy() { if (isNoRepateAccess) { return IPreferenceConstant.NO_REPEATE_ACCESS; } if (isAlwaysAccess) { return IPreferenceConstant.ALWAYS_ACCESS; } if (isNeverAccess) { return IPreferenceConstant.MANUAL_ACCESS; } return ""; } /** * 是否支持预翻译 * @return ; */ public boolean isSuportPreTrans() { return isSuportPreTrans; } /** * 是否重复访问API * @return the isNoRepateAccess */ public boolean isNoRepateAccess() { return isNoRepateAccess; } /** * 是否总是访问API * @return the isAlwaysAccess */ public boolean isAlwaysAccess() { return isAlwaysAccess; } /** * 是否从不访问API * @return the isNeverAccess */ public boolean isNeverAccess() { return isNeverAccess; } }
3,367
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IPreferenceConstant.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.bingtrans/src/net/heartsome/cat/ts/bingtrans/bean/IPreferenceConstant.java
/** * IPreferenceConstant.java * * Version information : * * Date:2012-5-13 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.bingtrans.bean; /** * bing翻译首选项常量 * @author jason * @version * @since JDK1.6 */ public interface IPreferenceConstant { /** * 当前bing 翻译状态,用于记录当前是否通过了验证 */ String STATE = "net.heartsome.cat.ts.bingtrans.state"; String ID = "net.heartsome.cat.ts.bingtrans.id"; /** bing 翻译的Key */ String KEY = "net.heartsome.cat.ts.bingtrans.key"; String NO_REPEATE_ACCESS = "net.heartsome.cat.ts.bingtrans.norepeate"; String ALWAYS_ACCESS = "net.heartsome.cat.ts.bingtrans.always"; String MANUAL_ACCESS = "net.heartsome.cat.ts.bingtrans.manual"; /** 是否支持预翻译 */ String PRETRANS_STATE = "net.heartsome.cat.ts.bingtrans.suportpretrans"; }
1,384
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ExecuteBingTransHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.bingtrans/src/net/heartsome/cat/ts/bingtrans/handler/ExecuteBingTransHandler.java
/** * ExecuteBingTransHandler.java * * Version information : * * Date:2012-6-14 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.bingtrans.handler; import net.heartsome.cat.ts.bingtrans.SimpleMatcherBingImpl; import net.heartsome.cat.ts.bingtrans.bean.PrefrenceParameters; import net.heartsome.cat.ts.bingtrans.resource.Messages; import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.translation.view.MatchViewPart; 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.IViewPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import org.slf4j.LoggerFactory; /** * @author jason * @version * @since JDK1.6 */ public class ExecuteBingTransHandler extends AbstractHandler { /** * (non-Javadoc) * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ public Object execute(ExecutionEvent event) throws ExecutionException { final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event); IEditorPart editor = HandlerUtil.getActiveEditor(event); if (!(editor instanceof IXliffEditor)) { return null; } // check the google translation state: check the key availability PrefrenceParameters ps = PrefrenceParameters.getInstance(); if (!ps.getState()) { MessageDialog.openError(window.getShell(), Messages.getString("handler.ExecuteBingTransHandler.msgTitle"), Messages.getString("handler.ExecuteBingTransHandler.msg")); return null; } String tshelp = System.getProperties().getProperty("TSHelp"); String tsstate = System.getProperties().getProperty("TSState"); if (tshelp == null || !"true".equals(tshelp) || tsstate == null || !"true".equals(tsstate)) { LoggerFactory.getLogger(ExecuteBingTransHandler.class).error("Exception:key hs008 is lost.(Can't find the key)"); System.exit(0); } final IXliffEditor xliffEditor = (IXliffEditor) editor; final int[] selectedRowIndexs = xliffEditor.getSelectedRows(); if (selectedRowIndexs.length == 0) { return null; } // int currentRowIndex = selectedRowIndexs[0]; // TransUnitBean transUnitBean = xliffEditor.getRowTransUnitBean(currentRowIndex); // if (transUnitBean == null) { // return null; // } // String srcPureText = transUnitBean.getSrcText(); // String tgtLanguage = xliffEditor.getTgtColumnName(); // String srcLanguage = xliffEditor.getSrcColumnName(); // TransUnitInfo2TranslationBean tuInfo2Trans = new TransUnitInfo2TranslationBean(); // tuInfo2Trans.setSrcPureText(srcPureText); // tuInfo2Trans.setSrcLanguage(srcLanguage); // tuInfo2Trans.setTgtLangugage(tgtLanguage); ISimpleMatcher matcher = new SimpleMatcherBingImpl(); // String tgtText = matcher.executeMatch(tuInfo2Trans); // if (tgtText.equals("")) { // return null; // } // AltTransBean bean = new AltTransBean(srcPureText, tgtText, srcLanguage, tgtLanguage, // matcher.getMathcerOrigin(), matcher.getMathcerToolId()); // bean.getMatchProps().put("match-quality", "100"); // bean.getMatchProps().put("hs:matchType", matcher.getMatcherType()); // bean.setSrcContent(srcPureText); // bean.setTgtContent(tgtText); // List<AltTransBean> newAltTrans = new ArrayList<AltTransBean>(); // newAltTrans.add(bean); // check if need save the AltTrans to file // if (CommonFunction.checkEdition("U") && matcher.isSuportPreTrans()) { // List<String> oldToolIds = new ArrayList<String>(); // oldToolIds.add(matcher.getMathcerToolId()); // xliffEditor.getXLFHandler().updateAltTrans(xliffEditor.getXLFHandler().getRowId(currentRowIndex), newAltTrans, oldToolIds); // } IViewPart viewPart = window.getActivePage().findView(MatchViewPart.ID); if (viewPart != null && viewPart instanceof MatchViewPart) { MatchViewPart matchView = (MatchViewPart) viewPart; //matchView.refreshView(xliffEditor, selectedRowIndexs[0]); // matchView.refreshViewByToolId(xliffEditor, newAltTrans, matcher.getMathcerToolId()); // matchView.replaceMatchs(newAltTrans); // newAltTrans.clear(); matchView.manualExecSimpleTranslation(matcher); } return null; } }
4,889
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.bingtrans/src/net/heartsome/cat/ts/bingtrans/resource/Messages.java
package net.heartsome.cat.ts.bingtrans.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.bingtrans.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; } } }
562
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.ui.translation/src/net/heartsome/cat/ts/ui/translation/Activator.java
package net.heartsome.cat.ts.ui.translation; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.ImageData; 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.ui.translation"; //$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; } /** * 提供一个图片文件对插件的相对路径,返回该图片的描述信息。 * @param path * 图片资源对插件的相对路径。 * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } /** * 提供一个图片文件对插件的相对路径,返回该图片被伸缩变换为16*16像素的描述信息。 * @param path * the path * @return the icon descriptor */ public static ImageDescriptor getIconDescriptor(String path) { ImageDescriptor image = getImageDescriptor(path); ImageData data = image.getImageData(); data = data.scaledTo(16, 16); image = ImageDescriptor.createFromImageData(data); return image; } }
1,943
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImageConstants.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/ImageConstants.java
package net.heartsome.cat.ts.ui.translation; /** * 图标常量定义 * @author jason * @version * @since JDK1.6 */ public interface ImageConstants { /** * 接受带标记的文本 */ String ACCEPT_FULLTEXT="images/tm-view/accept-all.png"; /** * 接受不带标记的文本 */ String ACCEPT_TEXT = "images/tm-view/accept-text.png"; /** * 匹配状态栏图标 */ String TM_INFO = "images/tm-view/tm-info.png"; String DELETE_MATCH = "images/tm-view/delete-match.png"; String EDIT_MATCH = "images/tm-view/edit-match.png"; }
562
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TranslationTaskContainer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/TranslationTaskContainer.java
/** * Task.java * * Version information : * * Date:2013-1-7 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.view; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.ts.tm.complexMatch.IComplexMatch; import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher; /** * @author Jason * @version * @since JDK1.6 */ public class TranslationTaskContainer { private List<TranslationTaskData> dataList; // // private List<ISimpleMatcher> simpleMatchers; // // private List<IComplexMatch> complexMatchers; public TranslationTaskContainer() { dataList = new ArrayList<TranslationTaskData>(); } public synchronized void clearContainer(){ dataList.clear(); } public boolean isEmpty() { if(dataList.size() == 0){ return true; } return false; } public synchronized TranslationTaskData popTranslationTask() { if (dataList.size() != 0) { return dataList.remove(dataList.size() - 1); } return null; } public synchronized void pushTranslationTask(TranslationTaskData data) { Object matcher = data.getMatcher(); if (matcher instanceof ISimpleMatcher) { ISimpleMatcher _matcher = (ISimpleMatcher) matcher; for(TranslationTaskData d: dataList){ Object m = d.getMatcher(); if(m instanceof ISimpleMatcher){ ISimpleMatcher _m = (ISimpleMatcher) m; if (_m.getMathcerToolId().equals(_matcher.getMathcerToolId())) { return; } } } } else if (matcher instanceof IComplexMatch) { IComplexMatch _matcher = (IComplexMatch) matcher; for(TranslationTaskData d: dataList){ Object m = d.getMatcher(); if(m instanceof IComplexMatch){ IComplexMatch _m = (IComplexMatch) m; if (_m.getToolId().equals(_matcher.getToolId())) { return; } } } } dataList.add(0, data); } }
2,341
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TargetColunmCellRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/TargetColunmCellRenderer.java
/** * MatchViewCellRenderer.java * * Version information : * * Date:Dec 26, 2011 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.view; import net.heartsome.cat.ts.ui.grid.XGridCellRenderer; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; /** * @author Jason * @version * @since JDK1.6 */ public class TargetColunmCellRenderer extends XGridCellRenderer { /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); boolean drawBackground = true; boolean drawAsSelected = isSelected(); if (isCellSelected()) { drawAsSelected = true; } gc.setForeground(item.getForeground(getColumn())); if (drawAsSelected) { gc.setBackground((Color) item.getParent().getData("selectedBgColor")); } else { if (item.getParent().isEnabled()) { Color back = item.getBackground(getColumn()); if (back != null) { gc.setBackground(back); } else { drawBackground = false; } } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } } if (drawBackground) { gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height); } TextLayout layout = getTextLayout(gc, item, getColumn(), true, false); String displayStr = layout.getText(); try { int y = getBounds().y + textTopMargin + topMargin; y += getVerticalAlignmentAdjustment(layout.getBounds().height, getBounds().height); if (item.getParent().isAutoHeight()) { int textHeight = topMargin + textTopMargin; // fix Bug #3116 库匹配面板--显示的匹配有截断 by Jason // for (int cnt = 0; cnt < layout.getLineCount(); cnt++) // textHeight += layout.getLineBounds(cnt).height; textHeight += layout.getBounds().height; textHeight += textBottomMargin + bottomMargin; int heigth = (Integer) item.getData("itemHeight"); textHeight = Math.max(textHeight, heigth); if (textHeight != item.getHeight()) { item.setHeight(textHeight); item.setData("itemHeight", textHeight); } } // Point selection = copyEnable.getSelectionRange(getColumn(), getRow() - 1); // row based zero ,get row // first row is 1 Point selection = copyEnable.getSelectionRange(getColumn(), item); if (selection == null || selection.x == selection.y) { layout.draw(gc, getBounds().x + leftMargin, y); } else { // textLayout.draw(gc, getBounds().x + leftMargin, y); int x = getBounds().x + leftMargin; int start = Math.max(0, selection.x); int end = Math.min(displayStr.length(), selection.y); layout.draw(gc, x, y, start, end - 1, getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT), getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); } drawInnerTag(gc, layout); if (item.getParent().getLinesVisible()) { if (isCellSelected()) { // XXX: should be user definable? gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } else { gc.setForeground(item.getParent().getLineColor()); } gc.drawLine(getBounds().x, getBounds().y + getBounds().height, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); } } finally { if (layout != null) { layout.dispose(); } } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); int x = 0; x += leftMargin; int y = 0; Image image = item.getImage(getColumn()); if (image != null) { y = topMargin + image.getBounds().height + bottomMargin; x += image.getBounds().width + 3; } // MOPR-DND // MOPR: replaced this code (to get correct preferred height for cells in word-wrap columns) // // x += gc.stringExtent(item.getText(column)).x + rightMargin; // // y = Math.max(y,topMargin + gc.getFontMetrics().getHeight() + bottomMargin); // // with this code: int textHeight = 0; if (!isWordWrap()) { x += gc.textExtent(item.getText(getColumn())).x + rightMargin; textHeight = topMargin + textTopMargin + gc.getFontMetrics().getHeight() + textBottomMargin + bottomMargin; } else { int plainTextWidth; if (wHint == SWT.DEFAULT) plainTextWidth = getBounds().width - x - rightMargin; else plainTextWidth = wHint - x - rightMargin; TextLayout currTextLayout = new TextLayout(gc.getDevice()); currTextLayout.setFont(gc.getFont()); currTextLayout.setText(item.getText(getColumn())); currTextLayout.setAlignment(getAlignment()); currTextLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth); x += plainTextWidth + rightMargin; textHeight += topMargin + textTopMargin; for (int cnt = 0; cnt < currTextLayout.getLineCount(); cnt++) textHeight += currTextLayout.getLineBounds(cnt).height; textHeight += textBottomMargin + bottomMargin; currTextLayout.dispose(); } y = Math.max(y, textHeight); return new Point(x, y); } /** * {@inheritDoc} */ public Rectangle getTextBounds(GridItem item, boolean preferred) { int x = leftMargin; Rectangle bounds = new Rectangle(x, topMargin + textTopMargin, 0, 0); GC gc = new GC(item.getParent()); gc.setFont(item.getFont(getColumn())); Point size = gc.stringExtent(item.getText(getColumn())); bounds.height = size.y; if (preferred) { bounds.width = size.x - 1; } else { bounds.width = getBounds().width - x - rightMargin; } gc.dispose(); return bounds; } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { return false; } }
6,607
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MatchViewerBodyMenu.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/MatchViewerBodyMenu.java
/** * MatchViewerMenuManager.java * * Version information : * * Date:2013-3-28 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.view; import java.util.Hashtable; import net.heartsome.cat.common.bean.FuzzySearchResult; import net.heartsome.cat.common.util.InnerTagClearUtil; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.translation.Activator; import net.heartsome.cat.ts.ui.translation.ImageConstants; import net.heartsome.cat.ts.ui.translation.dialog.TmMatchEditDialog; import net.heartsome.cat.ts.ui.translation.resource.Messages; import net.heartsome.cat.ts.ui.util.IntelligentTagPrcessor; import net.heartsome.cat.ts.ui.util.TmUtils; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.window.Window; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ST; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.WorkbenchMessages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jason * @version * @since JDK1.6 */ @SuppressWarnings("restriction") public class MatchViewerBodyMenu { private static final Logger logger = LoggerFactory.getLogger(MatchViewerBodyMenu.class); private Menu bodyMenu; private MatchViewPart view; CopyAction copyAction; DeleteTmAction deleteAction; EditTmAction editAction; AcceptMatchAction acceptMatchAction; private IXliffEditor editor; private int rowIndex; // AcceptMatchPureTextAction acceptMatchPureTextAction; public MatchViewerBodyMenu(MatchViewPart view) { this.view = view; createMenu(); bodyMenu.addListener(SWT.Show, new Listener() { public void handleEvent(Event event) { updateActionState(); } }); } public Menu getBodyMenu() { return this.bodyMenu; } private void createMenu() { MenuManager menuMgr = new MenuManager(); bodyMenu = menuMgr.createContextMenu(view.gridTable); copyAction = new CopyAction(); menuMgr.add(copyAction); editAction = new EditTmAction(); menuMgr.add(editAction); deleteAction = new DeleteTmAction(); menuMgr.add(deleteAction); acceptMatchAction = new AcceptMatchAction(); menuMgr.add(acceptMatchAction); // acceptMatchPureTextAction = new AcceptMatchPureTextAction(); // menuMgr.add(acceptMatchPureTextAction); } void updateActionState() { copyAction.updateEnabledState(); editAction.updateEnabledState(); deleteAction.updateEnabledState(); acceptMatchAction.updateEnabledState(); // acceptMatchPureTextAction.updateEnabledState(); } class EditTmAction extends Action { public EditTmAction() { setText(Messages.getString("view.MatchViewerBodyMenu.EditTmAction")); setToolTipText(Messages.getString("view.MatchViewerBodyMenu.EditTmAction.tooltip")); setImageDescriptor(Activator.getImageDescriptor(ImageConstants.EDIT_MATCH)); } @Override public void run() { int selectionIndex = view.gridTable.getSelectionIndex(); if (selectionIndex < 0 || selectionIndex > view.gridTable.getItemCount()) { return; } GridItem item = view.gridTable.getItem(selectionIndex); Object obj = item.getData("tmFuzzyInfo"); if (obj == null) { return; } FuzzySearchResult fuzzyResult = (FuzzySearchResult) obj; TmMatchEditDialog dlg = new TmMatchEditDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(), fuzzyResult); if (dlg.open() == Window.OK) { try { view.tmMatcher.updateFuzzResult(fuzzyResult); view.reLoadMatches(editor, rowIndex); } catch (Exception e) { MessageDialog.openError(view.getSite().getShell(), Messages.getString("view.MatchViewerBodyMenu.erorr.title"), Messages.getString("view.MatchViewerBodyMenu.error.editError") + e.getMessage()); logger.error("Updaste TM matche Error", e); } } } public void updateEnabledState() { int selectionIndex = view.gridTable.getSelectionIndex(); if (selectionIndex < 0 || selectionIndex > view.gridTable.getItemCount()) { setEnabled(false); return; } GridItem item = view.gridTable.getItem(selectionIndex); Object obj = item.getData("tmFuzzyInfo"); if (obj == null) { setEnabled(false); return; } FuzzySearchResult fuzzyResult = (FuzzySearchResult) obj; if (fuzzyResult.getDbOp() == null) { setEnabled(false); return; } setEnabled(true); } } class DeleteTmAction extends Action { public DeleteTmAction() { setText(Messages.getString("view.MatchViewerBodyMenu.DeleteTmAction")); setToolTipText(Messages.getString("view.MatchViewerBodyMenu.DeleteTmAction.tooltip")); setImageDescriptor(Activator.getImageDescriptor(ImageConstants.DELETE_MATCH)); } @Override public void run() { if (!MessageDialog.openConfirm(view.getSite().getShell(), Messages.getString("view.MatchViewerBodyMenu.confirm.title"), Messages.getString("view.MatchViewerBodyMenu.confirm.deleteInfo"))) { return; } int selectionIndex = view.gridTable.getSelectionIndex(); if (selectionIndex < 0 || selectionIndex > view.gridTable.getItemCount()) { return; } GridItem item = view.gridTable.getItem(selectionIndex); Object obj = item.getData("tmFuzzyInfo"); if (obj == null) { return; } FuzzySearchResult fuzzyResult = (FuzzySearchResult) obj; try { view.tmMatcher.deleteFuzzyResult(fuzzyResult); view.reLoadMatches(editor, rowIndex); } catch (Exception e) { MessageDialog.openError(view.getSite().getShell(), Messages.getString("view.MatchViewerBodyMenu.erorr.title"), Messages.getString("view.MatchViewerBodyMenu.error.deleteError") + e.getMessage()); } } public void updateEnabledState() { int selectionIndex = view.gridTable.getSelectionIndex(); if (selectionIndex < 0 || selectionIndex > view.gridTable.getItemCount()) { setEnabled(false); return; } GridItem item = view.gridTable.getItem(selectionIndex); Object obj = item.getData("tmFuzzyInfo"); if (obj == null) { setEnabled(false); return; } FuzzySearchResult fuzzyResult = (FuzzySearchResult) obj; if (fuzzyResult.getDbOp() == null) { setEnabled(false); return; } setEnabled(true); } }; class CopyAction extends Action { CopyAction() { super(WorkbenchMessages.Workbench_copy); ISharedImages sharedImages = view.getSite().getWorkbenchWindow().getWorkbench().getSharedImages(); setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY)); setDisabledImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED)); setEnabled(false); } @Override public void run() { view.copyEnable.doAction(ST.COPY); } public void updateEnabledState() { if (view.copyEnable != null && view.copyEnable.getSelectionCount() > 0) { setEnabled(true); return; } setEnabled(false); } }; class AcceptMatchAction extends Action { AcceptMatchAction() { setEnabled(false); setText(Messages.getString("view.MatchViewPart.firstAction")); setToolTipText(Messages.getString("view.MatchViewPart.firstAction.tooltip")); setImageDescriptor(Activator.getIconDescriptor(ImageConstants.ACCEPT_FULLTEXT)); } @Override public void run() { if (editor == null || rowIndex < 0) { return; } // 先判断文本段是否处理锁定状态,robert 2012-05-02 TransUnitBean transUnit = editor.getRowTransUnitBean(rowIndex); String translate = transUnit.getTuProps().get("translate"); if (translate != null && "no".equalsIgnoreCase(translate)) { // MessageDialog.openInformation(getSite().getShell(), // Messages.getString("view.MatchViewPart.msgTitle"), // Messages.getString("view.MatchViewPart.msg2")); return; } int selectionIndex = view.gridTable.getSelectionIndex(); if (selectionIndex < 0 || selectionIndex > view.gridTable.getItemCount()) { return; } GridItem item = view.gridTable.getItem(selectionIndex); String tgtContent = item.getData("tgtContent").toString(); // 译文内容 String matchType = item.getData("matchType").toString(); String quality = item.getData("quality").toString(); if (transUnit != null) { String srcContent = transUnit.getSrcContent(); if (srcContent != null && !srcContent.equals("") && view.transParameter.isAdjustSpacePosition()) { tgtContent = TmUtils.adjustSpace(srcContent, tgtContent); } } try { if (!matchType.equals("TM")) { matchType = null; quality = null; } String srcFullText = transUnit.getSrcContent(); String temp = IntelligentTagPrcessor.intelligentAppendTag(srcFullText, InnerTagClearUtil.clearTmx4Xliff(tgtContent)); editor.updateCell(rowIndex, editor.getTgtColumnIndex(), temp, matchType, quality); // editor.setFocus(); // 焦点给回编辑器 } catch (ExecutionException e) { MatchViewPart.LOGGER.error("", e); MessageDialog.openInformation(view.getSite().getShell(), Messages.getString("view.MatchViewPart.msgTitle"), Messages.getString("view.MatchViewPart.msg3") + e.getMessage()); } } public void updateEnabledState() { Item[] items = view.gridTable.getItems(); if (items.length == 0) { setEnabled(false); return; } if (view.gridTable.getSelectionIndex() == -1) { setEnabled(false); return; } setEnabled(true); } } class AcceptMatchPureTextAction extends Action { AcceptMatchPureTextAction() { setEnabled(false); setText(Messages.getString("view.MatchViewPart.secondAction")); setToolTipText(Messages.getString("view.MatchViewPart.secondAction.tooltip")); setImageDescriptor(Activator.getIconDescriptor(ImageConstants.ACCEPT_TEXT)); } @Override public void run() { if (editor == null || rowIndex < 0) { return; } TransUnitBean transUnit = editor.getRowTransUnitBean(rowIndex); Hashtable<String, String> tuProp = transUnit.getTuProps(); if (tuProp != null) { String translate = tuProp.get("translate"); if (translate != null && translate.equalsIgnoreCase("no")) { MessageDialog.openInformation(view.getSite().getShell(), Messages.getString("view.MatchViewPart.msgTitle"), Messages.getString("view.MatchViewPart.msg2")); return; } } int selectionIndex = view.gridTable.getSelectionIndex(); if (selectionIndex < 0 || selectionIndex > view.gridTable.getItemCount()) { return; } GridItem item = view.gridTable.getItem(selectionIndex); String pureText = (String) item.getData("tgtText"); String matchType = item.getData("matchType").toString(); String quality = item.getData("quality").toString(); try { if (!matchType.equals("TM")) { matchType = null; quality = null; } editor.updateCell(rowIndex, editor.getTgtColumnIndex(), pureText, matchType, quality); // editor.setFocus(); // 焦点给回编辑器 } catch (ExecutionException e) { MatchViewPart.LOGGER.error("", e); MessageDialog.openInformation(view.getSite().getShell(), Messages.getString("view.MatchViewPart.msgTitle"), Messages.getString("view.MatchViewPart.msg3") + e.getMessage()); } } public void updateEnabledState() { Item[] items = view.gridTable.getItems(); if (items.length == 0) { setEnabled(false); return; } if (view.gridTable.getSelectionIndex() == -1) { setEnabled(false); return; } setEnabled(true); } } /** * @param editor * the editor to set */ public void setEditor(IXliffEditor editor) { this.editor = editor; } /** * @param rowIndex * the rowIndex to set */ public void setRowIndex(int rowIndex) { this.rowIndex = rowIndex; } }
13,018
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TypeColunmCellRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/TypeColunmCellRenderer.java
/** * MatchViewCellRenderer.java * * Version information : * * Date:Dec 26, 2011 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.view; import net.heartsome.cat.ts.ui.grid.XGridCellRenderer; import net.heartsome.cat.ts.ui.util.TmUtils; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; /** * @author Jason * @version * @since JDK1.6 */ public class TypeColunmCellRenderer extends XGridCellRenderer { private TextLayout textLayout; /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); boolean drawBackground = true; boolean drawAsSelected = isSelected(); if (isCellSelected()) { drawAsSelected = true; } gc.setForeground(item.getForeground(getColumn())); if (drawAsSelected) { // if (backColor == null || backColor.isDisposed()) { gc.setBackground((Color) item.getParent().getData("selectedBgColor")); // } else { // gc.setBackground(backColor); // } } else { // if (item.getParent().isEnabled()) { // if (backColor == null || backColor.isDisposed()) { // drawBackground = false; // } else { // gc.setBackground(backColor); // } // } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE)); // } } if (drawBackground) { gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height); } int x = leftMargin; Image image = (Image) item.getData("typeImage"); if (image != null) { int y = getBounds().y; y += (getBounds().height - image.getBounds().height) / 2; gc.drawImage(image, getBounds().x + x, y); x += image.getBounds().width + 3; } int height = getBounds().height - bottomMargin; if (textLayout == null) { textLayout = new TextLayout(gc.getDevice()); item.getParent().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { textLayout.dispose(); } }); } textLayout.setFont(gc.getFont()); String quality = item.getText(getColumn()); textLayout.setText(quality); textLayout.setAlignment(SWT.LEFT); int width = getBounds().width - x - rightMargin; textLayout.setWidth(width < 1 ? 1 : width); int y = getBounds().y + textTopMargin + topMargin; y += getVerticalAlignmentAdjustment(textLayout.getBounds().height, height); // textLayout.draw(gc, getBounds().x + x, y); String type = (String) item.getData("matchType"); if (type.equals("TM")) { Color backColor = TmUtils.getMatchTypeColor(type, quality); if (backColor != null && !backColor.isDisposed()) { gc.setBackground(backColor); } gc.drawText(item.getText(getColumn()), getBounds().x + x, y); } if (item.getParent().getLinesVisible()) { if (isCellSelected()) { // XXX: should be user definable? gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } else { gc.setForeground(item.getParent().getLineColor()); } gc.drawLine(getBounds().x, getBounds().y + getBounds().height, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); int x = 0; x += leftMargin; int y = 0; Image image = item.getImage(getColumn()); if (image != null) { y = topMargin + image.getBounds().height + bottomMargin; x += image.getBounds().width + 3; } // MOPR-DND // MOPR: replaced this code (to get correct preferred height for cells in word-wrap columns) // // x += gc.stringExtent(item.getText(column)).x + rightMargin; // // y = Math.max(y,topMargin + gc.getFontMetrics().getHeight() + bottomMargin); // // with this code: int textHeight = 0; if (!isWordWrap()) { x += gc.textExtent(item.getText(getColumn())).x + rightMargin; textHeight = topMargin + textTopMargin + gc.getFontMetrics().getHeight() + textBottomMargin + bottomMargin; } else { int plainTextWidth; if (wHint == SWT.DEFAULT) plainTextWidth = getBounds().width - x - rightMargin; else plainTextWidth = wHint - x - rightMargin; TextLayout currTextLayout = new TextLayout(gc.getDevice()); currTextLayout.setFont(gc.getFont()); currTextLayout.setText(item.getText(getColumn())); currTextLayout.setAlignment(getAlignment()); currTextLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth); x += plainTextWidth + rightMargin; textHeight += topMargin + textTopMargin; for (int cnt = 0; cnt < currTextLayout.getLineCount(); cnt++) textHeight += currTextLayout.getLineBounds(cnt).height; textHeight += textBottomMargin + bottomMargin; currTextLayout.dispose(); } y = Math.max(y, textHeight); return new Point(x, y); } /** * {@inheritDoc} */ public Rectangle getTextBounds(GridItem item, boolean preferred) { int x = leftMargin; Image image = item.getImage(getColumn()); if (image != null) { x += image.getBounds().width + 3; } Rectangle bounds = new Rectangle(x, topMargin + textTopMargin, 0, 0); GC gc = new GC(item.getParent()); gc.setFont(item.getFont(getColumn())); Point size = gc.stringExtent(item.getText(getColumn())); bounds.height = size.y; if (preferred) { bounds.width = size.x - 1; } else { bounds.width = getBounds().width - x - rightMargin; } gc.dispose(); return bounds; } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { return false; } }
6,605
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TranslationTaskData.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/TranslationTaskData.java
/** * TranslationTaskData.java * * Version information : * * Date:2013-9-5 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.view; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import org.eclipse.core.resources.IProject; /** * @author Jason * @version * @since JDK1.6 */ public class TranslationTaskData { private Object matcher; private TransUnitBean transUnit; private TransUnitInfo2TranslationBean tuInfo; private IXliffEditor editor; private int rowIndex; private IProject project; /** * @param matcher * @param transUnit * @param tuInfo * @param editor */ public TranslationTaskData(Object matcher, TransUnitBean transUnit, TransUnitInfo2TranslationBean tuInfo, IXliffEditor editor, int rowIndex, IProject project) { this.matcher = matcher; this.transUnit = transUnit; this.tuInfo = tuInfo; this.editor = editor; this.rowIndex = rowIndex; this.project = project; } /** @return the matcher */ public Object getMatcher() { return matcher; } /** * @param matcher * the matcher to set */ public void setMatcher(Object matcher) { this.matcher = matcher; } /** @return the transUnit */ public TransUnitBean getTransUnit() { return transUnit; } /** * @param transUnit * the transUnit to set */ public void setTransUnit(TransUnitBean transUnit) { this.transUnit = transUnit; } /** @return the tuInfo */ public TransUnitInfo2TranslationBean getTuInfo() { return tuInfo; } /** * @param tuInfo * the tuInfo to set */ public void setTuInfo(TransUnitInfo2TranslationBean tuInfo) { this.tuInfo = tuInfo; } /** @return the editor */ public IXliffEditor getEditor() { return editor; } /** * @param editor * the editor to set */ public void setEditor(IXliffEditor editor) { this.editor = editor; } /** @return the rowIndex */ public int getRowIndex() { return rowIndex; } /** * @param rowIndex * the rowIndex to set */ public void setRowIndex(int rowIndex) { this.rowIndex = rowIndex; } /** @return the project */ public IProject getProject() { return project; } /** * @param project * the project to set */ public void setProject(IProject project) { this.project = project; } }
3,084
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MatchData.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/MatchData.java
/** * MatchData.java * * Version information : * * Date:2013-4-24 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.view; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import org.eclipse.core.resources.IProject; /** * 此封装用于存储需要在库中查询的翻译单元,当编辑器选择事件发生后,将数据存储在这里,等待匹配线程获取并从库中查询匹配 * @author Jason * @version * @since JDK1.6 */ public class MatchData { /** 当前需要匹配的翻译单元 */ private TransUnitBean transUnit; /** translation unit 所有在项目 */ private IProject project; /** 在编辑器中对应的 RowId */ private String rowId; /** 当前编辑器 */ private IXliffEditor editor; /** TU INFO for matcher */ private TransUnitInfo2TranslationBean tuInfo; public MatchData(TransUnitBean transUnit, TransUnitInfo2TranslationBean tuInfo, IProject project, String rowId, IXliffEditor editor) { this.transUnit = transUnit; this.tuInfo = tuInfo; this.project = project; this.rowId = rowId; this.editor = editor; } public TransUnitBean getTransUnit() { return transUnit; } public void setTransUnit(TransUnitBean transUnit) { this.transUnit = transUnit; } public IProject getProject() { return project; } public void setProject(IProject project) { this.project = project; } public String getRowId() { return rowId; } public void setRowId(String rowId) { this.rowId = rowId; } /** @return the editor */ public IXliffEditor getEditor() { return editor; } /** * @param editor * the editor to set */ public void setEditor(IXliffEditor editor) { this.editor = editor; } /** @return the tuInfo */ public TransUnitInfo2TranslationBean getTuInfo() { return tuInfo; } /** * @param tuInfo * the tuInfo to set */ public void setTuInfo(TransUnitInfo2TranslationBean tuInfo) { this.tuInfo = tuInfo; } }
2,706
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SourceColunmCellRenderer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/SourceColunmCellRenderer.java
/** * MatchViewCellRenderer.java * * Version information : * * Date:Dec 26, 2011 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.view; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import net.heartsome.cat.common.innertag.factory.PlaceHolderEditModeBuilder; import net.heartsome.cat.ts.ui.grid.XGridCellRenderer; import net.heartsome.cat.ts.ui.innertag.SegmentViewer; import net.heartsome.cat.ts.ui.translation.comparator.TextDiffMatcher; import net.heartsome.cat.ts.ui.translation.comparator.TextDiffMatcher.Diff; import net.heartsome.cat.ts.ui.translation.comparator.TextDiffMatcher.Operation; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.widgets.Display; /** * @author Jason * @version * @since JDK1.6 */ public class SourceColunmCellRenderer extends XGridCellRenderer { // private TextLayout textLayout; private Color diffColor = new Color(Display.getDefault(), new RGB(255, 255, 180)); private Color inOrDecreaseColor = new Color(Display.getDefault(), new RGB(162, 200, 255)); private Color positionColor = new Color(Display.getDefault(), new RGB(255, 180, 150)); private String tuSrcText; private SegmentViewer segmentViewer; /** * @param tuSrcText * the tuSrcText to set */ public void setTuSrcText(String tuSrcText) { this.tuSrcText = tuSrcText; } public void setSegmentViewer(SegmentViewer segmentViewer) { this.segmentViewer = segmentViewer; } /** * {@inheritDoc} */ public void paint(GC gc, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); boolean drawBackground = true; boolean drawAsSelected = isSelected(); if (isCellSelected()) { drawAsSelected = true; } gc.setForeground(item.getForeground(getColumn())); if (drawAsSelected) { gc.setBackground((Color) item.getParent().getData("selectedBgColor")); } else { if (item.getParent().isEnabled()) { Color back = item.getBackground(getColumn()); if (back != null) { gc.setBackground(back); } else { drawBackground = false; } } else { gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); } } if (drawBackground) { gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height); } String text = segmentViewer.getTextWidget().getText(); // 创建 TextLayout TextLayout layout = getTextLayout(gc, item, getColumn(), false, false); String displayStr = layout.getText(); // 附加内部标记样式前,先和源文比较,不一样的地方着色实现 if (!tuSrcText.equals(displayStr)) { // TextStyle style = new TextStyle(layout.getFont(), colorConfigBean.getSrcDiffFgColor(), // colorConfigBean.getSrcDiffBgColor()); // List<Position> diff = Comparator.Compare(tuSrcText, displayStr); // for (Iterator<Position> iterator = diff.iterator(); iterator.hasNext();) { // Position position = iterator.next(); // layout.setStyle(style, position.offset, position.length); // } TextStyle diffStyle = new TextStyle(layout.getFont(), null, diffColor); TextStyle InOrDecreaseStyle = new TextStyle(layout.getFont(), null, inOrDecreaseColor); // Increase or // decrease TextStyle positionStyle = new TextStyle(layout.getFont(), null, positionColor); TextDiffMatcher dmp = new TextDiffMatcher(); LinkedList<Diff> diffs = dmp.diff_main(text, displayStr); dmp.diff_cleanupEfficiency(diffs); boolean pFlg = positionDiff(diffs, text, displayStr); if (pFlg) { int insTextStart = 0; int delTextStart = 0; for (int i = 0; i < diffs.size(); i++) { Diff f = diffs.get(i); if (f.operation == Operation.EQUAL) { int l = f.text.length() - 1; insTextStart += l; delTextStart += l; continue; } else if (f.operation == Operation.DELETE && drawAsSelected) { String delText = f.text; Matcher m = PlaceHolderEditModeBuilder.PATTERN.matcher(delText); TextStyle style = positionStyle; boolean flg = m.find(); if (flg && delText.length() != 1) { int start = text.indexOf(delText, delTextStart); delTextStart = start + delText.length(); int mark = 0; List<StyleRange> rangeList = new ArrayList<StyleRange>(); do { int off = m.start(); StyleRange range = new StyleRange(style); range.start = start + mark; range.length = off - mark; mark = m.end(); rangeList.add(range); } while (m.find()); if (mark < delText.length()) { StyleRange range = new StyleRange(style); range.start = start + mark; range.length = delText.length() - mark; rangeList.add(range); } for (StyleRange range : rangeList) { segmentViewer.getTextWidget().setStyleRange(range); } } else if (!flg) { int start = text.indexOf(delText, delTextStart); delTextStart = start + delText.length(); StyleRange range = new StyleRange(style); range.start = start; range.length = delText.length(); segmentViewer.getTextWidget().setStyleRange(range); } } else if (f.operation == Operation.INSERT) { String insText = f.text; int start = displayStr.indexOf(insText, insTextStart); insTextStart += insText.length(); layout.setStyle(positionStyle, start, start + insText.length() - 1); } } } else { int insTextStart = 0; int delTextStart = 0; for (int i = 0; i < diffs.size(); i++) { Diff f = diffs.get(i); if (f.operation == Operation.EQUAL) { int l = f.text.length() - 1; insTextStart += l; delTextStart += l; continue; } else if (f.operation == Operation.DELETE) { String delText = f.text; boolean isDiff = false; if (i + 1 < diffs.size() && diffs.get(i + 1).operation == Operation.INSERT) { // 库和当前句子存在不一致部分 i += 1; // 处理库 f = diffs.get(i); String insText = f.text; int start = displayStr.indexOf(insText, insTextStart); layout.setStyle(diffStyle, start, start + insText.length() - 1); insTextStart = start + insText.length(); isDiff = true; } // 处理当前句子 if (drawAsSelected) { Matcher m = PlaceHolderEditModeBuilder.PATTERN.matcher(delText); TextStyle style = isDiff ? diffStyle : InOrDecreaseStyle; boolean flg = m.find(); if (flg && delText.length() != 1) { int start = text.indexOf(delText, delTextStart); delTextStart = start + delText.length(); int mark = 0; List<StyleRange> rangeList = new ArrayList<StyleRange>(); do { int off = m.start(); StyleRange range = new StyleRange(style); range.start = start + mark; range.length = off - mark; mark = m.end(); rangeList.add(range); } while (m.find()); if (mark < delText.length()) { StyleRange range = new StyleRange(style); range.start = start + mark; range.length = delText.length() - mark; rangeList.add(range); } for (StyleRange range : rangeList) { segmentViewer.getTextWidget().setStyleRange(range); } } else if (!flg) { int start = text.indexOf(delText, delTextStart); delTextStart = start + delText.length(); StyleRange range = new StyleRange(style); range.start = start; range.length = delText.length(); segmentViewer.getTextWidget().setStyleRange(range); } } } else if (f.operation == Operation.INSERT) { // 库多出来的 String insText = f.text; int start = displayStr.indexOf(insText, insTextStart); insTextStart += insText.length(); layout.setStyle(InOrDecreaseStyle, start, start + insText.length() - 1); } } } } // 添加标记样式,并创建标记 attachInnertTagStyle(gc, layout, false); try { int y = getBounds().y + textTopMargin + topMargin; y += getVerticalAlignmentAdjustment(layout.getBounds().height, getBounds().height); if (item.getParent().isAutoHeight()) { int textHeight = topMargin + textTopMargin; // fix Bug #3116 库匹配面板--显示的匹配有截断 by Jason // for (int cnt = 0; cnt < layout.getLineCount(); cnt++) // textHeight += layout.getLineBounds(cnt).height; textHeight += layout.getBounds().height; textHeight += textBottomMargin + bottomMargin; item.setData("itemHeight", textHeight); } Point selection = copyEnable.getSelectionRange(getColumn(), item); if (selection == null || selection.x == selection.y) { layout.draw(gc, getBounds().x + leftMargin, y); } else { int x = getBounds().x + leftMargin; int start = Math.max(0, selection.x); int end = Math.min(displayStr.length(), selection.y); layout.draw(gc, x, y, start, end - 1, getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT), getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION)); } drawInnerTag(gc, layout); if (item.getParent().getLinesVisible()) { if (isCellSelected()) { gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } else { gc.setForeground(item.getParent().getLineColor()); } gc.drawLine(getBounds().x, getBounds().y + getBounds().height, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1, getBounds().y + getBounds().height); } } finally { if (layout != null) { layout.dispose(); } } } /** * {@inheritDoc} */ public Point computeSize(GC gc, int wHint, int hHint, Object value) { GridItem item = (GridItem) value; gc.setFont(item.getFont(getColumn())); int x = 0; x += leftMargin; int y = 0; Image image = item.getImage(getColumn()); if (image != null) { y = topMargin + image.getBounds().height + bottomMargin; } // MOPR-DND // MOPR: replaced this code (to get correct preferred height for cells in word-wrap columns) // // x += gc.stringExtent(item.getText(column)).x + rightMargin; // // y = Math.max(y,topMargin + gc.getFontMetrics().getHeight() + bottomMargin); // // with this code: int textHeight = 0; if (!isWordWrap()) { x += gc.textExtent(item.getText(getColumn())).x + rightMargin; textHeight = topMargin + textTopMargin + gc.getFontMetrics().getHeight() + textBottomMargin + bottomMargin; } else { int plainTextWidth; if (wHint == SWT.DEFAULT) plainTextWidth = getBounds().width - x - rightMargin; else plainTextWidth = wHint - x - rightMargin; TextLayout currTextLayout = new TextLayout(gc.getDevice()); currTextLayout.setFont(gc.getFont()); currTextLayout.setText(item.getText(getColumn())); currTextLayout.setAlignment(getAlignment()); currTextLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth); x += plainTextWidth + rightMargin; textHeight += topMargin + textTopMargin; for (int cnt = 0; cnt < currTextLayout.getLineCount(); cnt++) textHeight += currTextLayout.getLineBounds(cnt).height; textHeight += textBottomMargin + bottomMargin; currTextLayout.dispose(); } y = Math.max(y, textHeight); return new Point(x, y); } /** * {@inheritDoc} */ public boolean notify(int event, Point point, Object value) { return false; } private boolean positionDiff(LinkedList<Diff> diffs, String text1, String text2) { if (diffs.size() > 2 && text1.length() == text2.length()) { // 判断位置不一样 LinkedList<Diff> delDiff = new LinkedList<Diff>(); LinkedList<Diff> insDiff = new LinkedList<Diff>(); for (int i = 0; i < diffs.size(); i++) { Diff f = diffs.get(i); if (f.operation == Operation.DELETE) { delDiff.add(f); } else if (f.operation == Operation.INSERT) { insDiff.add(f); } } if (delDiff.size() == 0 || insDiff.size() == 0) { return false; } label: for (int i = 0; i < delDiff.size(); i++) { Diff df = delDiff.get(i); for (int j = 0; j < insDiff.size(); j++) { Diff idf = insDiff.get(j); if (df.text.trim().equals(idf.text.trim())) { insDiff.remove(j); continue label; } } return false; } return true; } return false; } public void dispose() { if (!diffColor.isDisposed()) { diffColor.dispose(); } if (!inOrDecreaseColor.isDisposed()) { inOrDecreaseColor.dispose(); } if (!positionColor.isDisposed()) { positionColor.dispose(); } } }
13,622
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MatchViewPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/view/MatchViewPart.java
package net.heartsome.cat.ts.ui.translation.view; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Vector; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.common.locale.LocaleService; import net.heartsome.cat.common.ui.listener.PartAdapter2; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.common.util.DateUtils; import net.heartsome.cat.ts.core.bean.AltTransBean; import net.heartsome.cat.ts.core.bean.Constants; import net.heartsome.cat.ts.core.bean.PropBean; import net.heartsome.cat.ts.core.bean.PropGroupBean; import net.heartsome.cat.ts.core.bean.TransUnitBean; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean; import net.heartsome.cat.ts.tm.complexMatch.ComplexMatcherFactory; import net.heartsome.cat.ts.tm.complexMatch.IComplexMatch; import net.heartsome.cat.ts.tm.match.TmMatcher; import net.heartsome.cat.ts.tm.simpleMatch.ISimpleMatcher; import net.heartsome.cat.ts.tm.simpleMatch.SimpleMatcherFactory; import net.heartsome.cat.ts.ui.bean.TranslateParameter; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.grid.GridCopyEnable; import net.heartsome.cat.ts.ui.innertag.SegmentViewer; import net.heartsome.cat.ts.ui.translation.Activator; import net.heartsome.cat.ts.ui.translation.bean.TmConstants; import net.heartsome.cat.ts.ui.translation.resource.Messages; import net.heartsome.cat.ts.ui.util.TmUtils; import net.heartsome.cat.ts.ui.view.IMatchViewPart; import org.eclipse.core.resources.IProject; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.nebula.widgets.grid.Grid; import org.eclipse.nebula.widgets.grid.GridColumn; import org.eclipse.nebula.widgets.grid.GridItem; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; 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.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IMemento; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.ViewPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MatchViewPart extends ViewPart implements ISelectionListener, IMatchViewPart { public static final Logger LOGGER = LoggerFactory.getLogger(MatchViewPart.class); public static final String ID = "net.heartsome.cat.ts.ui.translation.view.matchview"; /** 当前编辑器中对应的XLIFF文件Handler */ // private XLFHandler handler; /** 被监听的编辑器。 */ // IXliffEditor editor; /** 编辑器中选中的行标识 */ // int rowIndex = -1; // private IProject currentProject; // TransUnitBean currentTransUnitBean; SegmentViewer sourceText; Grid gridTable; private SourceColunmCellRenderer sourceColunmCellRenderer = new SourceColunmCellRenderer(); private TypeColunmCellRenderer typeColumnCellRenderer = new TypeColunmCellRenderer(); private TargetColunmCellRenderer targetColumnCellRenderer = new TargetColunmCellRenderer(); GridCopyEnable copyEnable; private CLabel infoLabel; private Image infoLabelImage; private CLabel tipLabel; private Image tipLabelImage; MatchViewerBodyMenu menuMgr; TmMatcher tmMatcher; // private TransUnitInfo2TranslationBean tuInfoBean; TranslateParameter transParameter; private Image tmImage; private Image googleImage; private Image qtImage; private Image bingImage; private Image otherImage; private Color selectedBgColor; private List<AltTransBean> altTransCacheList = new ArrayList<AltTransBean>(); private FontPropertyChangeListener fontChangeListener = new FontPropertyChangeListener(); private ExecuteMatchThread matcherThread; private ManualTranslationTread manualTranslationThread; private TranslationTaskContainer manualTranslationTaskContainer; public MatchViewPart() { tmMatcher = new TmMatcher(); transParameter = TranslateParameter.getInstance(); tmImage = Activator.getImageDescriptor("images/match-type/tm.png").createImage(); qtImage = Activator.getImageDescriptor("images/match-type/qt.png").createImage(); googleImage = Activator.getImageDescriptor("images/match-type/google.png").createImage(); bingImage = Activator.getImageDescriptor("images/match-type/bing.png").createImage(); otherImage = Activator.getImageDescriptor("images/match-type/others.png").createImage(); selectedBgColor = new Color(Display.getDefault(), 210, 210, 240); JFaceResources.getFontRegistry().addListener(fontChangeListener); tipLabelImage = Activator.getImageDescriptor("images/status/Loading.png").createImage(); // 初始化自动任务线程在SelectionChange事件时,自动任务线程在任务到达时再启动,完成后任务后线程停止 // 初始化手动任务线程,手动任务线程在界面创建时启动,启动后等待任务的到达,到达后还需要等待自动任务线程结束才执行 manualTranslationTaskContainer = new TranslationTaskContainer(); manualTranslationThread = new ManualTranslationTread(manualTranslationTaskContainer); manualTranslationThread.start(); } @Override public void init(IViewSite site, IMemento memento) throws PartInitException { init(site); site.getPage().addPostSelectionListener(this); site.getPage().addPartListener(new PartAdapter2() { @Override public void partClosed(IWorkbenchPartReference partRef) { if (gridTable == null || gridTable.isDisposed()) { getSite().getPage().removePartListener(this); // 关闭视图后,移除此监听 } else { if ("net.heartsome.cat.ts.ui.xliffeditor.nattable.editor".equals(partRef.getId())) { IEditorReference[] editorReferences = getSite().getPage().getEditorReferences(); if (editorReferences.length == 0) { // 所有编辑器全部关闭的情况下。 synchronized (matchDataContainer) { matchDataContainer.clear(); if (matcherThread != null) { matcherThread.interrupt(); } } manualTranslationThread.interruptCurrentTask(); tmMatcher.clearDbResources(); copyEnable.resetSelection(); gridTable.removeAll(); sourceText.setText(""); setMatchMessage(null, "", ""); setProcessMessage(null, "", ""); } } } } }); site.getActionBars().getStatusLineManager().setMessage(Messages.getString("view.MatchViewPart.statusLine")); } @Override public void createPartControl(Composite parent) { GridLayout parentGl = new GridLayout(1, false); parentGl.marginWidth = 0; parentGl.marginHeight = 0; parent.setLayout(parentGl); final Composite composite = new Composite(parent, SWT.NONE); GridLayout compositeGl = new GridLayout(1, false); compositeGl.marginBottom = -1; compositeGl.marginLeft = -1; compositeGl.marginRight = -1; compositeGl.marginTop = 0; compositeGl.marginWidth = 0; compositeGl.marginHeight = 0; compositeGl.verticalSpacing = 0; composite.setLayout(compositeGl); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // sourceText = new StyledText(composite, SWT.BORDER | SWT.V_SCROLL | SWT.READ_ONLY); // GridData sTextGd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); // Font f = JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.MATCH_VIEWER_TEXT_FONT); // sourceText.setFont(f); // int lineH = sourceText.getLineHeight() * 3; // sTextGd.heightHint = lineH; // sTextGd.minimumHeight = lineH; // sourceText.setLayoutData(sTextGd); SashForm sashForm = new SashForm(composite, SWT.VERTICAL); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); sourceText = new SegmentViewer(sashForm, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL, null); StyledText srcTextControl = sourceText.getTextWidget(); srcTextControl.setLineSpacing(net.heartsome.cat.ts.ui.Constants.SEGMENT_LINE_SPACING); srcTextControl.setLeftMargin(net.heartsome.cat.ts.ui.Constants.SEGMENT_LEFT_MARGIN); srcTextControl.setRightMargin(net.heartsome.cat.ts.ui.Constants.SEGMENT_RIGHT_MARGIN); srcTextControl.setTopMargin(net.heartsome.cat.ts.ui.Constants.SEGMENT_TOP_MARGIN); srcTextControl.setBottomMargin(net.heartsome.cat.ts.ui.Constants.SEGMENT_TOP_MARGIN); srcTextControl.setFont(JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.MATCH_VIEWER_TEXT_FONT)); sourceText.setSource(""); sourceColunmCellRenderer.setSegmentViewer(sourceText); GridData sTextGd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); Font f = JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.MATCH_VIEWER_TEXT_FONT); srcTextControl.setFont(f); int lineH = srcTextControl.getLineHeight() * 2; sTextGd.heightHint = lineH; sTextGd.minimumHeight = lineH; srcTextControl.setLayoutData(sTextGd); net.heartsome.cat.ts.ui.innertag.tagstyle.TagStyleConfigurator.configure(sourceText); gridTable = new Grid(sashForm, SWT.BORDER | SWT.V_SCROLL); gridTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); gridTable.setHeaderVisible(false); gridTable.setAutoHeight(true); gridTable.setRowsResizeable(true); gridTable.setData("selectedBgColor", selectedBgColor); final GridColumn sourceCln = new GridColumn(gridTable, SWT.NONE); sourceColunmCellRenderer.setFont(JFaceResources .getFont(net.heartsome.cat.ts.ui.Constants.MATCH_VIEWER_TEXT_FONT)); sourceCln.setCellRenderer(sourceColunmCellRenderer); sourceCln.setText(Messages.getString("view.MatchViewPart.sourceCln")); sourceCln.setWordWrap(true); sourceCln.setAlignment(SWT.CENTER); sourceCln.setResizeable(false); final GridColumn typeCln = new GridColumn(gridTable, SWT.NONE); typeColumnCellRenderer.setVerticalAlignment(SWT.CENTER); typeCln.setCellRenderer(typeColumnCellRenderer); typeCln.setText(Messages.getString("view.MatchViewPart.typeCln")); typeCln.setWordWrap(true); typeCln.setAlignment(SWT.CENTER); typeCln.setResizeable(false); final GridColumn targetCln = new GridColumn(gridTable, SWT.NONE); targetColumnCellRenderer.setFont(JFaceResources .getFont(net.heartsome.cat.ts.ui.Constants.MATCH_VIEWER_TEXT_FONT)); targetCln.setCellRenderer(targetColumnCellRenderer); targetCln.setText(Messages.getString("view.MatchViewPart.targetCln")); targetCln.setWordWrap(true); targetCln.setAlignment(SWT.CENTER); targetCln.setResizeable(false); // 设置可复制功能 copyEnable = new GridCopyEnable(gridTable); sourceColunmCellRenderer.setCopyEnable(copyEnable); targetColumnCellRenderer.setCopyEnable(copyEnable); Composite statusComposite = new Composite(composite, SWT.NONE); GridLayout statusComptGridLayout = new GridLayout(2, false); statusComptGridLayout.marginBottom = -1; statusComptGridLayout.marginLeft = -1; statusComptGridLayout.marginRight = -1; statusComptGridLayout.marginTop = -1; statusComptGridLayout.marginWidth = 0; statusComptGridLayout.marginHeight = 0; statusComposite.setLayout(statusComptGridLayout); statusComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); tipLabel = new CLabel(statusComposite, SWT.NONE); tipLabel.setAlignment(SWT.LEFT); infoLabel = new CLabel(statusComposite, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd.heightHint = 20; infoLabel.setLayoutData(gd); infoLabel.setAlignment(SWT.RIGHT); // 设置列宽按比例4.5:1:4.5 composite.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { Rectangle area = composite.getClientArea(); Point preferredSize = gridTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); int width = area.width;// - 2 * gridTable.getBorderWidth(); if (preferredSize.y > area.height + gridTable.getHeaderHeight()) { Point vBarSize = gridTable.getVerticalBar().getSize(); width -= vBarSize.x; } gridTable.setSize(area.width, area.height); width = width - 42; sourceCln.setWidth((int) (width * 0.5)); typeCln.setWidth(42); targetCln.setWidth((int) (width * 0.5)); } }); gridTable.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { StyledText text = sourceText.getTextWidget(); text.setText(text.getText()); updateActionState(); GridItem[] selItems = gridTable.getSelection(); if (selItems.length != 1) { return; } GridItem item = selItems[0]; setMatchMessage(infoLabelImage, item.getData("info").toString(), item.getData("infoTooltip").toString()); composite.layout(); } }); gridTable.addListener(SWT.MouseDoubleClick, new Listener() { public void handleEvent(Event event) { menuMgr.acceptMatchAction.run(); } }); createActions(); sashForm.setWeights(new int[] { 3, 8 }); } /** * 监听XLFEditor的选择事件 */ public void selectionChanged(final IWorkbenchPart part, final ISelection selection) { if (part == null || selection == null) { return; } if (!(part instanceof IEditorPart)) { updateActionState(); return; } if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) { updateActionState(); return; } IXliffEditor editor = (IXliffEditor) part; IStructuredSelection structuredSelecion = (IStructuredSelection) selection; final Object object = structuredSelecion.getFirstElement(); if (object instanceof Integer) { int rowIndex = -1; int selRowIndex = (Integer) object; if (rowIndex == selRowIndex) { if (gridTable.getItemCount() != 0) { updateActionState(); } return; } else { rowIndex = selRowIndex; } XLFHandler handler = editor.getXLFHandler(); String rowId = handler.getRowId(rowIndex); TransUnitBean transUnit = editor.getRowTransUnitBean(rowIndex);// handler.getTransUnit(rowId); if (transUnit == null) { updateActionState(); return; } TransUnitInfo2TranslationBean tuInfoBean = getTuInfoBean(transUnit, handler, rowId); FileEditorInput input = (FileEditorInput) getSite().getPage().getActiveEditor().getEditorInput(); IProject currentProject = input.getFile().getProject(); copyEnable.resetSelection(); gridTable.removeAll(); altTransCacheList.clear(); menuMgr.setEditor(editor); menuMgr.setRowIndex(rowIndex); executeMatch(editor, rowId, transUnit, tuInfoBean, currentProject); } } private void executeMatch(IXliffEditor editor, String rowId, TransUnitBean transUnit, TransUnitInfo2TranslationBean tuInfo, IProject project) { if (matcherThread == null) { matcherThread = new ExecuteMatchThread(); matcherThread.start(); } synchronized (matchDataContainer) { matchDataContainer.clear(); matchDataContainer.add(new MatchData(transUnit, tuInfo, project, rowId, editor)); matchDataContainer.notify(); } } public void refreshTable() { gridTable.redraw(); } public void reLoadMatches(IXliffEditor editor, int rowIndex) { // 修复 Bug #3064 编辑匹配--更换记忆库后再编辑原记忆库匹配,出现异常.刷新问题 TransUnitBean transUnit = editor.getRowTransUnitBean(rowIndex);// handler.getTransUnit(rowId); if (transUnit == null) { return; } XLFHandler handler = editor.getXLFHandler(); if (handler == null) { return; } IProject prj = null; if (editor instanceof IEditorPart) { IEditorPart p = (IEditorPart) editor; FileEditorInput input = (FileEditorInput) p.getEditorInput(); prj = input.getFile().getProject(); } if (prj == null) { return; } String rowId = handler.getRowId(rowIndex); TransUnitInfo2TranslationBean tuInfoBean = getTuInfoBean(transUnit, handler, rowId); executeMatch(editor, rowId, transUnit, tuInfoBean, prj); } public void acceptMatchByIndex(int index) { if (index < 0 || index + 1 > gridTable.getItemCount()) { return; } gridTable.select(index); menuMgr.acceptMatchAction.run(); } public void manualExecComplexTranslation(int rowIndex, IXliffEditor editor, IComplexMatch complexMatcher) { if (rowIndex == -1) { return; } TransUnitBean transUnit = editor.getRowTransUnitBean(rowIndex);// handler.getTransUnit(rowId); if (transUnit == null) { return; } XLFHandler handler = editor.getXLFHandler(); if (handler == null) { return; } IProject prj = null; if (editor instanceof IEditorPart) { IEditorPart p = (IEditorPart) editor; FileEditorInput input = (FileEditorInput) p.getEditorInput(); prj = input.getFile().getProject(); } if (prj == null) { return; } String rowId = handler.getRowId(rowIndex); TransUnitInfo2TranslationBean tuInfo = getTuInfoBean(transUnit, handler, rowId); TranslationTaskData data = new TranslationTaskData(complexMatcher, transUnit, tuInfo, editor, rowIndex, prj); synchronized (manualTranslationTaskContainer) { manualTranslationTaskContainer.pushTranslationTask(data); manualTranslationTaskContainer.notify(); } } public void manualExecSimpleTranslation(int rowIndex, IXliffEditor editor, ISimpleMatcher simpleMatcher) { if (rowIndex == -1) { return; } TransUnitBean transUnit = editor.getRowTransUnitBean(rowIndex);// handler.getTransUnit(rowId); if (transUnit == null) { return; } XLFHandler handler = editor.getXLFHandler(); if (handler == null) { return; } IProject prj = null; if (editor instanceof IEditorPart) { IEditorPart p = (IEditorPart) editor; FileEditorInput input = (FileEditorInput) p.getEditorInput(); prj = input.getFile().getProject(); } if (prj == null) { return; } String rowId = handler.getRowId(rowIndex); TransUnitInfo2TranslationBean tuInfo = getTuInfoBean(transUnit, handler, rowId); TranslationTaskData data = new TranslationTaskData(simpleMatcher, transUnit, tuInfo, editor, rowIndex, prj); synchronized (manualTranslationTaskContainer) { manualTranslationTaskContainer.pushTranslationTask(data); manualTranslationTaskContainer.notify(); } } Vector<MatchData> matchDataContainer = new Vector<MatchData>(); /** * 自动任务线程 * @author Jason * @version * @since JDK1.6 */ class ExecuteMatchThread extends Thread { private TransUnitBean transUnit; private TransUnitInfo2TranslationBean tuInfoBean; private IProject project; private String rowId; private XLFHandler handler; private IXliffEditor editor; private boolean stop; public ExecuteMatchThread() { } /** * stop current thread */ public void setStop() { this.stop = true; } @Override public void run() { while (!stop) { try { // 无新数据到达前进行等待状态 synchronized (matchDataContainer) { if (matchDataContainer.isEmpty()) { try { matchDataContainer.wait(); } catch (InterruptedException e) { } } } if (matchDataContainer.size() == 0) { continue; } // 查找匹配前先清除当前界面中的内容 Display.getDefault().syncExec(new Runnable() { public void run() { copyEnable.resetSelection(); if (!gridTable.isDisposed()) { gridTable.removeAll(); } altTransCacheList.clear(); } }); MatchData d = matchDataContainer.remove(matchDataContainer.size() - 1); this.rowId = d.getRowId(); this.transUnit = d.getTransUnit(); this.project = d.getProject(); this.editor = d.getEditor(); this.handler = this.editor.getXLFHandler(); this.tuInfoBean = d.getTuInfo(); // -- execute translation memory match manualTranslationThread.interruptCurrentTask(); manualTranslationThread.setLock(true); updateStatusInfo(Messages.getString("view.MatchViewPart.processInfo.loadHSMatch")); Vector<AltTransBean> complexMatches = null; if (!CommonFunction.checkEdition("L")) { Vector<AltTransBean> fuzzy = TmUtils.fuzzyResult2Alttransbean(tmMatcher.executeFuzzySearch( project, tuInfoBean)); transUnit.updateMatches(Constants.TM_TOOLID, fuzzy); complexMatches = executeComplexMatch(transUnit, project); } final Vector<AltTransBean> tmAltTrans = transUnit.getMatchesByToolId(Constants.TM_TOOLID); altTransCacheList.addAll(tmAltTrans); if (complexMatches != null && complexMatches.size() > 0) { altTransCacheList.addAll(complexMatches); complexMatches.clear(); complexMatches = null; } loadData2UI(altTransCacheList); // 加载Simple Match,如google ,bing final List<String> needClearToolId = new ArrayList<String>(); // 需要清掉文件中原有的匹配 final List<AltTransBean> needSaveAltTransList = new ArrayList<AltTransBean>(); List<AltTransBean> needLoadAltTransList = new ArrayList<AltTransBean>(); executeSimpleMatch(tuInfoBean, transUnit, needClearToolId, needSaveAltTransList, needLoadAltTransList); loadData2UI(needLoadAltTransList); altTransCacheList.addAll(needLoadAltTransList); needLoadAltTransList.clear(); // 加载文件中的其他匹配 Vector<AltTransBean> cm = new Vector<AltTransBean>(); if (transUnit.getMatches() != null) { cm.addAll(transUnit.getMatches()); cm.removeAll(altTransCacheList); altTransCacheList.addAll(cm); if (cm.size() > 0) { loadData2UI(cm); } cm.clear(); } Display.getDefault().syncExec(new Runnable() { public void run() { updateUI(tmAltTrans, handler.getRowIndex(rowId)); setProcessMessage(null, "", ""); } }); if (needSaveAltTransList.size() > 0 && handler != null) { Display.getDefault().syncExec(new Runnable() { public void run() { // 重新写入altTrans handler.updateAltTrans(rowId, needSaveAltTransList, needClearToolId); needSaveAltTransList.clear(); needClearToolId.clear(); } }); } manualTranslationThread.setLock(false); } catch (Exception e) { continue; } } } /** * 将数据加载到界面中 * @param altTransVector * ; */ private void loadData2UI(final List<AltTransBean> altTransVector) { Display.getDefault().syncExec(new Runnable() { public void run() { sourceText.setText(transUnit.getSrcContent()); loadData(altTransVector); } }); } /** * 更新界面,执行默认选中以及应用最大匹配、复制源到目标自动策略 * @param tmAltTrans * ; */ private void updateUI(Vector<AltTransBean> tmAltTrans, int rowIndex) { if (gridTable.isDisposed()) { return; } int itemSize = gridTable.getItemCount(); String tgt = transUnit.getTgtContent(); if (itemSize > 0) { gridTable.setSelection(0); // 在编辑器中切换文本段时刷新 infoLabel 的内容 GridItem selItem = gridTable.getItem(0); setMatchMessage(infoLabelImage, selItem.getData("info").toString(), selItem.getData("infoTooltip") .toString()); infoLabel.getParent().layout(); updateActionState(); // 无译文时,应用最大记忆库匹配 if ((tgt == null || tgt.equals("")) && transParameter.isApplyTmMatch() && tmAltTrans.size() > 0) { menuMgr.acceptMatchAction.run(); } } else { // 在编辑器中切换文本段时刷新 infoLabel 的内容 setMatchMessage(null, "", ""); infoLabel.getParent().layout(); // 无译文,无匹配时,复制来源到目标 if (tgt == null || tgt.equals("") && transParameter.isApplySource()) { editor.affterFuzzyMatchApplayTarget(rowIndex, transUnit.getSrcContent(), null, null); } updateActionState(); } tmAltTrans.clear(); } /** * 更新状态信息 * @param content * ; */ private void updateStatusInfo(final String content) { Display.getDefault().syncExec(new Runnable() { public void run() { if (content != null && content.length() != 0) { setProcessMessage(tipLabelImage, content, ""); } else { setProcessMessage(null, "", ""); } } }); } private Vector<AltTransBean> executeComplexMatch(TransUnitBean transUnitBean, IProject currentProject) { List<IComplexMatch> matchers = ComplexMatcherFactory.getInstance().getCuurentMatcher(); Vector<AltTransBean> allMatchs = new Vector<AltTransBean>(); for (IComplexMatch matcher : matchers) { String toolId = matcher.getToolId(); if (!(toolId.equals(Constants.QT_TOOLID) && transParameter.isAutoQuickTrans())) { continue; } Vector<AltTransBean> result = matcher.executeTranslation(transUnitBean, currentProject); if (result.size() > 0) { allMatchs.addAll(result); } } return allMatchs; } private void executeSimpleMatch(TransUnitInfo2TranslationBean tuInfo, TransUnitBean transUnit, List<String> needClearToolId, List<AltTransBean> needSaveAltTransList, List<AltTransBean> needLoadAltTransList) { // 如果忽略锁定的文本,不进行机器翻译 if (TranslateParameter.getInstance().isIgnoreLock()) { if ("no".equals(transUnit.getTuProps().get("translate"))) { return; } } // 如果忽略上下文匹配和完全匹配,不翻译 if (TranslateParameter.getInstance().isIgnoreExactMatch()) { if ("100".equals(transUnit.getTgtProps().get("hs:quality")) || "101".equals(transUnit.getTgtProps().get("hs:quality"))) { return; } } List<ISimpleMatcher> simpleMatchers = SimpleMatcherFactory.getInstance().getCuurentMatcher(); for (ISimpleMatcher matcher : simpleMatchers) { String toolId = matcher.getMathcerToolId(); String matcherType = matcher.getMatcherType(); Vector<AltTransBean> currentMatch = transUnit.getMatchesByToolId(toolId); boolean isOverwrite = matcher.isOverwriteMatch(); if (!matcher.matchChecker()) { needLoadAltTransList.addAll(currentMatch); continue; } if (currentMatch.size() > 0 && !isOverwrite) { needLoadAltTransList.addAll(currentMatch); continue; } else { String tgtText = matcher.executeMatch(tuInfo); if (tgtText.equals("")) { continue; } AltTransBean bean = new AltTransBean(tuInfo.getSrcPureText(), tgtText, tuInfo.getSrcLanguage(), tuInfo.getTgtLangugage(), matcher.getMathcerOrigin(), toolId); bean.getMatchProps().put("match-quality", "100"); bean.setSrcContent(tuInfo.getSrcPureText()); bean.setTgtContent(tgtText); bean.getMatchProps().put("hs:matchType", matcherType); currentMatch.clear(); currentMatch.add(bean); needLoadAltTransList.addAll(currentMatch); if (CommonFunction.checkEdition("U") && matcher.isSuportPreTrans()) { needSaveAltTransList.add(bean); transUnit.updateMatches(toolId, currentMatch); if (currentMatch.size() > 0) { needClearToolId.add(toolId); } } } } } }; /** * 手动任务线程 * @author Jason * @version * @since JDK1.6 */ class ManualTranslationTread extends Thread { private boolean isLocked; private boolean stop; private boolean interrupt; private TranslationTaskContainer container; private MessageFormat msgFormat; private TransUnitBean transUnitBean; private TransUnitInfo2TranslationBean tuInfoBean; private IXliffEditor editor; private int rowIndex; private IProject project; public ManualTranslationTread(TranslationTaskContainer container) { this.container = container; isLocked = false; stop = false; interrupt = false; msgFormat = new MessageFormat(Messages.getString("view.MatchViewPart.processInfo.manualProcess")); } @Override public void run() { while (!stop) { synchronized (container) { if (container.isEmpty()) { try { container.wait(); } catch (InterruptedException e) { } } } if (isLocked) { synchronized (container) { try { container.wait(); } catch (InterruptedException e) { } } } TranslationTaskData data = container.popTranslationTask(); if (data == null) { interrupt = false; continue; } transUnitBean = data.getTransUnit(); tuInfoBean = data.getTuInfo(); editor = data.getEditor(); Object matcher = data.getMatcher(); rowIndex = data.getRowIndex(); project = data.getProject(); if (TranslateParameter.getInstance().isIgnoreLock()) { if ("no".equals(transUnitBean.getTuProps().get("translate"))) { continue; } } // 如果忽略上下文匹配和完全匹配,不翻译 if (TranslateParameter.getInstance().isIgnoreExactMatch()) { if ("100".equals(transUnitBean.getTgtProps().get("hs:quality")) || "101".equals(transUnitBean.getTgtProps().get("hs:quality"))) { continue; } } if (matcher instanceof ISimpleMatcher) { if (rowIndex == -1 || tuInfoBean == null) { continue; } if (interrupt) { interrupt = false; // reset for next task continue; } final ISimpleMatcher simpleMatcher = (ISimpleMatcher) matcher; updateStatusInfo(msgFormat.format(new String[] { simpleMatcher.getMathcerToolId() })); String tgtText = simpleMatcher.executeMatch(tuInfoBean); if (tgtText.equals("")) { updateStatusInfo(null); continue; } if (interrupt) { interrupt = false; // reset for next task updateStatusInfo(null); continue; } AltTransBean bean = new AltTransBean(tuInfoBean.getSrcPureText(), tgtText, tuInfoBean.getSrcLanguage(), tuInfoBean.getTgtLangugage(), simpleMatcher.getMathcerOrigin(), simpleMatcher.getMathcerToolId()); bean.getMatchProps().put("match-quality", "100"); bean.setSrcContent(tuInfoBean.getSrcPureText()); bean.setTgtContent(tgtText); bean.getMatchProps().put("hs:matchType", simpleMatcher.getMatcherType()); // first refresh cache, then use cache refresh UI final List<AltTransBean> newAltTrans = new ArrayList<AltTransBean>(); newAltTrans.add(bean); if (interrupt) { updateStatusInfo(null); interrupt = false; // reset for next task continue; } refreshAltTransCache(newAltTrans); refreshUI(); final XLFHandler handler = editor.getXLFHandler(); if (CommonFunction.checkEdition("U") && simpleMatcher.isSuportPreTrans() && handler != null) { Display.getDefault().syncExec(new Runnable() { public void run() { // 重新写入altTrans List<String> toolIdList = new ArrayList<String>(); toolIdList.add(simpleMatcher.getMathcerToolId()); handler.updateAltTrans(handler.getRowId(rowIndex), newAltTrans, toolIdList); toolIdList.clear(); newAltTrans.clear(); } }); } } else if (matcher instanceof IComplexMatch) { IComplexMatch complexMatch = (IComplexMatch) matcher; updateStatusInfo(msgFormat.format(new String[] { complexMatch.getToolId() })); if (rowIndex != -1 && transUnitBean != null && transUnitBean != null) { if (interrupt) { interrupt = false; // reset for next task updateStatusInfo(null); continue; } Vector<AltTransBean> result = complexMatch.executeTranslation(transUnitBean, project); if (interrupt) { interrupt = false; // reset for next task updateStatusInfo(null); continue; } if (result.size() > 0) { // first refresh cache, then use cache refresh UI refreshAltTransCache(result); refreshUI(); } else { updateStatusInfo(null); } } } } } /** * 中断当前任务,停止当前任务的执行,并清空任务列表,线程进入等待新任务状态 <br> * 如果当前任务已经进入阻塞状态,则不会产生任何效果 */ public void interruptCurrentTask() { this.interrupt = true; synchronized (container) { container.clearContainer(); } } public void setLock(boolean isLock) { this.isLocked = isLock; if (!isLocked) { // 取消锁定则恢复打断状态 interrupt = false; // 取消锁定则唤醒线程,此时可能container为空时再次进入阻塞 synchronized (container) { container.notify(); } } } /** * 停止线程 ; */ public void setStop() { this.stop = true; container.clearContainer(); interruptCurrentTask(); interrupt(); } /** * 更新状态信息 * @param content * ; */ private void updateStatusInfo(final String content) { Display.getDefault().syncExec(new Runnable() { public void run() { if (content != null && content.length() != 0) { setProcessMessage(tipLabelImage, content, ""); } else { setProcessMessage(null, "", ""); } } }); } /** * 将matches添加到needLoadAltTransList中 * @param matches * ; */ private void refreshAltTransCache(List<AltTransBean> matches) { if (matches.size() == 0) { return; } if (altTransCacheList.size() == 0) { altTransCacheList.addAll(matches); return; } int currIndex = -1; String type = matches.get(0).getMatchProps().get("hs:matchType"); for (int i = 0; i < altTransCacheList.size(); i++) { AltTransBean b = altTransCacheList.get(i); String t = b.getMatchProps().get("hs:matchType"); if (t != null && t.equals(type)) { if (currIndex == -1) { currIndex = i + 1; } altTransCacheList.remove(i); i--; } } if (currIndex > altTransCacheList.size() - 1 || currIndex == -1) { currIndex = altTransCacheList.size(); } altTransCacheList.addAll(currIndex, matches); } private void refreshUI() { Display.getDefault().asyncExec(new Runnable() { public void run() { copyEnable.resetSelection(); gridTable.removeAll(); loadData(altTransCacheList); int itemSize = gridTable.getItemCount(); if (itemSize > 0) { gridTable.setSelection(0); } updateStatusInfo(null); } }); } } /** * (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { gridTable.setFocus(); } private void setMatchMessage(Image image, String message, String tooltip) { infoLabel.setImage(image); infoLabel.setText(message); infoLabel.setToolTipText(tooltip); } private void setProcessMessage(Image image, String message, String tooltip) { if (!tipLabel.isDisposed()) { tipLabel.setImage(image); tipLabel.setText(message); tipLabel.setToolTipText(tooltip); tipLabel.pack(); } } @Override public void dispose() { getSite().getPage().removePostSelectionListener(this); tmMatcher.clearResources(); if (tmImage != null && !tmImage.isDisposed()) { tmImage.dispose(); } if (qtImage != null && !qtImage.isDisposed()) { qtImage.dispose(); } if (bingImage != null && !bingImage.isDisposed()) { bingImage.dispose(); } if (googleImage != null && !googleImage.isDisposed()) { googleImage.dispose(); } if (otherImage != null && !otherImage.isDisposed()) { otherImage.dispose(); } if (selectedBgColor != null && !selectedBgColor.isDisposed()) { selectedBgColor.dispose(); } if (tipLabelImage != null && !tipLabelImage.isDisposed()) { tipLabelImage.dispose(); } JFaceResources.getFontRegistry().removeListener(fontChangeListener); manualTranslationThread.setStop(); manualTranslationThread.interrupt(); if (matcherThread != null) { matcherThread.setStop(); matcherThread.interrupt(); } matcherThread = null; sourceColunmCellRenderer.dispose(); super.dispose(); } public Image getImageByType(String type) { // if (type.equals(TmConstants.MATCH_TYPE_TM)) { // return tmImage; // } if (type.equals(TmConstants.MATCH_TYPE_QT)) { return qtImage; } if (type.equals("Bing")) { return bingImage; } if (type.equals("Google")) { return googleImage; } if (type.equals("others")) { return otherImage; } return null; } class FontPropertyChangeListener implements IPropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { if (gridTable == null || gridTable.isDisposed()) { return; } String property = event.getProperty(); if (net.heartsome.cat.ts.ui.Constants.MATCH_VIEWER_TEXT_FONT.equals(property)) { Font font = JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.MATCH_VIEWER_TEXT_FONT); sourceColunmCellRenderer.setFont(font); targetColumnCellRenderer.setFont(font); GridData sTextGd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); sourceText.getTextWidget().setFont(font); int lineH = sourceText.getTextWidget().getLineHeight() * 2; sTextGd.heightHint = lineH; sTextGd.minimumHeight = lineH; sourceText.getTextWidget().setLayoutData(sTextGd); gridTable.redraw(); sourceText.getTextWidget().getParent().layout(); } } } /** * 创建视图工具栏的按钮。 */ private void createActions() { menuMgr = new MatchViewerBodyMenu(this); gridTable.setMenu(menuMgr.getBodyMenu()); IToolBarManager toolBarManager = getViewSite().getActionBars().getToolBarManager(); toolBarManager.add(menuMgr.editAction); toolBarManager.add(menuMgr.deleteAction); toolBarManager.add(menuMgr.acceptMatchAction); // toolBarManager.add(menuMgr.acceptMatchPureTextAction); menuMgr.updateActionState(); } /** * Sets the enabled state of this View. * @param enabled * ; */ private void updateActionState() { menuMgr.updateActionState(); } private synchronized void loadData(List<AltTransBean> matches) { if (matches == null) { return; } IEditorReference[] editorReferences = getSite().getPage().getEditorReferences(); if (editorReferences.length == 0) { return; } for (AltTransBean altTransBean : matches) { String type = altTransBean.getMatchProps().get("hs:matchType"); if (type == null || type.equals("")) { type = "others"; } String orgin = altTransBean.getMatchOrigin(); if (orgin == null) { // Fixed bug 2258 by Jason 翻译匹配面板不支持非 HS 工具匹配信息的显示 orgin = ""; } String srcContent = altTransBean.getSrcContent(); if (srcContent == null || srcContent.equals("")) { continue; } String tgtContent = altTransBean.getTgtContent(); if (tgtContent == null || tgtContent.equals("")) { continue; } String quality = altTransBean.getMatchProps().get("match-quality").trim(); if (quality == null) { quality = ""; } else { if (!quality.endsWith("%")) { quality += "%"; } } String changeDate = null; String changeid = null; String creationDate = null; String creationid = null; Vector<PropGroupBean> propGroups = altTransBean.getPropGroups(); StringBuffer toolTipBfTemp = new StringBuffer(); if (propGroups != null) { for (PropGroupBean propGroupBean : propGroups) { List<PropBean> propBeans = propGroupBean.getProps(); for (PropBean bean : propBeans) { String ptype = bean.getProptype(); String pVal = bean.getValue(); if (ptype.equals("changeDate")) { if (pVal != null && !pVal.equals("")) { changeDate = DateUtils.formatDateFromUTC(pVal); } } else if (ptype.equals("changeId")) { changeid = pVal; } else if (ptype.equals("creationId")) { creationid = pVal; } else if (ptype.equals("creationDate")) { if (pVal != null && !pVal.equals("")) { creationDate = DateUtils.formatDateFromUTC(pVal); } } else { toolTipBfTemp.append(ptype).append(" : ").append(pVal).append("\n"); } } } } StringBuffer toolTipBf = new StringBuffer(); if (creationid != null && !creationid.equals("")) { toolTipBf.append(Messages.getString("view.MatchViewPart.info.tooltip.creationId")).append(creationid) .append("\n"); } if (creationDate != null && !creationDate.equals("")) { toolTipBf.append(Messages.getString("view.MatchViewPart.info.tooltip.creationDate")) .append(creationDate).append("\n"); } toolTipBf.append(toolTipBfTemp); StringBuffer msgBf = new StringBuffer(); if (changeDate != null && !changeDate.equals("")) { msgBf.append(changeDate); } if (changeid != null && !changeid.equals("")) { if (msgBf.length() != 0) { msgBf.append(" | "); } msgBf.append(changeid); } if (orgin != null && !orgin.equals("")) { if (msgBf.length() != 0) { msgBf.append(" | "); } msgBf.append(orgin); } if (gridTable.isDisposed()) { return; } String toolId = altTransBean.getMatchProps().get("tool-id"); GridItem gridItem = new GridItem(gridTable, SWT.NONE); gridItem.setText(0, srcContent); gridItem.setText(1, quality); gridItem.setText(2, tgtContent); gridItem.setToolTipText(0, toolId); gridItem.setToolTipText(1, toolId); gridItem.setToolTipText(2, toolId); gridItem.setData("info", resetSpecialString(msgBf.toString())); // 保存信息 gridItem.setData("infoTooltip", resetSpecialString(toolTipBf.toString())); gridItem.setData("tgtText", altTransBean.getTgtText()); // 保存目标纯文本 gridItem.setData("tgtContent", tgtContent); // 保存目标纯文本 gridItem.setData("matchType", type); gridItem.setData("quality", quality.substring(0, quality.lastIndexOf('%'))); gridItem.setData("typeImage", getImageByType(type)); gridItem.setData("tmFuzzyInfo", altTransBean.getFuzzyResult()); } } private String resetSpecialString(String input) { input = input.replaceAll("&lt;", "<"); //$NON-NLS-1$ //$NON-NLS-2$ input = input.replaceAll("&gt;", ">"); //$NON-NLS-1$ //$NON-NLS-2$ input = input.replaceAll("&quot;", "\""); input = input.replaceAll("&apos;", "'"); input = input.replaceAll("&amp;", "&"); //$NON-NLS-1$ //$NON-NLS-2$ return input; } private TransUnitInfo2TranslationBean getTuInfoBean(TransUnitBean transUnit, XLFHandler handler, String rowId) { String srcFullText = transUnit.getSrcContent(); String srcPureText = transUnit.getSrcText(); if ("".equals(srcFullText.trim()) || "".equals(srcPureText.trim())) { return null; } sourceColunmCellRenderer.setTuSrcText(srcFullText); String srcLanguage = transUnit.getSrcLang(); String tgtLanguage = transUnit.getTgtLang(); tgtLanguage = handler.getNatTableColumnName().get("target"); Language srcLang = LocaleService.getLanguageConfiger().getLanguageByCode(srcLanguage); Language tgtLang = LocaleService.getLanguageConfiger().getLanguageByCode(tgtLanguage); if (srcLang.isBidi() || tgtLang.isBidi()) { gridTable.setOrientation(SWT.RIGHT_TO_LEFT); } else { gridTable.setOrientation(SWT.LEFT_TO_RIGHT); } TransUnitInfo2TranslationBean tuInfoBean = new TransUnitInfo2TranslationBean(); tuInfoBean.setSrcFullText(srcFullText); tuInfoBean.setSrcPureText(srcPureText); tuInfoBean.setSrcLanguage(srcLanguage); tuInfoBean.setTgtLangugage(tgtLanguage); int contextSize = tmMatcher.getContextSize(); if (contextSize != 0) { Map<String, String> context = handler.getTransUnitContext(rowId, contextSize); tuInfoBean.setPreContext(context.get("x-preContext")); tuInfoBean.setNextContext(context.get("x-nextContext")); } else { tuInfoBean.setPreContext(""); tuInfoBean.setNextContext(""); } return tuInfoBean; } }
44,543
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TmConstants.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/bean/TmConstants.java
/** * Constants.java * * Version information : * * Date:2012-5-2 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.bean; /** * @author jason * @version * @since JDK1.6 */ public class TmConstants { public static String MATCH_TYPE_TM = "TM"; public static String MATCH_TYPE_PT = "PT"; public static String MATCH_TYPE_QT = "QT"; public static String MATCH_TYPE_MT = "MT"; private TmConstants() { } }
958
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Comparator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/comparator/Comparator.java
package net.heartsome.cat.ts.ui.translation.comparator; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.common.bean.ColorConfigBean; import net.heartsome.cat.common.ui.utils.InnerTagUtil; import org.eclipse.compare.rangedifferencer.RangeDifference; import org.eclipse.compare.rangedifferencer.RangeDifferencer; import org.eclipse.jface.text.Position; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Color; public class Comparator { public static List<Position> Compare(String referenceText, String targetText) { List<Position> differencePosition = new ArrayList<Position>(); Position[] tagRanges = InnerTagUtil.getStyledTagRanges(targetText); TokenComparator left = new TokenComparator(InnerTagUtil.getDisplayValueWithoutTags(targetText)); TokenComparator right = new TokenComparator(referenceText); RangeDifference[] e = RangeDifferencer.findRanges(left, right); for (int i = 0; i < e.length; i++) { RangeDifference es = e[i]; int leftStart = es.leftStart(); int leftEnd = es.leftEnd(); int lStart = left.getTokenStart(leftStart); int lEnd = left.getTokenStart(leftEnd); if (es.kind() == RangeDifference.CHANGE) { int start = lStart; int end = lEnd; if (tagRanges.length > 0) { for (Position tagRange : tagRanges) { int tagStart = tagRange.getOffset(); int tagEnd = tagRange.getOffset() + tagRange.getLength(); if (tagStart <= start) { start += tagRange.getLength(); end += tagRange.getLength(); } else if (start < tagStart && tagStart < end) { if (start >= 0 && end - 1 >= 0) { Position position = new Position(start, tagStart - 1); differencePosition.add(position); } start = tagEnd; end += tagRange.getLength(); } else { break; } } } if (start >= 0 && end - 1 >= 0) { Position position = new Position(start, end - 1); differencePosition.add(position); } } } return differencePosition; } /** * 用于比较的参照文本(不含内部标记) * @param referenceText * @param text * ; */ public static void Compare(String referenceText, StyledText text) { ColorConfigBean colorCfgBean = ColorConfigBean.getInstance(); final Color differencefg = colorCfgBean.getSrcDiffFgColor(); final Color differencebg = colorCfgBean.getSrcDiffBgColor(); Position[] tagRanges = InnerTagUtil.getStyledTagRanges(text.getText()); TokenComparator left = new TokenComparator(InnerTagUtil.getDisplayValueWithoutTags(text.getText())); TokenComparator right = new TokenComparator(referenceText); ArrayList<StyleRange> styleRanges = new ArrayList<StyleRange>(); RangeDifference[] e = RangeDifferencer.findRanges(left, right); for (int i = 0; i < e.length; i++) { RangeDifference es = e[i]; int leftStart = es.leftStart(); int leftEnd = es.leftEnd(); int lStart = left.getTokenStart(leftStart); int lEnd = left.getTokenStart(leftEnd); if (es.kind() == RangeDifference.CHANGE) { int start = lStart; int end = lEnd; if (tagRanges.length > 0) { for (Position tagRange : tagRanges) { int tagStart = tagRange.getOffset(); int tagEnd = tagRange.getOffset() + tagRange.getLength(); if (tagStart <= start) { start += tagRange.getLength(); end += tagRange.getLength(); } else if (start < tagStart && tagStart < end) { StyleRange range = new StyleRange(start, tagStart - start, differencefg, differencebg); styleRanges.add(range); start = tagEnd; end += tagRange.getLength(); } else { break; } } } StyleRange range = new StyleRange(start, end - start, differencefg, differencebg); styleRanges.add(range); } } for (int i = 0; i < styleRanges.size(); i++) { text.setStyleRange(styleRanges.get(i)); text.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { differencefg.dispose(); differencebg.dispose(); } }); } } }
4,225
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TokenComparator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/comparator/TokenComparator.java
/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package net.heartsome.cat.ts.ui.translation.comparator; import org.eclipse.compare.rangedifferencer.IRangeComparator; import org.eclipse.core.runtime.Assert; /** * Implements the <code>ITokenComparator</code> interface for words (or tokens) * in a string. * A <code>TokenComparator</code> is used as the input for the <code>RangeDifferencer</code> * engine to perform a token oriented compare on strings. * <p> * This class may be instantiated by clients but is not intended to be subclassed. * @since 3.4 */ public class TokenComparator implements IRangeComparator { private String fText; private int fCount; private int[] fStarts; private int[] fLengths; /** * Creates a <code>TokenComparator</code> for the given string. * * @param text the string that is split into token */ public TokenComparator(String text) { Assert.isNotNull(text); fText= text; int length= fText.length(); fStarts= new int[length]; // pessimistic assumption! fLengths= new int[length]; fCount= 0; char lastCategory= 0; // 0: no category for (int i= 0; i < length; i++) { char c= fText.charAt(i); char category= '?'; // unspecified category if (Character.isWhitespace(c)) category= ' '; // white space category else if (Character.isDigit(c)) category= '0'; // digits else if (Character.isLetter(c)) category= 'a'; // letters else if (c == '\"' || c == '\'') category= '\"'; // quotes (see bug 198671) if (category != lastCategory) { // start a new token fStarts[fCount++]= i; lastCategory= category; } fLengths[fCount-1]++; } } /* (non-Javadoc) * @see org.eclipse.compare.rangedifferencer.IRangeComparator#getRangeCount() */ public int getRangeCount() { return fCount; } /* (non-Javadoc) * @see org.eclipse.compare.contentmergeviewer.ITokenComparator#getTokenStart(int) */ public int getTokenStart(int index) { if (index < fCount) return fStarts[index]; return fText.length(); } /* (non-Javadoc) * @see org.eclipse.compare.contentmergeviewer.ITokenComparator#getTokenLength(int) */ public int getTokenLength(int index) { if (index < fCount) return fLengths[index]; return 0; } /* (non-Javadoc) * @see org.eclipse.compare.rangedifferencer.IRangeComparator#rangesEqual(int, org.eclipse.compare.rangedifferencer.IRangeComparator, int) */ public boolean rangesEqual(int thisIndex, IRangeComparator other, int otherIndex) { if (other != null && getClass() == other.getClass()) { TokenComparator tc= (TokenComparator) other; int thisLen= getTokenLength(thisIndex); int otherLen= tc.getTokenLength(otherIndex); if (thisLen == otherLen) return fText.regionMatches(false, getTokenStart(thisIndex), tc.fText, tc.getTokenStart(otherIndex), thisLen); } return false; } /* (non-Javadoc) * @see org.eclipse.compare.rangedifferencer.IRangeComparator#skipRangeComparison(int, int, org.eclipse.compare.rangedifferencer.IRangeComparator) */ public boolean skipRangeComparison(int length, int max, IRangeComparator other) { if (getRangeCount() < 50 || other.getRangeCount() < 50) return false; if (max < 100) return false; if (length < 100) return false; if (max > 800) return true; if (length < max / 4) return false; return true; } }
3,864
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TextDiffMatcher.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/comparator/TextDiffMatcher.java
/* * Diff Match and Patch * * Copyright 2006 Google Inc. * http://code.google.com/p/google-diff-match-patch/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.heartsome.cat.ts.ui.translation.comparator; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * Functions for diff, match and patch. * Computes the difference between two texts to create a patch. * Applies the patch onto another text, allowing for errors. * * @author [email protected] (Neil Fraser) */ /** * Class containing the diff, match and patch methods. * Also contains the behaviour settings. */ public class TextDiffMatcher { // Defaults. // Set these on your diff_match_patch instance to override the defaults. /** * Number of seconds to map a diff before giving up (0 for infinity). */ public float Diff_Timeout = 1.0f; /** * Cost of an empty edit operation in terms of edit characters. */ public short Diff_EditCost = 4; /** * At what point is no match declared (0.0 = perfection, 1.0 = very loose). */ public float Match_Threshold = 0.5f; /** * How far to search for a match (0 = exact location, 1000+ = broad match). * A match this many characters away from the expected location will add * 1.0 to the score (0.0 is a perfect match). */ public int Match_Distance = 1000; /** * When deleting a large block of text (over ~64 characters), how close do * the contents have to be to match the expected contents. (0.0 = perfection, * 1.0 = very loose). Note that Match_Threshold controls how closely the * end points of a delete need to match. */ public float Patch_DeleteThreshold = 0.5f; /** * Chunk size for context length. */ public short Patch_Margin = 4; /** * The number of bits in an int. */ private short Match_MaxBits = 32; /** * Internal class for returning results from diff_linesToChars(). * Other less paranoid languages just use a three-element array. */ protected static class LinesToCharsResult { protected String chars1; protected String chars2; protected List<String> lineArray; protected LinesToCharsResult(String chars1, String chars2, List<String> lineArray) { this.chars1 = chars1; this.chars2 = chars2; this.lineArray = lineArray; } } // DIFF FUNCTIONS /** * The data structure representing a diff is a Linked list of Diff objects: * {Diff(Operation.DELETE, "Hello"), Diff(Operation.INSERT, "Goodbye"), * Diff(Operation.EQUAL, " world.")} * which means: delete "Hello", add "Goodbye" and keep " world." */ public enum Operation { DELETE, INSERT, EQUAL } /** * Find the differences between two texts. * Run a faster, slightly less optimal diff. * This method allows the 'checklines' of diff_main() to be optional. * Most of the time checklines is wanted, so default to true. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @return Linked List of Diff objects. */ public LinkedList<Diff> diff_main(String text1, String text2) { return diff_main(text1, text2, true); } /** * Find the differences between two texts. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param checklines Speedup flag. If false, then don't run a * line-level diff first to identify the changed areas. * If true, then run a faster slightly less optimal diff. * @return Linked List of Diff objects. */ public LinkedList<Diff> diff_main(String text1, String text2, boolean checklines) { // Set a deadline by which time the diff must be complete. long deadline; if (Diff_Timeout <= 0) { deadline = Long.MAX_VALUE; } else { deadline = System.currentTimeMillis() + (long) (Diff_Timeout * 1000); } return diff_main(text1, text2, checklines, deadline); } /** * Find the differences between two texts. Simplifies the problem by * stripping any common prefix or suffix off the texts before diffing. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param checklines Speedup flag. If false, then don't run a * line-level diff first to identify the changed areas. * If true, then run a faster slightly less optimal diff. * @param deadline Time when the diff should be complete by. Used * internally for recursive calls. Users should set DiffTimeout instead. * @return Linked List of Diff objects. */ private LinkedList<Diff> diff_main(String text1, String text2, boolean checklines, long deadline) { // Check for null inputs. if (text1 == null || text2 == null) { throw new IllegalArgumentException("Null inputs. (diff_main)"); } // Check for equality (speedup). LinkedList<Diff> diffs; if (text1.equals(text2)) { diffs = new LinkedList<Diff>(); if (text1.length() != 0) { diffs.add(new Diff(Operation.EQUAL, text1)); } return diffs; } // Trim off common prefix (speedup). int commonlength = diff_commonPrefix(text1, text2); String commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); // Trim off common suffix (speedup). commonlength = diff_commonSuffix(text1, text2); String commonsuffix = text1.substring(text1.length() - commonlength); text1 = text1.substring(0, text1.length() - commonlength); text2 = text2.substring(0, text2.length() - commonlength); // Compute the diff on the middle block. diffs = diff_compute(text1, text2, checklines, deadline); // Restore the prefix and suffix. if (commonprefix.length() != 0) { diffs.addFirst(new Diff(Operation.EQUAL, commonprefix)); } if (commonsuffix.length() != 0) { diffs.addLast(new Diff(Operation.EQUAL, commonsuffix)); } diff_cleanupMerge(diffs); return diffs; } /** * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param checklines Speedup flag. If false, then don't run a * line-level diff first to identify the changed areas. * If true, then run a faster slightly less optimal diff. * @param deadline Time when the diff should be complete by. * @return Linked List of Diff objects. */ private LinkedList<Diff> diff_compute(String text1, String text2, boolean checklines, long deadline) { LinkedList<Diff> diffs = new LinkedList<Diff>(); if (text1.length() == 0) { // Just add some text (speedup). diffs.add(new Diff(Operation.INSERT, text2)); return diffs; } if (text2.length() == 0) { // Just delete some text (speedup). diffs.add(new Diff(Operation.DELETE, text1)); return diffs; } String longtext = text1.length() > text2.length() ? text1 : text2; String shorttext = text1.length() > text2.length() ? text2 : text1; int i = longtext.indexOf(shorttext); if (i != -1) { // Shorter text is inside the longer text (speedup). Operation op = (text1.length() > text2.length()) ? Operation.DELETE : Operation.INSERT; diffs.add(new Diff(op, longtext.substring(0, i))); diffs.add(new Diff(Operation.EQUAL, shorttext)); diffs.add(new Diff(op, longtext.substring(i + shorttext.length()))); return diffs; } if (shorttext.length() == 1) { // Single character string. // After the previous speedup, the character can't be an equality. diffs.add(new Diff(Operation.DELETE, text1)); diffs.add(new Diff(Operation.INSERT, text2)); return diffs; } // Check to see if the problem can be split in two. String[] hm = diff_halfMatch(text1, text2); if (hm != null) { // A half-match was found, sort out the return data. String text1_a = hm[0]; String text1_b = hm[1]; String text2_a = hm[2]; String text2_b = hm[3]; String mid_common = hm[4]; // Send both pairs off for separate processing. LinkedList<Diff> diffs_a = diff_main(text1_a, text2_a, checklines, deadline); LinkedList<Diff> diffs_b = diff_main(text1_b, text2_b, checklines, deadline); // Merge the results. diffs = diffs_a; diffs.add(new Diff(Operation.EQUAL, mid_common)); diffs.addAll(diffs_b); return diffs; } if (checklines && text1.length() > 100 && text2.length() > 100) { return diff_lineMode(text1, text2, deadline); } return diff_bisect(text1, text2, deadline); } /** * Do a quick line-level diff on both strings, then rediff the parts for * greater accuracy. * This speedup can produce non-minimal diffs. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param deadline Time when the diff should be complete by. * @return Linked List of Diff objects. */ private LinkedList<Diff> diff_lineMode(String text1, String text2, long deadline) { // Scan the text on a line-by-line basis first. LinesToCharsResult b = diff_linesToChars(text1, text2); text1 = b.chars1; text2 = b.chars2; List<String> linearray = b.lineArray; LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline); // Convert the diff back to original text. diff_charsToLines(diffs, linearray); // Eliminate freak matches (e.g. blank lines) diff_cleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. diffs.add(new Diff(Operation.EQUAL, "")); int count_delete = 0; int count_insert = 0; String text_delete = ""; String text_insert = ""; ListIterator<Diff> pointer = diffs.listIterator(); Diff thisDiff = pointer.next(); while (thisDiff != null) { switch (thisDiff.operation) { case INSERT: count_insert++; text_insert += thisDiff.text; break; case DELETE: count_delete++; text_delete += thisDiff.text; break; case EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete >= 1 && count_insert >= 1) { // Delete the offending records and add the merged ones. pointer.previous(); for (int j = 0; j < count_delete + count_insert; j++) { pointer.previous(); pointer.remove(); } for (Diff newDiff : diff_main(text_delete, text_insert, false, deadline)) { pointer.add(newDiff); } } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } thisDiff = pointer.hasNext() ? pointer.next() : null; } diffs.removeLast(); // Remove the dummy entry at the end. return diffs; } /** * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param deadline Time at which to bail if not yet complete. * @return LinkedList of Diff objects. */ protected LinkedList<Diff> diff_bisect(String text1, String text2, long deadline) { // Cache the text lengths to prevent multiple calls. int text1_length = text1.length(); int text2_length = text2.length(); int max_d = (text1_length + text2_length + 1) / 2; int v_offset = max_d; int v_length = 2 * max_d; int[] v1 = new int[v_length]; int[] v2 = new int[v_length]; for (int x = 0; x < v_length; x++) { v1[x] = -1; v2[x] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; int delta = text1_length - text2_length; // If the total number of characters is odd, then the front path will // collide with the reverse path. boolean front = (delta % 2 != 0); // Offsets for start and end of k loop. // Prevents mapping of space beyond the grid. int k1start = 0; int k1end = 0; int k2start = 0; int k2end = 0; for (int d = 0; d < max_d; d++) { // Bail out if deadline is reached. if (System.currentTimeMillis() > deadline) { break; } // Walk the front path one step. for (int k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { int k1_offset = v_offset + k1; int x1; if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } int y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) == text2.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { // Ran off the right of the graph. k1end += 2; } else if (y1 > text2_length) { // Ran off the bottom of the graph. k1start += 2; } else if (front) { int k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { // Mirror x2 onto top-left coordinate system. int x2 = text1_length - v2[k2_offset]; if (x1 >= x2) { // Overlap detected. return diff_bisectSplit(text1, text2, x1, y1, deadline); } } } } // Walk the reverse path one step. for (int k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { int k2_offset = v_offset + k2; int x2; if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { x2 = v2[k2_offset + 1]; } else { x2 = v2[k2_offset - 1] + 1; } int y2 = x2 - k2; while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) == text2.charAt(text2_length - y2 - 1)) { x2++; y2++; } v2[k2_offset] = x2; if (x2 > text1_length) { // Ran off the left of the graph. k2end += 2; } else if (y2 > text2_length) { // Ran off the top of the graph. k2start += 2; } else if (!front) { int k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { int x1 = v1[k1_offset]; int y1 = v_offset + x1 - k1_offset; // Mirror x2 onto top-left coordinate system. x2 = text1_length - x2; if (x1 >= x2) { // Overlap detected. return diff_bisectSplit(text1, text2, x1, y1, deadline); } } } } } // Diff took too long and hit the deadline or // number of diffs equals number of characters, no commonality at all. LinkedList<Diff> diffs = new LinkedList<Diff>(); diffs.add(new Diff(Operation.DELETE, text1)); diffs.add(new Diff(Operation.INSERT, text2)); return diffs; } /** * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param x Index of split point in text1. * @param y Index of split point in text2. * @param deadline Time at which to bail if not yet complete. * @return LinkedList of Diff objects. */ private LinkedList<Diff> diff_bisectSplit(String text1, String text2, int x, int y, long deadline) { String text1a = text1.substring(0, x); String text2a = text2.substring(0, y); String text1b = text1.substring(x); String text2b = text2.substring(y); // Compute both diffs serially. LinkedList<Diff> diffs = diff_main(text1a, text2a, false, deadline); LinkedList<Diff> diffsb = diff_main(text1b, text2b, false, deadline); diffs.addAll(diffsb); return diffs; } /** * Split two texts into a list of strings. Reduce the texts to a string of * hashes where each Unicode character represents one line. * @param text1 First string. * @param text2 Second string. * @return An object containing the encoded text1, the encoded text2 and * the List of unique strings. The zeroth element of the List of * unique strings is intentionally blank. */ protected LinesToCharsResult diff_linesToChars(String text1, String text2) { List<String> lineArray = new ArrayList<String>(); Map<String, Integer> lineHash = new HashMap<String, Integer>(); // e.g. linearray[4] == "Hello\n" // e.g. linehash.get("Hello\n") == 4 // "\x00" is a valid character, but various debuggers don't like it. // So we'll insert a junk entry to avoid generating a null character. lineArray.add(""); String chars1 = diff_linesToCharsMunge(text1, lineArray, lineHash); String chars2 = diff_linesToCharsMunge(text2, lineArray, lineHash); return new LinesToCharsResult(chars1, chars2, lineArray); } /** * Split a text into a list of strings. Reduce the texts to a string of * hashes where each Unicode character represents one line. * @param text String to encode. * @param lineArray List of unique strings. * @param lineHash Map of strings to indices. * @return Encoded string. */ private String diff_linesToCharsMunge(String text, List<String> lineArray, Map<String, Integer> lineHash) { int lineStart = 0; int lineEnd = -1; String line; StringBuilder chars = new StringBuilder(); // Walk the text, pulling out a substring for each line. // text.split('\n') would would temporarily double our memory footprint. // Modifying text would create many large strings to garbage collect. while (lineEnd < text.length() - 1) { lineEnd = text.indexOf('\n', lineStart); if (lineEnd == -1) { lineEnd = text.length() - 1; } line = text.substring(lineStart, lineEnd + 1); lineStart = lineEnd + 1; if (lineHash.containsKey(line)) { chars.append(String.valueOf((char) (int) lineHash.get(line))); } else { lineArray.add(line); lineHash.put(line, lineArray.size() - 1); chars.append(String.valueOf((char) (lineArray.size() - 1))); } } return chars.toString(); } /** * Rehydrate the text in a diff from a string of line hashes to real lines of * text. * @param diffs LinkedList of Diff objects. * @param lineArray List of unique strings. */ protected void diff_charsToLines(LinkedList<Diff> diffs, List<String> lineArray) { StringBuilder text; for (Diff diff : diffs) { text = new StringBuilder(); for (int y = 0; y < diff.text.length(); y++) { text.append(lineArray.get(diff.text.charAt(y))); } diff.text = text.toString(); } } /** * Determine the common prefix of two strings * @param text1 First string. * @param text2 Second string. * @return The number of characters common to the start of each string. */ public int diff_commonPrefix(String text1, String text2) { // Performance analysis: http://neil.fraser.name/news/2007/10/09/ int n = Math.min(text1.length(), text2.length()); for (int i = 0; i < n; i++) { if (text1.charAt(i) != text2.charAt(i)) { return i; } } return n; } /** * Determine the common suffix of two strings * @param text1 First string. * @param text2 Second string. * @return The number of characters common to the end of each string. */ public int diff_commonSuffix(String text1, String text2) { // Performance analysis: http://neil.fraser.name/news/2007/10/09/ int text1_length = text1.length(); int text2_length = text2.length(); int n = Math.min(text1_length, text2_length); for (int i = 1; i <= n; i++) { if (text1.charAt(text1_length - i) != text2.charAt(text2_length - i)) { return i - 1; } } return n; } /** * Determine if the suffix of one string is the prefix of another. * @param text1 First string. * @param text2 Second string. * @return The number of characters common to the end of the first * string and the start of the second string. */ protected int diff_commonOverlap(String text1, String text2) { // Cache the text lengths to prevent multiple calls. int text1_length = text1.length(); int text2_length = text2.length(); // Eliminate the null case. if (text1_length == 0 || text2_length == 0) { return 0; } // Truncate the longer string. if (text1_length > text2_length) { text1 = text1.substring(text1_length - text2_length); } else if (text1_length < text2_length) { text2 = text2.substring(0, text1_length); } int text_length = Math.min(text1_length, text2_length); // Quick check for the worst case. if (text1.equals(text2)) { return text_length; } // Start by looking for a single character match // and increase length until no match is found. // Performance analysis: http://neil.fraser.name/news/2010/11/04/ int best = 0; int length = 1; while (true) { String pattern = text1.substring(text_length - length); int found = text2.indexOf(pattern); if (found == -1) { return best; } length += found; if (found == 0 || text1.substring(text_length - length).equals( text2.substring(0, length))) { best = length; length++; } } } /** * Do the two texts share a substring which is at least half the length of * the longer text? * This speedup can produce non-minimal diffs. * @param text1 First string. * @param text2 Second string. * @return Five element String array, containing the prefix of text1, the * suffix of text1, the prefix of text2, the suffix of text2 and the * common middle. Or null if there was no match. */ protected String[] diff_halfMatch(String text1, String text2) { if (Diff_Timeout <= 0) { // Don't risk returning a non-optimal diff if we have unlimited time. return null; } String longtext = text1.length() > text2.length() ? text1 : text2; String shorttext = text1.length() > text2.length() ? text2 : text1; if (longtext.length() < 4 || shorttext.length() * 2 < longtext.length()) { return null; // Pointless. } // First check if the second quarter is the seed for a half-match. String[] hm1 = diff_halfMatchI(longtext, shorttext, (longtext.length() + 3) / 4); // Check again based on the third quarter. String[] hm2 = diff_halfMatchI(longtext, shorttext, (longtext.length() + 1) / 2); String[] hm; if (hm1 == null && hm2 == null) { return null; } else if (hm2 == null) { hm = hm1; } else if (hm1 == null) { hm = hm2; } else { // Both matched. Select the longest. hm = hm1[4].length() > hm2[4].length() ? hm1 : hm2; } // A half-match was found, sort out the return data. if (text1.length() > text2.length()) { return hm; //return new String[]{hm[0], hm[1], hm[2], hm[3], hm[4]}; } else { return new String[]{hm[2], hm[3], hm[0], hm[1], hm[4]}; } } /** * Does a substring of shorttext exist within longtext such that the * substring is at least half the length of longtext? * @param longtext Longer string. * @param shorttext Shorter string. * @param i Start index of quarter length substring within longtext. * @return Five element String array, containing the prefix of longtext, the * suffix of longtext, the prefix of shorttext, the suffix of shorttext * and the common middle. Or null if there was no match. */ private String[] diff_halfMatchI(String longtext, String shorttext, int i) { // Start with a 1/4 length substring at position i as a seed. String seed = longtext.substring(i, i + longtext.length() / 4); int j = -1; String best_common = ""; String best_longtext_a = "", best_longtext_b = ""; String best_shorttext_a = "", best_shorttext_b = ""; while ((j = shorttext.indexOf(seed, j + 1)) != -1) { int prefixLength = diff_commonPrefix(longtext.substring(i), shorttext.substring(j)); int suffixLength = diff_commonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); if (best_common.length() < suffixLength + prefixLength) { best_common = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); best_longtext_a = longtext.substring(0, i - suffixLength); best_longtext_b = longtext.substring(i + prefixLength); best_shorttext_a = shorttext.substring(0, j - suffixLength); best_shorttext_b = shorttext.substring(j + prefixLength); } } if (best_common.length() * 2 >= longtext.length()) { return new String[]{best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common}; } else { return null; } } /** * Reduce the number of edits by eliminating semantically trivial equalities. * @param diffs LinkedList of Diff objects. */ public void diff_cleanupSemantic(LinkedList<Diff> diffs) { if (diffs.isEmpty()) { return; } boolean changes = false; Stack<Diff> equalities = new Stack<Diff>(); // Stack of qualities. String lastequality = null; // Always equal to equalities.lastElement().text ListIterator<Diff> pointer = diffs.listIterator(); // Number of characters that changed prior to the equality. int length_insertions1 = 0; int length_deletions1 = 0; // Number of characters that changed after the equality. int length_insertions2 = 0; int length_deletions2 = 0; Diff thisDiff = pointer.next(); while (thisDiff != null) { if (thisDiff.operation == Operation.EQUAL) { // Equality found. equalities.push(thisDiff); length_insertions1 = length_insertions2; length_deletions1 = length_deletions2; length_insertions2 = 0; length_deletions2 = 0; lastequality = thisDiff.text; } else { // An insertion or deletion. if (thisDiff.operation == Operation.INSERT) { length_insertions2 += thisDiff.text.length(); } else { length_deletions2 += thisDiff.text.length(); } // Eliminate an equality that is smaller or equal to the edits on both // sides of it. if (lastequality != null && (lastequality.length() <= Math.max(length_insertions1, length_deletions1)) && (lastequality.length() <= Math.max(length_insertions2, length_deletions2))) { //System.out.println("Splitting: '" + lastequality + "'"); // Walk back to offending equality. while (thisDiff != equalities.lastElement()) { thisDiff = pointer.previous(); } pointer.next(); // Replace equality with a delete. pointer.set(new Diff(Operation.DELETE, lastequality)); // Insert a corresponding an insert. pointer.add(new Diff(Operation.INSERT, lastequality)); equalities.pop(); // Throw away the equality we just deleted. if (!equalities.empty()) { // Throw away the previous equality (it needs to be reevaluated). equalities.pop(); } if (equalities.empty()) { // There are no previous equalities, walk back to the start. while (pointer.hasPrevious()) { pointer.previous(); } } else { // There is a safe equality we can fall back to. thisDiff = equalities.lastElement(); while (thisDiff != pointer.previous()) { // Intentionally empty loop. } } length_insertions1 = 0; // Reset the counters. length_insertions2 = 0; length_deletions1 = 0; length_deletions2 = 0; lastequality = null; changes = true; } } thisDiff = pointer.hasNext() ? pointer.next() : null; } // Normalize the diff. if (changes) { diff_cleanupMerge(diffs); } diff_cleanupSemanticLossless(diffs); // Find any overlaps between deletions and insertions. // e.g: <del>abcxxx</del><ins>xxxdef</ins> // -> <del>abc</del>xxx<ins>def</ins> // e.g: <del>xxxabc</del><ins>defxxx</ins> // -> <ins>def</ins>xxx<del>abc</del> // Only extract an overlap if it is as big as the edit ahead or behind it. pointer = diffs.listIterator(); Diff prevDiff = null; thisDiff = null; if (pointer.hasNext()) { prevDiff = pointer.next(); if (pointer.hasNext()) { thisDiff = pointer.next(); } } while (thisDiff != null) { if (prevDiff.operation == Operation.DELETE && thisDiff.operation == Operation.INSERT) { String deletion = prevDiff.text; String insertion = thisDiff.text; int overlap_length1 = this.diff_commonOverlap(deletion, insertion); int overlap_length2 = this.diff_commonOverlap(insertion, deletion); if (overlap_length1 >= overlap_length2) { if (overlap_length1 >= deletion.length() / 2.0 || overlap_length1 >= insertion.length() / 2.0) { // Overlap found. Insert an equality and trim the surrounding edits. pointer.previous(); pointer.add(new Diff(Operation.EQUAL, insertion.substring(0, overlap_length1))); prevDiff.text = deletion.substring(0, deletion.length() - overlap_length1); thisDiff.text = insertion.substring(overlap_length1); // pointer.add inserts the element before the cursor, so there is // no need to step past the new element. } } else { if (overlap_length2 >= deletion.length() / 2.0 || overlap_length2 >= insertion.length() / 2.0) { // Reverse overlap found. // Insert an equality and swap and trim the surrounding edits. pointer.previous(); pointer.add(new Diff(Operation.EQUAL, deletion.substring(0, overlap_length2))); prevDiff.operation = Operation.INSERT; prevDiff.text = insertion.substring(0, insertion.length() - overlap_length2); thisDiff.operation = Operation.DELETE; thisDiff.text = deletion.substring(overlap_length2); // pointer.add inserts the element before the cursor, so there is // no need to step past the new element. } } thisDiff = pointer.hasNext() ? pointer.next() : null; } prevDiff = thisDiff; thisDiff = pointer.hasNext() ? pointer.next() : null; } } /** * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. * @param diffs LinkedList of Diff objects. */ public void diff_cleanupSemanticLossless(LinkedList<Diff> diffs) { String equality1, edit, equality2; String commonString; int commonOffset; int score, bestScore; String bestEquality1, bestEdit, bestEquality2; // Create a new iterator at the start. ListIterator<Diff> pointer = diffs.listIterator(); Diff prevDiff = pointer.hasNext() ? pointer.next() : null; Diff thisDiff = pointer.hasNext() ? pointer.next() : null; Diff nextDiff = pointer.hasNext() ? pointer.next() : null; // Intentionally ignore the first and last element (don't need checking). while (nextDiff != null) { if (prevDiff.operation == Operation.EQUAL && nextDiff.operation == Operation.EQUAL) { // This is a single edit surrounded by equalities. equality1 = prevDiff.text; edit = thisDiff.text; equality2 = nextDiff.text; // First, shift the edit as far left as possible. commonOffset = diff_commonSuffix(equality1, edit); if (commonOffset != 0) { commonString = edit.substring(edit.length() - commonOffset); equality1 = equality1.substring(0, equality1.length() - commonOffset); edit = commonString + edit.substring(0, edit.length() - commonOffset); equality2 = commonString + equality2; } // Second, step character by character right, looking for the best fit. bestEquality1 = equality1; bestEdit = edit; bestEquality2 = equality2; bestScore = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2); while (edit.length() != 0 && equality2.length() != 0 && edit.charAt(0) == equality2.charAt(0)) { equality1 += edit.charAt(0); edit = edit.substring(1) + equality2.charAt(0); equality2 = equality2.substring(1); score = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2); // The >= encourages trailing rather than leading whitespace on edits. if (score >= bestScore) { bestScore = score; bestEquality1 = equality1; bestEdit = edit; bestEquality2 = equality2; } } if (!prevDiff.text.equals(bestEquality1)) { // We have an improvement, save it back to the diff. if (bestEquality1.length() != 0) { prevDiff.text = bestEquality1; } else { pointer.previous(); // Walk past nextDiff. pointer.previous(); // Walk past thisDiff. pointer.previous(); // Walk past prevDiff. pointer.remove(); // Delete prevDiff. pointer.next(); // Walk past thisDiff. pointer.next(); // Walk past nextDiff. } thisDiff.text = bestEdit; if (bestEquality2.length() != 0) { nextDiff.text = bestEquality2; } else { pointer.remove(); // Delete nextDiff. nextDiff = thisDiff; thisDiff = prevDiff; } } } prevDiff = thisDiff; thisDiff = nextDiff; nextDiff = pointer.hasNext() ? pointer.next() : null; } } /** * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * @param one First string. * @param two Second string. * @return The score. */ private int diff_cleanupSemanticScore(String one, String two) { if (one.length() == 0 || two.length() == 0) { // Edges are the best. return 6; } // Each port of this function behaves slightly differently due to // subtle differences in each language's definition of things like // 'whitespace'. Since this function's purpose is largely cosmetic, // the choice has been made to use each language's native features // rather than force total conformity. char char1 = one.charAt(one.length() - 1); char char2 = two.charAt(0); boolean nonAlphaNumeric1 = !Character.isLetterOrDigit(char1); boolean nonAlphaNumeric2 = !Character.isLetterOrDigit(char2); boolean whitespace1 = nonAlphaNumeric1 && Character.isWhitespace(char1); boolean whitespace2 = nonAlphaNumeric2 && Character.isWhitespace(char2); boolean lineBreak1 = whitespace1 && Character.getType(char1) == Character.CONTROL; boolean lineBreak2 = whitespace2 && Character.getType(char2) == Character.CONTROL; boolean blankLine1 = lineBreak1 && BLANKLINEEND.matcher(one).find(); boolean blankLine2 = lineBreak2 && BLANKLINESTART.matcher(two).find(); if (blankLine1 || blankLine2) { // Five points for blank lines. return 5; } else if (lineBreak1 || lineBreak2) { // Four points for line breaks. return 4; } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { // Three points for end of sentences. return 3; } else if (whitespace1 || whitespace2) { // Two points for whitespace. return 2; } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { // One point for non-alphanumeric. return 1; } return 0; } // Define some regex patterns for matching boundaries. private Pattern BLANKLINEEND = Pattern.compile("\\n\\r?\\n\\Z", Pattern.DOTALL); private Pattern BLANKLINESTART = Pattern.compile("\\A\\r?\\n\\r?\\n", Pattern.DOTALL); /** * Reduce the number of edits by eliminating operationally trivial equalities. * @param diffs LinkedList of Diff objects. */ public void diff_cleanupEfficiency(LinkedList<Diff> diffs) { if (diffs.isEmpty()) { return; } boolean changes = false; Stack<Diff> equalities = new Stack<Diff>(); // Stack of equalities. String lastequality = null; // Always equal to equalities.lastElement().text ListIterator<Diff> pointer = diffs.listIterator(); // Is there an insertion operation before the last equality. boolean pre_ins = false; // Is there a deletion operation before the last equality. boolean pre_del = false; // Is there an insertion operation after the last equality. boolean post_ins = false; // Is there a deletion operation after the last equality. boolean post_del = false; Diff thisDiff = pointer.next(); Diff safeDiff = thisDiff; // The last Diff that is known to be unsplitable. while (thisDiff != null) { if (thisDiff.operation == Operation.EQUAL) { // Equality found. if (thisDiff.text.length() < Diff_EditCost && (post_ins || post_del)) { // Candidate found. equalities.push(thisDiff); pre_ins = post_ins; pre_del = post_del; lastequality = thisDiff.text; } else { // Not a candidate, and can never become one. equalities.clear(); lastequality = null; safeDiff = thisDiff; } post_ins = post_del = false; } else { // An insertion or deletion. if (thisDiff.operation == Operation.DELETE) { post_del = true; } else { post_ins = true; } /* * Five types to be split: * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> * <ins>A</ins>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<ins>C</ins> * <ins>A</del>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<del>C</del> */ if (lastequality != null && ((pre_ins && pre_del && post_ins && post_del) || ((lastequality.length() < Diff_EditCost / 2) && ((pre_ins ? 1 : 0) + (pre_del ? 1 : 0) + (post_ins ? 1 : 0) + (post_del ? 1 : 0)) == 3))) { //System.out.println("Splitting: '" + lastequality + "'"); // Walk back to offending equality. while (thisDiff != equalities.lastElement()) { thisDiff = pointer.previous(); } pointer.next(); // Replace equality with a delete. pointer.set(new Diff(Operation.DELETE, lastequality)); // Insert a corresponding an insert. pointer.add(thisDiff = new Diff(Operation.INSERT, lastequality)); equalities.pop(); // Throw away the equality we just deleted. lastequality = null; if (pre_ins && pre_del) { // No changes made which could affect previous entry, keep going. post_ins = post_del = true; equalities.clear(); safeDiff = thisDiff; } else { if (!equalities.empty()) { // Throw away the previous equality (it needs to be reevaluated). equalities.pop(); } if (equalities.empty()) { // There are no previous questionable equalities, // walk back to the last known safe diff. thisDiff = safeDiff; } else { // There is an equality we can fall back to. thisDiff = equalities.lastElement(); } while (thisDiff != pointer.previous()) { // Intentionally empty loop. } post_ins = post_del = false; } changes = true; } } thisDiff = pointer.hasNext() ? pointer.next() : null; } if (changes) { diff_cleanupMerge(diffs); } } /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param diffs LinkedList of Diff objects. */ public void diff_cleanupMerge(LinkedList<Diff> diffs) { diffs.add(new Diff(Operation.EQUAL, "")); // Add a dummy entry at the end. ListIterator<Diff> pointer = diffs.listIterator(); int count_delete = 0; int count_insert = 0; String text_delete = ""; String text_insert = ""; Diff thisDiff = pointer.next(); Diff prevEqual = null; int commonlength; while (thisDiff != null) { switch (thisDiff.operation) { case INSERT: count_insert++; text_insert += thisDiff.text; prevEqual = null; break; case DELETE: count_delete++; text_delete += thisDiff.text; prevEqual = null; break; case EQUAL: if (count_delete + count_insert > 1) { boolean both_types = count_delete != 0 && count_insert != 0; // Delete the offending records. pointer.previous(); // Reverse direction. while (count_delete-- > 0) { pointer.previous(); pointer.remove(); } while (count_insert-- > 0) { pointer.previous(); pointer.remove(); } if (both_types) { // Factor out any common prefixies. commonlength = diff_commonPrefix(text_insert, text_delete); if (commonlength != 0) { if (pointer.hasPrevious()) { thisDiff = pointer.previous(); assert thisDiff.operation == Operation.EQUAL : "Previous diff should have been an equality."; thisDiff.text += text_insert.substring(0, commonlength); pointer.next(); } else { pointer.add(new Diff(Operation.EQUAL, text_insert.substring(0, commonlength))); } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } // Factor out any common suffixies. commonlength = diff_commonSuffix(text_insert, text_delete); if (commonlength != 0) { thisDiff = pointer.next(); thisDiff.text = text_insert.substring(text_insert.length() - commonlength) + thisDiff.text; text_insert = text_insert.substring(0, text_insert.length() - commonlength); text_delete = text_delete.substring(0, text_delete.length() - commonlength); pointer.previous(); } } // Insert the merged records. if (text_delete.length() != 0) { pointer.add(new Diff(Operation.DELETE, text_delete)); } if (text_insert.length() != 0) { pointer.add(new Diff(Operation.INSERT, text_insert)); } // Step forward to the equality. thisDiff = pointer.hasNext() ? pointer.next() : null; } else if (prevEqual != null) { // Merge this equality with the previous one. prevEqual.text += thisDiff.text; pointer.remove(); thisDiff = pointer.previous(); pointer.next(); // Forward direction } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; prevEqual = thisDiff; break; } thisDiff = pointer.hasNext() ? pointer.next() : null; } if (diffs.getLast().text.length() == 0) { diffs.removeLast(); // Remove the dummy entry at the end. } /* * Second pass: look for single edits surrounded on both sides by equalities * which can be shifted sideways to eliminate an equality. * e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC */ boolean changes = false; // Create a new iterator at the start. // (As opposed to walking the current one back.) pointer = diffs.listIterator(); Diff prevDiff = pointer.hasNext() ? pointer.next() : null; thisDiff = pointer.hasNext() ? pointer.next() : null; Diff nextDiff = pointer.hasNext() ? pointer.next() : null; // Intentionally ignore the first and last element (don't need checking). while (nextDiff != null) { if (prevDiff.operation == Operation.EQUAL && nextDiff.operation == Operation.EQUAL) { // This is a single edit surrounded by equalities. if (thisDiff.text.endsWith(prevDiff.text)) { // Shift the edit over the previous equality. thisDiff.text = prevDiff.text + thisDiff.text.substring(0, thisDiff.text.length() - prevDiff.text.length()); nextDiff.text = prevDiff.text + nextDiff.text; pointer.previous(); // Walk past nextDiff. pointer.previous(); // Walk past thisDiff. pointer.previous(); // Walk past prevDiff. pointer.remove(); // Delete prevDiff. pointer.next(); // Walk past thisDiff. thisDiff = pointer.next(); // Walk past nextDiff. nextDiff = pointer.hasNext() ? pointer.next() : null; changes = true; } else if (thisDiff.text.startsWith(nextDiff.text)) { // Shift the edit over the next equality. prevDiff.text += nextDiff.text; thisDiff.text = thisDiff.text.substring(nextDiff.text.length()) + nextDiff.text; pointer.remove(); // Delete nextDiff. nextDiff = pointer.hasNext() ? pointer.next() : null; changes = true; } } prevDiff = thisDiff; thisDiff = nextDiff; nextDiff = pointer.hasNext() ? pointer.next() : null; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { diff_cleanupMerge(diffs); } } /** * loc is a location in text1, compute and return the equivalent location in * text2. * e.g. "The cat" vs "The big cat", 1->1, 5->8 * @param diffs LinkedList of Diff objects. * @param loc Location within text1. * @return Location within text2. */ public int diff_xIndex(LinkedList<Diff> diffs, int loc) { int chars1 = 0; int chars2 = 0; int last_chars1 = 0; int last_chars2 = 0; Diff lastDiff = null; for (Diff aDiff : diffs) { if (aDiff.operation != Operation.INSERT) { // Equality or deletion. chars1 += aDiff.text.length(); } if (aDiff.operation != Operation.DELETE) { // Equality or insertion. chars2 += aDiff.text.length(); } if (chars1 > loc) { // Overshot the location. lastDiff = aDiff; break; } last_chars1 = chars1; last_chars2 = chars2; } if (lastDiff != null && lastDiff.operation == Operation.DELETE) { // The location was deleted. return last_chars2; } // Add the remaining character length. return last_chars2 + (loc - last_chars1); } /** * Convert a Diff list into a pretty HTML report. * @param diffs LinkedList of Diff objects. * @return HTML representation. */ public String diff_prettyHtml(LinkedList<Diff> diffs) { StringBuilder html = new StringBuilder(); for (Diff aDiff : diffs) { String text = aDiff.text.replace("&", "&amp;").replace("<", "&lt;") .replace(">", "&gt;").replace("\n", "&para;<br>"); switch (aDiff.operation) { case INSERT: html.append("<ins style=\"background:#e6ffe6;\">").append(text) .append("</ins>"); break; case DELETE: html.append("<del style=\"background:#ffe6e6;\">").append(text) .append("</del>"); break; case EQUAL: html.append("<span>").append(text).append("</span>"); break; } } return html.toString(); } /** * Compute and return the source text (all equalities and deletions). * @param diffs LinkedList of Diff objects. * @return Source text. */ public String diff_text1(LinkedList<Diff> diffs) { StringBuilder text = new StringBuilder(); for (Diff aDiff : diffs) { if (aDiff.operation != Operation.INSERT) { text.append(aDiff.text); } } return text.toString(); } /** * Compute and return the destination text (all equalities and insertions). * @param diffs LinkedList of Diff objects. * @return Destination text. */ public String diff_text2(LinkedList<Diff> diffs) { StringBuilder text = new StringBuilder(); for (Diff aDiff : diffs) { if (aDiff.operation != Operation.DELETE) { text.append(aDiff.text); } } return text.toString(); } /** * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. * @param diffs LinkedList of Diff objects. * @return Number of changes. */ public int diff_levenshtein(LinkedList<Diff> diffs) { int levenshtein = 0; int insertions = 0; int deletions = 0; for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: insertions += aDiff.text.length(); break; case DELETE: deletions += aDiff.text.length(); break; case EQUAL: // A deletion and an insertion is one substitution. levenshtein += Math.max(insertions, deletions); insertions = 0; deletions = 0; break; } } levenshtein += Math.max(insertions, deletions); return levenshtein; } /** * Crush the diff into an encoded string which describes the operations * required to transform text1 into text2. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. * Operations are tab-separated. Inserted text is escaped using %xx notation. * @param diffs Array of Diff objects. * @return Delta text. */ public String diff_toDelta(LinkedList<Diff> diffs) { StringBuilder text = new StringBuilder(); for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: try { text.append("+").append(URLEncoder.encode(aDiff.text, "UTF-8") .replace('+', ' ')).append("\t"); } catch (UnsupportedEncodingException e) { // Not likely on modern system. throw new Error("This system does not support UTF-8.", e); } break; case DELETE: text.append("-").append(aDiff.text.length()).append("\t"); break; case EQUAL: text.append("=").append(aDiff.text.length()).append("\t"); break; } } String delta = text.toString(); if (delta.length() != 0) { // Strip off trailing tab character. delta = delta.substring(0, delta.length() - 1); delta = unescapeForEncodeUriCompatability(delta); } return delta; } /** * Given the original text1, and an encoded string which describes the * operations required to transform text1 into text2, compute the full diff. * @param text1 Source string for the diff. * @param delta Delta text. * @return Array of Diff objects or null if invalid. * @throws IllegalArgumentException If invalid input. */ public LinkedList<Diff> diff_fromDelta(String text1, String delta) throws IllegalArgumentException { LinkedList<Diff> diffs = new LinkedList<Diff>(); int pointer = 0; // Cursor in text1 String[] tokens = delta.split("\t"); for (String token : tokens) { if (token.length() == 0) { // Blank tokens are ok (from a trailing \t). continue; } // Each token begins with a one character parameter which specifies the // operation of this token (delete, insert, equality). String param = token.substring(1); switch (token.charAt(0)) { case '+': // decode would change all "+" to " " param = param.replace("+", "%2B"); try { param = URLDecoder.decode(param, "UTF-8"); } catch (UnsupportedEncodingException e) { // Not likely on modern system. throw new Error("This system does not support UTF-8.", e); } catch (IllegalArgumentException e) { // Malformed URI sequence. throw new IllegalArgumentException( "Illegal escape in diff_fromDelta: " + param, e); } diffs.add(new Diff(Operation.INSERT, param)); break; case '-': // Fall through. case '=': int n; try { n = Integer.parseInt(param); } catch (NumberFormatException e) { throw new IllegalArgumentException( "Invalid number in diff_fromDelta: " + param, e); } if (n < 0) { throw new IllegalArgumentException( "Negative number in diff_fromDelta: " + param); } String text; try { text = text1.substring(pointer, pointer += n); } catch (StringIndexOutOfBoundsException e) { throw new IllegalArgumentException("Delta length (" + pointer + ") larger than source text length (" + text1.length() + ").", e); } if (token.charAt(0) == '=') { diffs.add(new Diff(Operation.EQUAL, text)); } else { diffs.add(new Diff(Operation.DELETE, text)); } break; default: // Anything else is an error. throw new IllegalArgumentException( "Invalid diff operation in diff_fromDelta: " + token.charAt(0)); } } if (pointer != text1.length()) { throw new IllegalArgumentException("Delta length (" + pointer + ") smaller than source text length (" + text1.length() + ")."); } return diffs; } // MATCH FUNCTIONS /** * Locate the best instance of 'pattern' in 'text' near 'loc'. * Returns -1 if no match found. * @param text The text to search. * @param pattern The pattern to search for. * @param loc The location to search around. * @return Best match index or -1. */ public int match_main(String text, String pattern, int loc) { // Check for null inputs. if (text == null || pattern == null) { throw new IllegalArgumentException("Null inputs. (match_main)"); } loc = Math.max(0, Math.min(loc, text.length())); if (text.equals(pattern)) { // Shortcut (potentially not guaranteed by the algorithm) return 0; } else if (text.length() == 0) { // Nothing to match. return -1; } else if (loc + pattern.length() <= text.length() && text.substring(loc, loc + pattern.length()).equals(pattern)) { // Perfect match at the perfect spot! (Includes case of null pattern) return loc; } else { // Do a fuzzy compare. return match_bitap(text, pattern, loc); } } /** * Locate the best instance of 'pattern' in 'text' near 'loc' using the * Bitap algorithm. Returns -1 if no match found. * @param text The text to search. * @param pattern The pattern to search for. * @param loc The location to search around. * @return Best match index or -1. */ protected int match_bitap(String text, String pattern, int loc) { assert (Match_MaxBits == 0 || pattern.length() <= Match_MaxBits) : "Pattern too long for this application."; // Initialise the alphabet. Map<Character, Integer> s = match_alphabet(pattern); // Highest score beyond which we give up. double score_threshold = Match_Threshold; // Is there a nearby exact match? (speedup) int best_loc = text.indexOf(pattern, loc); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore(0, best_loc, loc, pattern), score_threshold); // What about in the other direction? (speedup) best_loc = text.lastIndexOf(pattern, loc + pattern.length()); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore(0, best_loc, loc, pattern), score_threshold); } } // Initialise the bit arrays. int matchmask = 1 << (pattern.length() - 1); best_loc = -1; int bin_min, bin_mid; int bin_max = pattern.length() + text.length(); // Empty initialization added to appease Java compiler. int[] last_rd = new int[0]; for (int d = 0; d < pattern.length(); d++) { // Scan for the best match; each iteration allows for one more error. // Run a binary search to determine how far from 'loc' we can stray at // this error level. bin_min = 0; bin_mid = bin_max; while (bin_min < bin_mid) { if (match_bitapScore(d, loc + bin_mid, loc, pattern) <= score_threshold) { bin_min = bin_mid; } else { bin_max = bin_mid; } bin_mid = (bin_max - bin_min) / 2 + bin_min; } // Use the result from this iteration as the maximum for the next. bin_max = bin_mid; int start = Math.max(1, loc - bin_mid + 1); int finish = Math.min(loc + bin_mid, text.length()) + pattern.length(); int[] rd = new int[finish + 2]; rd[finish + 1] = (1 << d) - 1; for (int j = finish; j >= start; j--) { int charMatch; if (text.length() <= j - 1 || !s.containsKey(text.charAt(j - 1))) { // Out of range. charMatch = 0; } else { charMatch = s.get(text.charAt(j - 1)); } if (d == 0) { // First pass: exact match. rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; } else { // Subsequent passes: fuzzy match. rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1]; } if ((rd[j] & matchmask) != 0) { double score = match_bitapScore(d, j - 1, loc, pattern); // This match will almost certainly be better than any existing // match. But check anyway. if (score <= score_threshold) { // Told you so. score_threshold = score; best_loc = j - 1; if (best_loc > loc) { // When passing loc, don't exceed our current distance from loc. start = Math.max(1, 2 * loc - best_loc); } else { // Already passed loc, downhill from here on in. break; } } } } if (match_bitapScore(d + 1, loc, loc, pattern) > score_threshold) { // No hope for a (better) match at greater error levels. break; } last_rd = rd; } return best_loc; } /** * Compute and return the score for a match with e errors and x location. * @param e Number of errors in match. * @param x Location of match. * @param loc Expected location of match. * @param pattern Pattern being sought. * @return Overall score for match (0.0 = good, 1.0 = bad). */ private double match_bitapScore(int e, int x, int loc, String pattern) { float accuracy = (float) e / pattern.length(); int proximity = Math.abs(loc - x); if (Match_Distance == 0) { // Dodge divide by zero error. return proximity == 0 ? accuracy : 1.0; } return accuracy + (proximity / (float) Match_Distance); } /** * Initialise the alphabet for the Bitap algorithm. * @param pattern The text to encode. * @return Hash of character locations. */ protected Map<Character, Integer> match_alphabet(String pattern) { Map<Character, Integer> s = new HashMap<Character, Integer>(); char[] char_pattern = pattern.toCharArray(); for (char c : char_pattern) { s.put(c, 0); } int i = 0; for (char c : char_pattern) { s.put(c, s.get(c) | (1 << (pattern.length() - i - 1))); i++; } return s; } // PATCH FUNCTIONS /** * Increase the context until it is unique, * but don't let the pattern expand beyond Match_MaxBits. * @param patch The patch to grow. * @param text Source text. */ protected void patch_addContext(Patch patch, String text) { if (text.length() == 0) { return; } String pattern = text.substring(patch.start2, patch.start2 + patch.length1); int padding = 0; // Look for the first and last matches of pattern in text. If two different // matches are found, increase the pattern length. while (text.indexOf(pattern) != text.lastIndexOf(pattern) && pattern.length() < Match_MaxBits - Patch_Margin - Patch_Margin) { padding += Patch_Margin; pattern = text.substring(Math.max(0, patch.start2 - padding), Math.min(text.length(), patch.start2 + patch.length1 + padding)); } // Add one chunk for good luck. padding += Patch_Margin; // Add the prefix. String prefix = text.substring(Math.max(0, patch.start2 - padding), patch.start2); if (prefix.length() != 0) { patch.diffs.addFirst(new Diff(Operation.EQUAL, prefix)); } // Add the suffix. String suffix = text.substring(patch.start2 + patch.length1, Math.min(text.length(), patch.start2 + patch.length1 + padding)); if (suffix.length() != 0) { patch.diffs.addLast(new Diff(Operation.EQUAL, suffix)); } // Roll back the start points. patch.start1 -= prefix.length(); patch.start2 -= prefix.length(); // Extend the lengths. patch.length1 += prefix.length() + suffix.length(); patch.length2 += prefix.length() + suffix.length(); } /** * Compute a list of patches to turn text1 into text2. * A set of diffs will be computed. * @param text1 Old text. * @param text2 New text. * @return LinkedList of Patch objects. */ public LinkedList<Patch> patch_make(String text1, String text2) { if (text1 == null || text2 == null) { throw new IllegalArgumentException("Null inputs. (patch_make)"); } // No diffs provided, compute our own. LinkedList<Diff> diffs = diff_main(text1, text2, true); if (diffs.size() > 2) { diff_cleanupSemantic(diffs); diff_cleanupEfficiency(diffs); } return patch_make(text1, diffs); } /** * Compute a list of patches to turn text1 into text2. * text1 will be derived from the provided diffs. * @param diffs Array of Diff objects for text1 to text2. * @return LinkedList of Patch objects. */ public LinkedList<Patch> patch_make(LinkedList<Diff> diffs) { if (diffs == null) { throw new IllegalArgumentException("Null inputs. (patch_make)"); } // No origin string provided, compute our own. String text1 = diff_text1(diffs); return patch_make(text1, diffs); } /** * Compute a list of patches to turn text1 into text2. * text2 is ignored, diffs are the delta between text1 and text2. * @param text1 Old text * @param text2 Ignored. * @param diffs Array of Diff objects for text1 to text2. * @return LinkedList of Patch objects. * @deprecated Prefer patch_make(String text1, LinkedList<Diff> diffs). */ public LinkedList<Patch> patch_make(String text1, String text2, LinkedList<Diff> diffs) { return patch_make(text1, diffs); } /** * Compute a list of patches to turn text1 into text2. * text2 is not provided, diffs are the delta between text1 and text2. * @param text1 Old text. * @param diffs Array of Diff objects for text1 to text2. * @return LinkedList of Patch objects. */ public LinkedList<Patch> patch_make(String text1, LinkedList<Diff> diffs) { if (text1 == null || diffs == null) { throw new IllegalArgumentException("Null inputs. (patch_make)"); } LinkedList<Patch> patches = new LinkedList<Patch>(); if (diffs.isEmpty()) { return patches; // Get rid of the null case. } Patch patch = new Patch(); int char_count1 = 0; // Number of characters into the text1 string. int char_count2 = 0; // Number of characters into the text2 string. // Start with text1 (prepatch_text) and apply the diffs until we arrive at // text2 (postpatch_text). We recreate the patches one by one to determine // context info. String prepatch_text = text1; String postpatch_text = text1; for (Diff aDiff : diffs) { if (patch.diffs.isEmpty() && aDiff.operation != Operation.EQUAL) { // A new patch starts here. patch.start1 = char_count1; patch.start2 = char_count2; } switch (aDiff.operation) { case INSERT: patch.diffs.add(aDiff); patch.length2 += aDiff.text.length(); postpatch_text = postpatch_text.substring(0, char_count2) + aDiff.text + postpatch_text.substring(char_count2); break; case DELETE: patch.length1 += aDiff.text.length(); patch.diffs.add(aDiff); postpatch_text = postpatch_text.substring(0, char_count2) + postpatch_text.substring(char_count2 + aDiff.text.length()); break; case EQUAL: if (aDiff.text.length() <= 2 * Patch_Margin && !patch.diffs.isEmpty() && aDiff != diffs.getLast()) { // Small equality inside a patch. patch.diffs.add(aDiff); patch.length1 += aDiff.text.length(); patch.length2 += aDiff.text.length(); } if (aDiff.text.length() >= 2 * Patch_Margin) { // Time for a new patch. if (!patch.diffs.isEmpty()) { patch_addContext(patch, prepatch_text); patches.add(patch); patch = new Patch(); // Unlike Unidiff, our patch lists have a rolling context. // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff // Update prepatch text & pos to reflect the application of the // just completed patch. prepatch_text = postpatch_text; char_count1 = char_count2; } } break; } // Update the current character count. if (aDiff.operation != Operation.INSERT) { char_count1 += aDiff.text.length(); } if (aDiff.operation != Operation.DELETE) { char_count2 += aDiff.text.length(); } } // Pick up the leftover patch if not empty. if (!patch.diffs.isEmpty()) { patch_addContext(patch, prepatch_text); patches.add(patch); } return patches; } /** * Given an array of patches, return another array that is identical. * @param patches Array of Patch objects. * @return Array of Patch objects. */ public LinkedList<Patch> patch_deepCopy(LinkedList<Patch> patches) { LinkedList<Patch> patchesCopy = new LinkedList<Patch>(); for (Patch aPatch : patches) { Patch patchCopy = new Patch(); for (Diff aDiff : aPatch.diffs) { Diff diffCopy = new Diff(aDiff.operation, aDiff.text); patchCopy.diffs.add(diffCopy); } patchCopy.start1 = aPatch.start1; patchCopy.start2 = aPatch.start2; patchCopy.length1 = aPatch.length1; patchCopy.length2 = aPatch.length2; patchesCopy.add(patchCopy); } return patchesCopy; } /** * Merge a set of patches onto the text. Return a patched text, as well * as an array of true/false values indicating which patches were applied. * @param patches Array of Patch objects * @param text Old text. * @return Two element Object array, containing the new text and an array of * boolean values. */ public Object[] patch_apply(LinkedList<Patch> patches, String text) { if (patches.isEmpty()) { return new Object[]{text, new boolean[0]}; } // Deep copy the patches so that no changes are made to originals. patches = patch_deepCopy(patches); String nullPadding = patch_addPadding(patches); text = nullPadding + text + nullPadding; patch_splitMax(patches); int x = 0; // delta keeps track of the offset between the expected and actual location // of the previous patch. If there are patches expected at positions 10 and // 20, but the first patch was found at 12, delta is 2 and the second patch // has an effective expected position of 22. int delta = 0; boolean[] results = new boolean[patches.size()]; for (Patch aPatch : patches) { int expected_loc = aPatch.start2 + delta; String text1 = diff_text1(aPatch.diffs); int start_loc; int end_loc = -1; if (text1.length() > this.Match_MaxBits) { // patch_splitMax will only provide an oversized pattern in the case of // a monster delete. start_loc = match_main(text, text1.substring(0, this.Match_MaxBits), expected_loc); if (start_loc != -1) { end_loc = match_main(text, text1.substring(text1.length() - this.Match_MaxBits), expected_loc + text1.length() - this.Match_MaxBits); if (end_loc == -1 || start_loc >= end_loc) { // Can't find valid trailing context. Drop this patch. start_loc = -1; } } } else { start_loc = match_main(text, text1, expected_loc); } if (start_loc == -1) { // No match found. :( results[x] = false; // Subtract the delta for this failed patch from subsequent patches. delta -= aPatch.length2 - aPatch.length1; } else { // Found a match. :) results[x] = true; delta = start_loc - expected_loc; String text2; if (end_loc == -1) { text2 = text.substring(start_loc, Math.min(start_loc + text1.length(), text.length())); } else { text2 = text.substring(start_loc, Math.min(end_loc + this.Match_MaxBits, text.length())); } if (text1.equals(text2)) { // Perfect match, just shove the replacement text in. text = text.substring(0, start_loc) + diff_text2(aPatch.diffs) + text.substring(start_loc + text1.length()); } else { // Imperfect match. Run a diff to get a framework of equivalent // indices. LinkedList<Diff> diffs = diff_main(text1, text2, false); if (text1.length() > this.Match_MaxBits && diff_levenshtein(diffs) / (float) text1.length() > this.Patch_DeleteThreshold) { // The end points match, but the content is unacceptably bad. results[x] = false; } else { diff_cleanupSemanticLossless(diffs); int index1 = 0; for (Diff aDiff : aPatch.diffs) { if (aDiff.operation != Operation.EQUAL) { int index2 = diff_xIndex(diffs, index1); if (aDiff.operation == Operation.INSERT) { // Insertion text = text.substring(0, start_loc + index2) + aDiff.text + text.substring(start_loc + index2); } else if (aDiff.operation == Operation.DELETE) { // Deletion text = text.substring(0, start_loc + index2) + text.substring(start_loc + diff_xIndex(diffs, index1 + aDiff.text.length())); } } if (aDiff.operation != Operation.DELETE) { index1 += aDiff.text.length(); } } } } } x++; } // Strip the padding off. text = text.substring(nullPadding.length(), text.length() - nullPadding.length()); return new Object[]{text, results}; } /** * Add some padding on text start and end so that edges can match something. * Intended to be called only from within patch_apply. * @param patches Array of Patch objects. * @return The padding string added to each side. */ public String patch_addPadding(LinkedList<Patch> patches) { short paddingLength = this.Patch_Margin; String nullPadding = ""; for (short x = 1; x <= paddingLength; x++) { nullPadding += String.valueOf((char) x); } // Bump all the patches forward. for (Patch aPatch : patches) { aPatch.start1 += paddingLength; aPatch.start2 += paddingLength; } // Add some padding on start of first diff. Patch patch = patches.getFirst(); LinkedList<Diff> diffs = patch.diffs; if (diffs.isEmpty() || diffs.getFirst().operation != Operation.EQUAL) { // Add nullPadding equality. diffs.addFirst(new Diff(Operation.EQUAL, nullPadding)); patch.start1 -= paddingLength; // Should be 0. patch.start2 -= paddingLength; // Should be 0. patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs.getFirst().text.length()) { // Grow first equality. Diff firstDiff = diffs.getFirst(); int extraLength = paddingLength - firstDiff.text.length(); firstDiff.text = nullPadding.substring(firstDiff.text.length()) + firstDiff.text; patch.start1 -= extraLength; patch.start2 -= extraLength; patch.length1 += extraLength; patch.length2 += extraLength; } // Add some padding on end of last diff. patch = patches.getLast(); diffs = patch.diffs; if (diffs.isEmpty() || diffs.getLast().operation != Operation.EQUAL) { // Add nullPadding equality. diffs.addLast(new Diff(Operation.EQUAL, nullPadding)); patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs.getLast().text.length()) { // Grow last equality. Diff lastDiff = diffs.getLast(); int extraLength = paddingLength - lastDiff.text.length(); lastDiff.text += nullPadding.substring(0, extraLength); patch.length1 += extraLength; patch.length2 += extraLength; } return nullPadding; } /** * Look through the patches and break up any which are longer than the * maximum limit of the match algorithm. * Intended to be called only from within patch_apply. * @param patches LinkedList of Patch objects. */ public void patch_splitMax(LinkedList<Patch> patches) { short patch_size = Match_MaxBits; String precontext, postcontext; Patch patch; int start1, start2; boolean empty; Operation diff_type; String diff_text; ListIterator<Patch> pointer = patches.listIterator(); Patch bigpatch = pointer.hasNext() ? pointer.next() : null; while (bigpatch != null) { if (bigpatch.length1 <= Match_MaxBits) { bigpatch = pointer.hasNext() ? pointer.next() : null; continue; } // Remove the big old patch. pointer.remove(); start1 = bigpatch.start1; start2 = bigpatch.start2; precontext = ""; while (!bigpatch.diffs.isEmpty()) { // Create one of several smaller patches. patch = new Patch(); empty = true; patch.start1 = start1 - precontext.length(); patch.start2 = start2 - precontext.length(); if (precontext.length() != 0) { patch.length1 = patch.length2 = precontext.length(); patch.diffs.add(new Diff(Operation.EQUAL, precontext)); } while (!bigpatch.diffs.isEmpty() && patch.length1 < patch_size - Patch_Margin) { diff_type = bigpatch.diffs.getFirst().operation; diff_text = bigpatch.diffs.getFirst().text; if (diff_type == Operation.INSERT) { // Insertions are harmless. patch.length2 += diff_text.length(); start2 += diff_text.length(); patch.diffs.addLast(bigpatch.diffs.removeFirst()); empty = false; } else if (diff_type == Operation.DELETE && patch.diffs.size() == 1 && patch.diffs.getFirst().operation == Operation.EQUAL && diff_text.length() > 2 * patch_size) { // This is a large deletion. Let it pass in one chunk. patch.length1 += diff_text.length(); start1 += diff_text.length(); empty = false; patch.diffs.add(new Diff(diff_type, diff_text)); bigpatch.diffs.removeFirst(); } else { // Deletion or equality. Only take as much as we can stomach. diff_text = diff_text.substring(0, Math.min(diff_text.length(), patch_size - patch.length1 - Patch_Margin)); patch.length1 += diff_text.length(); start1 += diff_text.length(); if (diff_type == Operation.EQUAL) { patch.length2 += diff_text.length(); start2 += diff_text.length(); } else { empty = false; } patch.diffs.add(new Diff(diff_type, diff_text)); if (diff_text.equals(bigpatch.diffs.getFirst().text)) { bigpatch.diffs.removeFirst(); } else { bigpatch.diffs.getFirst().text = bigpatch.diffs.getFirst().text .substring(diff_text.length()); } } } // Compute the head context for the next patch. precontext = diff_text2(patch.diffs); precontext = precontext.substring(Math.max(0, precontext.length() - Patch_Margin)); // Append the end context for this patch. if (diff_text1(bigpatch.diffs).length() > Patch_Margin) { postcontext = diff_text1(bigpatch.diffs).substring(0, Patch_Margin); } else { postcontext = diff_text1(bigpatch.diffs); } if (postcontext.length() != 0) { patch.length1 += postcontext.length(); patch.length2 += postcontext.length(); if (!patch.diffs.isEmpty() && patch.diffs.getLast().operation == Operation.EQUAL) { patch.diffs.getLast().text += postcontext; } else { patch.diffs.add(new Diff(Operation.EQUAL, postcontext)); } } if (!empty) { pointer.add(patch); } } bigpatch = pointer.hasNext() ? pointer.next() : null; } } /** * Take a list of patches and return a textual representation. * @param patches List of Patch objects. * @return Text representation of patches. */ public String patch_toText(List<Patch> patches) { StringBuilder text = new StringBuilder(); for (Patch aPatch : patches) { text.append(aPatch); } return text.toString(); } /** * Parse a textual representation of patches and return a List of Patch * objects. * @param textline Text representation of patches. * @return List of Patch objects. * @throws IllegalArgumentException If invalid input. */ public List<Patch> patch_fromText(String textline) throws IllegalArgumentException { List<Patch> patches = new LinkedList<Patch>(); if (textline.length() == 0) { return patches; } List<String> textList = Arrays.asList(textline.split("\n")); LinkedList<String> text = new LinkedList<String>(textList); Patch patch; Pattern patchHeader = Pattern.compile("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$"); Matcher m; char sign; String line; while (!text.isEmpty()) { m = patchHeader.matcher(text.getFirst()); if (!m.matches()) { throw new IllegalArgumentException( "Invalid patch string: " + text.getFirst()); } patch = new Patch(); patches.add(patch); patch.start1 = Integer.parseInt(m.group(1)); if (m.group(2).length() == 0) { patch.start1--; patch.length1 = 1; } else if (m.group(2).equals("0")) { patch.length1 = 0; } else { patch.start1--; patch.length1 = Integer.parseInt(m.group(2)); } patch.start2 = Integer.parseInt(m.group(3)); if (m.group(4).length() == 0) { patch.start2--; patch.length2 = 1; } else if (m.group(4).equals("0")) { patch.length2 = 0; } else { patch.start2--; patch.length2 = Integer.parseInt(m.group(4)); } text.removeFirst(); while (!text.isEmpty()) { try { sign = text.getFirst().charAt(0); } catch (IndexOutOfBoundsException e) { // Blank line? Whatever. text.removeFirst(); continue; } line = text.getFirst().substring(1); line = line.replace("+", "%2B"); // decode would change all "+" to " " try { line = URLDecoder.decode(line, "UTF-8"); } catch (UnsupportedEncodingException e) { // Not likely on modern system. throw new Error("This system does not support UTF-8.", e); } catch (IllegalArgumentException e) { // Malformed URI sequence. throw new IllegalArgumentException( "Illegal escape in patch_fromText: " + line, e); } if (sign == '-') { // Deletion. patch.diffs.add(new Diff(Operation.DELETE, line)); } else if (sign == '+') { // Insertion. patch.diffs.add(new Diff(Operation.INSERT, line)); } else if (sign == ' ') { // Minor equality. patch.diffs.add(new Diff(Operation.EQUAL, line)); } else if (sign == '@') { // Start of next patch. break; } else { // WTF? throw new IllegalArgumentException( "Invalid patch mode '" + sign + "' in: " + line); } text.removeFirst(); } } return patches; } /** * Class representing one diff operation. */ public static class Diff { /** * One of: INSERT, DELETE or EQUAL. */ public Operation operation; /** * The text associated with this diff operation. */ public String text; /** * Constructor. Initializes the diff with the provided values. * @param operation One of INSERT, DELETE or EQUAL. * @param text The text being applied. */ public Diff(Operation operation, String text) { // Construct a diff with the specified operation and text. this.operation = operation; this.text = text; } /** * Display a human-readable version of this Diff. * @return text version. */ public String toString() { String prettyText = this.text.replace('\n', '\u00b6'); return "Diff(" + this.operation + ",\"" + prettyText + "\")"; } /** * Create a numeric hash value for a Diff. * This function is not used by DMP. * @return Hash value. */ @Override public int hashCode() { final int prime = 31; int result = (operation == null) ? 0 : operation.hashCode(); result += prime * ((text == null) ? 0 : text.hashCode()); return result; } /** * Is this Diff equivalent to another Diff? * @param obj Another Diff to compare against. * @return true or false. */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Diff other = (Diff) obj; if (operation != other.operation) { return false; } if (text == null) { if (other.text != null) { return false; } } else if (!text.equals(other.text)) { return false; } return true; } } /** * Class representing one patch operation. */ public static class Patch { public LinkedList<Diff> diffs; public int start1; public int start2; public int length1; public int length2; /** * Constructor. Initializes with an empty list of diffs. */ public Patch() { this.diffs = new LinkedList<Diff>(); } /** * Emmulate GNU diff's format. * Header: @@ -382,8 +481,9 @@ * Indicies are printed as 1-based, not 0-based. * @return The GNU diff string. */ public String toString() { String coords1, coords2; if (this.length1 == 0) { coords1 = this.start1 + ",0"; } else if (this.length1 == 1) { coords1 = Integer.toString(this.start1 + 1); } else { coords1 = (this.start1 + 1) + "," + this.length1; } if (this.length2 == 0) { coords2 = this.start2 + ",0"; } else if (this.length2 == 1) { coords2 = Integer.toString(this.start2 + 1); } else { coords2 = (this.start2 + 1) + "," + this.length2; } StringBuilder text = new StringBuilder(); text.append("@@ -").append(coords1).append(" +").append(coords2) .append(" @@\n"); // Escape the body of the patch with %xx notation. for (Diff aDiff : this.diffs) { switch (aDiff.operation) { case INSERT: text.append('+'); break; case DELETE: text.append('-'); break; case EQUAL: text.append(' '); break; } try { text.append(URLEncoder.encode(aDiff.text, "UTF-8").replace('+', ' ')) .append("\n"); } catch (UnsupportedEncodingException e) { // Not likely on modern system. throw new Error("This system does not support UTF-8.", e); } } return unescapeForEncodeUriCompatability(text.toString()); } } /** * Unescape selected chars for compatability with JavaScript's encodeURI. * In speed critical applications this could be dropped since the * receiving application will certainly decode these fine. * Note that this function is case-sensitive. Thus "%3f" would not be * unescaped. But this is ok because it is only called with the output of * URLEncoder.encode which returns uppercase hex. * * Example: "%3F" -> "?", "%24" -> "$", etc. * * @param str The string to escape. * @return The escaped string. */ private static String unescapeForEncodeUriCompatability(String str) { return str.replace("%21", "!").replace("%7E", "~") .replace("%27", "'").replace("%28", "(").replace("%29", ")") .replace("%3B", ";").replace("%2F", "/").replace("%3F", "?") .replace("%3A", ":").replace("%40", "@").replace("%26", "&") .replace("%3D", "=").replace("%2B", "+").replace("%24", "$") .replace("%2C", ",").replace("%23", "#"); } }
89,040
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TmMatchEditorBodyMenu.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/dialog/TmMatchEditorBodyMenu.java
/** * TmMatchEditorBodyMenu.java * * Version information : * * Date:2013-3-28 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.dialog; import net.heartsome.cat.ts.ui.innertag.SegmentViewer; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.WorkbenchMessages; /** * @author Jason * @version * @since JDK1.6 */ @SuppressWarnings("restriction") public class TmMatchEditorBodyMenu { CopyAction copyAction; CutAction cutAction; public PasteAction pasteAction; UndoAction undoAction; RedoAction redoAction; SegmentViewer viewer; Menu bodyMenu; public TmMatchEditorBodyMenu(SegmentViewer viewer) { this.viewer = viewer; createMenu(); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateActionsEnableState(); } }); viewer.getTextWidget().addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateActionsEnableState(); } }); viewer.getTextWidget().addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event event) { int t = event.keyCode | event.stateMask; if (t == ('Z' | SWT.MOD1) || t == ('z' | SWT.MOD1)) { undoAction.runWithEvent(event); } else if (t == ('Y' | SWT.MOD1) || t == ('y' | SWT.MOD1)) { redoAction.runWithEvent(event); } else if (t == ('V' | SWT.MOD1) || t == ('v' | SWT.MOD1)) { pasteAction.runWithEvent(event); } else if (t == ('C' | SWT.MOD1) || t == ('c' | SWT.MOD1)) { copyAction.runWithEvent(event); } } }); viewer.getTextWidget().setKeyBinding('V' | SWT.MOD1, SWT.NULL); viewer.getTextWidget().setKeyBinding(SWT.INSERT | SWT.MOD2, SWT.NULL); } public Menu getBodyMenu() { return this.bodyMenu; } private void createMenu() { MenuManager menuMgr = new MenuManager(); bodyMenu = menuMgr.createContextMenu(viewer.getControl()); copyAction = new CopyAction(); cutAction = new CutAction(); pasteAction = new PasteAction(); undoAction = new UndoAction(); redoAction = new RedoAction(); menuMgr.add(undoAction); menuMgr.add(redoAction); menuMgr.add(new Separator()); menuMgr.add(copyAction); menuMgr.add(cutAction); menuMgr.add(pasteAction); } public void updateActionsEnableState() { cutAction.updateEnabledState(); copyAction.updateEnabledState(); pasteAction.updateEnabledState(); undoAction.updateEnabledState(); redoAction.updateEnabledState(); } private class CopyAction extends Action { protected CopyAction() { super(WorkbenchMessages.Workbench_copy); setEnabled(false); ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY)); setDisabledImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED)); } 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 PasteAction extends Action { protected PasteAction() { super(WorkbenchMessages.Workbench_paste); setEnabled(false); ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE)); setDisabledImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED)); } 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 CutAction extends Action { protected CutAction() { super(WorkbenchMessages.Workbench_cut); setEnabled(false); ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT)); setDisabledImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED)); } 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 UndoAction extends Action { protected UndoAction() { super(WorkbenchMessages.Workbench_undo); setEnabled(false); ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO)); setDisabledImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO_DISABLED)); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { // 使用TextViewer组件的撤销功能 viewer.doOperation(ITextOperationTarget.UNDO); updateActionsEnableState(); return; } if (undoAction != null) { undoAction.runWithEvent(event); return; } } /** * Update the state. */ public void updateEnabledState() { if (viewer != null && !viewer.getTextWidget().isDisposed()) { setEnabled(viewer.canDoOperation(ITextOperationTarget.UNDO)); return; } if (undoAction != null) { setEnabled(undoAction.isEnabled()); return; } setEnabled(false); } } /** * 重做处理 * @author Leakey * @version * @since JDK1.6 */ private class RedoAction extends Action { protected RedoAction() { super(WorkbenchMessages.Workbench_redo); setEnabled(false); ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO)); setDisabledImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO_DISABLED)); } public void runWithEvent(Event event) { if (viewer != null && !viewer.getTextWidget().isDisposed()) { // 使用TextViewer提供的重做功能 viewer.doOperation(ITextOperationTarget.REDO); updateActionsEnableState(); return; } if (redoAction != null) { redoAction.runWithEvent(event); return; } } /** * Update the state. */ public void updateEnabledState() { if (viewer != null && !viewer.getTextWidget().isDisposed()) { setEnabled(viewer.canDoOperation(ITextOperationTarget.REDO)); return; } if (undoAction != null) { setEnabled(redoAction.isEnabled()); return; } setEnabled(false); } } }
8,904
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TmMatchEditDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.translation/src/net/heartsome/cat/ts/ui/translation/dialog/TmMatchEditDialog.java
/** * TmMatchEditDialog.java * * Version information : * * Date:2013-3-28 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.ui.translation.dialog; import java.text.MessageFormat; import net.heartsome.cat.common.bean.FuzzySearchResult; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.ui.Activator; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.innertag.SegmentViewer; import net.heartsome.cat.ts.ui.preferencepage.IPreferenceConstants; import net.heartsome.cat.ts.ui.translation.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; 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.Group; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.keys.IBindingService; /** * 匹配面板匹配面编辑对话框。 * @author Jason * @version * @since JDK1.6 */ public class TmMatchEditDialog extends Dialog { private SegmentViewer srcSegmentViewer; private SegmentViewer tgtSegmentViewer; private FuzzySearchResult fuzzyResult; /** * Create the dialog. * @param parentShell */ public TmMatchEditDialog(Shell parentShell, FuzzySearchResult fuzzyResult) { super(parentShell); this.fuzzyResult = fuzzyResult; setShellStyle(getShellStyle() | SWT.RESIZE); IBindingService bindingService = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class); bindingService.setKeyFilterEnabled(false); } @Override protected void okPressed() { String srcFullText = srcSegmentViewer.getText(); String tgtFullText = tgtSegmentViewer.getText(); String title = Messages.getString("dialog.TmMatchEditDialog.error.title"); if (srcFullText == null || srcFullText.length() == 0) { MessageDialog.openError(getShell(), title, Messages.getString("dialog.TmMatchEditDialog.error.srcNull")); return; } if (tgtFullText == null || tgtFullText.length() == 0) { MessageDialog.openError(getShell(), title, Messages.getString("dialog.TmMatchEditDialog.error.tgtNull")); return; } if (srcFullText.equals(fuzzyResult.getTu().getSource().getFullText()) && tgtFullText.equals(fuzzyResult.getTu().getTarget().getFullText())) { super.cancelPressed(); return; } fuzzyResult.getTu().getSource().setFullText(srcFullText); fuzzyResult.getTu().getSource().setPureText(srcSegmentViewer.getPureText()); fuzzyResult.getTu().getTarget().setFullText(tgtFullText); fuzzyResult.getTu().getTarget().setPureText(tgtSegmentViewer.getPureText()); fuzzyResult.getTu().setChangeDate(CommonFunction.retTMXDate()); fuzzyResult.getTu().setChangeUser( Activator.getDefault().getPreferenceStore().getString(IPreferenceConstants.SYSTEM_USER)); super.okPressed(); } @Override public boolean close() { IBindingService bindingService = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class); bindingService.setKeyFilterEnabled(true); srcSegmentViewer.reset(); tgtSegmentViewer.reset(); return super.close(); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("dialog.TmMatchEditDialog.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)); Group srcGroup = new Group(container, SWT.NONE); srcGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); srcGroup.setLayout(new GridLayout(1, false)); String srcGroupTile = Messages.getString("dialog.TmMatchEditDialog.component.src"); srcGroupTile = MessageFormat.format(srcGroupTile, fuzzyResult.getTu().getSource().getLangCode()); srcGroup.setText(srcGroupTile); srcSegmentViewer = new SegmentViewer(srcGroup, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL, null); StyledText srcTextControl = srcSegmentViewer.getTextWidget(); srcTextControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); srcTextControl.setLineSpacing(Constants.SEGMENT_LINE_SPACING); srcTextControl.setLeftMargin(Constants.SEGMENT_LEFT_MARGIN); srcTextControl.setRightMargin(Constants.SEGMENT_RIGHT_MARGIN); srcTextControl.setTopMargin(Constants.SEGMENT_TOP_MARGIN); srcTextControl.setBottomMargin(Constants.SEGMENT_TOP_MARGIN); srcTextControl.setFont(JFaceResources.getFont(Constants.MATCH_VIEWER_TEXT_FONT)); Group targetGroup = new Group(container, SWT.NONE); targetGroup.setLayout(new GridLayout(1, false)); targetGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); String tgtGroupTile = Messages.getString("dialog.TmMatchEditDialog.component.tgt"); tgtGroupTile = MessageFormat.format(tgtGroupTile, fuzzyResult.getTu().getSource().getLangCode()); targetGroup.setText(tgtGroupTile); tgtSegmentViewer = new SegmentViewer(targetGroup, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL, null); StyledText tgtTextControl = tgtSegmentViewer.getTextWidget(); tgtTextControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); tgtTextControl.setLineSpacing(Constants.SEGMENT_LINE_SPACING); tgtTextControl.setLeftMargin(Constants.SEGMENT_LEFT_MARGIN); tgtTextControl.setRightMargin(Constants.SEGMENT_RIGHT_MARGIN); tgtTextControl.setTopMargin(Constants.SEGMENT_TOP_MARGIN); tgtTextControl.setBottomMargin(Constants.SEGMENT_TOP_MARGIN); tgtTextControl.setFont(JFaceResources.getFont(Constants.MATCH_VIEWER_TEXT_FONT)); net.heartsome.cat.ts.ui.innertag.tagstyle.TagStyleConfigurator.configure(srcSegmentViewer); net.heartsome.cat.ts.ui.innertag.tagstyle.TagStyleConfigurator.configure(tgtSegmentViewer); TmMatchEditorBodyMenu srcMenu = new TmMatchEditorBodyMenu(srcSegmentViewer); srcSegmentViewer.getTextWidget().setMenu(srcMenu.getBodyMenu()); TmMatchEditorBodyMenu tgtMenu = new TmMatchEditorBodyMenu(tgtSegmentViewer); tgtSegmentViewer.getTextWidget().setMenu(tgtMenu.getBodyMenu()); loadData(); return container; } private void loadData() { srcSegmentViewer.setText(fuzzyResult.getTu().getSource().getFullText()); srcSegmentViewer.setSource(""); srcSegmentViewer.initUndoManager(50); tgtSegmentViewer.setText(fuzzyResult.getTu().getTarget().getFullText()); tgtSegmentViewer.setSource(""); tgtSegmentViewer.initUndoManager(50); tgtSegmentViewer.getTextWidget().setFocus(); tgtSegmentViewer.getTextWidget().setCaretOffset(tgtSegmentViewer.getText().length()); } /** * 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(700, 300); } }
8,099
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.translation/src/net/heartsome/cat/ts/ui/translation/resource/Messages.java
package net.heartsome.cat.ts.ui.translation.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.translation.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; } } }
572
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.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/Activator.java
package net.heartsome.cat.ts.ui.advanced; 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.ui.advanced"; //$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; } /** * 提供一个图片文件对插件的相对路径,返回该图片的描述信息。 * @param path * 图片资源对插件的相对路径。 * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } }
1,433
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ADConstants.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/ADConstants.java
package net.heartsome.cat.ts.ui.advanced; import java.io.File; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Platform; /** * 高级插件所用到的常量 * @author robert 2012-02-17 * @version * @since JDK1.6 */ public class ADConstants { private static String sep = File.separator; public static String configLocation = Platform.getConfigurationLocation().getURL().getPath(); /** catalogue.xml的文件路径 */ public static final String catalogueXmlPath = ".metadata/net.heartsome.cat.converter/catalogue/catalogue.xml"; public static final String cataloguePath = ".metadata/net.heartsome.cat.converter/catalogue"; /** 选择目录后保存所选文件的文件夹路径 */ public static final String AD_cataBrowseFileMemory = "ts.ad.cataBrowseFileMemory"; /** xml转换器配置中,配置文件在产品所存放的位置 */ public static final String AD_xmlConverterConfigFolder = ".metadata/net.heartsome.cat.converter/ini"; public static final String AD_SRXConfigFolder = "net.heartsome.cat.converter" + sep + "srx"; }
1,088
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TableViewerLabelProvider.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/TableViewerLabelProvider.java
package net.heartsome.cat.ts.ui.advanced; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; /** * tableViewer的标签提供器 * @author robert */ public 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; } }
614
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SRXConfigrationHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/handlers/SRXConfigrationHandler.java
package net.heartsome.cat.ts.ui.advanced.handlers; import net.heartsome.cat.ts.ui.advanced.dialogs.srx.SrxConfigurationDialog; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.handlers.HandlerUtil; /** * 高级菜单下配置分段规则子菜单的handler * @author robert 2012-02-28 * @version * @since JDK1.6 */ public class SRXConfigrationHandler extends AbstractHandler { public Object execute(ExecutionEvent event) throws ExecutionException { // IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); Shell shell = HandlerUtil.getActiveShell(event); // String srxConfigLocation = ADConstants.configLocation + File.separator + ADConstants.AD_SRXConfigFolder; // // 首先验证本次所要用到的SRX(分段规则)文件是否存在于工作空间中。如果没有,那么将相关文件拷贝到指定工作空间的目录 // File srxConfigFolderFile = new File(srxConfigLocation); // // 如果不存在,则将安装文件中的相关配置文件复制到工作工间 // if (!srxConfigFolderFile.exists() || !srxConfigFolderFile.isDirectory() // || new File(srxConfigLocation).list().length <= 0) { // String srcLocation = Platform.getConfigurationLocation().getURL().getPath() + "net.heartsome.cat.converter" // + System.getProperty("file.separator") + "srx"; // try { // ResourceUtils.copyDirectory(new File(srcLocation), new File(srxConfigLocation)); // } catch (Exception e) { // e.printStackTrace(); // } // // File _srxConfigFolderFile = new File(srxConfigLocation); // if (!_srxConfigFolderFile.exists() || !_srxConfigFolderFile.isDirectory()) { // MessageDialog.openInformation(shell, Messages.getString("handlers.SRXConfigrationHandler.msgTitle"), // Messages.getString("handlers.SRXConfigrationHandler.msg")); // return null; // } // } SrxConfigurationDialog dialog = new SrxConfigurationDialog(shell); dialog.open(); return null; } }
2,097
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ADXmlHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/handlers/ADXmlHandler.java
package net.heartsome.cat.ts.ui.advanced.handlers; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.advanced.model.ElementBean; import net.heartsome.cat.ts.ui.advanced.model.LanguageRuleBean; import net.heartsome.cat.ts.ui.advanced.model.MapRuleBean; import net.heartsome.xml.vtdimpl.VTDUtils; import com.ximpleware.AutoPilot; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; /** * 品质检查的xml文件解析类 * @author robert 2012-02-20 * @version * @since JDK1.6 */ public class ADXmlHandler extends QAXmlHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ADXmlHandler.class); /** * 获取catalogue.xml文件中的数据 * @param xmlLocation * @return ; */ public List<String[]> getCatalogValueList(String xmlLocation){ List<String[]> catalogList = new LinkedList<String[]>(); int index = 1; VTDNav vn = super.getVTDNav(xmlLocation); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath("/catalog/*"); while (ap.evalXPath() != -1) { String cataName = vn.toString(vn.getCurrentIndex()); String name = null; int idIdx = -1; int urlIdx = -1; String idStr; String urlStr ; if ("public".equals(cataName)) { name = "PUBLIC"; idIdx = vn.getAttrVal("publicId"); urlIdx = vn.getAttrVal("uri"); }else if ("system".equals(cataName)) { name = "SYSTEM"; idIdx = vn.getAttrVal("systemId"); urlIdx = vn.getAttrVal("uri"); }else if ("uri".equals(cataName)) { name = "URI"; idIdx = vn.getAttrVal("name"); urlIdx = vn.getAttrVal("uri"); }else if ("nextCatalog".equals(cataName)) { name = "nextCatalog"; urlIdx = vn.getAttrVal("catalog"); } if (name == null) { continue; } idStr = (idIdx != -1 ? vn.toString(idIdx) : "" ); urlStr = (urlIdx != -1 ? vn.toString(urlIdx) : "" ); catalogList.add(new String[]{"" + index, name, idStr, urlStr}); index ++; } } catch (Exception e) { LOGGER.error("", e); } return catalogList; } /** * 向catalogue.xml中添加数据 * @param xmlLocation * @param addData ; */ public void deleteCatalog(String xmlLocation, List<String> xpathList, List<String[]> dataList){ VTDNav vn = super.getVTDNav(xmlLocation); AutoPilot ap = new AutoPilot(vn); try { VTDUtils vu = new VTDUtils(); for (int i = 0; i < xpathList.size(); i++) { vn = super.getVTDNav(xmlLocation); vu.bind(vn); String xpath = xpathList.get(i); ap.selectXPath(xpath); if (ap.evalXPath() != -1) { XMLModifier xm = vu.delete(xpath); saveAndReparse(xm, xmlLocation); ap.resetXPath(); }else { //如果找不到,就是xpath配置问题,比如没有任何一个属性 /*String name = dataList.get(i)[0]; String id = dataList.get(i)[1]; String uri = dataList.get(i)[2]; if ("".equals(id) && "".equals(uri)) { }*/ } } } catch (Exception e) { LOGGER.error("", e); } } /** * 修改数据(修改整个节点) * @param xmlLocation * @param xpath * @param newData ; */ public boolean updataDataToXml(String xmlLocation, String xpath, String newData){ VTDNav vn = super.getVTDNav(xmlLocation); AutoPilot ap = new AutoPilot(vn); try { VTDUtils vu = new VTDUtils(vn); ap.selectXPath(xpath); if (ap.evalXPath() != -1) { return saveAndReparse(vu.update(xpath, newData), xmlLocation); } } catch (Exception e) { LOGGER.error("", e); } return false; } /** * 获取转换配置文件的所有内容 * @return ; */ public List<ElementBean> getconvertXmlElements(String xmlLocation) { List<ElementBean> elementsList = new LinkedList<ElementBean>(); VTDNav vn = super.getVTDNav(xmlLocation); AutoPilot ap = new AutoPilot(vn); ElementBean bean; try { ap.selectXPath("/ini-file/tag"); while (ap.evalXPath() != -1) { // 如果元素名与元素类型为空,那么当前节点不被添加 if (vn.getText() == -1 || vn.getAttrVal("hard-break") == -1 || "".equals(vn.toString(vn.getText())) || "".equals(vn.toString(vn.getAttrVal("hard-break")))) { continue; } //开始添加元素名称 bean = new ElementBean(); bean.setName(vn.toString(vn.getText())); bean.setType(vn.toString(vn.getAttrVal("hard-break"))); bean.setInlineType(vn.getAttrVal("ctype") != -1 ? vn.toString(vn.getAttrVal("ctype")) : ""); bean.setTransAttribute(vn.getAttrVal("attributes") != -1 ? vn.toString(vn.getAttrVal("attributes")) : ""); bean.setRemainSpace(vn.getAttrVal("keep-format") != -1 ? vn.toString(vn.getAttrVal("keep-format")) : ""); elementsList.add(bean); } } catch (Exception e) { LOGGER.error("", e); } return elementsList; } /** * 获取分析XML文件后的数据(针对于分析XML文件) * @param xmlLocation * @return ; */ public List<ElementBean> getAnalysisXmlData(String xmlLocation) { List<ElementBean> beanList = new LinkedList<ElementBean>(); List<String> elementNameList = new ArrayList<String>(); VTDNav vn = getVTDNav(xmlLocation); AutoPilot ap = new AutoPilot(vn); ElementBean bean; try { ap.selectXPath("//*[text()!='' or not(./*)]"); while (ap.evalXPath() != -1) { String elementName = vn.toString(vn.getCurrentIndex()); //如果元素名不重复,那么就添加到结果集中 if (elementNameList.indexOf(elementName) == -1) { bean = new ElementBean(); bean.setName(elementName); bean.setType("segment"); bean.setInlineType(""); bean.setTransAttribute(""); bean.setRemainSpace(""); beanList.add(bean); elementNameList.add(elementName); } } } catch (Exception e) { LOGGER.error("", e); } return beanList; } /** * 验证指定的srx文件是否符合srx标准,通过验证其根元素是否为srx * @param srxLoaction * @return ; */ public boolean validSrx(String srxLoaction){ VTDNav vn = super.getVTDNav(srxLoaction); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath("/srx"); if (ap.evalXPath() != -1) { return true; } } catch (Exception e) { LOGGER.error("", e); return false; } return false; } /** * 验证给出的xpath所表示的节点是否存在,如果存在,则返回true,如果不存在,则返回false * @param xmlLoaction * @param validXpath * @return ; */ public boolean validNodeExist(String xmlLocation, String validXpath) { VTDNav vn = super.getVTDNav(xmlLocation); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath(validXpath); if (ap.evalXPath() != -1) { return true; } } catch (Exception e) { LOGGER.error("", e); } return false; } /** * 将言语规则节点添加到指定的文件中 * @param srxLoaction * @param langRulsList * @return true:添加成功,false:添加失败; */ public boolean addLanguageRules(String srxLoaction, String languageRulesData) { VTDNav vn = super.getVTDNav(srxLoaction); AutoPilot ap = new AutoPilot(vn); //在添加之前,先判断body与languagerules节点是否存在,如果存在,则创建 try { //在添加之前,先判断body节点是否存在,如果不存在,则创建 ap.selectXPath("/srx/body"); if (ap.evalXPath() == -1) { String bodyStr = "\t<body>\n\t</body>"; if (super.addDataToXml(srxLoaction, "/srx", bodyStr)) { vn = super.getVTDNav(srxLoaction); } } ap.resetXPath(); //若无languagerule节点存在,创建此节点 ap.selectXPath("/srx/body/languagerules"); if (ap.evalXPath() == -1) { String langRuleStr = "\t<languagerules>\n" + "\t\t</languagerules>"; if (super.addDataToXml(srxLoaction, "/srx/body", langRuleStr)) { vn = super.getVTDNav(srxLoaction); } } ap.resetXPath(); return super.addDataToXml(srxLoaction, "/srx/body/languagerules", languageRulesData); } catch (Exception e) { LOGGER.error("", e); } return false; } /** * 分段规则中,添加映射规则 * @param srxLoaction * @param mapRulesData * @param mapRuleName * @return true:添加成功,false:添加失败; */ public boolean addMapRules(String srxLoaction, String mapRulesData) { VTDNav vn = super.getVTDNav(srxLoaction); AutoPilot ap = new AutoPilot(vn); //在添加之前,先判断body与maprules节点是否存在,如果存在,则创建 try { //在添加之前,先判断body节点是否存在,如果不存在,则创建 ap.selectXPath("/srx/body"); if (ap.evalXPath() == -1) { String bodyStr = "\t<body>\n\t</body>"; if (super.addDataToXml(srxLoaction, "/srx", bodyStr)) { vn = super.getVTDNav(srxLoaction); } } ap.resetXPath(); //若无languagerule节点存在,创建此节点 ap.selectXPath("/srx/body/maprules"); if (ap.evalXPath() == -1) { String langRuleStr = "\t<maprules>\n" + "\t\t</maprules>"; if (super.addDataToXml(srxLoaction, "/srx/body", langRuleStr)) { vn = super.getVTDNav(srxLoaction); } } ap.resetXPath(); return super.addDataToXml(srxLoaction, "/srx/body/maprules", mapRulesData); } catch (Exception e) { LOGGER.error("", e); } return false; } /** * 获取语言规则的名称,返回结果为list<String[]> * @param srxLoaction * @return ; */ public List<String[]> getLanguageRuleNamesOfSrx_1(String srxLocation){ List<String[]> langRuleNames = new LinkedList<String[]>(); VTDNav vn = super.getVTDNav(srxLocation); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath("/srx/body/languagerules/languagerule"); while(ap.evalXPath() != -1){ if (vn.getAttrVal("languagerulename") != -1) { langRuleNames.add(new String[] { "" + (langRuleNames.size() + 1), vn.toString(vn.getAttrVal("languagerulename")) }); } } } catch (Exception e) { LOGGER.error("", e); } return langRuleNames; } /** * 获取语言规则的名称,返回结果为list<String>类型 * @param srxLocation * @return ; */ public List<String> getLanguageRuleNamesOfSrx_2(String srxLocation) { List<String> langRuleNames = new LinkedList<String>(); VTDNav vn = super.getVTDNav(srxLocation); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath("/srx/body/languagerules/languagerule"); while (ap.evalXPath() != -1) { if (vn.getAttrVal("languagerulename") != -1) { langRuleNames.add(vn.toString(vn.getAttrVal("languagerulename"))); } } } catch (Exception e) { LOGGER.error("", e); } return langRuleNames; } /** * 获取srx文件所有的映射节点名称 * @param srxLocation * @return ; */ public List<String[]> getMapRuleNames(String srxLocation){ List<String[]> mapRuleNames = new LinkedList<String[]>(); VTDNav vn = super.getVTDNav(srxLocation); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath("/srx/body/maprules/maprule"); while (ap.evalXPath() != -1) { if (vn.getAttrVal("maprulename") != -1) { mapRuleNames.add(new String[] { "" + (mapRuleNames.size() + 1), vn.toString(vn.getAttrVal("maprulename")) }); } } } catch (Exception e) { LOGGER.error("", e); } return mapRuleNames; } public List<LanguageRuleBean> getLangRulesByName(String srxLocation, String langRuleName){ List<LanguageRuleBean> languageRulesList = new LinkedList<LanguageRuleBean>(); VTDNav vn = super.getVTDNav(srxLocation); AutoPilot ap = new AutoPilot(vn); AutoPilot ruleAP = new AutoPilot(vn); AutoPilot childAP = new AutoPilot(vn); try { ap.selectXPath("/srx/body/languagerules/languagerule[@languagerulename='"+ langRuleName +"']"); if (ap.evalXPath() != -1) { ruleAP.selectXPath("./rule"); LanguageRuleBean bean; while (ruleAP.evalXPath() != -1) { String isBreak = ""; String preBreak = ""; String afterBreak = ""; if (vn.getAttrVal("break") != -1) { isBreak = vn.toString(vn.getAttrVal("break")); } vn.push(); childAP.selectXPath("./beforebreak"); if (childAP.evalXPath() != -1) { if (vn.getText() != -1) { preBreak = vn.toString(vn.getText()); } } vn.pop(); childAP.resetXPath(); vn.push(); childAP.selectXPath("./afterbreak"); if (childAP.evalXPath() != -1) { if (vn.getText() != -1) { afterBreak = vn.toString(vn.getText()); } } vn.pop(); bean = new LanguageRuleBean(isBreak, preBreak, afterBreak); languageRulesList.add(bean); } } } catch (Exception e) { LOGGER.error("", e); } return languageRulesList; } public List<MapRuleBean> getMapRulesByName(String srxLocation, String mapRuleName){ List<MapRuleBean> mapRulesList = new LinkedList<MapRuleBean>(); VTDNav vn = super.getVTDNav(srxLocation); AutoPilot ap = new AutoPilot(vn); AutoPilot ruleAP = new AutoPilot(vn); try { MapRuleBean bean; ap.selectXPath("/srx/body/maprules/maprule[@maprulename='"+ mapRuleName +"']"); if (ap.evalXPath() != -1) { ruleAP.selectXPath("./languagemap"); while (ruleAP.evalXPath() != -1) { String languageModel = ""; String langRuleName = ""; int index = 0; if ((index = vn.getAttrVal("languagepattern")) != -1) { languageModel = vn.toString(index); } if ((index = vn.getAttrVal("languagerulename")) != -1) { langRuleName = vn.toString(index); } bean = new MapRuleBean(languageModel, langRuleName); mapRulesList.add(bean); } } } catch (Exception e) { LOGGER.error("", e); } return mapRulesList; } /** * 验证所指定的语言规则是否添加映射,如果已经添加,就返回true,若未被添加映射,则返回false * @param srxLoaction * @param languageRuleName * @return ; */ public boolean checkLangRuleNameMaped(String srxLoaction, String languageRuleName){ VTDNav vn = super.getVTDNav(srxLoaction); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath("/srx/body/maprules/maprule/languagemap[@languagerulename='"+ languageRuleName +"']"); if (ap.evalXPath() != -1) { return true; } } catch (Exception e) { LOGGER.error("", e); } return false; } /** * 当语言规则名称改变以后,同步更新映射规则中的语言规则名称 * @param xmlLocation * @param updateXpath * @param newData * @return ; */ public boolean updateMapRuleLangName(String xmlLocation, String updateXpath, String newValue) { VTDNav vn = super.getVTDNav(xmlLocation); AutoPilot ap = new AutoPilot(vn); try { ap.selectXPath(updateXpath); XMLModifier xm = new XMLModifier(vn); boolean needReparse = false; while (ap.evalXPath() != -1) { xm.updateToken(vn.getAttrVal("languagerulename"), newValue); needReparse = true; } if (needReparse) { return saveAndReparse(xm, xmlLocation); } } catch (Exception e) { LOGGER.error("", e); } return true; } }
15,110
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CatalogManagerHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/handlers/CatalogManagerHandler.java
package net.heartsome.cat.ts.ui.advanced.handlers; import java.io.File; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.dialogs.CatalogManagerDialog; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.handlers.HandlerUtil; /** * 配置目录管理的handler * @author robert 2012-02-17 * @version * @since JDK1.6 */ public class CatalogManagerHandler extends AbstractHandler { private IWorkspaceRoot root; public Object execute(ExecutionEvent event) throws ExecutionException { root = ResourcesPlugin.getWorkspace().getRoot(); //先检查目录管理器配置所需要的文件是否都存在于工作空间 File catalogXmlFile = root.getLocation().append(ADConstants.catalogueXmlPath).toFile(); // 如果不存在,就将net.heartsome.cat.ts.configurationfile.feature插件的net.heartsome.cat.converter里的catalogue.xml拷到工作空间 if (!catalogXmlFile.exists() || new File(catalogXmlFile.getParent()).list().length <= 0) { //这是产品打包后,catalogue.xml所在的路径 String srcLocation = Platform.getConfigurationLocation().getURL().getPath() + "net.heartsome.cat.converter" + System.getProperty("file.separator") + "catalogue" + System.getProperty("file.separator") + "catalogue.xml"; String tagLoaction = catalogXmlFile.getParent(); try { ResourceUtils.copyDirectory(new File(srcLocation).getParentFile(), new File(tagLoaction)); } catch (Exception e) { e.printStackTrace(); } } catalogXmlFile = root.getLocation().append(ADConstants.catalogueXmlPath).toFile(); if (!catalogXmlFile.exists()) { MessageDialog.openInformation(HandlerUtil.getActiveSite(event).getShell(), Messages.getString("handlers.CatalogManagerHandler.msgTitle"), Messages.getString("handlers.CatalogManagerHandler.msg")); return null; } CatalogManagerDialog dialog = new CatalogManagerDialog(HandlerUtil.getActiveSite(event).getShell(), root); dialog.open(); return null; } }
2,439
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XmlConverterConfigurationHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/handlers/XmlConverterConfigurationHandler.java
package net.heartsome.cat.ts.ui.advanced.handlers; import java.io.File; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.dialogs.XmlConverterConfigurationDialog; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.handlers.HandlerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 配置XML转换器的handler类 * @author robert 2012-02-22 * @version * @since JDK1.6 */ public class XmlConverterConfigurationHandler extends AbstractHandler { private static final Logger LOGGER = LoggerFactory.getLogger(XmlConverterConfigurationHandler.class); private IWorkspaceRoot root; public Object execute(ExecutionEvent event) throws ExecutionException { root = ResourcesPlugin.getWorkspace().getRoot(); String configFileLocation = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder).toOSString(); Shell shell = HandlerUtil.getActiveShell(event); // 首先验证安装文件中本次所需要的文件是否转存至工作工间,如果没有,就转过去。 File xmlConfigFolderFile = new File(configFileLocation); String tgtLocation = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder).toOSString(); // 如果不存在,则将安装文件中的相关配置文件复制到工作工间 if (!xmlConfigFolderFile.exists() || !xmlConfigFolderFile.isDirectory() || new File(tgtLocation).list().length <= 0) { String srcLocation = Platform.getConfigurationLocation().getURL().getPath() + "net.heartsome.cat.converter" + System.getProperty("file.separator") + "ini"; try { ResourceUtils.copyDirectory(new File(srcLocation), new File(tgtLocation)); } catch (Exception e) { LOGGER.error("", e); } File _xmlConfigFolderFile = new File(configFileLocation); if (!_xmlConfigFolderFile.exists() || !_xmlConfigFolderFile.isDirectory()) { MessageDialog.openInformation(shell, Messages.getString("handlers.XmlConverterConfigurationHandler.msgTitle"), Messages.getString("handlers.XmlConverterConfigurationHandler.msg")); return null; } } XmlConverterConfigurationDialog dialog = new XmlConverterConfigurationDialog(shell, configFileLocation); dialog.open(); return null; } }
2,715
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AnalysisXmlConvertConfigDialg.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/AnalysisXmlConvertConfigDialg.java
package net.heartsome.cat.ts.ui.advanced.dialogs; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.MessageFormat; import java.util.Map; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.Activator; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; 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.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 分析XML转换配置文件 * @author robert 2012-02-25 * @version * @since JDK1.6 */ public class AnalysisXmlConvertConfigDialg extends XmlConvertManagerDialog { private Text analysisTxt; private Button okBtn; /** 正在分析的XML的路径 */ private String curAnalysisXmlLocation; private Image icon = Activator.getImageDescriptor("icons/tips.gif").createImage(); public AnalysisXmlConvertConfigDialg(Shell parentShell) { super(parentShell); root = ResourcesPlugin.getWorkspace().getRoot(); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.title")); } @Override protected boolean isResizable() { return true; } @Override protected Control createButtonBar(Composite parent) { Composite buttonCmp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); buttonCmp.setLayout(layout); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); buttonCmp.setLayoutData(data); buttonCmp.setFont(parent.getFont()); Composite leftCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(leftCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).equalWidth(false).applyTo(leftCmp); addBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.addBtn"), false); editBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.editBtn"), false); deleteBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.deleteBtn"), false); Composite rightCmp = new Composite(buttonCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).equalWidth(false).applyTo(rightCmp); new Label(rightCmp, SWT.NONE); Label separatorLbl = new Label(buttonCmp, SWT.HORIZONTAL | SWT.SEPARATOR); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(separatorLbl); new Label(buttonCmp, SWT.NONE); Composite bottomCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(false, false).applyTo(bottomCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(2).applyTo(bottomCmp); okBtn = createButton(bottomCmp, IDialogConstants.OK_ID, Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.ok"), false); okBtn.setEnabled(false); // 禁用确定按钮 createButton(bottomCmp, IDialogConstants.CANCEL_ID, Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.cancel"), true).setFocus(); initListener(); return buttonCmp; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(700, 500).applyTo(tparent); createRootTxt(tparent); createTable(tparent); return tparent; } private void createRootTxt(Composite tparent) { Composite composite = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(composite); GridLayoutFactory.fillDefaults().spacing(0, 1).numColumns(5).applyTo(composite); Label analysisXmlLbl = new Label(composite, SWT.NONE); analysisXmlLbl.setText(Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.analysisXmlLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(analysisXmlLbl); Composite browseCmp = new Composite(composite, SWT.NONE); GridDataFactory.fillDefaults().indent(6, SWT.DEFAULT).grab(true, false).span(4, SWT.DEFAULT).applyTo(browseCmp); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(0, 0, 0, 0).applyTo(browseCmp); analysisTxt = new Text(browseCmp, SWT.BORDER); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(analysisTxt); Button browseBtn = new Button(browseCmp, SWT.NONE); browseBtn.setText(Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.browseBtn")); Label rootLbl = new Label(composite, SWT.NONE); rootLbl.setText(Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.rootLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(rootLbl); rootTxt = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().indent(6, SWT.DEFAULT).hint(100, SWT.DEFAULT).applyTo(rootTxt); // 显示一个图标与“被保存到:” Label iconLbl = new Label(composite, SWT.NONE); iconLbl.setImage(icon); GridDataFactory.fillDefaults().indent(4, SWT.DEFAULT).applyTo(iconLbl); Label textLbl = new Label(composite, SWT.NONE); textLbl.setText(Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.textLbl")); rootTipLbl = new Label(composite, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).align(SWT.LEFT, SWT.CENTER).applyTo(rootTipLbl); rootTxt.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String tipText = root.getFullPath().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootTxt.getText().trim().toLowerCase() + ".xml").toOSString(); rootTipLbl.setText(tipText); rootTipLbl.pack(); rootTipLbl.setToolTipText(tipText); } }); // 在添加状态下,当根元素文本框失去焦点后,验证是否为空,验证是否重复 rootTxt.addFocusListener(new org.eclipse.swt.events.FocusAdapter() { public void focusLost(FocusEvent e) { String rootStr = rootTxt.getText().trim().toLowerCase(); if ("".equals(rootStr)) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msgTitle"), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msg1")); } else { // 提示文件是否重复 String configXmlLoaction = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); File xmlConfigFile = new File(configXmlLoaction); if (xmlConfigFile.exists()) { String configXmlFullPath = root.getFullPath().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); MessageDialog.openInformation(getShell(), Messages .getString("dialogs.AnalysisXmlConvertConfigDialg.msgTitle"), MessageFormat.format( Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msg2"), configXmlFullPath)); } } super.focusLost(e); } }); browseBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog fd = new FileDialog(getShell(), SWT.OPEN); String[] extensions = { "*.xml", "*" }; String[] names = { Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.filterXML"), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.filterAll") }; fd.setText(Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.fdTitle")); fd.setFilterExtensions(extensions); fd.setFilterNames(names); String xmlLocation = fd.open(); analysisTxt.setText(xmlLocation); // 解析XML文件并且填充到列表 analysisXml(xmlLocation); } }); analysisTxt.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { analysisXml(analysisTxt.getText()); super.focusLost(e); } }); } @Override protected void okPressed() { String rootStr = rootTxt.getText().trim(); // 验证根元素是否为空 if (rootStr == null || "".equals(rootStr)) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msgTitle"), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msg1")); return; } // 创建文件 String configXmlLoaction = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr.toLowerCase() + ".xml").toOSString(); System.out.println("configXmlLoaction = " + configXmlLoaction); File configXml = new File(configXmlLoaction); if (configXml.exists()) { String configXmlFullPath = root.getFullPath().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); boolean response = MessageDialog.openConfirm(getShell(), Messages .getString("dialogs.AnalysisXmlConvertConfigDialg.msgTitle2"), MessageFormat.format( Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msg3"), configXmlFullPath)); if (!response) { return; } } curConvertXml = configXmlLoaction; // 创建文件 createConfigXML(configXmlLoaction); super.okPressed(); } private void analysisXml(String xmlLocation) { curAnalysisXmlLocation = xmlLocation; // 如果所选文件不为空,就解析该文件 if (xmlLocation != null && !"".equals(xmlLocation)) { // 判断是否是文件 File xmlFile = new File(xmlLocation); if (xmlFile.isDirectory()) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msgTitle"), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msg4")); // 禁用okbutton okBtn.setEnabled(false); return; } if (!xmlFile.exists()) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msgTitle"), Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msg5")); okBtn.setEnabled(false); } String encoding = getEncoding(new File(xmlLocation)); if (!"UTF-8".equalsIgnoreCase(encoding)) { try { File tempFile = File.createTempFile("analysisXmlCverter", ".xml"); // File tempFile = new File("/home/robert/Desktop/test.xml"); copyFile(xmlLocation, tempFile.getAbsolutePath(), encoding, "utf-8"); xmlLocation = tempFile.getAbsolutePath(); tempFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } } // 开始填充表格 Map<String, Object> newResultMap = handler.openFile(xmlLocation, null); // 文件解析出错 if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap .get(QAConstant.RETURNVALUE_RESULT)) { MessageDialog.openInformation(getShell(), Messages .getString("dialogs.AnalysisXmlConvertConfigDialg.msgTitle"), MessageFormat.format( Messages.getString("dialogs.AnalysisXmlConvertConfigDialg.msg6"), xmlLocation)); // 禁用okbutton okBtn.setEnabled(false); return; } okBtn.setEnabled(true); elementsList = handler.getAnalysisXmlData(xmlLocation); refreshTable(null); } } @Override public boolean close() { if(icon != null && !icon.isDisposed()){ icon.dispose(); } return super.close(); } public static String getEncoding(File file) { String charset = "GBK"; byte[] first3Bytes = new byte[3]; boolean checked = false; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); bis.mark(0); int read = bis.read(first3Bytes, 0, 3); if (read == -1) return charset; if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) { charset = "UTF-16LE"; checked = true; } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) { charset = "UTF-16BE"; checked = true; } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) { charset = "UTF-8"; checked = true; } bis.reset(); if (!checked) { int loc = 0; while ((read = bis.read()) != -1) { loc++; if (read >= 0xF0) break; if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK break; if (0xC0 <= read && read <= 0xDF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)// (0x80 - 0xBF),也可能在GB编码内 continue; else break; } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小 read = bis.read(); if (0x80 <= read && read <= 0xBF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else break; } else break; } } } bis.close(); } catch (Exception e) { e.printStackTrace(); } return charset; } private static void copyFile(String oldFile, String newFilePath, String strOldEncoding, String strNewEncoding) throws Exception { FileInputStream fileInputStream = null; InputStreamReader inputStreamRead = null; BufferedReader bufferRead = null; BufferedWriter newFileBW = null; OutputStreamWriter outputStreamWriter = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(oldFile); inputStreamRead = new InputStreamReader(fileInputStream, strOldEncoding); bufferRead = new BufferedReader(inputStreamRead); fileOutputStream = new FileOutputStream(newFilePath, false); outputStreamWriter = new OutputStreamWriter(fileOutputStream, strNewEncoding); newFileBW = new BufferedWriter(outputStreamWriter); String strTSVLine = ""; while ((strTSVLine = bufferRead.readLine()) != null) { if (strTSVLine.equals("")) { continue; } newFileBW.write(strTSVLine.replaceAll("Shift_JIS", "UTF-8")); newFileBW.write("\n"); } } finally { if (bufferRead != null) bufferRead.close(); if (newFileBW != null) { newFileBW.flush(); newFileBW.close(); } } } }
15,673
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CatalogManagerDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/CatalogManagerDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.TableViewerLabelProvider; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; 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; import org.eclipse.swt.widgets.TableItem; public class CatalogManagerDialog extends Dialog { private Button addBtn; private Button deleteBtn; private Button editBtn; private TableViewer tableViewer; private IWorkspaceRoot root; private ADXmlHandler adHandler; private Table table; private String catalogXmlLocation; public CatalogManagerDialog(Shell parentShell, IWorkspaceRoot root) { super(parentShell); this.root = root; catalogXmlLocation = root.getLocation().append(ADConstants.catalogueXmlPath).toOSString(); } @Override protected boolean isResizable() { return true; } @Override protected void configureShell(Shell newShell) { // TODO Auto-generated method stub super.configureShell(newShell); newShell.setText(Messages.getString("dialogs.CatalogManagerDialog.title")); } @Override protected void createButtonsForButtonBar(Composite parent) { addBtn = createButton(parent, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.CatalogManagerDialog.addBtn"), false); editBtn = createButton(parent, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.CatalogManagerDialog.editBtn"), false); deleteBtn = createButton(parent, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.CatalogManagerDialog.deleteBtn"), false); createButton(parent, IDialogConstants.CANCEL_ID, Messages.getString("dialogs.CatalogManagerDialog.cancel"), true); initListener(); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true); parentData.widthHint = 700; parentData.heightHint = 400; tparent.setLayoutData(parentData); tableViewer = new TableViewer(tparent, SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.MULTI); table = tableViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); GridDataFactory.fillDefaults().grab(true, true).applyTo(table); String[] columnNames = new String[] { Messages.getString("dialogs.CatalogManagerDialog.columnNames1"), Messages.getString("dialogs.CatalogManagerDialog.columnNames2"), Messages.getString("dialogs.CatalogManagerDialog.columnNames3"), Messages.getString("dialogs.CatalogManagerDialog.columnNames4") }; int[] columnAlignments = new int[] { SWT.LEFT, SWT.LEFT, 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(getCatalogValue()); // 让列表列宽动态变化 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.08, 0.15, 0.36, 0.36 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); return tparent; } /** * 获取目录数据,从catalogue.xml文件中获取 * @return ; */ public String[][] getCatalogValue() { adHandler = new ADXmlHandler(); adHandler.openFile(catalogXmlLocation); return adHandler.getCatalogValueList(catalogXmlLocation).toArray(new String[][] {}); } /** * 给三个按钮添加事件 ; */ public void initListener() { addBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { AddOrEditCatalogDialog addDialog = new AddOrEditCatalogDialog(getShell(), root, adHandler, true); // 如果是点击的确定按钮,那么更新数据 if (addDialog.open() == IDialogConstants.OK_ID) { String[][] cataValue = getCatalogValue(); tableViewer.setInput(cataValue); tableViewer.getTable().setSelection(cataValue.length - 1); tableViewer.getTable().showSelection(); } } }); // <public publicId="-//W3C//DTD XMLSCHEMA 200102//EN" uri="xml/XMLSchema.dtd"/> // <system systemId="xliff.dtd" uri="xliff/xliff.dtd"/> // <uri name="http://www.heartsome.net.cn/2008/XLFExtension" uri="heartsome/XLFExtension.xsd"/> // <nextCatalog catalog="docbook5.0/catalog.xml"/> deleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (table.getSelectionCount() >= 1) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("dialogs.CatalogManagerDialog.msgTitle"), Messages.getString("dialogs.CatalogManagerDialog.msg1")); if (!response) { return; } TableItem[] selectItems = table.getSelection(); List<String> xpathList = new LinkedList<String>(); List<String[]> dataList = new LinkedList<String[]>(); for (int i = 0; i < selectItems.length; i++) { String name = selectItems[i].getText(1); String id = selectItems[i].getText(2); String url = selectItems[i].getText(3); StringBuffer xpathSB = new StringBuffer(); if ("public".equalsIgnoreCase(name)) { xpathSB.append("/catalog/public[@publicId='" + id + "' and @uri='" + url + "']"); } else if ("system".equalsIgnoreCase(name)) { xpathSB.append("/catalog/system[@systemId='" + id + "' and @uri='" + url + "']"); } else if ("uri".equalsIgnoreCase(name)) { xpathSB.append("/catalog/uri[@name='" + id + "' and @uri='" + url + "']"); } else if ("nextCatalog".equalsIgnoreCase(name)) { xpathSB.append("/catalog/nextCatalog[@catalog='" + url + "']"); } xpathList.add(xpathSB.toString()); dataList.add(new String[] { name, id, url }); } adHandler.deleteCatalog(catalogXmlLocation, xpathList, dataList); tableViewer.setInput(getCatalogValue()); // 更新列表 } else { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.CatalogManagerDialog.msgTitle2"), Messages.getString("dialogs.CatalogManagerDialog.msg2")); } } }); editBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editCatalog(); } }); table.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { editCatalog(); } }); } public void editCatalog() { if (table.getSelectionCount() >= 1) { TableItem item = table.getSelection()[0]; String name = item.getText(1); String id = item.getText(2); String url = item.getText(3); String xpath = ""; if ("public".equalsIgnoreCase(name)) { xpath = ("/catalog/public[@publicId='" + id + "' and @uri='" + url + "']"); } else if ("system".equalsIgnoreCase(name)) { xpath = ("/catalog/system[@systemId='" + id + "' and @uri='" + url + "']"); } else if ("uri".equalsIgnoreCase(name)) { xpath = ("/catalog/uri[@name='" + id + "' and @uri='" + url + "']"); } else if ("nextCatalog".equalsIgnoreCase(name)) { xpath = ("/catalog/nextCatalog[@catalog='" + url + "']"); } AddOrEditCatalogDialog dialog = new AddOrEditCatalogDialog(getShell(), root, adHandler, false); dialog.create(); dialog.setInitData(name, id, url, xpath); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { tableViewer.setInput(getCatalogValue()); // 更新列表 } } else { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.CatalogManagerDialog.msgTitle2"), Messages.getString("dialogs.CatalogManagerDialog.msg3")); } } }
9,095
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddOrEditElementOfXmlConvertDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/AddOrEditElementOfXmlConvertDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs; import java.text.MessageFormat; import java.util.Iterator; import java.util.List; import net.heartsome.cat.ts.ui.advanced.model.ElementBean; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * XML转换器配置的元素配置,包括添加或修改 * @author robert 2012-02-23 * @version * @since JDK1.6 */ public class AddOrEditElementOfXmlConvertDialog extends Dialog { /** 是否是添加界面 */ private boolean isAdd; /** 元素名称文本框 */ private Text nameTxt; /** 类型下拉框 */ private Combo typeCmb; /** 内联类型下拉框 */ private Combo inlineCmb; /** 可翻译属性文本框 */ private Text transAtrriTxt; /** 保留空格下拉框 */ private Combo remainSpaceCmb; private List<ElementBean> elementsList; /** 当前所添加,或修改的元素,用于操作之后列表的定位 */ private ElementBean currentElement; public AddOrEditElementOfXmlConvertDialog(Shell parentShell, boolean isAdd, List<ElementBean> elementsList) { super(parentShell); this.isAdd = isAdd; this.elementsList = elementsList; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.title")); } @Override protected boolean isResizable() { return true; } @Override protected void createButtonsForButtonBar(Composite parent) { super.createButtonsForButtonBar(parent); getButton(IDialogConstants.OK_ID).setText(Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.ok")); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).applyTo(tparent); Composite composite = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(composite); // 元素类型下拉框的值, 备注:不能本地化 String[] typeValues = { "segment", "inline", "ignore" }; // 内联类型下拉框的值, 备注:不能本地化 String[] internalValues = { "", "image", "pb", "lb", "x-bold", "x-entry", "x-font", "x-italic", "x-link", "x-underlined", "x-other" }; // 保留空格下拉框的值, 备注:不能本地化 String[] remainSpaceVlaues = { "", "yes", "no" }; GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false); textData.widthHint = 100; // 元素名称 Label nameLbl = new Label(composite, SWT.NONE); nameLbl.setText(Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.nameLbl")); nameLbl.setAlignment(SWT.RIGHT); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(nameLbl); nameTxt = new Text(composite, SWT.BORDER); nameTxt.setLayoutData(textData); // 元素类型 Label typeLbl = new Label(composite, SWT.NONE); typeLbl.setText(Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.typeLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(typeLbl); typeCmb = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); typeCmb.setLayoutData(textData); typeCmb.setItems(typeValues); typeCmb.select(0); // 内联类型 Label inlineLbl = new Label(composite, SWT.NONE); inlineLbl.setText(Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.inlineLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(inlineLbl); inlineCmb = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); inlineCmb.setLayoutData(textData); inlineCmb.setItems(internalValues); inlineCmb.setEnabled(false); // 可翻译属性 Label transAttriLbl = new Label(composite, SWT.NONE); transAttriLbl.setText(Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.transAttriLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(transAttriLbl); transAtrriTxt = new Text(composite, SWT.BORDER); transAtrriTxt.setLayoutData(textData); // 保留空格 Label remainSpaceLbl = new Label(composite, SWT.NONE); remainSpaceLbl.setText(Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.remainSpaceLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(remainSpaceLbl); remainSpaceCmb = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); remainSpaceCmb.setLayoutData(textData); remainSpaceCmb.setItems(remainSpaceVlaues); // 当元素类型是segment时,禁用内联内型,当元素类型是inline时,禁用可翻译属性。当元素类型是ignore时,禁用可翻译属性与内联内型 typeCmb.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String type = typeCmb.getText(); if ("segment".equals(type)) { inlineCmb.setText(""); inlineCmb.setEnabled(false); transAtrriTxt.setEnabled(true); } else if ("inline".equals(type)) { inlineCmb.setEnabled(true); transAtrriTxt.setText(""); transAtrriTxt.setEnabled(false); } else if ("ignore".equals(type)) { inlineCmb.setText(""); inlineCmb.setEnabled(false); transAtrriTxt.setText(""); transAtrriTxt.setEnabled(false); } } }); return tparent; } @Override protected void okPressed() { String elementName = nameTxt.getText().trim(); // 添加 if (isAdd) { int index = -1; // 验证是否为空 if (validNameNull(elementName)) { return; } else { ElementBean element = new ElementBean(elementName, typeCmb.getText(), inlineCmb.getText(), transAtrriTxt.getText().trim(), remainSpaceCmb.getText()); // 验证添加的元素名是否重复 if ((index = validrepeat(elementName)) != -1) { boolean response = MessageDialog.openConfirm(getShell(), Messages .getString("dialogs.AddOrEditElementOfXmlConvertDialog.msgTitle1"), MessageFormat.format( Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.msg1"), elementName)); if (response) { elementsList.set(index, element); } else { return; } } else { // 没有重复。则添加 elementsList.add(element); } currentElement = element; } } else {// 这是修改 // 验证是否为空 if (validNameNull(elementName)) { return; } else { int index = elementsList.indexOf(currentElement); ElementBean element = new ElementBean(elementName, typeCmb.getText(), inlineCmb.getText(), transAtrriTxt.getText().trim(), remainSpaceCmb.getText()); elementsList.set(index, element); currentElement = element; } } super.okPressed(); } /** * 设置编辑时的初始化数据 ; */ public void setInitEditData(ElementBean bean) { nameTxt.setText(bean.getName()); typeCmb.setText(bean.getType()); inlineCmb.setText(bean.getInlineType()); transAtrriTxt.setText(bean.getTransAttribute()); remainSpaceCmb.setText(bean.getRemainSpace()); currentElement = bean; } /** * 验证所要添加的元素名是否重复 返回重复元素的下标值,若返回-1,则标志不重复 * @return ; */ public int validrepeat(String elementName) { Iterator<ElementBean> iter = elementsList.iterator(); ElementBean bean; while (iter.hasNext()) { bean = iter.next(); if (elementName.equals(bean.getName())) { return elementsList.indexOf(bean); } } return -1; } public ElementBean getElementBean(String elementName) { ElementBean bean; Iterator<ElementBean> iter = elementsList.iterator(); while (iter.hasNext()) { bean = iter.next(); if (elementName.equals(bean.getName())) { return bean; } } return null; } public ElementBean getCurrentElement() { return currentElement; } /** * 验证元素名是否为空,针对用户未在元素名一栏填写元素名 * @param elementName * @return ;若为空,则为true */ public boolean validNameNull(String elementName) { if (elementName == null || "".equals(elementName)) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.msgTitle2"), Messages.getString("dialogs.AddOrEditElementOfXmlConvertDialog.msg2")); nameTxt.setFocus(); return true; } return false; } }
9,076
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XmlConverterConfigurationDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/XmlConverterConfigurationDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs; import java.io.File; import java.io.FilenameFilter; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.TableViewerLabelProvider; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; 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.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.PlatformUI; /** * XML转换器配制器的主窗口 * @author robert 2012-02-22 * @version * @since JDK1.6 */ public class XmlConverterConfigurationDialog extends TrayDialog { private Button addBtn; private Button editBtn; private Button deleteBtn; private Button analysisBtn; /** xml转换器配置文件所在的目录 */ private String configXmlFolderLocation; private TableViewer tableViewer; private Table table; private IWorkspaceRoot root; public XmlConverterConfigurationDialog(Shell parentShell, String configXmlFolderLocation) { super(parentShell); this.configXmlFolderLocation = configXmlFolderLocation; root = ResourcesPlugin.getWorkspace().getRoot(); } @Override protected boolean isResizable() { return true; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("dialogs.XmlConverterConfigurationDialog.title")); } /** * 添加帮助按钮,备注,这里的配置与其他的不一样 * robert 2012-09-06 */ protected Control createHelpToolItem(Composite parent) { // ROBERTHELP xml 转换器配置 String language = CommonFunction.getSystemLanguage(); final String helpUrl = MessageFormat.format( "/net.heartsome.cat.ts.ui.help/html/{0}/ch08.html#configure-xml-converter", language); Image helpImage = JFaceResources.getImage(DLG_IMG_HELP); ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS); toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND); toolBar.setCursor(cursor); toolBar.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { cursor.dispose(); } }); ToolItem helpItem = new ToolItem(toolBar, SWT.NONE); helpItem.setImage(helpImage); helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$ helpItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl); } }); return toolBar; } @Override protected Control createButtonBar(Composite parent) { Composite buttonCmp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); buttonCmp.setLayout(layout); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); buttonCmp.setLayoutData(data); buttonCmp.setFont(parent.getFont()); Composite leftCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(leftCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).equalWidth(false).applyTo(leftCmp); addBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.XmlConverterConfigurationDialog.addBtn"), false); editBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.XmlConverterConfigurationDialog.editBtn"), false); deleteBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.XmlConverterConfigurationDialog.deleteBtn"), false); Composite rightCmp = new Composite(buttonCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).equalWidth(false).applyTo(rightCmp); analysisBtn = createButton(rightCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.XmlConverterConfigurationDialog.analysisBtn"), false); Label separatorLbl = new Label(buttonCmp, SWT.HORIZONTAL | SWT.SEPARATOR); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(separatorLbl); createHelpToolItem(buttonCmp); Composite bottomCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(false, false).align(SWT.RIGHT, SWT.CENTER).applyTo(bottomCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).applyTo(bottomCmp); createButton(bottomCmp, IDialogConstants.CANCEL_ID, Messages.getString("dialogs.XmlConverterConfigurationDialog.cancel"), true).setFocus(); initListener(); return buttonCmp; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(400, 450).minSize(400, 450).applyTo(tparent); tableViewer = new TableViewer(tparent, SWT.FULL_SELECTION | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); table = tableViewer.getTable(); table.setLinesVisible(true); table.setHeaderVisible(true); GridDataFactory.fillDefaults().grab(true, true).applyTo(table); tableViewer.setLabelProvider(new TableViewerLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); String[] columnNames = new String[] { Messages.getString("dialogs.XmlConverterConfigurationDialog.columnNames1"), Messages.getString("dialogs.XmlConverterConfigurationDialog.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); // 处理排序的问题 switch (i) { case 0: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; // 升序 @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? XmlConvertOrder.index_ASC : XmlConvertOrder.index_DESC); asc = !asc; } }); break; case 1: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; // 升序 @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? XmlConvertOrder.xmlName_ASC : XmlConvertOrder.xmlName_DESC); asc = !asc; } }); break; default: break; } } tableViewer.setInput(getXmlConfigFilesInfo()); // 让列表列宽动态变化 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.85 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { editConfigXml(); } }); return tparent; } public void initListener() { addBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { AddOrEditXmlConvertConfigDialog dialog = new AddOrEditXmlConvertConfigDialog(getShell(), true); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { String curentConvertXMl = dialog.getCurentConverXML(); refreshTable(); setTableSelection(curentConvertXMl); } } }); editBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editConfigXml(); } }); deleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> iter = structuredSelection.iterator(); while (iter.hasNext()) { String convertXmlName = iter.next()[1]; String convertXmlLoaction = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder) .append(convertXmlName).toOSString(); File convertXml = new File(convertXmlLoaction); convertXml.delete(); } refreshTable(); } else { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.XmlConverterConfigurationDialog.msgTitle"), Messages.getString("dialogs.XmlConverterConfigurationDialog.msg1")); } } }); analysisBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { AnalysisXmlConvertConfigDialg dialog = new AnalysisXmlConvertConfigDialg(getShell()); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { String curentConvertXMl = dialog.getCurentConverXML(); refreshTable(); setTableSelection(curentConvertXMl); } } }); } public void refreshTable() { tableViewer.setInput(getXmlConfigFilesInfo()); } /** * 查询位于configXmlFolderLocation目录下的所有xml转换器的配置文件 * @return ; */ public String[][] getXmlConfigFilesInfo() { List<String[]> infoList = new LinkedList<String[]>(); File[] array = new File(configXmlFolderLocation).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.startsWith("config_") && name.endsWith(".xml")) {return true;} //$NON-NLS-1$ //$NON-NLS-2$ return false; } }); for (int i = 0; i < array.length; i++) { infoList.add(new String[] { "" + (i + 1), array[i].getName() }); } return infoList.toArray(new String[][] {}); } /** * 编辑转换配置XML文件 ; */ public void editConfigXml() { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> iter = structuredSelection.iterator(); String convertXml = iter.next()[1]; AddOrEditXmlConvertConfigDialog dialog = new AddOrEditXmlConvertConfigDialog(getShell(), false); dialog.create(); String convertXmlLoaction = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder) .append(convertXml).toOSString(); if (dialog.setInitEditData(convertXmlLoaction)) { int result = dialog.open(); // 如果点击的是确定按钮,那么更新列表 if (result == IDialogConstants.OK_ID) { String curentConvertXMl = dialog.getCurentConverXML(); refreshTable(); setTableSelection(curentConvertXMl); } } } else { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.XmlConverterConfigurationDialog.msgTitle"), Messages.getString("dialogs.XmlConverterConfigurationDialog.msg2")); } } /** * 选中列中表中已经编辑或已经添加的文件 * @param curentConvertXMl * ; */ public void setTableSelection(String curConvertXMl) { File convertXml = new File(curConvertXMl); String convertXmlName = convertXml.getName(); TableItem[] items = table.getItems(); for (int i = 0; i < items.length; i++) { if (items[i].getText(1).equals(convertXmlName)) { table.setSelection(i); return; } } } /** * XML转换器列表排序类 * @author robert * @version * @since JDK1.6 */ public static class XmlConvertOrder extends ViewerSorter { private static final int index_ID = 1; // 第一行,序列 private static final int xmlName_ID = 2; // 第二行,XML转换文件名称 public static final XmlConvertOrder index_ASC = new XmlConvertOrder(index_ID); public static final XmlConvertOrder index_DESC = new XmlConvertOrder(-index_ID); public static final XmlConvertOrder xmlName_ASC = new XmlConvertOrder(xmlName_ID); public static final XmlConvertOrder xmlName_DESC = new XmlConvertOrder(-xmlName_ID); private int sortType; private XmlConvertOrder(int sortType) { this.sortType = sortType; } @Override public int compare(Viewer viewer, Object e1, Object e2) { String[] data1 = (String[]) e1; String[] data2 = (String[]) e2; switch (sortType) { case index_ID: { int lineNumber1 = Integer.parseInt(data1[index_ID - 1]); int lineNumber2 = Integer.parseInt(data2[index_ID - 1]); return lineNumber1 > lineNumber2 ? 1 : -1; } case -index_ID: { int lineNumber1 = Integer.parseInt(data1[index_ID - 1]); int lineNumber2 = Integer.parseInt(data2[index_ID - 1]); return lineNumber1 > lineNumber2 ? -1 : 1; } case xmlName_ID: { String xmlName1 = data1[xmlName_ID - 1]; String xmlName2 = data2[xmlName_ID - 1]; return xmlName1.compareToIgnoreCase(xmlName2); } case -xmlName_ID: { String xmlName1 = data1[xmlName_ID - 1]; String xmlName2 = data2[xmlName_ID - 1]; return xmlName2.compareToIgnoreCase(xmlName1); } } return 0; } } }
15,398
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddOrEditXmlConvertConfigDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/AddOrEditXmlConvertConfigDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs; import java.io.File; import java.text.MessageFormat; import java.util.Map; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.Activator; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 添加或者修改xml转换配置文件 * @author robert 2012-02-22 * @version * @since JDK1.6 */ public class AddOrEditXmlConvertConfigDialog extends XmlConvertManagerDialog { private boolean isAdd; private Text rootTxt; private Label rootTipLbl; /** 编辑状态下的根元素 */ private String curRootStr; private Image icon = Activator.getImageDescriptor("icons/tips.gif").createImage(); public AddOrEditXmlConvertConfigDialog(Shell parentShell, boolean isAdd) { super(parentShell); this.isAdd = isAdd; root = ResourcesPlugin.getWorkspace().getRoot(); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(isAdd ? Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.title1") : Messages .getString("dialogs.AddOrEditXmlConvertConfigDialog.title2")); } @Override protected boolean isResizable() { return true; } @Override protected Control createButtonBar(Composite parent) { Composite buttonCmp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); buttonCmp.setLayout(layout); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); buttonCmp.setLayoutData(data); buttonCmp.setFont(parent.getFont()); Composite leftCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(leftCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).equalWidth(false).applyTo(leftCmp); addBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.addBtn"), false); editBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.editBtn"), false); deleteBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.deleteBtn"), false); Composite rightCmp = new Composite(buttonCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).equalWidth(false).applyTo(rightCmp); // createButton(rightCmp, IDialogConstants.CLIENT_ID, "分析XML(&N)", false); new Label(rightCmp, SWT.NONE); Label separatorLbl = new Label(buttonCmp, SWT.HORIZONTAL | SWT.SEPARATOR); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(separatorLbl); new Label(buttonCmp, SWT.NONE); Composite bottomCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(false, false).applyTo(bottomCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(2).applyTo(bottomCmp); createButton(bottomCmp, IDialogConstants.OK_ID, Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.ok"), false); createButton(bottomCmp, IDialogConstants.CANCEL_ID, Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.cancel"), true).setFocus(); initListener(); return buttonCmp; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(700, 500).applyTo(tparent); createRootTxt(tparent); createTable(tparent); return tparent; } /** * 创建xml根,与存储目录 * @param tparent * ; */ private void createRootTxt(Composite tparent) { Composite composite = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(composite); GridLayoutFactory.fillDefaults().spacing(0, SWT.DEFAULT).numColumns(5).applyTo(composite); Label rootLbl = new Label(composite, SWT.NONE); rootLbl.setText(Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.rootLbl")); rootTxt = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().indent(6, SWT.DEFAULT).hint(100, SWT.DEFAULT).applyTo(rootTxt); // 显示一个图标与“被保存到:” Label iconLbl = new Label(composite, SWT.NONE); iconLbl.setImage(icon); GridDataFactory.fillDefaults().indent(4, SWT.DEFAULT).applyTo(iconLbl); Label textLbl = new Label(composite, SWT.NONE); textLbl.setText(Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.textLbl")); rootTipLbl = new Label(composite, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).align(SWT.LEFT, SWT.CENTER).applyTo(rootTipLbl); rootTxt.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String tipText = root.getFullPath().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootTxt.getText().trim() + ".xml").toOSString(); rootTipLbl.setText(tipText); rootTipLbl.pack(); rootTipLbl.setToolTipText(tipText); } }); // 在添加状态下,当根元素文本框失去焦点后,验证是否为空,验证是否重复 rootTxt.addFocusListener(new org.eclipse.swt.events.FocusAdapter() { @Override public void focusLost(FocusEvent e) { String rootStr = rootTxt.getText().trim(); if (isAdd || (!rootStr.equals(curRootStr))) { if ("".equals(rootStr)) { MessageDialog.openWarning(getShell(), Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msgTitle1"), Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msg1")); } else { // 提示文件是否重复 String configXmlLoaction = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); File xmlConfigFile = new File(configXmlLoaction); if (xmlConfigFile.exists()) { String configXmlFullPath = root.getFullPath() .append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); MessageDialog.openWarning(getShell(), Messages .getString("dialogs.AddOrEditXmlConvertConfigDialog.msgTitle1"), MessageFormat .format(Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msg2"), configXmlFullPath)); } } super.focusLost(e); } } }); } @Override protected void okPressed() { String rootStr = rootTxt.getText().trim(); // 验证根元素是否为空 if (rootStr == null || "".equals(rootStr)) { MessageDialog.openWarning(getShell(), Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msgTitle1"), Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msg1")); return; } // 添加 if (isAdd) { // 创建文件 String configXmlLoaction = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); File configXml = new File(configXmlLoaction); if (configXml.exists()) { String configXmlFullPath = root.getFullPath().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); boolean response = MessageDialog.openConfirm(getShell(), Messages .getString("dialogs.AddOrEditXmlConvertConfigDialog.msgTitle2"), MessageFormat.format( Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msg3"), configXmlFullPath)); if (!response) { return; } } curConvertXml = configXmlLoaction; // 创建文件 createConfigXML(configXmlLoaction); } else { String configXmlLoaction = root.getLocation().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); // 编辑,如果根元素与当前所编辑的根元素不相等,那么检查是否重复 if (!rootStr.equals(curRootStr)) { File configXml = new File(configXmlLoaction); if (configXml.exists()) { String configXmlFullPath = root.getFullPath().append(ADConstants.AD_xmlConverterConfigFolder) .append("config_" + rootStr + ".xml").toOSString(); boolean response = MessageDialog.openConfirm(getShell(), Messages .getString("dialogs.AddOrEditXmlConvertConfigDialog.msgTitle2"), MessageFormat.format( Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msg4"), configXmlFullPath)); if (!response) { return; } } // 删除当前编辑的文件 File curEditFile = new File(curConvertXml); curEditFile.delete(); } curConvertXml = configXmlLoaction; // 覆盖或者生成新的文件 createConfigXML(configXmlLoaction); } super.okPressed(); } /** * 编辑状态下设置初始化数据 * @param convertXml * @return ; */ public boolean setInitEditData(String convertXml) { this.curConvertXml = convertXml; File xmlFile = new File(convertXml); // 开始填充表格 Map<String, Object> newResultMap = handler.openFile(curConvertXml, null); // 文件解析出错 if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap .get(QAConstant.RETURNVALUE_RESULT)) { MessageDialog.openWarning(getShell(), Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msgTitle1"), MessageFormat.format(Messages.getString("dialogs.AddOrEditXmlConvertConfigDialog.msg5"), xmlFile.getName())); return false; } // String fullPath = ResourceUtils.getIFileByLocation(curConfigXml).getFullPath().toOSString(); // System.out.println("fullPath = " + fullPath); elementsList = handler.getconvertXmlElements(convertXml); refreshTable(null); String xmlName = xmlFile.getName(); xmlName = xmlName.substring(7, xmlName.length() - 4); // 获取config_html.xml中的html rootTxt.setText(xmlName); curRootStr = xmlName; return true; } @Override public boolean close() { if(icon != null && !icon.isDisposed()){ icon.dispose(); } return super.close(); } }
11,206
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XmlConvertManagerDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/XmlConvertManagerDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs; import java.io.FileOutputStream; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.model.ElementBean; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * XMLl转换器管理(这是添加,和修改,和分析XML样式文件的父类) * @author robert 2012-02-27 * @version * @since JDK1.6 */ public class XmlConvertManagerDialog extends Dialog { private static final Logger LOGGER = LoggerFactory.getLogger(XmlConvertManagerDialog.class); protected TableViewer tableViewer; protected Table table; protected List<ElementBean> elementsList = new LinkedList<ElementBean>(); protected ADXmlHandler handler = new ADXmlHandler(); /** 当前生成的XML转换文件 */ protected String curConvertXml; protected Button addBtn; protected Button editBtn; protected Button deleteBtn; protected IWorkspaceRoot root; protected Text rootTxt; protected Label rootTipLbl; protected XmlConvertManagerDialog(Shell parentShell) { super(parentShell); } protected void createTable(Composite tparent) { tableViewer = new TableViewer(tparent, SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER); table = tableViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); GridDataFactory.fillDefaults().grab(true, true).applyTo(table); createTableColumns(); // 让列表列宽动态变化 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.2, 0.2, 0.2, 0.20, 0.14 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); tableViewer.setLabelProvider(new TViewerLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { editElement(); } }); } /** * 创建列表的头并且排序 ; */ private void createTableColumns() { String[] columnNames = new String[] { Messages.getString("dialogs.XmlConvertManagerDialog.columnNames1"), Messages.getString("dialogs.XmlConvertManagerDialog.columnNames2"), Messages.getString("dialogs.XmlConvertManagerDialog.columnNames3"), Messages.getString("dialogs.XmlConvertManagerDialog.columnNames4"), Messages.getString("dialogs.XmlConvertManagerDialog.columnNames5") }; int[] columnAlignments = new int[] { SWT.LEFT, SWT.LEFT, SWT.LEFT, 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); // 处理排序的问题 switch (i) { case 0: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? ElementsOrder.name_ASC : ElementsOrder.name_DESC); asc = !asc; } }); break; case 1: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? ElementsOrder.type_ASC : ElementsOrder.type_DESC); asc = !asc; } }); break; case 2: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? ElementsOrder.inlineType_ASC : ElementsOrder.inlineType_DESC); asc = !asc; } }); break; case 3: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? ElementsOrder.attributes_ASC : ElementsOrder.attributes_DESC); asc = !asc; } }); break; case 4: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? ElementsOrder.remainSpace_ASC : ElementsOrder.remainSpace_DESC); asc = !asc; } }); break; default: break; } } } /** * 刷新列表,并且定位 * @param bean * ; */ protected void refreshTable(ElementBean bean) { tableViewer.setInput(elementsList); if (bean != null) { tableViewer.setSelection(new StructuredSelection(bean)); } } /** * 给增删改三个按钮添加点击事件 ; */ protected void initListener() { addBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { AddOrEditElementOfXmlConvertDialog dialog = new AddOrEditElementOfXmlConvertDialog(getShell(), true, elementsList); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshTable(dialog.getCurrentElement()); } } }); editBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editElement(); } }); deleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { if (MessageDialog.openConfirm(getShell(), Messages.getString("dialogs.XmlConvertManagerDialog.msgTitle1"), Messages.getString("dialogs.XmlConvertManagerDialog.msg1"))) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<ElementBean> iter = structuredSelection.iterator(); ElementBean bean = new ElementBean(); while (iter.hasNext()) { bean = iter.next(); elementsList.remove(bean); } refreshTable(null); } } else { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.XmlConvertManagerDialog.msgTitle2"), Messages.getString("dialogs.XmlConvertManagerDialog.msg2")); } } }); } /** * 创建新的配置文件 * @param configXMLLocation * ; */ protected void createConfigXML(String configXMLLocation) { // 先创建一个空文本 try { FileOutputStream outPut = new FileOutputStream(configXMLLocation); StringBuffer configDataSB = new StringBuffer(); configDataSB.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); configDataSB .append("<!DOCTYPE ini-file PUBLIC \"-//HEARTSOME//Converters 2.0.0//EN\" \"configuration.dtd\">\n"); configDataSB.append("<ini-file>\n"); ElementBean bean; for (int i = 0; i < elementsList.size(); i++) { configDataSB.append("\t<tag "); bean = elementsList.get(i); // 添加元素类型 configDataSB.append(MessageFormat.format("hard-break=\"{0}\" ", bean.getType())); // 添加可翻译属性 String attributes = bean.getTransAttribute(); if (!"".equals(attributes) && attributes != null) { configDataSB.append(MessageFormat.format("attributes=\"{0}\" ", attributes)); } // 添加内联类型 String inlineType = bean.getInlineType(); if (!"".equals(inlineType) && inlineType != null) { configDataSB.append(MessageFormat.format("ctype=\"{0}\" ", inlineType)); } // 添加可保留空格属性 String remainSpace = bean.getRemainSpace(); if (!"".equals(remainSpace) && remainSpace != null) { configDataSB.append(MessageFormat.format("keep-format=\"{0}\" ", remainSpace)); } // 添加元素名 configDataSB.append(MessageFormat.format(">{0}</tag>\n", bean.getName())); } configDataSB.append("</ini-file>"); outPut.write(configDataSB.toString().getBytes("UTF-8")); outPut.close(); } catch (Exception e) { LOGGER.error("", e); } } public String getCurentConverXML() { return curConvertXml; } /** * 编辑选中的元素 ; */ protected void editElement() { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<ElementBean> iter = structuredSelection.iterator(); ElementBean bean = iter.next(); AddOrEditElementOfXmlConvertDialog dialog = new AddOrEditElementOfXmlConvertDialog(getShell(), false, elementsList); dialog.create(); dialog.setInitEditData(bean); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshTable(dialog.getCurrentElement()); } } else { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.XmlConvertManagerDialog.msgTitle2"), Messages.getString("dialogs.XmlConvertManagerDialog.msg3")); } } /** * XML配置文件列表的标签提供器 * @author robert 2012-02-24 * @version * @since JDK1.6 */ private class TViewerLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof ElementBean) { ElementBean bean = (ElementBean) element; switch (columnIndex) { case 0: return bean.getName(); case 1: return bean.getType(); case 2: return bean.getInlineType(); case 3: return bean.getTransAttribute(); case 4: return bean.getRemainSpace(); default: return null; } } return null; } } /** * XML转换器列表排序类 * @author robert * @version * @since JDK1.6 */ static class ElementsOrder extends ViewerSorter { private static final int name_ID = 1; // 第一列,元素名 private static final int type_ID = 2; // 第二列,元素类型 private static final int inlineType_ID = 3; // 第三列,内联类型 private static final int attributes_ID = 4; // 第四列,可翻译属性 private static final int remainSpace_ID = 5; // 第五行,保留空格 public static final ElementsOrder name_ASC = new ElementsOrder(name_ID); public static final ElementsOrder name_DESC = new ElementsOrder(-name_ID); public static final ElementsOrder type_ASC = new ElementsOrder(type_ID); public static final ElementsOrder type_DESC = new ElementsOrder(-type_ID); public static final ElementsOrder inlineType_ASC = new ElementsOrder(inlineType_ID); public static final ElementsOrder inlineType_DESC = new ElementsOrder(-inlineType_ID); public static final ElementsOrder attributes_ASC = new ElementsOrder(attributes_ID); public static final ElementsOrder attributes_DESC = new ElementsOrder(-attributes_ID); public static final ElementsOrder remainSpace_ASC = new ElementsOrder(remainSpace_ID); public static final ElementsOrder remainSpace_DESC = new ElementsOrder(-remainSpace_ID); private int sortType; private ElementsOrder(int sortType) { this.sortType = sortType; } @Override public int compare(Viewer viewer, Object e1, Object e2) { ElementBean bean1 = (ElementBean) e1; ElementBean bean2 = (ElementBean) e2; switch (sortType) { case name_ID: { String name1 = bean1.getName(); String name2 = bean2.getName(); return name1.compareToIgnoreCase(name2); } case -name_ID: { String name1 = bean1.getName(); String name2 = bean2.getName(); return name2.compareToIgnoreCase(name1); } case type_ID: { String type1 = bean1.getType(); String type2 = bean2.getType(); return type1.compareToIgnoreCase(type2); } case -type_ID: { String type1 = bean1.getType(); String type2 = bean2.getType(); return type2.compareToIgnoreCase(type1); } case inlineType_ID: { String inlineType1 = bean1.getInlineType(); String inlineType2 = bean2.getInlineType(); return inlineType1.compareToIgnoreCase(inlineType2); } case -inlineType_ID: { String inlineType1 = bean1.getInlineType(); String inlineType2 = bean2.getInlineType(); return inlineType2.compareToIgnoreCase(inlineType1); } case attributes_ID: { String attributes1 = bean1.getTransAttribute(); String attributes2 = bean2.getTransAttribute(); return attributes1.compareToIgnoreCase(attributes2); } case -attributes_ID: { String attributes1 = bean1.getTransAttribute(); String attributes2 = bean2.getTransAttribute(); return attributes2.compareToIgnoreCase(attributes1); } case remainSpace_ID: { String remainSpace1 = bean1.getRemainSpace(); String remainSpace2 = bean2.getRemainSpace(); return remainSpace1.compareToIgnoreCase(remainSpace2); } case -remainSpace_ID: { String remainSpace1 = bean1.getRemainSpace(); String remainSpace2 = bean2.getRemainSpace(); return remainSpace2.compareToIgnoreCase(remainSpace1); } } return 0; } } }
14,867
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddOrEditCatalogDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/AddOrEditCatalogDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs; import java.text.MessageFormat; import net.heartsome.cat.common.ui.dialog.FileFolderSelectionDialog; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.URIUtil; import org.eclipse.core.internal.filesystem.local.LocalFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 添加条目框 * @author robert 2011-02-20 * @version * @since JDK1.6 */ @SuppressWarnings("restriction") public class AddOrEditCatalogDialog extends Dialog { private Button publicBtn; private Button systermBtn; private Button uriBtn; private Button nextCataBtn; private Text idTxt; private Text urlTxt; private IWorkspaceRoot root; private ADXmlHandler adHandler; private String catalogXmlLocation; private Label idLbl; private boolean isAdd; private String curXpath; public AddOrEditCatalogDialog(Shell parentShell, IWorkspaceRoot root, ADXmlHandler adHandler, boolean isAdd) { super(parentShell); this.root = root; this.adHandler = adHandler; catalogXmlLocation = root.getLocation().append(ADConstants.catalogueXmlPath).toOSString(); this.isAdd = isAdd; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(isAdd ? Messages.getString("dialogs.AddOrEditCatalogDialog.title1") : Messages .getString("dialogs.AddOrEditCatalogDialog.title2")); } @Override protected Control createDialogArea(Composite parent) { Composite tParent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().hint(600, 150).grab(true, true).applyTo(tParent); Composite contentCmp = new Composite(tParent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(contentCmp); GridLayoutFactory.fillDefaults().numColumns(3).applyTo(contentCmp); GridData labelData = new GridData(SWT.FILL, SWT.CENTER, false, false); // 第一行,类型选择行 Label typeLbl = new Label(contentCmp, SWT.RIGHT | SWT.NONE); typeLbl.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.typeLbl")); typeLbl.setLayoutData(labelData); Composite radioCmp = new Composite(contentCmp, SWT.NONE); radioCmp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, SWT.DEFAULT)); radioCmp.setLayout(new GridLayout(4, false)); publicBtn = new Button(radioCmp, SWT.RADIO); publicBtn.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.publicBtn")); systermBtn = new Button(radioCmp, SWT.RADIO); systermBtn.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.systermBtn")); uriBtn = new Button(radioCmp, SWT.RADIO); uriBtn.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.uriBtn")); nextCataBtn = new Button(radioCmp, SWT.RADIO); nextCataBtn.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.nextCataBtn")); // 第二行--id行 idLbl = new Label(contentCmp, SWT.RIGHT); idLbl.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.idLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(idLbl); idTxt = new Text(contentCmp, SWT.BORDER); idTxt.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, SWT.DEFAULT)); // 第三行--url选择行 Label urlLbl = new Label(contentCmp, SWT.RIGHT); urlLbl.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.urlLbl")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(urlLbl); urlTxt = new Text(contentCmp, SWT.BORDER); urlTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); urlTxt.setEditable(false); Button browseBtn = new Button(contentCmp, SWT.NONE); browseBtn.setText(Messages.getString("dialogs.AddOrEditCatalogDialog.browseBtn")); browseBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { browseFiles(); } public void widgetDefaultSelected(SelectionEvent e) { browseFiles(); } }); publicBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { displayIdTxt(true); } }); systermBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { displayIdTxt(true); } }); uriBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { displayIdTxt(true); } }); nextCataBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { displayIdTxt(false); } }); return tParent; } @Override protected void okPressed() { if (!publicBtn.getSelection() && !systermBtn.getSelection() && !uriBtn.getSelection() && !nextCataBtn.getSelection()) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AddOrEditCatalogDialog.msgTitle"), Messages.getString("dialogs.AddOrEditCatalogDialog.msg1")); return; } StringBuffer strB = new StringBuffer(); if (publicBtn.getSelection()) { strB.append(MessageFormat.format("{2}<public publicId=\"{0}\" uri=\"{1}\"/>", new Object[] { idTxt.getText(), urlTxt.getText(), isAdd ? "\t" : "" })); } else if (systermBtn.getSelection()) { strB.append(MessageFormat.format("{2}<system systemId=\"{0}\" uri=\"{1}\" />", new Object[] { idTxt.getText(), urlTxt.getText(), isAdd ? "\t" : "" })); } else if (uriBtn.getSelection()) { strB.append(MessageFormat.format("{2}<uri name=\"{0}\" uri=\"{1}\" />", new Object[] { idTxt.getText(), urlTxt.getText(), isAdd ? "\t" : "" })); } else if (nextCataBtn.getSelection()) { strB.append(MessageFormat.format("{1}<nextCatalog catalog=\"{0}\" />", new Object[] { urlTxt.getText(), isAdd ? "\t" : "" })); } // 添加 if (isAdd) { if (!adHandler.addDataToXml(catalogXmlLocation, "/catalog", strB.toString())) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AddOrEditCatalogDialog.msgTitle"), Messages.getString("dialogs.AddOrEditCatalogDialog.msg2")); } } else { // 修改 if (!adHandler.updataDataToXml(catalogXmlLocation, curXpath, strB.toString())) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.AddOrEditCatalogDialog.msgTitle"), Messages.getString("dialogs.AddOrEditCatalogDialog.msg2")); } } super.okPressed(); } public void setInitData(String name, String id, String url, String curXpath) { this.curXpath = curXpath; if ("public".equalsIgnoreCase(name)) { publicBtn.setSelection(true); idTxt.setText(id); urlTxt.setText(url); } else if ("system".equalsIgnoreCase(name)) { systermBtn.setSelection(true); idTxt.setText(id); urlTxt.setText(url); } else if ("uri".equalsIgnoreCase(name)) { uriBtn.setSelection(true); idTxt.setText(id); urlTxt.setText(url); } else if ("nextCatalog".equalsIgnoreCase(name)) { nextCataBtn.setSelection(true); displayIdTxt(false); urlTxt.setText(url); } } public void displayIdTxt(boolean isDisplay) { idLbl.setVisible(isDisplay); idTxt.setVisible(isDisplay); } /** * 选择文件 ; */ public void browseFiles() { FileFolderSelectionDialog dialog = new FileFolderSelectionDialog(getShell(), false, IResource.FILE); dialog.setMessage(Messages.getString("dialogs.AddOrEditCatalogDialog.dialogMsg")); dialog.setDoubleClickSelects(true); try { dialog.setInput(EFS.getStore(URIUtil.toURI(root.getLocation().append(ADConstants.cataloguePath)))); } catch (CoreException e1) { e1.printStackTrace(); } dialog.create(); dialog.getShell().setText(Messages.getString("dialogs.AddOrEditCatalogDialog.dialogTitle")); dialog.open(); if (dialog.getFirstResult() != null) { Object object = dialog.getFirstResult(); if (object instanceof LocalFile) { LocalFile localFile = (LocalFile) object; String location = localFile.toString(); String catalogurePath = root.getLocation().append(ADConstants.cataloguePath).toOSString(); String uriStr = ""; if (location.indexOf(catalogurePath) != -1) { uriStr = location.substring(location.indexOf(catalogurePath) + catalogurePath.length(), location.length()); } uriStr = uriStr.substring(1, uriStr.length()); urlTxt.setText(uriStr); } } } }
9,237
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SrxMapRulesManageDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/srx/SrxMapRulesManageDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs.srx; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.model.MapRuleBean; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; 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.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; public class SrxMapRulesManageDialog extends Dialog { private Button addBtn; private Button editBtn; private Button deleteBtn; private Text nameTxt; private TableViewer tableViewer; private Table table; private List<MapRuleBean> mapRulesList = new LinkedList<MapRuleBean>(); private boolean isAdd; private ADXmlHandler handler; private String srxLocation; private String curMapRuleName; public SrxMapRulesManageDialog(Shell parentShell, boolean isAdd, ADXmlHandler handler, String srxLocation) { super(parentShell); this.isAdd = isAdd; this.handler = handler; this.srxLocation = srxLocation; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("srx.SrxMapRulesManageDialog.title")); } @Override protected boolean isResizable() { return true; } @Override protected Control createButtonBar(Composite parent) { Composite buttonCmp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); buttonCmp.setLayout(layout); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); buttonCmp.setLayoutData(data); buttonCmp.setFont(parent.getFont()); Composite leftCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(leftCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).equalWidth(false).applyTo(leftCmp); addBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxMapRulesManageDialog.addBtn"), false); editBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxMapRulesManageDialog.editBtn"), false); deleteBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxMapRulesManageDialog.deleteBtn"), false); Composite rightCmp = new Composite(buttonCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).equalWidth(false).applyTo(rightCmp); new Label(rightCmp, SWT.NONE); Label separatorLbl = new Label(buttonCmp, SWT.HORIZONTAL | SWT.SEPARATOR); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(separatorLbl); new Label(buttonCmp, SWT.NONE); Composite bottomCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(false, false).applyTo(bottomCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(2).applyTo(bottomCmp); createButton(bottomCmp, IDialogConstants.OK_ID, Messages.getString("srx.SrxMapRulesManageDialog.ok"), false); createButton(bottomCmp, IDialogConstants.CANCEL_ID, Messages.getString("srx.SrxMapRulesManageDialog.cancel"), true).setFocus(); initListener(); return buttonCmp; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(600, 500).minSize(600, 500).applyTo(tparent); Composite nameCmp = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(nameCmp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(nameCmp); Label nameLbl = new Label(nameCmp, SWT.NONE); nameLbl.setText(Messages.getString("srx.SrxMapRulesManageDialog.nameLbl")); nameTxt = new Text(nameCmp, SWT.BORDER); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(nameTxt); createTable(tparent); return tparent; } private void createTable(Composite tparent) { tableViewer = new TableViewer(tparent, SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); table = tableViewer.getTable(); table.setLinesVisible(true); table.setHeaderVisible(true); GridDataFactory.fillDefaults().span(4, SWT.DEFAULT).grab(true, true).applyTo(table); tableViewer.setLabelProvider(new TViewerLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); String[] columnNames = new String[] { Messages.getString("srx.SrxMapRulesManageDialog.columnNames1"), Messages.getString("srx.SrxMapRulesManageDialog.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); } // 让列表列宽动态变化 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.2, 0.77 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { editMapRule(); } }); } public void initListener() { addBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { AddOrEditMapRuleOfSrxDialog dialog = new AddOrEditMapRuleOfSrxDialog(getShell(), true, mapRulesList, handler, srxLocation); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshTable(dialog.getCurMapRuleBean()); } } }); editBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editMapRule(); } }); deleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { boolean respose = MessageDialog.openConfirm(getShell(), Messages.getString("srx.SrxMapRulesManageDialog.msgTitle"), Messages.getString("srx.SrxMapRulesManageDialog.msg1")); if (!respose) { return; } StructuredSelection structSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<MapRuleBean> it = structSelection.iterator(); while (it.hasNext()) { mapRulesList.remove(it.next()); } refreshTable(null); } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxMapRulesManageDialog.msgTitle2"), Messages.getString("srx.SrxMapRulesManageDialog.msg2")); } } }); } /** * 更新语言列表 * @param bean * ; */ private void refreshTable(MapRuleBean bean) { tableViewer.setInput(mapRulesList); if (bean != null) { // 定位操作 tableViewer.setSelection(new StructuredSelection(bean)); } } @Override protected void okPressed() { String mapRuleName = nameTxt.getText().trim(); if (mapRuleName == null || "".equals(mapRuleName)) { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxMapRulesManageDialog.msgTitle2"), Messages.getString("srx.SrxMapRulesManageDialog.msg3")); nameTxt.setFocus(); return; } if (isAdd) { // 先验证所添加的语言规则名是否存在,如果存在就提示 boolean isExist = handler.validNodeExist(srxLocation, "/srx/body/maprules/maprule[@maprulename='" + mapRuleName + "']"); if (isExist) { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxMapRulesManageDialog.msgTitle2"), MessageFormat.format(Messages.getString("srx.SrxMapRulesManageDialog.msg4"), mapRuleName)); return; } String languageRulesData = buildLangRules(mapRuleName); boolean addResult = handler.addMapRules(srxLocation, languageRulesData); if (!addResult) { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxMapRulesManageDialog.msgTitle2"), Messages.getString("srx.SrxMapRulesManageDialog.msg5")); } } else { // 在编辑的情况 // 首先判断语言规则节点名是否被修改,如果被修改,要判断其修改后的节点名是否已经存在,如果存在,则提示是否覆盖 if (!curMapRuleName.equals(mapRuleName)) { boolean isExist = handler.validNodeExist(srxLocation, "/srx/body/maprules/maprule[@maprulename='" + mapRuleName + "']"); if (isExist) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.SrxMapRulesManageDialog.msgTitle"), MessageFormat.format(Messages.getString("srx.SrxMapRulesManageDialog.msg6"), mapRuleName)); // 如果选择覆盖,那么先删除与修改后同节点名的那个节点,再修改相对应的数据 if (response) { handler.deleteNode(srxLocation, "/srx/body/maprules/maprule[@maprulename='" + mapRuleName + "']"); } else { return; } } } String newData = buildLangRules(mapRuleName); handler.updataDataToXml(srxLocation, "/srx/body/maprules/maprule[@maprulename='" + curMapRuleName + "']", newData); } curMapRuleName = mapRuleName; super.okPressed(); } public void editMapRule() { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { StructuredSelection structSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<MapRuleBean> it = structSelection.iterator(); if (it.hasNext()) { MapRuleBean selectBean = it.next(); AddOrEditMapRuleOfSrxDialog dialog = new AddOrEditMapRuleOfSrxDialog(getShell(), false, mapRulesList, handler, srxLocation); dialog.create(); dialog.setEditInitData(selectBean); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshTable(dialog.getCurMapRuleBean()); } } refreshTable(null); } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxMapRulesManageDialog.msgTitle2"), Messages.getString("srx.SrxMapRulesManageDialog.msg2")); } } public String getCurMapRuleName() { return curMapRuleName; } public void setEditInitData(String mapRuleName) { curMapRuleName = mapRuleName; nameTxt.setText(mapRuleName); mapRulesList = handler.getMapRulesByName(srxLocation, mapRuleName); refreshTable(null); } private String buildLangRules(String mapRuleName) { StringBuffer mapRuleSB = new StringBuffer(); mapRuleSB.append(MessageFormat.format("<maprule maprulename=\"{0}\">\n", mapRuleName)); for (int i = 0; i < mapRulesList.size(); i++) { MapRuleBean mapRuleBean = mapRulesList.get(i); String languageModel = mapRuleBean.getLanguageModel(); String languageRuleName = mapRuleBean.getLangRuleName(); mapRuleSB.append(MessageFormat.format( "\t<languagemap languagepattern=\"{0}\" languagerulename=\"{1}\"/>\n", new Object[] { languageModel, languageRuleName })); } mapRuleSB.append(MessageFormat.format("</maprule>\n", mapRuleName)); return mapRuleSB.toString(); } /** * 印射规则列表标签提供器 * @author robert 2012-03-02 * @version * @since JDK1.6 */ private class TViewerLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof MapRuleBean) { MapRuleBean bean = (MapRuleBean) element; switch (columnIndex) { case 0: return bean.getLanguageModel(); case 1: return bean.getLangRuleName(); default: return null; } } return null; } } }
13,800
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SrxLanguageRulesManageDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/srx/SrxLanguageRulesManageDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs.srx; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.model.LanguageRuleBean; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; 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.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; /** * SRX的语言规则管理器 * @author robert 2012-02-29 * @version * @since JDK1.6 */ public class SrxLanguageRulesManageDialog extends Dialog { private Button addBtn; private Button editBtn; private Button deleteBtn; private Text nameTxt; private TableViewer tableViewer; private Table table; private List<LanguageRuleBean> langRulesList = new LinkedList<LanguageRuleBean>(); private boolean isAdd; private ADXmlHandler handler; private String srxLocation; private String curLanguageRuleName; public SrxLanguageRulesManageDialog(Shell parentShell, boolean isAdd, ADXmlHandler handler, String srxLocation) { super(parentShell); this.isAdd = isAdd; this.handler = handler; this.srxLocation = srxLocation; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("srx.SrxLanguageRulesManageDialog.title")); } @Override protected boolean isResizable() { return true; } @Override protected Control createButtonBar(Composite parent) { Composite buttonCmp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); buttonCmp.setLayout(layout); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); buttonCmp.setLayoutData(data); buttonCmp.setFont(parent.getFont()); Composite leftCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(leftCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).equalWidth(false).applyTo(leftCmp); addBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxLanguageRulesManageDialog.addBtn"), false); editBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxLanguageRulesManageDialog.editBtn"), false); deleteBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxLanguageRulesManageDialog.deleteBtn"), false); Composite rightCmp = new Composite(buttonCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).equalWidth(false).applyTo(rightCmp); new Label(rightCmp, SWT.NONE); Label separatorLbl = new Label(buttonCmp, SWT.HORIZONTAL | SWT.SEPARATOR); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(separatorLbl); new Label(buttonCmp, SWT.NONE); Composite bottomCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(false, false).applyTo(bottomCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(2).applyTo(bottomCmp); createButton(bottomCmp, IDialogConstants.OK_ID, Messages.getString("srx.SrxLanguageRulesManageDialog.ok"), false); createButton(bottomCmp, IDialogConstants.CANCEL_ID, Messages.getString("srx.SrxLanguageRulesManageDialog.cancel"), true).setFocus(); initListener(); return buttonCmp; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(600, 500).minSize(600, 500).applyTo(tparent); Composite nameCmp = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(nameCmp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(nameCmp); Label nameLbl = new Label(nameCmp, SWT.NONE); nameLbl.setText(Messages.getString("srx.SrxLanguageRulesManageDialog.nameLbl")); nameTxt = new Text(nameCmp, SWT.BORDER); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(nameTxt); createTable(tparent); return tparent; } private void createTable(Composite tparent) { tableViewer = new TableViewer(tparent, SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); table = tableViewer.getTable(); table.setLinesVisible(true); table.setHeaderVisible(true); GridDataFactory.fillDefaults().span(4, SWT.DEFAULT).grab(true, true).applyTo(table); tableViewer.setLabelProvider(new TViewerLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); String[] columnNames = new String[] { Messages.getString("srx.SrxLanguageRulesManageDialog.columnNames1"), Messages.getString("srx.SrxLanguageRulesManageDialog.columnNames2"), Messages.getString("srx.SrxLanguageRulesManageDialog.columnNames3") }; int[] columnAlignments = new int[] { SWT.LEFT, 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); } // 让列表列宽动态变化 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.2, 0.37, 0.37 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { editLangRule(); } }); } @Override protected void okPressed() { String langRuleName = nameTxt.getText().trim(); if (langRuleName == null || "".equals(langRuleName)) { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxLanguageRulesManageDialog.msgTitle"), Messages.getString("srx.SrxLanguageRulesManageDialog.msg1")); nameTxt.setFocus(); return; } // 如果是添加 if (isAdd) { // 先验证所添加的语言规则名是否存在,如果存在就提示 boolean isExist = handler.validNodeExist(srxLocation, "/srx/body/languagerules/languagerule[@languagerulename='" + langRuleName + "']"); if (isExist) { MessageDialog .openInformation(getShell(), Messages.getString("srx.SrxLanguageRulesManageDialog.msgTitle"), MessageFormat.format(Messages.getString("srx.SrxLanguageRulesManageDialog.msg2"), langRuleName)); return; } String languageRulesData = buildLangRules(langRuleName); boolean addResult = handler.addLanguageRules(srxLocation, languageRulesData); if (!addResult) { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxLanguageRulesManageDialog.msgTitle"), Messages.getString("srx.SrxLanguageRulesManageDialog.msg3")); } } else { // 在编辑的情况 // 首先判断语言规则节点名是否被修改,如果被修改,要判断其修改后的节点名是否已经存在,如果存在,则提示是否覆盖 if (!curLanguageRuleName.equals(langRuleName)) { boolean isExist = handler.validNodeExist(srxLocation, "/srx/body/languagerules/languagerule[@languagerulename='" + langRuleName + "']"); if (isExist) { boolean response = MessageDialog.openConfirm(getShell(), Messages .getString("srx.SrxLanguageRulesManageDialog.msgTitle2"), MessageFormat.format( Messages.getString("srx.SrxLanguageRulesManageDialog.msg4"), langRuleName)); // 如果选择覆盖,那么先删除与修改后同节点名的那个节点,再修改相对应的数据 if (response) { handler.deleteNode(srxLocation, "/srx/body/languagerules/languagerule[@languagerulename='" + langRuleName + "']"); } else { return; } } // 同步修改映射中的语言规则名称 handler.updateMapRuleLangName(srxLocation, "/srx/body/maprules/maprule/languagemap[@languagerulename='" + curLanguageRuleName + "']", langRuleName); } String newData = buildLangRules(langRuleName); handler.updataDataToXml(srxLocation, "/srx/body/languagerules/languagerule[@languagerulename='" + curLanguageRuleName + "']", newData); } curLanguageRuleName = langRuleName; super.okPressed(); } public void initListener() { addBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { AddOrEditLangRuleOfSrxDialog dialog = new AddOrEditLangRuleOfSrxDialog(getShell(), true, langRulesList); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshTable(dialog.getCurLangRuleBean()); } } }); editBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editLangRule(); } }); deleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { boolean respose = MessageDialog.openConfirm(getShell(), Messages.getString("srx.SrxLanguageRulesManageDialog.msgTitle2"), Messages.getString("srx.SrxLanguageRulesManageDialog.msg5")); if (!respose) { return; } StructuredSelection structSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<LanguageRuleBean> it = structSelection.iterator(); while (it.hasNext()) { langRulesList.remove(it.next()); } refreshTable(null); } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxLanguageRulesManageDialog.msgTitle"), Messages.getString("srx.SrxLanguageRulesManageDialog.msg6")); } } }); } /** * 更新语言列表 * @param bean * ; */ private void refreshTable(LanguageRuleBean bean) { tableViewer.setInput(langRulesList); if (bean != null) { // 定位操作 tableViewer.setSelection(new StructuredSelection(bean)); } } public void editLangRule() { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { StructuredSelection structSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<LanguageRuleBean> it = structSelection.iterator(); // 只修改选中规则中的一个 if (it.hasNext()) { LanguageRuleBean selectBean = it.next(); AddOrEditLangRuleOfSrxDialog editDialog = new AddOrEditLangRuleOfSrxDialog(getShell(), false, langRulesList); editDialog.create(); editDialog.setEditInitData(selectBean); int editResult = editDialog.open(); if (editResult == IDialogConstants.OK_ID) { refreshTable(editDialog.getCurLangRuleBean()); } } } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxLanguageRulesManageDialog.msgTitle"), Messages.getString("srx.SrxLanguageRulesManageDialog.msg7")); } } /** * 开始组装语言规则的字符串 ; */ public String buildLangRules(String langRuleName) { StringBuffer rulesSB = new StringBuffer(); rulesSB.append(MessageFormat.format("<languagerule languagerulename=\"{0}\">\n", langRuleName)); for (int i = 0; i < langRulesList.size(); i++) { LanguageRuleBean language = langRulesList.get(i); String isBreak = language.getIsBreak(); String preBreak = language.getPreBreak(); String afterBreak = language.getAfterBreak(); rulesSB.append(MessageFormat.format("\t<rule break=\"{0}\">\n", isBreak)); rulesSB.append(MessageFormat.format("\t\t<beforebreak>{0}</beforebreak>\n", preBreak)); rulesSB.append(MessageFormat.format("\t\t<afterbreak>{0}</afterbreak>\n", afterBreak)); rulesSB.append("\t</rule>\n"); } rulesSB.append(MessageFormat.format("</languagerule>\n", langRuleName)); return rulesSB.toString(); } public String getCurLanguageRuleName() { return curLanguageRuleName; } /** * 编辑状态下赋初始化值 * @param langRuleName */ public void setEditInitData(String langRuleName) { curLanguageRuleName = langRuleName; nameTxt.setText(langRuleName); langRulesList = handler.getLangRulesByName(srxLocation, langRuleName); refreshTable(null); } /** * 语言规则列表标签提供器 * @author robert 2012-02-29 * @version * @since JDK1.6 */ private class TViewerLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof LanguageRuleBean) { LanguageRuleBean bean = (LanguageRuleBean) element; switch (columnIndex) { case 0: return bean.getIsBreak(); case 1: return bean.getPreBreak(); case 2: return bean.getAfterBreak(); default: return null; } } return null; } } }
14,857
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddOrEditMapRuleOfSrxDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/srx/AddOrEditMapRuleOfSrxDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs.srx; import java.util.List; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.model.MapRuleBean; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 添加或修改映射规则窗体 * @author robert 2012-03-02 * @version * @since JDK1.6 */ public class AddOrEditMapRuleOfSrxDialog extends Dialog { private ADXmlHandler handler; private boolean isAdd; private Text langModelTxt; private Combo langRuleNameCmb; private List<MapRuleBean> mapRulesList; private MapRuleBean curMapRuleBean; private String srxLocation; public AddOrEditMapRuleOfSrxDialog(Shell parentShell, boolean isAdd, List<MapRuleBean> mapRulesList, ADXmlHandler handler, String srxLocation) { super(parentShell); this.isAdd = isAdd; this.mapRulesList = mapRulesList; this.handler = handler; this.srxLocation = srxLocation; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(isAdd ? Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.title1") : Messages .getString("srx.AddOrEditMapRuleOfSrxDialog.title2")); } @Override protected boolean isResizable() { return true; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).applyTo(tparent); Composite langCmp = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).hint(450, 100).applyTo(langCmp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(langCmp); Label modelLbl = new Label(langCmp, SWT.NONE); modelLbl.setText(Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.modelLbl")); GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false); langModelTxt = new Text(langCmp, SWT.BORDER); langModelTxt.setLayoutData(textData); Label langRuleNameLbl = new Label(langCmp, SWT.NONE); langRuleNameLbl.setText(Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.langRuleNameLbl")); langRuleNameCmb = new Combo(langCmp, SWT.BORDER | SWT.READ_ONLY); langRuleNameCmb.setLayoutData(textData); // 给语言规则名称下拉框赋值 langRuleNameCmb.setItems(handler.getLanguageRuleNamesOfSrx_2(srxLocation).toArray(new String[] {})); return tparent; } @Override protected void okPressed() { String langModel = langModelTxt.getText().trim(); String langRuleName = langRuleNameCmb.getText().trim(); MapRuleBean bean = new MapRuleBean(langModel, langRuleName); if ("".equals(langModel) || "".equals(langRuleName)) { MessageDialog.openInformation(getShell(), Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.msgTitle1"), Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.msg1")); return; } if (isAdd) { // 添加之前验证是否重复 if (mapRulesList.indexOf(bean) == -1) { mapRulesList.add(bean); this.curMapRuleBean = bean; } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.msgTitle1"), Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.msg2")); return; } } else { // 先验证是否该条数据是否已经被修改,如果已经被修改,但是修改后的数据已经存在,那么直接覆盖 if (!curMapRuleBean.equals(bean)) { if (mapRulesList.indexOf(bean) != -1) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.msgTitle2"), Messages.getString("srx.AddOrEditMapRuleOfSrxDialog.msg3")); if (response) { mapRulesList.remove(curMapRuleBean); curMapRuleBean = bean; } else { return; } } else { // 如果修改后的数据没有重复,那么删除修改之前的数据,并且添加到修改前数据的位置 mapRulesList.add(mapRulesList.indexOf(curMapRuleBean), bean); mapRulesList.remove(curMapRuleBean); curMapRuleBean = bean; } } } super.okPressed(); } public MapRuleBean getCurMapRuleBean() { return curMapRuleBean; } public void setEditInitData(MapRuleBean editBean) { curMapRuleBean = editBean; langModelTxt.setText(editBean.getLanguageModel()); langRuleNameCmb.setText(editBean.getLangRuleName()); } }
4,862
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SrxConfigurationDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/srx/SrxConfigurationDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs.srx; import java.io.File; import java.io.FilenameFilter; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.TableViewerLabelProvider; import net.heartsome.cat.ts.ui.advanced.dialogs.XmlConverterConfigurationDialog.XmlConvertOrder; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; 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.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.PlatformUI; /** * 配置分段规则的第一个对话框,即显示出所有分段规则文件的对话框 * @author robert 2012-02-28 * @version * @since JDK1.6 */ public class SrxConfigurationDialog extends TrayDialog { private Button addBtn; private Button editBtn; private Button deleteBtn; private TableViewer tableViewer; private Table table; private IWorkspaceRoot root; private ADXmlHandler handler = new ADXmlHandler(); /** 系统默认的分段规则名称 */ private static final String[] systemSrxName = new String[]{"default_rules.srx", "trados_rules.srx"}; private Cursor cursorWait = new Cursor(Display.getDefault(), SWT.CURSOR_WAIT); private Cursor cursorArrow = new Cursor(Display.getDefault(), SWT.CURSOR_ARROW); public SrxConfigurationDialog(Shell parentShell) { super(parentShell); root = ResourcesPlugin.getWorkspace().getRoot(); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("srx.SrxConfigurationDialog.title")); } @Override protected boolean isResizable() { return true; } /** * 添加帮助按钮,备注,这里的配置与其他的不一样 * robert 2012-09-06 */ protected Control createHelpToolItem(Composite parent) { // ROBERTHELP 分段规则管理器 String language = CommonFunction.getSystemLanguage(); final String helpUrl = MessageFormat.format( "/net.heartsome.cat.ts.ui.help/html/{0}/ch05s03#segmentation-rule-manager", language); Image helpImage = JFaceResources.getImage(DLG_IMG_HELP); ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS); toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND); toolBar.setCursor(cursor); toolBar.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { cursor.dispose(); } }); ToolItem helpItem = new ToolItem(toolBar, SWT.NONE); helpItem.setImage(helpImage); helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$ helpItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl); } }); return toolBar; } @Override protected Control createButtonBar(Composite parent) { Composite buttonCmp = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); buttonCmp.setLayout(layout); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false); buttonCmp.setLayoutData(data); buttonCmp.setFont(parent.getFont()); Composite leftCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(leftCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).equalWidth(false).applyTo(leftCmp); addBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxConfigurationDialog.addBtn"), false); editBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxConfigurationDialog.editBtn"), false); deleteBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID, Messages.getString("srx.SrxConfigurationDialog.deleteBtn"), false); Composite rightCmp = new Composite(buttonCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).equalWidth(false).applyTo(rightCmp); new Label(rightCmp, SWT.NONE); Label separatorLbl = new Label(buttonCmp, SWT.HORIZONTAL | SWT.SEPARATOR); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(separatorLbl); // new Label(buttonCmp, SWT.NONE); createHelpToolItem(buttonCmp); Composite bottomCmp = new Composite(buttonCmp, SWT.NONE); GridDataFactory.fillDefaults().grab(false, false).applyTo(bottomCmp); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(1).applyTo(bottomCmp); createButton(bottomCmp, IDialogConstants.CANCEL_ID, Messages.getString("srx.SrxConfigurationDialog.cancel"), true).setFocus(); initListener(); return buttonCmp; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(400, 400).minSize(400, 400).applyTo(tparent); tableViewer = new TableViewer(tparent, SWT.FULL_SELECTION | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); table = tableViewer.getTable(); table.setLinesVisible(true); table.setHeaderVisible(true); GridDataFactory.fillDefaults().grab(true, true).applyTo(table); tableViewer.setLabelProvider(new TableViewerLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); String[] columnNames = new String[] { Messages.getString("srx.SrxConfigurationDialog.columnNames1"), Messages.getString("srx.SrxConfigurationDialog.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); // 处理排序的问题 switch (i) { case 0: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; // 升序 @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? XmlConvertOrder.index_ASC : XmlConvertOrder.index_DESC); asc = !asc; } }); break; case 1: tableColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; // 升序 @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? XmlConvertOrder.xmlName_ASC : XmlConvertOrder.xmlName_DESC); asc = !asc; } }); break; default: break; } } tableViewer.setInput(getSRXConfigFilesInfo()); // 让列表列宽动态变化 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.85 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { editSrx(); } }); refreshTable(null); return tparent; } /** * 给增删改三个按钮提示添加事件 ; */ private void initListener() { addBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { CreateOrUpdataSRXDialog createDialog = new CreateOrUpdataSRXDialog(getShell(), true); int createResult = createDialog.open(); if (IDialogConstants.OK_ID == createResult) { String addedSrxName = createDialog.getCurSrxName(); // 添加完成该文件后,解析该文件 boolean openResult = openSrx(ADConstants.configLocation + ADConstants.AD_SRXConfigFolder + File.separator + addedSrxName); if (!openResult) { return; } AddOrEditSrxConfigDialog addDialog = new AddOrEditSrxConfigDialog(getShell(), addedSrxName, handler); addDialog.open(); refreshTable(addedSrxName); } } }); editBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editSrx(); } }); deleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.SrxConfigurationDialog.msgTitle1"), Messages.getString("srx.SrxConfigurationDialog.msg1")); if (!response) { return; } StructuredSelection structSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> it = structSelection.iterator(); File deleteSrx; boolean isTiped = false; while (it.hasNext()) { String srxName = it.next()[1]; if (isSystemSrx(srxName)) { if (!isTiped) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.CatalogManagerDialog.msgTitle2"), Messages.getString("srx.SrxConfigurationDialog.msg4")); isTiped = true; } continue; } deleteSrx = new File(ADConstants.configLocation + ADConstants.AD_SRXConfigFolder + File.separator + srxName); if (!deleteSrx.delete()) { MessageDialog.openInformation(getShell(), Messages .getString("srx.SrxConfigurationDialog.msgTitle2"), MessageFormat.format( Messages.getString("srx.SrxConfigurationDialog.msg2"), srxName)); } } refreshTable(null); } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.SrxConfigurationDialog.msgTitle2"), Messages.getString("srx.SrxConfigurationDialog.msg3")); } } }); } @Override protected void okPressed() { super.okPressed(); } /** * 编辑SRX文件 ; */ private void editSrx() { ISelection selection = tableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { StructuredSelection structSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> it = structSelection.iterator(); if (it.hasNext()) { String srxName = it.next()[1]; if (isSystemSrx(srxName)) { MessageDialog.openInformation(getShell(), Messages.getString("dialogs.CatalogManagerDialog.msgTitle2"), Messages.getString("srx.SrxConfigurationDialog.msg4")); return; } CreateOrUpdataSRXDialog editDialog = new CreateOrUpdataSRXDialog(getShell(), false); editDialog.create(); editDialog.setEditInitData(srxName); int result = editDialog.open(); if (result == IDialogConstants.OK_ID) { String editedSrxName = editDialog.getCurSrxName(); if (!openSrx(ADConstants.configLocation + ADConstants.AD_SRXConfigFolder + File.separator + editedSrxName)) { return; } AddOrEditSrxConfigDialog addDialog = new AddOrEditSrxConfigDialog(getShell(), editedSrxName, handler); addDialog.open(); refreshTable(editedSrxName); } } } } /** * 判断指定的 分段规则是否是 系统默认的分段规则,因为系统默认的分段规则是不充许修改与删除的 * @param srxName * @return true 是系统默认的分段规则 false 不是系统默认的分段规则 */ private boolean isSystemSrx(String srxName){ boolean isSystem = false; for(String curSrxName : systemSrxName){ if (curSrxName.equals(srxName)) { isSystem = true; } } return isSystem; } public String[][] getSRXConfigFilesInfo() { getShell().setCursor(cursorWait); String srxConfigLocation = ADConstants.configLocation + ADConstants.AD_SRXConfigFolder; File[] array = new File(srxConfigLocation).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.endsWith(".srx")) {return true;} //$NON-NLS-1$ //$NON-NLS-2$ return false; } }); List<String[]> srxFileInfoList = new LinkedList<String[]>(); // 解析每个文件,查看其是否符合SRX标准 for (int i = 0; i < array.length; i++) { File srxFile = array[i]; Map<String, Object> newResultMap = handler.openFile(srxFile.getAbsolutePath()); // 文件解析出错 if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap .get(QAConstant.RETURNVALUE_RESULT)) { continue; } if (handler.validSrx(srxFile.getAbsolutePath())) { srxFileInfoList.add(new String[] { "" + (srxFileInfoList.size() + 1), srxFile.getName() }); } } getShell().setCursor(cursorArrow); return srxFileInfoList.toArray(new String[][] {}); } /** * 刷新列表,如果srxName(SRX文件名)不为空,还要定位到当前文件名 * @param srxName * ; */ public void refreshTable(String srxName) { tableViewer.setInput(getSRXConfigFilesInfo()); if (srxName != null) { TableItem[] items = table.getItems(); for (int i = 0; i < items.length; i++) { if (srxName.equals(items[i].getText(1))) { table.setSelection(i); } } } } private boolean openSrx(String srxLocation) { Map<String, Object> newResultMap = handler.openFile(srxLocation); // 文件解析出错 if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap .get(QAConstant.RETURNVALUE_RESULT)) { return false; } return true; } @Override public boolean close() { if(cursorArrow != null && !cursorArrow.isDisposed()){ cursorArrow.dispose(); } if(cursorWait != null && !cursorWait.isDisposed()){ cursorWait.dispose(); } return super.close(); } }
16,062
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddOrEditSrxConfigDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/srx/AddOrEditSrxConfigDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs.srx; import java.io.File; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.TableViewerLabelProvider; import net.heartsome.cat.ts.ui.advanced.handlers.ADXmlHandler; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; 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.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; /** * 添加或修改srx文件 * @author robert * @version * @since JDK1.6 */ public class AddOrEditSrxConfigDialog extends Dialog { private String curSrxName; private TableViewer langTableViewer; private Table langTable; private Button langAddBtn; private Button langEditBtn; private Button langDeleteBtn; private TableViewer mapTableViewer; private Table mapTable; private Button mapAddBtn; private Button mapEditBtn; private Button mapDeleteBtn; private ADXmlHandler handler; private IWorkspaceRoot root; private String srxLocation; public AddOrEditSrxConfigDialog(Shell parentShell, String curSrxName, ADXmlHandler handler) { super(parentShell); this.curSrxName = curSrxName; this.handler = handler; root = ResourcesPlugin.getWorkspace().getRoot(); srxLocation = ADConstants.configLocation + ADConstants.AD_SRXConfigFolder + File.separator + curSrxName; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.title")); } @Override protected boolean isResizable() { return true; } @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.CANCEL_ID, Messages.getString("srx.AddOrEditSrxConfigDialog.cancel"), true); } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(500, 500).minSize(500, 500).applyTo(tparent); Composite nameCmp = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(nameCmp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(nameCmp); Label nameLbl = new Label(nameCmp, SWT.NONE); nameLbl.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.nameLbl")); Text nameTxt = new Text(nameCmp, SWT.BORDER); nameTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); nameTxt.setText(curSrxName); nameTxt.setEnabled(false); GridData groupData = new GridData(SWT.FILL, SWT.FILL, true, true); GridLayout groupLayout = new GridLayout(4, false); createLanguageGroup(tparent, groupData, groupLayout); createMapGroup(tparent, groupData, groupLayout); initListener(); refreshLangTable(null); refreshMapTable(null); return tparent; } /** * 创建语言规则配置 * @param tparent * ; */ private void createLanguageGroup(Composite tparent, GridData groupData, GridLayout groupLayout) { Group group = new Group(tparent, SWT.BORDER); group.setLayoutData(groupData); group.setLayout(groupLayout); group.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.groupLang")); langTableViewer = new TableViewer(group, SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); langTable = langTableViewer.getTable(); langTable.setLinesVisible(true); langTable.setHeaderVisible(true); GridDataFactory.fillDefaults().span(4, SWT.DEFAULT).grab(true, true).applyTo(langTable); langTableViewer.setLabelProvider(new TableViewerLabelProvider()); langTableViewer.setContentProvider(new ArrayContentProvider()); String[] columnNames = new String[] { Messages.getString("srx.AddOrEditSrxConfigDialog.langColumnNames1"), Messages.getString("srx.AddOrEditSrxConfigDialog.langColumnNames2") }; int[] columnAlignments = new int[] { SWT.LEFT, SWT.LEFT }; for (int i = 0; i < columnNames.length; i++) { TableColumn tableColumn = new TableColumn(langTable, columnAlignments[i]); tableColumn.setText(columnNames[i]); tableColumn.setWidth(50); } refreshTableWidth(langTable); langAddBtn = new Button(group, SWT.NONE); langAddBtn.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.langAddBtn")); setButtonLayoutData(langAddBtn); langEditBtn = new Button(group, SWT.NONE); langEditBtn.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.langEditBtn")); setButtonLayoutData(langEditBtn); langDeleteBtn = new Button(group, SWT.NONE); langDeleteBtn.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.langDeleteBtn")); setButtonLayoutData(langDeleteBtn); new Label(group, SWT.NONE); langTableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { editLangRules(); } }); } /** * 创建映身 * @param tparent * ; */ private void createMapGroup(Composite tparent, GridData groupData, GridLayout groupLayout) { Group group = new Group(tparent, SWT.BORDER); group.setLayoutData(groupData); group.setLayout(groupLayout); group.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.group")); mapTableViewer = new TableViewer(group, SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); mapTable = mapTableViewer.getTable(); mapTable.setLinesVisible(true); mapTable.setHeaderVisible(true); GridDataFactory.fillDefaults().span(4, SWT.DEFAULT).grab(true, true).applyTo(mapTable); mapTableViewer.setLabelProvider(new TableViewerLabelProvider()); mapTableViewer.setContentProvider(new ArrayContentProvider()); String[] columnNames = new String[] { Messages.getString("srx.AddOrEditSrxConfigDialog.columnNames1"), Messages.getString("srx.AddOrEditSrxConfigDialog.columnNames2") }; int[] columnAlignments = new int[] { SWT.LEFT, SWT.LEFT }; for (int i = 0; i < columnNames.length; i++) { TableColumn tableColumn = new TableColumn(mapTable, columnAlignments[i]); tableColumn.setText(columnNames[i]); tableColumn.setWidth(50); } refreshTableWidth(mapTable); mapAddBtn = new Button(group, SWT.NONE); mapAddBtn.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.mapAddBtn")); setButtonLayoutData(mapAddBtn); mapEditBtn = new Button(group, SWT.NONE); mapEditBtn.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.mapEditBtn")); setButtonLayoutData(mapEditBtn); mapDeleteBtn = new Button(group, SWT.NONE); mapDeleteBtn.setText(Messages.getString("srx.AddOrEditSrxConfigDialog.mapDeleteBtn")); setButtonLayoutData(mapDeleteBtn); new Label(group, SWT.NONE); mapTableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { editMapRules(); } }); } @Override protected void okPressed() { // TODO Auto-generated method stub super.okPressed(); } public void initListener() { // 语言规则下添加按钮 langAddBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { SrxLanguageRulesManageDialog dialog = new SrxLanguageRulesManageDialog(getShell(), true, handler, srxLocation); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshLangTable(dialog.getCurLanguageRuleName()); } } }); langEditBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editLangRules(); } }); langDeleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = langTableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.AddOrEditSrxConfigDialog.msgTitle1"), Messages.getString("srx.AddOrEditSrxConfigDialog.msg1")); if (!response) { return; } StructuredSelection struSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> it = struSelection.iterator(); List<String> deleRuleNameList = new LinkedList<String>(); List<String> mapedRuleNameList = new LinkedList<String>(); while (it.hasNext()) { // 获取所选中的语言规则的名称 String langRuleName = it.next()[1]; if (handler.checkLangRuleNameMaped(srxLocation, langRuleName)) { mapedRuleNameList.add(langRuleName); continue; } deleRuleNameList.add(langRuleName); } // 如果要删除的语言规则已经被映射,提示是否删除 if (mapedRuleNameList.size() > 0) { String mapedNameStr = ""; for (int i = 0; i < mapedRuleNameList.size(); i++) { mapedNameStr += " '" + mapedRuleNameList.get(i) + "'、"; } mapedNameStr = mapedNameStr.substring(0, mapedNameStr.length() - 1); boolean deleResponse = MessageDialog.openConfirm(getShell(), Messages .getString("srx.AddOrEditSrxConfigDialog.msgTitle1"), MessageFormat.format( Messages.getString("srx.AddOrEditSrxConfigDialog.msg2"), mapedNameStr)); if (deleResponse) { for (int i = 0; i < mapedRuleNameList.size(); i++) { String langRuleName = mapedRuleNameList.get(i); handler.deleteNode(srxLocation, "/srx/body/languagerules/languagerule[@languagerulename='" + langRuleName + "']"); handler.deleteNode(srxLocation, "/srx/body/maprules/maprule/languagemap[@languagerulename='" + langRuleName + "']"); } } refreshMapTable(null); } for (int i = 0; i < deleRuleNameList.size(); i++) { String langRuleName = deleRuleNameList.get(i); handler.deleteNode(srxLocation, "/srx/body/languagerules/languagerule[@languagerulename='" + langRuleName + "']"); } refreshLangTable(null); } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.AddOrEditSrxConfigDialog.msgTitle2"), Messages.getString("srx.AddOrEditSrxConfigDialog.msg3")); } } }); mapAddBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { SrxMapRulesManageDialog dialog = new SrxMapRulesManageDialog(getShell(), true, handler, srxLocation); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshMapTable(dialog.getCurMapRuleName()); } } }); mapEditBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editMapRules(); } }); mapDeleteBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = mapTableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.AddOrEditSrxConfigDialog.msgTitle1"), Messages.getString("srx.AddOrEditSrxConfigDialog.msg4")); if (!response) { return; } StructuredSelection struSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> it = struSelection.iterator(); while (it.hasNext()) { // 获取所选中的语言规则的名称 String mapRuleName = it.next()[1]; handler.deleteNode(srxLocation, "/srx/body/maprules/maprule[@maprulename='" + mapRuleName + "']"); } refreshMapTable(null); } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.AddOrEditSrxConfigDialog.msgTitle2"), Messages.getString("srx.AddOrEditSrxConfigDialog.msg5")); } } }); } /** * 动态改变两个列表的列宽 * @param table * ; */ private void refreshTableWidth(Table table) { 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.25, 0.7 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); } /** * 更新语言规则列表 ; */ private void refreshLangTable(String langRuleName) { langTableViewer.setInput(handler.getLanguageRuleNamesOfSrx_1(srxLocation).toArray(new String[][] {})); if (langRuleName != null) { TableItem[] items = langTable.getItems(); for (int i = 0; i < items.length; i++) { if (langRuleName.equals(items[i].getText(1))) { langTable.setSelection(i); } } } } /** * 更新映射规则列表 ; */ private void refreshMapTable(String mapRuleName) { mapTableViewer.setInput(handler.getMapRuleNames(srxLocation).toArray(new String[][] {})); if (mapRuleName != null) { TableItem[] items = mapTable.getItems(); for (int i = 0; i < items.length; i++) { if (mapRuleName.equals(items[i].getText(1))) { mapTable.setSelection(i); } } } } /** * 修改语言规则,备注,在修改语言规则名称时,也会同步修改映射中语言规则的名称 ; */ private void editLangRules() { ISelection selection = langTableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { StructuredSelection struSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> it = struSelection.iterator(); if (it.hasNext()) { // 获取所选中的语言规则的名称 String langRuleName = it.next()[1]; SrxLanguageRulesManageDialog dialog = new SrxLanguageRulesManageDialog(getShell(), false, handler, srxLocation); dialog.create(); dialog.setEditInitData(langRuleName); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshLangTable(dialog.getCurLanguageRuleName()); } } } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.AddOrEditSrxConfigDialog.msgTitle2"), Messages.getString("srx.AddOrEditSrxConfigDialog.msg6")); } } public void editMapRules() { ISelection selection = mapTableViewer.getSelection(); if (!selection.isEmpty() && selection != null && selection instanceof StructuredSelection) { StructuredSelection struSelection = (StructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<String[]> it = struSelection.iterator(); if (it.hasNext()) { // 获取所选中的映射规则的名称 String mapRuleName = it.next()[1]; SrxMapRulesManageDialog dialog = new SrxMapRulesManageDialog(getShell(), false, handler, srxLocation); dialog.create(); dialog.setEditInitData(mapRuleName); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { refreshMapTable(dialog.getCurMapRuleName()); } } } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.AddOrEditSrxConfigDialog.msgTitle2"), Messages.getString("srx.AddOrEditSrxConfigDialog.msg7")); } } }
16,702
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AddOrEditLangRuleOfSrxDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/srx/AddOrEditLangRuleOfSrxDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs.srx; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.ts.ui.advanced.model.LanguageRuleBean; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; 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.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 添加语言规则对话框 * @author robert 2012-02-29 * @version * @since JDK1.6 */ public class AddOrEditLangRuleOfSrxDialog extends Dialog { private boolean isAdd; private List<LanguageRuleBean> langRulesList = new LinkedList<LanguageRuleBean>(); private Button isBreakBtn; private Text preBreakTxt; private Text afterBreakTxt; /** 当前所添加的或正在修改的语言规则 */ private LanguageRuleBean curLangRuleBean; public AddOrEditLangRuleOfSrxDialog(Shell parentShell, boolean isAdd, List<LanguageRuleBean> langRulesList) { super(parentShell); this.isAdd = isAdd; this.langRulesList = langRulesList; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(isAdd ? Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.title1") : Messages .getString("srx.AddOrEditLangRuleOfSrxDialog.title2")); } @Override protected boolean isResizable() { return true; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).applyTo(tparent); Composite langCmp = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).hint(450, 100).applyTo(langCmp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(langCmp); isBreakBtn = new Button(langCmp, SWT.CHECK); isBreakBtn.setText(Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.isBreakBtn")); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, SWT.DEFAULT) .applyTo(isBreakBtn); Label preLbl = new Label(langCmp, SWT.NONE); preLbl.setText(Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.preLbl")); GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false); preBreakTxt = new Text(langCmp, SWT.BORDER); preBreakTxt.setLayoutData(textData); Label afterLbl = new Label(langCmp, SWT.NONE); afterLbl.setText(Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.afterLbl")); afterBreakTxt = new Text(langCmp, SWT.BORDER); afterBreakTxt.setLayoutData(textData); return tparent; } @Override protected void okPressed() { String isBreak = isBreakBtn.getSelection() ? "yes" : "no"; String preBreak = preBreakTxt.getText(); String afterBreak = afterBreakTxt.getText(); LanguageRuleBean bean = new LanguageRuleBean(isBreak, preBreak, afterBreak); if (isAdd) { // 添加之前验证是否重复 if (langRulesList.indexOf(bean) == -1) { langRulesList.add(bean); this.curLangRuleBean = bean; } else { MessageDialog.openInformation(getShell(), Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.msgTitle1"), Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.msg1")); return; } } else { // 先验证是否该条数据是否已经被修改,如果已经被修改,但是修改后的数据已经存在,那么直接覆盖 if (!curLangRuleBean.equals(bean)) { if (langRulesList.indexOf(bean) != -1) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.msgTitle2"), Messages.getString("srx.AddOrEditLangRuleOfSrxDialog.msg2")); if (response) { langRulesList.remove(curLangRuleBean); curLangRuleBean = bean; } else { return; } } else { // 如果修改后的数据没有重复,那么删除修改之前的数据,并且添加到修改前数据的位置 langRulesList.add(langRulesList.indexOf(curLangRuleBean), bean); langRulesList.remove(curLangRuleBean); curLangRuleBean = bean; } } } super.okPressed(); } /** * 设置编辑的初始化数据 * @param editBean * ; */ public void setEditInitData(LanguageRuleBean editBean) { curLangRuleBean = editBean; if (editBean.getIsBreak().equals("yes")) { isBreakBtn.setSelection(true); } preBreakTxt.setText(editBean.getPreBreak()); afterBreakTxt.setText(editBean.getAfterBreak()); } public LanguageRuleBean getCurLangRuleBean() { return curLangRuleBean; } }
4,857
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CreateOrUpdataSRXDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/dialogs/srx/CreateOrUpdataSRXDialog.java
package net.heartsome.cat.ts.ui.advanced.dialogs.srx; import java.io.File; import java.io.FileOutputStream; import java.text.MessageFormat; import net.heartsome.cat.ts.ui.advanced.ADConstants; import net.heartsome.cat.ts.ui.advanced.resource.Messages; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 创建(修改)srx文件(名) * @author robert 2012-02-28 * @version * @since JDK1.6 */ public class CreateOrUpdataSRXDialog extends Dialog { private static final Logger LOGGER = LoggerFactory.getLogger(CreateOrUpdataSRXDialog.class); private boolean isAdd; private Text nameTxt; private IWorkspaceRoot root; /** 当前已经创建完成的,或者正在修改文件文件的名称 */ private String curSrxName; public CreateOrUpdataSRXDialog(Shell parentShell, boolean isAdd) { super(parentShell); root = ResourcesPlugin.getWorkspace().getRoot(); this.isAdd = isAdd; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(isAdd ? Messages.getString("srx.CreateOrUpdataSRXDialog.title1") : Messages .getString("srx.CreateOrUpdataSRXDialog.title2")); } @Override protected boolean isResizable() { return false; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).hint(300, 50).minSize(300, 50).applyTo(tparent); Composite nameCmp = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).applyTo(nameCmp); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(nameCmp); Label nameLbl = new Label(nameCmp, SWT.NONE); nameLbl.setText(Messages.getString("srx.CreateOrUpdataSRXDialog.nameLbl")); nameTxt = new Text(nameCmp, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(nameTxt); return tparent; } @Override protected void okPressed() { String srxName = nameTxt.getText().trim(); // 先判断该文件名是否合法 if ("".equals(srxName) || srxName == null) { MessageDialog.openInformation(getShell(), Messages.getString("srx.CreateOrUpdataSRXDialog.msgTitle1"), Messages.getString("srx.CreateOrUpdataSRXDialog.msg1")); return; } else if (!srxName.endsWith(".srx")) { MessageDialog.openInformation(getShell(), Messages.getString("srx.CreateOrUpdataSRXDialog.msgTitle1"), Messages.getString("srx.CreateOrUpdataSRXDialog.msg2")); return; } // String srxLoaction = root.getLocation().append(ADConstants.AD_SRXConfigFolder).append(srxName).toOSString(); String srxLocation = ADConstants.configLocation + ADConstants.AD_SRXConfigFolder + File.separator + srxName; // 创建文件的情况 if (isAdd) { // 在添加之前先难证是否重复 File srxFile = new File(srxLocation); if (srxFile.exists()) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.CreateOrUpdataSRXDialog.msgTitle2"), MessageFormat.format(Messages.getString("srx.CreateOrUpdataSRXDialog.msg3"), srxName)); if (!response) { return; } } try { FileOutputStream output = new FileOutputStream(srxLocation); String initData = "<?xml version=\"1.0\"?>\n" + "<!DOCTYPE srx PUBLIC \"-//SRX//DTD SRX//EN\" \"srx.dtd\">\n" + "<srx version=\"1.0\">\n" + "\t<header segmentsubflows=\"yes\">\n" + "\t\t<formathandle type=\"start\" include=\"no\"/>\n" + "\t\t<formathandle type=\"end\" include=\"yes\"/>\n" + "\t\t<formathandle type=\"isolated\" include=\"yes\"/>\n" + "\t</header>\n" + "</srx>\n"; output.write(initData.getBytes("UTF-8")); output.close(); } catch (Exception e) { LOGGER.error("", e); } curSrxName = srxName; } else { // 修改 if (!curSrxName.equals(srxName)) { // 验证修改之后的文件名是否重复 File editedSrx = new File(ADConstants.configLocation + ADConstants.AD_SRXConfigFolder + File.separator + srxName); if (editedSrx.exists()) { boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("srx.CreateOrUpdataSRXDialog.msgTitle2"), MessageFormat.format(Messages.getString("srx.CreateOrUpdataSRXDialog.msg4"), srxName)); if (!response) { return; } } // 执行对文件名的修改工作 File curSrx = new File(ADConstants.configLocation + ADConstants.AD_SRXConfigFolder + File.separator + curSrxName); curSrx.renameTo(editedSrx); curSrxName = srxName; } } super.okPressed(); } public String getCurSrxName() { return curSrxName; } public void setEditInitData(String srxName) { nameTxt.setText(srxName); curSrxName = srxName; } }
5,238
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.advanced/src/net/heartsome/cat/ts/ui/advanced/resource/Messages.java
package net.heartsome.cat.ts.ui.advanced.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.advanced.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; } } }
566
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ElementBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/model/ElementBean.java
package net.heartsome.cat.ts.ui.advanced.model; /** * XML转换器配置中元素的POJO类 * @author robert 2012-02-23 * @version * @since JDK1.6 */ public class ElementBean { /** 元素名 */ private String name; /** 元素类型,对应生成文件属性hard-break */ private String type; /** 内联类型,对应生成文件属性ctype */ private String inlineType; /** 可翻译属性,对应生成文件属性attributes */ private String transAttribute; /** 保留空格,对应生成文件属性keep-format */ private String remainSpace; public ElementBean() { } public ElementBean(String name, String type, String inlineType, String transAttribute, String remainSpace) { this.name = name; this.type = type; this.inlineType = inlineType; this.transAttribute = transAttribute; this.remainSpace = remainSpace; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getInlineType() { return inlineType; } public void setInlineType(String inlineType) { this.inlineType = inlineType; } public String getTransAttribute() { return transAttribute; } public void setTransAttribute(String transAttribute) { this.transAttribute = transAttribute; } public String getRemainSpace() { return remainSpace; } public void setRemainSpace(String remainSpace) { this.remainSpace = remainSpace; } }
1,526
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
LanguageRuleBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/model/LanguageRuleBean.java
package net.heartsome.cat.ts.ui.advanced.model; public class LanguageRuleBean { private String isBreak; private String preBreak; private String afterBreak; public LanguageRuleBean(){} public LanguageRuleBean(String isBreak, String preBreak, String afterBreak){ this.isBreak = isBreak; this.preBreak = preBreak; this.afterBreak = afterBreak; } public String getIsBreak() { return isBreak; } public void setIsBreak(String isBreak) { this.isBreak = isBreak; } public String getPreBreak() { return preBreak; } public void setPreBreak(String preBreak) { this.preBreak = preBreak; } public String getAfterBreak() { return afterBreak; } public void setAfterBreak(String afterBreak) { this.afterBreak = afterBreak; } @Override public boolean equals(Object obj) { if (obj instanceof LanguageRuleBean) { LanguageRuleBean targetBean = (LanguageRuleBean) obj; if (targetBean.getIsBreak().equals(this.isBreak) && targetBean.getPreBreak().equals(this.preBreak) && targetBean.getAfterBreak().equals(this.afterBreak)) { return true; }else { return false; } } return false; } }
1,142
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MapRuleBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.advanced/src/net/heartsome/cat/ts/ui/advanced/model/MapRuleBean.java
package net.heartsome.cat.ts.ui.advanced.model; /** * 高级菜单下分段规则印射规则的pojo类 * @author robert 2012-03-02 * @version * @since JDK1.6 */ public class MapRuleBean { private String languageModel; private String langRuleName; public MapRuleBean (){} public MapRuleBean(String languageModel, String langRuleName){ this.languageModel = languageModel; this.langRuleName = langRuleName; } public String getLanguageModel() { return languageModel; } public void setLanguageModel(String languageModel) { this.languageModel = languageModel; } public String getLangRuleName() { return langRuleName; } public void setLangRuleName(String langRuleName) { this.langRuleName = langRuleName; } @Override public boolean equals(Object obj) { if (obj != null && obj instanceof MapRuleBean) { MapRuleBean targetBean = (MapRuleBean) obj; if (targetBean.getLanguageModel().equals(this.languageModel) && targetBean.getLangRuleName().equals(this.langRuleName)) { return true; } } return false; } }
1,059
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TgtTextLengthLimitQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/TgtTextLengthLimitQA.java
package net.heartsome.cat.ts.ui.qa; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; /** * 目标文本段长度限制检查 * 备注:使用的是纯文本 * @author robert * @version * @since JDK1.6 */ public class TgtTextLengthLimitQA extends QARealization { private int level; private IPreferenceStore preferenceStore; private boolean hasError; private boolean isCheckTgtMinLength = false; private boolean isCheckTgtMaxLength = false; /** 目标文本段长度允许减少的比例 */ private float minPercentage; /** 目标文本段长度允许增加的比例 */ private float maxPercentage; public TgtTextLengthLimitQA(){ preferenceStore = Activator.getDefault().getPreferenceStore(); level = preferenceStore.getInt(QAConstant.QA_PREF_tgtLengthLimit_TIPLEVEL); isCheckTgtMinLength = preferenceStore.getBoolean(QAConstant.QA_PREF_isCheckTgtMinLength); isCheckTgtMaxLength = preferenceStore.getBoolean(QAConstant.QA_PREF_isCheckTgtMaxLength); if (isCheckTgtMinLength) { String minValue = preferenceStore.getString(QAConstant.QA_PREF_tgtMinLength); if (minValue == null || "".equals(minValue)) { minValue = "0"; } minPercentage = Float.parseFloat(minValue) / 100; } if (isCheckTgtMaxLength) { String maxValue = preferenceStore.getString(QAConstant.QA_PREF_tgtMaxLength); if (maxValue == null || "".equals(maxValue)) { maxValue = "0"; } maxPercentage = Float.parseFloat(maxValue) / 100; } } @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } @Override public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } hasError = false; String lineNumber = tuDataBean.getLineNumber(); String qaTypeText = Messages.getString("qa.all.qaItem.TgtTextLengthLimitQA"); String rowId = tuDataBean.getRowId(); String srcPureText = tuDataBean.getSrcPureText(); String tgtPureText = tuDataBean.getTgtPureText(); int srcTextLength = srcPureText.length(); int tgtTextLength = tgtPureText.length(); if (isCheckTgtMaxLength) { int maxWidth = (int) (srcTextLength + srcTextLength * maxPercentage); if (tgtTextLength > maxWidth) { // String errorTip = MessageFormat.format(Messages.getString("qa.TgtTextLengthLimitQA.tip1"), // new Object[] { tgtTextLength, maxWidth }); hasError = true; } } if (isCheckTgtMinLength) { int minWidth = (int) (srcTextLength - srcTextLength * minPercentage); minWidth = minWidth >= 0 ? minWidth : 0; if (tgtTextLength < minWidth) { // String errorTip = MessageFormat.format(Messages.getString("qa.TgtTextLengthLimitQA.tip2"), // new Object[] { tgtTextLength, minWidth }); hasError = true; } } if (hasError) { super.printQAResult(new QAResultBean(level, QAConstant.QA_TGTTEXTLENGTHLIMIT, qaTypeText, null, tuDataBean.getFileName(), lineNumber, tuDataBean.getSrcContent(), tuDataBean.getTgtContent(), rowId)); } String result = ""; if (hasError && level == 0) { result = QAConstant.QA_TGTTEXTLENGTHLIMIT; } return result; } }
3,704
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ParagraphConsistenceQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/ParagraphConsistenceQA.java
package net.heartsome.cat.ts.ui.qa; import java.io.File; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.qa.ParaConsisDataBean; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; /** * 文本段一致性检查,包括: * 相同源文,不同译文;相同译文,不同源文, * 检查时,要从首选项中获取的参数项是:忽略标记,忽略大小写 * 进度条提示格式为 MessageFormat.format("检查{0}文件,术语一致性检查:术语比较...) * 进度条推进方法:设一个间隔值workInterval,先计算出要循环的所有的tu节点的数量,每workInterval个tu节点,推进一格 * @author robert 2011-11-16 */ public class ParagraphConsistenceQA extends QARealization { /** 相同源文不同译文比较时是否忽略大小写,从首选项中获取 */ private boolean srcIgnoreCase ; /** 相同源文不同译文比较时是否忽略标记,从首选项中获取 */ private boolean srcIgnoreTag ; /** 相同译文不同源文比较时是否忽略大小写,从首选项中获取 */ private boolean tgtIgnoreCase ; /** 相同译文不同源文比较时是否忽略大小写,从首选项中获取 */ private boolean tgtIgnoreTag; /** 是否检查相同源文,不同译文的情况,从首选项中获取 */ private boolean checkSameSource; /** 是否检查相同译文,不同源文的情况,从首选项中获取 */ private boolean checkSameTarget; /** 品质检查的过滤条件,如不包括上下文匹配文本段,完全匹配文本段,已锁定文本段 */ private Map<String, Boolean> filterMap; /** 保存当前正在处理的文件路径 */ private String curXlfPath = ""; /** 针对每一个文件(或者合并打开时的一个语言对)获取整个要进行比较的数据,以便进行处理 */ private Map<String, ParaConsisDataBean> dataMap = new HashMap<String, ParaConsisDataBean>(); /** 数据经过处理后,会把源文相同的文本段的rowId放到一起,以便于集中处理 */ private List<List<String>> srcRowIdList = new ArrayList<List<String>>(); /** 数据经过处理后,会把源文相同的文本段的rowId放到一起,以便于集中处理 */ private List<List<String>> tgtRowIdList = new ArrayList<List<String>>(); /** 合并打开的文本段一致性查,是否初始化数据 */ private boolean isMultiInit = false; private int level; public ParagraphConsistenceQA(){ //filterMap = model.getNotInclude(); IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); checkSameSource = preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SAMESOURCE); checkSameTarget = preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SAMETARGET); srcIgnoreTag = preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SRC_IGNORCETAG); srcIgnoreCase = preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SRC_IGNORCECASE); tgtIgnoreTag = preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_TAR_IGNORCETAG); tgtIgnoreCase = preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_TAR_IGNORCECASE); level = preferenceStore.getInt(QAConstant.QA_PREF_para_TIPLEVEL); } public void setParentQaResult(QAResult qaResult){ super.setQaResult(qaResult); } @Override public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } String xlfPath = tuDataBean.getXlfPath(); String rowId = tuDataBean.getRowId(); filterMap = (filterMap == null ? model.getNotInclude() : filterMap); init(model, xlfPath, xmlHandler); //如果是针对合并打开的品质检查,使用以下方法 if (model.isMuliFiles()) { compareNext(rowId); }else { compareNext(rowId); } return ""; } /** * 初始化相关数据 */ public void init(QAModel model, String xlfPath, QAXmlHandler xmlHandler){ if (!model.isMuliFiles()) { if ("".equals(curXlfPath) || !curXlfPath.equals(xlfPath)) { curXlfPath = xlfPath; dataMap.clear(); dataMap = xmlHandler.getFilteredTUPureTextOrContent(xlfPath, filterMap, checkSameSource, checkSameTarget, srcIgnoreTag, tgtIgnoreTag); try { analysisSameSrc(); analysisSameTgt(); } catch (Exception e) { e.printStackTrace(); logger.error("", e); } } }else { if (!isMultiInit) { dataMap = xmlHandler.getFilteredTUTextForMultiParaConsis(model.getRowIdsList(), filterMap, checkSameSource, checkSameTarget, srcIgnoreTag, tgtIgnoreTag); try { analysisSameSrc(); analysisSameTgt(); } catch (Exception e) { e.printStackTrace(); logger.error("", e); } isMultiInit = true; } } } /** * 将相同源文的所有文本段进行整合,放到一块去方便进行处理。 */ private void analysisSameSrc() throws Exception{ if (!checkSameSource) { return; } List<Entry<String, ParaConsisDataBean>> mapList = new ArrayList<Entry<String, ParaConsisDataBean>>(dataMap.entrySet()); //排序 Collections.sort(mapList, new Comparator<Entry<String, ParaConsisDataBean>>() { public int compare(Entry<String, ParaConsisDataBean> o1, Entry<String, ParaConsisDataBean> o2) { String str1 = srcIgnoreTag ? o1.getValue().getSrcPureText() : o1.getValue().getSrcContent(); String str2 = srcIgnoreTag ? o2.getValue().getSrcPureText() : o2.getValue().getSrcContent(); return srcIgnoreCase ? str1.compareToIgnoreCase(str2) : str1.compareTo(str2); } }); for (int i = 0; i < mapList.size(); i++) { Entry<String, ParaConsisDataBean> entry = mapList.get(i); String srcText = srcIgnoreTag ? entry.getValue().getSrcPureText() : entry.getValue().getSrcContent(); ArrayList<String> resultList = new ArrayList<String>(); boolean isSame = false; for (int j = i + 1; j < mapList.size(); j++) { Entry<String, ParaConsisDataBean> curEntry = mapList.get(j); String curSrcText = srcIgnoreTag ? curEntry.getValue().getSrcPureText() : curEntry.getValue().getSrcContent(); if (srcText.length() != curSrcText.length()) { continue; } if (srcIgnoreCase ? srcText.equalsIgnoreCase(curSrcText) : srcText.equals(curSrcText)) { if (!isSame) { resultList.add(entry.getKey()); } isSame = true; resultList.add(curEntry.getKey()); mapList.remove(j); j --; } } if (resultList.size() > 0) { // 对 resultList 以行号进行排序 Collections.sort(resultList, new Comparator<String>() { public int compare(String rowId1, String rowId2) { return dataMap.get(rowId1).getLineNumber() - dataMap.get(rowId2).getLineNumber(); } }); srcRowIdList.add(resultList); } } } /** * 将相同译文的所有文本段进行整合,放到一块去方便进行处理。 */ private void analysisSameTgt(){ if (!checkSameTarget) { return; } List<Entry<String, ParaConsisDataBean>> mapList = new ArrayList<Entry<String, ParaConsisDataBean>>(dataMap.entrySet()); //排序 Collections.sort(mapList, new Comparator<Entry<String, ParaConsisDataBean>>() { public int compare(Entry<String, ParaConsisDataBean> o1, Entry<String, ParaConsisDataBean> o2) { String str1 = tgtIgnoreTag ? o1.getValue().getTgtPureText() : o1.getValue().getTgtContent(); String str2 = tgtIgnoreTag ? o2.getValue().getTgtPureText() : o2.getValue().getTgtContent(); return tgtIgnoreCase ? str1.compareToIgnoreCase(str2) : str1.compareTo(str2); } }); for (int i = 0; i < mapList.size(); i++) { Entry<String, ParaConsisDataBean> entry = mapList.get(i); String tgtText = tgtIgnoreTag ? entry.getValue().getTgtPureText() : entry.getValue().getTgtContent(); ArrayList<String> resultList = new ArrayList<String>(); boolean isSame = false; for (int j = i + 1; j < mapList.size(); j++) { Entry<String, ParaConsisDataBean> curEntry = mapList.get(j); String curTgtText = tgtIgnoreTag ? curEntry.getValue().getTgtPureText() : curEntry.getValue().getTgtContent(); if (tgtText.length() != curTgtText.length()) { continue; } if (tgtIgnoreCase ? tgtText.equalsIgnoreCase(curTgtText) : tgtText.equals(curTgtText)) { if (!isSame) { resultList.add(entry.getKey()); } isSame = true; resultList.add(curEntry.getKey()); mapList.remove(j); j --; } } if (resultList.size() > 0) { // 对 resultList 以行号进行排序 Collections.sort(resultList, new Comparator<String>() { public int compare(String rowId1, String rowId2) { return dataMap.get(rowId1).getLineNumber() - dataMap.get(rowId2).getLineNumber(); } }); tgtRowIdList.add(resultList); } } } /** * 与其他文本段进行比较,获取相关值 * @param rowId */ private void compareNext(String rowId){ // 先比较相同源文不同译文的情况 String sameSrcQaTypeText = Messages.getString("qa.ParagraphConsistenceQA.name1"); String mergeRowId = CommonFunction.createUUID(); for (int i = 0; i < srcRowIdList.size(); i++) { // 如果该文本段存在与其他文本段的相同源文不同译文,那么就进行处理 List<String> curList = srcRowIdList.get(i); if (curList.contains(rowId)) { // 循环比较,找出源文相同,译文不同的文本段 List<Integer> sameSourceData = new LinkedList<Integer>(); for(String rowId_1 : curList){ sameSourceData.clear(); ParaConsisDataBean bean_1 = dataMap.get(rowId_1); String tgtText_1 = srcIgnoreTag ? bean_1.getTgtPureText() : bean_1.getTgtContent(); for (String rowId_2 : curList) { if (rowId_2.equals(rowId_1)) { continue; } ParaConsisDataBean bean_2 = dataMap.get(rowId_2); String tgtText_2 = srcIgnoreTag ? bean_2.getTgtPureText() : bean_2.getTgtContent(); if (!checkEquals(tgtText_2, tgtText_1, srcIgnoreCase)) { sameSourceData.add(bean_2.getLineNumber()); } } if (sameSourceData.size() > 0) { int lineNum = bean_1.getLineNumber(); // String notSameTip = ""; // for (int k = 0; k < sameSourceData.size(); k++) { // int k_lineNum = sameSourceData.get(k); // notSameTip += MessageFormat.format(Messages.getString("qa.ParagraphConsistenceQA.tip1"), k_lineNum); // } // notSameTip = notSameTip.length() > 0 ? notSameTip.substring(0, notSameTip.length() - 1): notSameTip; // // String errorTip = Messages.getString("qa.ParagraphConsistenceQA.tip2"); // errorTip += Messages.getString("qa.ParagraphConsistenceQA.tip3"); // errorTip += notSameTip; // errorTip += Messages.getString("qa.ParagraphConsistenceQA.tip4"); super.printQAResult(new QAResultBean(level, QAConstant.QA_PARAGRAPH, sameSrcQaTypeText, mergeRowId, new File(RowIdUtil.getFileNameByRowId(rowId_1)).getName(), lineNum + "", bean_1.getSrcContent(), bean_1.getTgtContent(), rowId_1)); } } srcRowIdList.remove(curList); i --; } } // 再比较相同译文不同源文的情况 mergeRowId = CommonFunction.createUUID(); String sameTgtQaTypeText = Messages.getString("qa.ParagraphConsistenceQA.name2"); for (int i = 0; i < tgtRowIdList.size(); i++) { // 如果该文本段存在与其他文本段的相同源文不同译文,那么就进行处理 List<String> curList = tgtRowIdList.get(i); if (curList.contains(rowId)) { // 循环比较,找出源文相同,译文不同的文本段 List<Integer> sameTargetData = new LinkedList<Integer>(); for(String rowId_1 : curList){ sameTargetData.clear(); ParaConsisDataBean bean_1 = dataMap.get(rowId_1); String srcText_1 = tgtIgnoreTag ? bean_1.getSrcPureText() : bean_1.getSrcContent(); for (String rowId_2 : curList) { if (rowId_2.equals(rowId_1)) { continue; } ParaConsisDataBean bean_2 = dataMap.get(rowId_2); String srcText_2 = tgtIgnoreTag ? bean_2.getSrcPureText() : bean_2.getSrcContent(); if (!checkEquals(srcText_2, srcText_1, tgtIgnoreCase)) { sameTargetData.add(bean_2.getLineNumber()); } } if (sameTargetData.size() > 0) { int lineNum = bean_1.getLineNumber(); // String notSameTip = ""; // for (int k = 0; k < sameTargetData.size(); k++) { // int k_lineNum = sameTargetData.get(k); // notSameTip += MessageFormat.format(Messages.getString("qa.ParagraphConsistenceQA.tip1"), k_lineNum); // } // notSameTip = notSameTip.length() > 0 ? notSameTip.substring(0, notSameTip.length() - 1): notSameTip; // // String errorTip = Messages.getString("qa.ParagraphConsistenceQA.tip2"); // errorTip += Messages.getString("qa.ParagraphConsistenceQA.tip3"); // errorTip += notSameTip; // errorTip += Messages.getString("qa.ParagraphConsistenceQA.tip5"); super.printQAResult(new QAResultBean(level, QAConstant.QA_PARAGRAPH, sameTgtQaTypeText, mergeRowId, new File(RowIdUtil.getFileNameByRowId(rowId_1)).getName(), "" + lineNum, bean_1.getSrcContent(), bean_1.getTgtContent(), rowId_1)); } } tgtRowIdList.remove(curList); i --; } } } /** * 判断两个文本段是否相等 * @param text1 * @param text2 * @return */ public boolean checkEquals(String text1, String text2, boolean ignoreCase){ if (ignoreCase) { return text1.equalsIgnoreCase(text2); }else { return text1.equals(text2); } } /** * 进度条前进处理方法,针对遍历tu节点总数不是workInterval的倍数情况下,程序运行要结束时,就前进一格。 * 如果是在程序运行中,就判断是tu节点遍历序列号是否是workInterval的倍数,若是,则前进一格 * @param monitor 进度条实例 * @param traversalTuIndex 遍历的序列号 * @param last 是否是程序运行的结尾处 */ /* public void monitorWork(IProgressMonitor monitor, int traversalTuIndex, boolean last){ if (last) { if (traversalTuIndex % workInterval != 0) { monitor.worked(1); } }else { if (traversalTuIndex % workInterval == 0) { monitor.worked(1); } } }*/ }
15,156
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AutomaticQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/AutomaticQA.java
package net.heartsome.cat.ts.ui.qa; import java.io.File; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.util.MultiFilesOper; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.ui.xliffeditor.nattable.qa.IAutomaticQA; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 自动品质检查解发类 * 若某个检查项的级别是错误,则弹出提示对话框 * @author robert 2012-02-13 * @version * @since JDK1.6 */ public class AutomaticQA implements IAutomaticQA{ /** 品质检查运行时机,从首选项中获取, 当此值等于0时:为从不执行;等于1时,为入库时执行;等于2时,为批准文本段时执行 */ private int runTime = -1; private IPreferenceStore preferenceStore; /** 保存某个检查项的实例 */ private Map<String, QARealization> qaItemClassMap = new HashMap<String, QARealization>(); private QAModel model; private IWorkbenchWindow window; private XLFHandler handler; private Map<String, Boolean> filterMap; private IWorkspaceRoot root; private IFile iFile; private QAXmlHandler xmlHandler; private QAResult qaResult; public final static Logger logger = LoggerFactory.getLogger(AutomaticQA.class.getName()); private boolean isCancel = false; public AutomaticQA(){ } public void setInitData(XLFHandler handler) { this.handler = handler; preferenceStore = Activator.getDefault().getPreferenceStore(); model = new QAModel(); window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); filterMap = getNotIncludePara(); root = ResourcesPlugin.getWorkspace().getRoot(); xmlHandler = new QAXmlHandler(); // 存储品质检查的检查项 model.setBatchQAItemIdList(getAutoQAItems()); // 存储品质检查的检查时不包括的文本段 model.setNotInclude(filterMap); model.setShell(window.getShell()); XLIFFEditorImplWithNatTable nattable = XLIFFEditorImplWithNatTable.getCurrent(); boolean isMultiFile = nattable.isMultiFile(); if (isMultiFile) { model.setMuliFiles(true); IFile multiTempIFile = ((FileEditorInput) nattable.getEditorInput()).getFile(); ArrayList<IFile> selectIFiles = (ArrayList<IFile>) ResourceUtils.filesToIFiles(nattable.getMultiFileList()); model.setMultiOper(new MultiFilesOper(selectIFiles.get(0).getProject(), selectIFiles, multiTempIFile)); }else { model.setMuliFiles(false); } } /** * 开始进行自动品质检查 * @param isAddToDb 若为true,则是入库操作,若false,则为批准操作 * @return 若返回 "",则表示没有检查到错误,若返回 null,则标识退出操作。 */ public String beginAutoQa(boolean isAddToDb, String rowId, boolean needInitQAResultViewer) { runTime = preferenceStore.getInt(QAConstant.QA_PREF_AUTO_QARUNTIME); //从不执行 if (runTime == QAConstant.QA_ZERO) { return ""; } if (needInitQAResultViewer) { initQAResult(); } //等于1时,为入库时执行 if ((runTime == QAConstant.QA_FIRST || runTime == QAConstant.QA_THREE) && isAddToDb) { StringBuffer resultSB = new StringBuffer(); autoQA(rowId, resultSB, isAddToDb); if (resultSB.length() > 0) { resultSB.append(MessageFormat.format(Messages.getString("qa.AutomaticQATrigger.tip5"), new Object[]{Messages.getString("qa.AutomaticQATrigger.name1")})); } return isCancel ? null : resultSB.toString(); } //等于2时,为批准文本段时执行 if ((runTime == QAConstant.QA_TWO || runTime == QAConstant.QA_THREE) && !isAddToDb) { StringBuffer resultSB = new StringBuffer(); autoQA(rowId, resultSB, isAddToDb); if (resultSB.length() > 0) { resultSB.append(MessageFormat.format(Messages.getString("qa.AutomaticQATrigger.tip5"), new Object[]{Messages.getString("qa.AutomaticQATrigger.name2")})); } return isCancel ? null : resultSB.toString(); } return ""; } public void informQAEndFlag(){ if (qaResult != null) { qaResult.informQAEndFlag(); } } public void autoQA(String rowId, StringBuffer resultSB, boolean isAddToDb){ iFile = root.getFileForLocation(Path.fromOSString(RowIdUtil.getFileNameByRowId(rowId))); //先通过rowId获取品质检查所需要的数据 QATUDataBean tuDataBean = handler.getAutoQAFilteredTUText(rowId, filterMap); if (!tuDataBean.isPassFilter()){ return; } String lineNumber = "" + (handler.getRowIndex(rowId) + 1); tuDataBean.setLineNumber(lineNumber); tuDataBean.setRowId(rowId); tuDataBean.setFileName(iFile.getName()); // 译文为空时,只有文本段完整性里面有检查,而,自动品质检查时已经翻译了的,因此不考虑此种情况 if (tuDataBean.getTgtContent() == null || tuDataBean.getTgtContent().isEmpty()) { return; } resultSB.append(MessageFormat.format( Messages.getString("qa.AutomaticQATrigger.tip1"), new Object[] { lineNumber, isAddToDb ? Messages.getString("qa.AutomaticQATrigger.name1") : Messages .getString("qa.AutomaticQATrigger.name2") })); // 品质检查项的总数 QARealization realization = null; boolean hasError = false; IProgressMonitor monitor = new NullProgressMonitor(); for (int i = 0; i < model.getBatchQAItemIdList().size(); i++) { final String qaItemId = model.getBatchQAItemIdList().get(i); realization = getClassInstance(qaItemId, qaResult); // 若没有该项检查的实例,提示出错 if (realization == null) { MessageDialog.openError(model.getShell(), Messages.getString("qa.AutomaticQATrigger.name3"), MessageFormat.format(Messages.getString("qa.AutomaticQATrigger.tip2"), new Object[] { model.getQaItemId_Name_Class().get(qaItemId).get(QAConstant.QA_ITEM_NAME) })); } // 开始进行该项文件的该项检查 String result = realization.startQA(model, monitor, iFile, xmlHandler, tuDataBean); if (monitor.isCanceled()) { isCancel = true; return; } // 未配置术语库, if (result == null) { model.getBatchQAItemIdList().remove(qaItemId); i --; } if (result != null && !"".equals(result)) { hasError = true; result = model.getQaItemId_Name_Class().get(result).get(QAConstant.QA_ITEM_NAME); resultSB.append("\t" + result).append(Messages.getString("qa.AutomaticQATrigger.tip3")).append("\n"); } } // 这一步很重要,将数据传送至结果视图 qaResult.sendDataToViewer(tuDataBean.getRowId()); if (!hasError) { resultSB.delete(0, resultSB.length()); } monitor.done(); return; } /** * 初始化品质检查结果视图, ; */ public void initQAResult() { qaResult = new QAResult(); qaResult.setMultiOper(model.getMultiOper()); qaResult.setAutoQA(true); qaResult.setFilePathList(handler.getFiles()); } public void bringQAResultViewerToTop() { qaResult.bringQAResultViewerToTop(); } /** * 获取某个检查项实现类的实例 * @param qaItemId * @return */ public QARealization getClassInstance(String qaItemId, QAResult qaResult) { if (qaItemClassMap.get(qaItemId) != null) { return (QARealization) qaItemClassMap.get(qaItemId); } try { HashMap<String, String> valueMap = model.getQaItemId_Name_Class().get(qaItemId); Object obj = null; try { obj = Class.forName(valueMap.get(QAConstant.QA_ITEM_CLASSNAME)).newInstance(); } catch (Exception e) { logger.error("", e); e.printStackTrace(); } if (QARealization.class.isInstance(obj)) { qaItemClassMap.put(qaItemId, (QARealization) obj); ((QARealization) obj).setParentQaResult(qaResult); return (QARealization) obj; } } catch (Exception e) { logger.error(Messages.getString("qa.AutomaticQATrigger.tip4"), e); } return null; } /** * 从首选项中获取自动检查中要检查的项 * @return */ public LinkedList<String> getAutoQAItems() { LinkedList<String> itemsList = new LinkedList<String>(); String itemsValue = preferenceStore.getString(QAConstant.QA_PREF_AUTO_QAITEMS); List<String> itemsValList = new ArrayList<String>(); String[] itemsValArray = itemsValue.split(","); for (int index = 0; index < itemsValArray.length; index++) { itemsValList.add(itemsValArray[index]); } //获取所有的品质检查项的标识符 model.getQaItemId_Name_Class().keySet(); Iterator<String> qaIt = model.getQaItemId_Name_Class().keySet().iterator(); while (qaIt.hasNext()) { String qaItermId = qaIt.next(); if (itemsValList.indexOf(qaItermId) >= 0) { itemsList.add(qaItermId); } } return itemsList; } /** * 获取首选项中品质检查的不包括的文本段 * @return */ public Map<String, Boolean> getNotIncludePara() { Map<String, Boolean> notInclude = new HashMap<String, Boolean>(); // 不包括上下文匹配 notInclude.put(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE)); // 不包括完成匹配 notInclude.put(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE)); // 不包括已锁文本段 notInclude.put(QAConstant.QA_PREF_LOCKED_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_LOCKED_NOTINCLUDE)); return notInclude; } /** * 关闭数据库,只针对术语一致性查 * ; */ public void closeDB(){ if (qaItemClassMap.get(QAConstant.QA_TERM) != null) { QARealization termRealize = qaItemClassMap.get(QAConstant.QA_TERM); termRealize.closeDB(); } } }
10,655
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QualityAssurance.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/QualityAssurance.java
package net.heartsome.cat.ts.ui.qa; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.util.ProgressIndicatorManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 品质检查类 处理所有的品质检查 * @author robert 2011-12-08 */ public class QualityAssurance { private QAModel model; private Shell shell; /** 保存某个检查项的实例 */ private Map<String, QARealization> qaItemClassMap = new HashMap<String, QARealization>(); private QAXmlHandler handler; /** 解析出错时是否继续执行,0为继续,1为出错时继续执行,2为出错时退出执行 */ private int continuResponse; /** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格 */ private static int workInterval = 1; /** 处理品质检查结果的model */ private QAResult qaResult; private static String _INFO = Messages.getString("qa.all.dialog.info"); private static String _ERROR = Messages.getString("qa.all.dialog.error"); /** 连接符号,用于连接源语言和目标语言的种类,例如“zh-CN -&gt; en” ,这个要与nattable界面上的过滤条件保持一致*/ private static final String Hyphen = " -> "; public final static Logger logger = LoggerFactory.getLogger(QualityAssurance.class.getName()); public QualityAssurance(QAModel model) { this.model = model; this.shell = model.getShell(); init(); } /** * 初始化相关实例 */ public void init() { } //------------------下面是优化品质检查的试用代码 public void beginQA(final QAResult qaResult) { this.qaResult = qaResult; handler = new QAXmlHandler(); Job job = new Job(Messages.getString("qa.all.qa")) { @Override protected IStatus run(IProgressMonitor monitor) { long time1 = System.currentTimeMillis(); // 品质检查项的总数 int fileNum = model.getQaXlfList().size(); // 定义的进度条总共五格,其中,解析文件一格,进行检查四格 monitor.beginTask(Messages.getString("qa.QualityAssurance.tip1"), fileNum * 5); //先将所有的文件进行解析 if (!openFile(monitor)) { monitor.done(); return Status.CANCEL_STATUS; } if (model.getQaXlfList().size() == 0) { MessageDialog.openInformation(shell, _INFO, Messages.getString("qa.QualityAssurance.tip2")); return Status.CANCEL_STATUS; } initWorkInterval(); QARealization realization = null; //先遍历每个文件 for (int fileIndex = 0; fileIndex < model.getQaXlfList().size(); fileIndex++) { final IFile iFile = model.getQaXlfList().get(fileIndex); String xlfPath = iFile.getLocation().toOSString(); String iFileFullPath = iFile.getFullPath().toOSString(); IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); int allTuSum = handler.getNodeCount(xlfPath, "/xliff/file/body//trans-unit"); subMonitor.beginTask("", allTuSum % workInterval == 0 ? (allTuSum / workInterval) : (allTuSum / workInterval) + 1 ); subMonitor.setTaskName(MessageFormat.format(Messages.getString("qa.QualityAssurance.tip3"), new Object[] { Messages.getString("qa.all.qa"), iFileFullPath })); int fileNodeSum = handler.getNodeCount(xlfPath, "/xliff/file"); int lineNumber = 0; //行号 int traversalTuIndex = 0; //遍历tu节点的序列号 for (int fileNodeIdx = QAConstant.QA_FIRST; fileNodeIdx <= fileNodeSum; fileNodeIdx++) { //获取语言对 String srcLang = handler.getNodeAttribute(xlfPath, "/xliff/file[" + fileNodeIdx + "]", "source-language"); String tgtLang = handler.getNodeAttribute(xlfPath, "/xliff/file[" + fileNodeIdx + "]", "target-language"); String langPair = srcLang + Hyphen + tgtLang; int curFileTUNodeSum = handler.getNodeCount(xlfPath, "/xliff/file[" + fileNodeIdx + "]/body//trans-unit"); for (int tuIndex = QAConstant.QA_FIRST; tuIndex <= curFileTUNodeSum; tuIndex++) { traversalTuIndex ++; String tuXpath = "/xliff/file[" + fileNodeIdx + "]/body/descendant::trans-unit[" + tuIndex + "]"; QATUDataBean dataBean = handler.getFilteredTUText(xlfPath, tuXpath, model.getNotInclude()); //如果返回的map为null,则进行下一循环,行号也不加自加,这样可以保持这里的行号与界面上的行号一致性,方便定位,出现这种情况的可能很小,因为 rowID 的过滤已经处理过了。 if (dataBean == null) { if (!monitorWork(subMonitor, traversalTuIndex, false)) { closeDB(); return Status.CANCEL_STATUS; } continue; } lineNumber ++; if (lineNumber == 73) { System.out.println("开始处理。。。。"); } // 未通过 过滤器过滤的情况, if (!dataBean.isPassFilter()) { if (!monitorWork(subMonitor, traversalTuIndex, false)) { closeDB(); return Status.CANCEL_STATUS; } continue; } dataBean.setLineNumber(lineNumber + ""); dataBean.setFileName(iFile.getName()); dataBean.setSrcLang(srcLang); dataBean.setTgtLang(tgtLang); dataBean.setXlfPath(xlfPath); for (int i = 0; i < model.getBatchQAItemIdList().size(); i++) { final String qaItemId = model.getBatchQAItemIdList().get(i); realization = getClassInstance(qaItemId); // 若没有该项检查的实例,提示出错 if (realization == null) { Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(shell, _ERROR, MessageFormat.format(Messages.getString("qa.QualityAssurance.tip4"), new Object[] { model.getQaItemId_Name_Class() .get(qaItemId).get(QAConstant.QA_ITEM_NAME) })); } }); closeDB(); return Status.CANCEL_STATUS; } // 开始进行该项文件的该项检查 final String result = realization.startQA(model, subMonitor, iFile, handler, dataBean); // 当未设置术语库、拼写检查词典配置 错误时才会返回 null,所以这时可以直接删。 if (result == null) { model.getBatchQAItemIdList().remove(qaItemId); i --; } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } } // UNDO 发现这里很耗时,需要处理。 qaResult.sendDataToViewer(null); if (!monitorWork(subMonitor, traversalTuIndex, false)) { closeDB(); return Status.CANCEL_STATUS; } } if (!monitorWork(subMonitor, traversalTuIndex, true)) { closeDB(); return Status.CANCEL_STATUS; } } subMonitor.done(); } closeDB(); qaResult.informQAEndFlag(); monitor.done(); System.out.println("所用时间为" + (System.currentTimeMillis() - time1)); return Status.OK_STATUS; } }; // 当程序退出时,检测当前 job 是否正常关闭 CommonFunction.jobCantCancelTip(job); job.addJobChangeListener(new JobChangeAdapter(){ @Override public void running(IJobChangeEvent event) { ProgressIndicatorManager.displayProgressIndicator(); super.running(event); } @Override public void done(IJobChangeEvent event) { ProgressIndicatorManager.hideProgressIndicator(); super.done(event); } }); job.setUser(true); job.schedule(); } /** * 开始处理多个合并打开文件的品质检查,由于合并打开文件的处理,是个很特殊的例子,因为处理对像不再是单个文件,而是针对语言对。 * @param qaResult ; */ public void beginMultiFileQA(final QAResult qaResult) { this.qaResult = qaResult; handler = new QAXmlHandler(); Job job = new Job(Messages.getString("qa.all.qa")) { @Override protected IStatus run(IProgressMonitor monitor) { long time1 = System.currentTimeMillis(); int fileNum = model.getQaXlfList().size(); // 定义的进度条总共五格,其中,解析文件1格,进行检查9格 monitor.beginTask(Messages.getString("qa.QualityAssurance.tip1"), fileNum * 10); //先将所有的文件进行解析 if (!openFile(monitor)) { monitor.done(); return Status.CANCEL_STATUS; } if (model.getQaXlfList().size() == 0) { MessageDialog.openInformation(shell, _INFO, Messages.getString("qa.QualityAssurance.tip2")); return Status.CANCEL_STATUS; } initWorkInterval(); int allTUSize = handler.getAllTUSize(); int traversalTuIndex = 0; //遍历tu节点的序列号 IProgressMonitor subMonitor = new SubProgressMonitor(monitor, fileNum * 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); subMonitor.beginTask("", allTUSize % workInterval == 0 ? (allTUSize / workInterval) : (allTUSize / workInterval) + 1); QARealization realization = null; Map<String, ArrayList<String>> languageList = handler.getLanguages(); int lineNumber = 0; IFile iFile; for(Entry<String, ArrayList<String>> langEntry : languageList.entrySet()){ String srcLang = langEntry.getKey(); for(String tgtLang : langEntry.getValue()){ List<String> rowIdsList = handler.getAllRowIdsByLanguages(srcLang.toUpperCase(), tgtLang.toUpperCase()); model.setRowIdsList(rowIdsList); //开始针对每一个文本段进行检查 for(String rowId : rowIdsList){ traversalTuIndex ++; lineNumber = rowIdsList.indexOf(rowId) + 1; //行号 String filePath = RowIdUtil.getFileNameByRowId(rowId); iFile = ResourceUtils.fileToIFile(filePath); String langPair = srcLang + Hyphen + tgtLang; QATUDataBean tuDataBean = handler.getFilteredTUText(filePath, RowIdUtil.parseRowIdToXPath(rowId), model.getNotInclude()); if (tuDataBean == null) { if (!monitorWork(subMonitor, traversalTuIndex, false)) { closeDB(); return Status.CANCEL_STATUS; } continue; } if (!tuDataBean.isPassFilter()) { if (!monitorWork(subMonitor, traversalTuIndex, false)) { closeDB(); return Status.CANCEL_STATUS; } continue; } tuDataBean.setLineNumber(lineNumber + ""); tuDataBean.setFileName(iFile.getName()); tuDataBean.setSrcLang(srcLang); tuDataBean.setTgtLang(tgtLang); for (int i = 0; i < model.getBatchQAItemIdList().size(); i++) { final String qaItemId = model.getBatchQAItemIdList().get(i); realization = getClassInstance(qaItemId); // 若没有该项检查的实例,提示出错 if (realization == null) { Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(shell, _ERROR, MessageFormat.format(Messages.getString("qa.QualityAssurance.tip4"), new Object[] { model.getQaItemId_Name_Class() .get(qaItemId).get(QAConstant.QA_ITEM_NAME) })); } }); closeDB(); return Status.CANCEL_STATUS; } // 开始进行该项文件的该项检查 final String result = realization.startQA(model, subMonitor, iFile, handler, tuDataBean); // // 当未设置术语库、拼写检查词典配置 错误时才会返回 null,所以这时可以直接删。 if (result == null) { model.getBatchQAItemIdList().remove(qaItemId); i --; } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } } qaResult.sendDataToViewer(null); if (!monitorWork(subMonitor, traversalTuIndex, false)) { closeDB(); return Status.CANCEL_STATUS; } } } if (!monitorWork(subMonitor, traversalTuIndex, true)) { closeDB(); return Status.CANCEL_STATUS; } } closeDB(); qaResult.informQAEndFlag(); subMonitor.done(); monitor.done(); System.out.println("所用时间为" + (System.currentTimeMillis() - time1)); return Status.OK_STATUS; } }; // 当程序退出时,检测当前 job 是否正常关闭 CommonFunction.jobCantCancelTip(job); job.addJobChangeListener(new JobChangeAdapter(){ @Override public void running(IJobChangeEvent event) { ProgressIndicatorManager.displayProgressIndicator(); super.running(event); } @Override public void done(IJobChangeEvent event) { ProgressIndicatorManager.hideProgressIndicator(); super.done(event); } }); job.setUser(true); job.schedule(); } /** * 获取某个检查项实现类的实例 * @param qaItemId * @return */ public QARealization getClassInstance(String qaItemId) { if (qaItemClassMap.get(qaItemId) != null) { return (QARealization) qaItemClassMap.get(qaItemId); } try { HashMap<String, String> valueMap = model.getQaItemId_Name_Class().get(qaItemId); Object obj = null; try { obj = Class.forName(valueMap.get(QAConstant.QA_ITEM_CLASSNAME)).newInstance(); } catch (Exception e) { e.printStackTrace(); logger.error( MessageFormat.format(Messages.getString("qa.QualityAssurance.log1"), valueMap.get(QAConstant.QA_ITEM_NAME)), e); } if (QARealization.class.isInstance(obj)) { qaItemClassMap.put(qaItemId, (QARealization) obj); ((QARealization) obj).setParentQaResult(qaResult); return (QARealization) obj; } } catch (Exception e) { logger.error(Messages.getString("qa.all.qaError"), e); } return null; } /** * 解析该文件,若返回false,则标志退出程序的执行 */ public boolean openFile(IProgressMonitor monitor) { for (int fileIndex = 0; fileIndex < model.getQaXlfList().size(); fileIndex++) { IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); final IFile iFile = model.getQaXlfList().get(fileIndex); subMonitor.setTaskName(MessageFormat.format(Messages.getString("qa.QualityAssurance.tip5"), new Object[] { Messages.getString("qa.all.qa"), iFile.getFullPath().toString() })); continuResponse = QAConstant.QA_ZERO; try { Map<String, Object> newResultMap = handler.openFile(iFile.getLocation().toOSString(), subMonitor); // 针对退出解析 if (newResultMap != null && QAConstant.RETURNVALUE_RESULT_RETURN.equals(newResultMap.get(QAConstant.RETURNVALUE_RESULT))) { return false; } if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap .get(QAConstant.RETURNVALUE_RESULT)) { // 针对文件解析出错 Display.getDefault().syncExec(new Runnable() { public void run() { boolean response = MessageDialog.openConfirm(shell, _ERROR, MessageFormat.format( Messages.getString("qa.QualityAssurance.tip6"), new Object[] { iFile.getFullPath().toOSString() })); if (response) { continuResponse = QAConstant.QA_FIRST; } else { continuResponse = QAConstant.QA_TWO; } } }); } if (continuResponse == QAConstant.QA_FIRST) { model.getQaXlfList().remove(fileIndex); fileIndex--; continue; } else if (continuResponse == QAConstant.QA_TWO) { return false; } } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.all.log.openXmlError"), e); } } return true; } /** * 进度条前进处理类,若返回false,则标志退出程序的执行 * @param monitor * @param traversalTuIndex * @param last * @return ; */ public boolean monitorWork(IProgressMonitor monitor, int traversalTuIndex, boolean last){ if (last) { if (traversalTuIndex % workInterval != 0) { if (monitor.isCanceled()) { return false; } monitor.worked(1); } }else { if (traversalTuIndex % workInterval == 0) { if (monitor.isCanceled()) { return false; } monitor.worked(1); } } return true; } /** * 关闭数据库,只针对术语一致性查 * ; */ public void closeDB(){ System.out.println("关闭数据库"); if (qaItemClassMap.get(QAConstant.QA_TERM) != null) { QARealization termRealize = qaItemClassMap.get(QAConstant.QA_TERM); termRealize.closeDB(); } } /** * 初始化进度条前进前隔值,使之总值不大于五百。 */ private int initWorkInterval(){ int allTUSize = 0; for (IFile iFile : model.getQaXlfList()) { allTUSize += handler.getTuSizeMap().get(iFile.getLocation().toOSString()); } if (allTUSize > 500) { workInterval = allTUSize / 500; } return allTUSize; } }
17,981
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QARealization.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/QARealization.java
package net.heartsome.cat.ts.ui.qa; import java.util.Map; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 所有品质检查项实现类的父类 * @author robert 2011-11-10 */ public abstract class QARealization { private QAResult qaResult = null; public final static Logger logger = LoggerFactory.getLogger(QARealization.class.getName()); /** * @param model * 存放品质检查所用到的相关属性 * @param monitor * 进度条实例 * @param iFile * 要品质检查的文件 * @param handler * 对文件操作的类 * @return */ public int start(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QAResult qaResult) { this.qaResult = qaResult; return -1; } /** * 给本类设置消息传送model * @param qaResult ; */ public void setQaResult(QAResult qaResult) { this.qaResult = qaResult; } /** * 当初始化品质检查项实例时,设置消息传送model * @param qaResult ; */ abstract void setParentQaResult(QAResult qaResult); /** * 将品质检查的结果输出到相关视图 * @param lineNumber * 行号 * @param qaType * 检查类别 * @param errorTip * 错误信息提示 * @param filePath * 文件资源 * @param langPair * 语言对 */ public void printQAResult(final QAResultBean bean) { // 设置当前的数据是否是 自动品质检查 的数据 bean.setAutoQA(qaResult.isAutoQA()); qaResult.firePropertyChange(bean); } /** * 关闭数据库连接,目前只针对术语一致性分析 * ; */ public void closeDB(){} /** * 品质检查,针对于自动检查中,若返回结果的字符串长度大于1,则标识错误 * <div style="color:red">当未设置术语库、拼写检查词典配置 错误时才会返回 null,所以这时可以直接删。</div> * @param model * @param monitor * @param iFile * @param xmlHandler * @param qaResult * @param tuMap * @return ; */ public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { return ""; } }
2,575
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NumberConsistenceQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/NumberConsistenceQA.java
package net.heartsome.cat.ts.ui.qa; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; /** * 品质检查--术语一致性检查 * 进度条提示格式为 MessageFormat.format("检查{0}文件,术语一致性检查:术语比较...) * 进度条推进方法:设一个间隔值workInterval,先计算出要循环的所有的tu节点的数量,每workInterval个tu节点,推进一格 * @author robert * */ public class NumberConsistenceQA extends QARealization { private int level; private IPreferenceStore preferenceStore; private boolean hasError; public NumberConsistenceQA(){ preferenceStore = Activator.getDefault().getPreferenceStore(); level = preferenceStore.getInt(QAConstant.QA_PREF_number_TIPLEVEL); } @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } @Override public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } hasError = false; //获取纯文本 String srcPureText = tuDataBean.getSrcPureText(); String tgtPureText = tuDataBean.getTgtPureText(); String pattern = "-?\\d{1,}(\\.?\\d{1,})?"; Pattern patt = Pattern.compile(pattern); //获取源文本中的所有数字 Matcher matcher = patt.matcher(srcPureText); List<String> sourceNumbers = new LinkedList<String>(); while (matcher.find()) { sourceNumbers.add(matcher.group()) ; } //获取目标文本中的数字 matcher = patt.matcher(tgtPureText); List<String> targetNumbers = new LinkedList<String>(); while (matcher.find()) { targetNumbers.add(matcher.group()) ; } String lineNumber = tuDataBean.getLineNumber(); String rowId = tuDataBean.getRowId(); String qaTypeText = Messages.getString("qa.all.qaItem.NumberConsistenceQA"); Map<String, List<String>> resultMap = compareNumber(sourceNumbers, targetNumbers); if (resultMap.get("source") != null && resultMap.get("source").size() > 0) { //输出数字一致性中目标文件所遗失的数字 List<String> resultList = resultMap.get("source"); String resultStr = ""; for (int index = 0; index < resultList.size(); index++) { resultStr += "'" + resultList.get(index) + "', "; } if (resultStr.length() > 0) { resultStr = resultStr.substring(QAConstant.QA_ZERO, resultStr.length() - QAConstant.QA_TWO); // String errorTip = MessageFormat.format(Messages.getString("qa.NumberConsistenceQA.tip1"), resultStr); hasError = true; } } //输出数字一致性检查中目标文件中多出的数字 if (resultMap.get("target") != null && resultMap.get("target").size() > 0) { //输出数字一致性中目标文件所遗失的数字 List<String> resultList = resultMap.get("target"); String resultStr = ""; for (int index = 0; index < resultList.size(); index++) { resultStr += "'" + resultList.get(index) + "', "; } if (resultStr.length() > 0) { resultStr = resultStr.substring(QAConstant.QA_ZERO, resultStr.length() - QAConstant.QA_TWO); // String errorTip = MessageFormat.format(Messages.getString("qa.NumberConsistenceQA.tip2"), resultStr); hasError = true; } } if (hasError) { super.printQAResult(new QAResultBean(level, QAConstant.QA_NUMBER, qaTypeText, null, tuDataBean.getFileName(), lineNumber, tuDataBean.getSrcContent(), tuDataBean.getTgtContent(), rowId)); } String result = ""; if (hasError && level == 0) { result = QAConstant.QA_NUMBER; } return result; } /** * 将查出的数字与目标文本进行相关的比较 * @param findNumber * @param targetText * @return */ public Map<String, List<String>> compareNumber(List<String> sourceNumbers, List<String> targetNumbers){ Map<String, List<String>> resultMap = new HashMap<String, List<String>>(); List<String> resultList = new LinkedList<String>(); //下面查看其目标数字集合中是否有源文本中的数字,如果有,则将这个数字从目标数字集合中删除 int tarIndex; if (targetNumbers.size() == 0) { resultMap.put("source", sourceNumbers); return resultMap; } for (int index = 0; index < sourceNumbers.size(); index++) { String sourceNumber = sourceNumbers.get(index); if ((tarIndex = targetNumbers.indexOf(sourceNumber)) >= 0) { targetNumbers.remove(tarIndex); }else { resultList.add(sourceNumber); } } resultMap.put("source", resultList); if (targetNumbers.size() > 0) { resultMap.put("target", targetNumbers); } return resultMap; } }
5,268
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.ui.qa/src/net/heartsome/cat/ts/ui/qa/Activator.java
package net.heartsome.cat.ts.ui.qa; 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.ui.qa"; //$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; } /** * 提供一个图片文件对插件的相对路径,返回该图片的描述信息。 * @param path * 图片资源对插件的相对路径。 * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } }
1,417
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ParaCompletenessQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/ParaCompletenessQA.java
package net.heartsome.cat.ts.ui.qa; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; /** * 文本段完整性检查 * 分三种情况: * a、目标文本不能为空。 * b、若目标文本有一个空格,那么就检查源文本是否是一个空格,若源文本中并不是空格,那么也不得行。 * c、检查源文本与目标文本是否一致。 * @author robert * @version * @since JDK1.6 */ public class ParaCompletenessQA extends QARealization{ private int level; private IPreferenceStore preferenceStore; private boolean hasError; public ParaCompletenessQA(){ preferenceStore = Activator.getDefault().getPreferenceStore(); level = preferenceStore.getInt(QAConstant.QA_PREF_paraComplete_TIPLEVEL); } @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } @Override public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { hasError = false; String lineNumber = tuDataBean.getLineNumber(); String qaTypeText = Messages.getString("qa.all.qaItem.ParaCompletenessQA"); String srcContent = tuDataBean.getSrcContent(); String tgtContent = tuDataBean.getTgtContent(); String rowId = tuDataBean.getRowId(); // String errorTip = ""; // 检查未翻译的情况 if (tgtContent == null || "".equals(tgtContent)) { // errorTip = Messages.getString("qa.ParaCompletenessQA.tip1"); hasError = true; } else if (tgtContent.length() > 0 && "".equals(tgtContent.trim())) { // 检查目标文本中有一空格的情况 // 如果源文也是一个空格,那么通过检查,如果源文不是空格,则提示未翻译 if (!(srcContent.length() > 0 && "".equals(srcContent.trim()))) { // errorTip = Messages.getString("qa.ParaCompletenessQA.tip2"); hasError = true; } } else if (tgtContent.trim().equals(srcContent.trim())) {// 检查源文与译文一致的情况 // errorTip = Messages.getString("qa.ParaCompletenessQA.tip3"); hasError = true; } if (hasError) { super.printQAResult(new QAResultBean(level, QAConstant.QA_PARACOMPLETENESS, qaTypeText, null, tuDataBean.getFileName(), lineNumber, srcContent, tgtContent, rowId)); } String result = ""; if (hasError && level == 0) { result = QAConstant.QA_PARACOMPLETENESS; } return result; } }
2,839
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NonTranslationQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/NonTranslationQA.java
package net.heartsome.cat.ts.ui.qa; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.NontransElementBean; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.nonTransElement.NonTransElementOperate; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 品质检查-非译元素 * 进度条提示格式为 MessageFormat.format("检查{0}文件,非译元素检查...) * 2011-11-22 完成功能:检查内置元素,如邮件,IP地址,web链接 * @author robert 2011-11-21 */ public class NonTranslationQA extends QARealization { /** 译文中丢失非译元素的集合 */ private List<String> srcNonTransData; /** 源文中丢失非译元素的集合 */ private List<String> tgtNonTransData; private String srcLang = ""; private String tgtLang = ""; private List<NontransElementBean> nonTransElementsMap; private int level; private IPreferenceStore preferenceStore; private boolean hasError; public final static Logger logger = LoggerFactory.getLogger(NonTranslationQA.class.getName()); public NonTranslationQA(){ preferenceStore = Activator.getDefault().getPreferenceStore(); level = preferenceStore.getInt(QAConstant.QA_PREF_nonTrans_TIPLEVEL); } @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } @Override public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } hasError = false; if (nonTransElementsMap == null) { //非译元素库的操作类 NonTransElementOperate operater = new NonTransElementOperate(); //先打开库 operater.openNonTransDB(); //开始从非译元素库中获取相关信息 nonTransElementsMap = operater.getNonTransElements(); } srcNonTransData = new LinkedList<String>(); tgtNonTransData = new LinkedList<String>(); //获取纯文本 String sourceText = tuDataBean.getSrcPureText(); String targetText = tuDataBean.getTgtPureText(); String rowId = tuDataBean.getRowId(); srcLang = tuDataBean.getSrcLang(); tgtLang = tuDataBean.getTgtLang(); // UNDO 这里存在一个问题,就是web地址检查与ip地址检查的语句差不多,故存在会引起一个非译元素会同时被检查并多次提示。 for (int index = 0; index < nonTransElementsMap.size(); index++) { NontransElementBean elementBean = nonTransElementsMap.get(index); String elementContent = elementBean.getContent(); String elementRegular = elementBean.getRegular(); matchNontrans(sourceText, targetText, elementContent, elementRegular); } // UNDO 非译元素检查时,把数字也检查出来了 String lineNumber = tuDataBean.getLineNumber(); String fileName = tuDataBean.getFileName(); String qaTypeText = Messages.getString("qa.all.qaItem.NonTranslationQA"); //处理源文中的非译元素在译文中丢失的情况 if (srcNonTransData.size() > 0) { String nonTransStr = ""; for (int index = 0; index < srcNonTransData.size(); index++) { nonTransStr += "'" + srcNonTransData.get(index) + "', "; } nonTransStr = nonTransStr.substring(0, nonTransStr.length() - 2); // String errorTip = MessageFormat.format(Messages.getString("qa.NonTranslationQA.tip1"), nonTransStr); hasError = true; } //处理译文中的非译元素在源文中丢失的情况 if (tgtNonTransData.size() > 0) { String nonTransStr = ""; for (int index = 0; index < tgtNonTransData.size(); index++) { nonTransStr += "'" + tgtNonTransData.get(index) + "', "; } nonTransStr = nonTransStr.substring(0, nonTransStr.length() - 2); // String errorTip = MessageFormat.format(Messages.getString("qa.NonTranslationQA.tip2"), nonTransStr); hasError = true; } if (hasError) { super.printQAResult(new QAResultBean(level, QAConstant.QA_NONTRANSLATION, qaTypeText, null, fileName, lineNumber, sourceText, targetText, rowId)); } String result = ""; if (hasError && level == 0) { result = QAConstant.QA_NONTRANSLATION; } return result; } /** * 检查邮件名 * @param sourceText * @param targetText */ public void matchNontrans(String sourceText, String targetText, String elementContent, String elementRegular){ if (elementRegular == null || "".equals(elementRegular)) { elementRegular = elementContent; } if (elementRegular == null || "".equals(elementRegular)) { return; } Pattern patt = Pattern.compile(CommonFunction.isAsiaLang(srcLang) ? elementRegular.replace("\\b", "") : elementRegular); //先匹配源文本里面是否有邮箱名 List<String> sourceEmailList = new LinkedList<String>(); Matcher matcher = patt.matcher(sourceText); while (matcher.find()) { sourceEmailList.add(matcher.group()); } //现在检查目标文本中是否有相关匹配 List<String> targetEmailList = new LinkedList<String>(); patt = Pattern.compile(CommonFunction.isAsiaLang(tgtLang) ? elementRegular.replace("\\b", "") : elementRegular); Matcher tarMatcher = patt.matcher(targetText); while (tarMatcher.find()) { targetEmailList.add(tarMatcher.group()); } //下面比较两个list所包含的email的不同 if (sourceEmailList.size() > 0 ) { for (int sourIndex = 0; sourIndex < sourceEmailList.size(); sourIndex++) { String nonTransStr = sourceEmailList.get(sourIndex); boolean equals = false; for (int tarIndex = 0; tarIndex < targetEmailList.size(); tarIndex++) { if (nonTransStr.equals(targetEmailList.get(tarIndex))) { equals = true; targetEmailList.remove(tarIndex); break; } } if (!equals && srcNonTransData.indexOf(nonTransStr) < 0) { srcNonTransData.add(nonTransStr); } } } // 下面比译文中有的非译元素,但是源文中没得的情况 for (String nonTransStr : targetEmailList) { if (tgtNonTransData.indexOf(nonTransStr) < 0) { tgtNonTransData.add(nonTransStr); } } return; } /** * 匹配IP,备注,这个方法改动比较大,之前的版本有备份,详见代码备份 ,task33 * @param sourceText * @param targetText */ public void matchIP(String sourceText, String targetText, String elementContent, String elementRegular){ if (elementRegular == null || "".equals(elementRegular)) { elementRegular = elementContent; } if (elementRegular == null || "".equals(elementRegular)) { return; } elementRegular = TextUtil.resetSpecialString(elementRegular); Pattern patt = Pattern.compile(elementRegular); //先匹配源文本里面是否有邮箱名 List<String> sourceIpList = new LinkedList<String>(); Matcher matcher = patt.matcher(sourceText); while (matcher.find()) { sourceIpList.add(matcher.group()); } //现在检查目标文本中是否有相关匹配 List<String> targetIpList = new LinkedList<String>(); Matcher tarMatcher = patt.matcher(targetText); while (tarMatcher.find()) { targetIpList.add(tarMatcher.group()); } //下面比较两个list所包含的email的不同 if (sourceIpList.size() > 0 ) { for (int sourIndex = 0; sourIndex < sourceIpList.size(); sourIndex++) { String nonTransStr = sourceIpList.get(sourIndex); boolean equals = false; for (int tarIndex = 0; tarIndex < targetIpList.size(); tarIndex++) { if (nonTransStr.equals(targetIpList.get(tarIndex))) { equals = true; targetIpList.remove(tarIndex); break; } } if (!equals && srcNonTransData.indexOf(nonTransStr) < 0) { srcNonTransData.add(nonTransStr); } } } // 下面比译文中有的非译元素,但是源文中没得的情况 for (String nonTransStr : targetIpList) { if (tgtNonTransData.indexOf(nonTransStr) < 0) { tgtNonTransData.add(nonTransStr); } } return; } /** * 匹配网址 * @param sourceText * @param targetText */ public void matchWebAddress(String sourceText, String targetText, String elementContent, String elementRegular){ if (elementRegular == null || "".equals(elementRegular)) { elementRegular = elementContent; } if (elementRegular == null || "".equals(elementRegular)) { return; } //这能匹配有IP的情况,但是无法保证IP是否是合法 //String pattern = "((http|https|ftp)://(www.)?((((\\w+)+[.])*(net|com|cn|org|cc|tv|[0-9]{1,3}(:\\d{1,})?)))(/([+-_.=%&?#|]?(\\w+)[+-_.=%&?#|]?)*)*)"; //String pattern = "(((http|https|ftp|gopher|wais)://)?((((\\w+|[-]*)+))+:(((\\w+|[-]*)+))+@)?((www[.])?((\\w+[.])+|((\\w+|[-]*)+[.]))+(net|com|org|mil|gov|edu|int)(.(cn|hk|uk|sg|us|jp|cc|tv))?|(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}))(:\\d{1,})?(/?)([+-_.=%&?#|/]*([\\w\\S]+)[+-_.=%&?#|/]*)*(/?))"; // String pattern = "(((http|https|ftp|gopher|wais)://)?(www\\.)?(([^,,\\s])*(\\.(net|com|cn|org|cc|tv|hk|uk|sg|us|jp|mil|gov|edu|int)))(((:port)|[0-9]{1,3}(:\\d{1,})?)?)([^,,\\s])*)"; Pattern patt = Pattern.compile(elementRegular); // 先匹配源文本里面是否有邮箱名 Matcher matcher = patt.matcher(sourceText); List<String> sourceURLList = new LinkedList<String>(); while (matcher.find()) { sourceURLList.add(matcher.group()); } //再匹配目标文本中是否有网址 Matcher tarMatcher = patt.matcher(targetText); List<String> targetURLList = new LinkedList<String>(); while (tarMatcher.find()) { targetURLList.add(tarMatcher.group()); } //比较网址是否被翻译或缺失 if (sourceURLList.size() > 0 ) { for (int sourIndex = 0; sourIndex < sourceURLList.size(); sourIndex++) { String nonTransStr = sourceURLList.get(sourIndex); boolean equals = false; for (int tarIndex = 0; tarIndex < targetURLList.size(); tarIndex++) { if (nonTransStr.equals(targetURLList.get(tarIndex))) { equals = true; targetURLList.remove(tarIndex); break; } } if (!equals && srcNonTransData.indexOf(nonTransStr) < 0) { srcNonTransData.add(nonTransStr); } } } // 下面比译文中有的非译元素,但是源文中没得的情况 for (String nonTransStr : targetURLList) { if (tgtNonTransData.indexOf(nonTransStr) < 0) { tgtNonTransData.add(nonTransStr); } } return; } /** * 匹配除内置非译元素除 * @param sourceText * @param targetText * @param elementContent * @param elementRegular */ public void matchOthers(String sourceText, String targetText, String elementName, String elementContent, String elementRegular){ if (elementRegular == null || "".equals(elementRegular)) { elementRegular = elementContent; } if (elementRegular == null || "".equals(elementRegular)) { return; } Pattern patt = Pattern.compile(elementRegular); // 先匹配源文本里面是否有合适的匹配 Matcher matcher = patt.matcher(sourceText); List<String> sourceMatchList = new LinkedList<String>(); while (matcher.find()) { sourceMatchList.add(matcher.group()); } //再匹配目标文本中是否有合适的匹配 Matcher tarMatcher = patt.matcher(targetText); List<String> targetMatchList = new LinkedList<String>(); while (tarMatcher.find()) { targetMatchList.add(tarMatcher.group()); } //比较匹配结果是否被翻译或缺失 if (sourceMatchList.size() > 0 ) { for (int sourIndex = 0; sourIndex < sourceMatchList.size(); sourIndex++) { String nonTransStr = sourceMatchList.get(sourIndex); boolean equals = false; for (int tarIndex = 0; tarIndex < targetMatchList.size(); tarIndex++) { if (nonTransStr.equals(targetMatchList.get(tarIndex))) { equals = true; targetMatchList.remove(tarIndex); break; } } if (!equals) { srcNonTransData.add(nonTransStr); } } } // 下面比译文中有的非译元素,但是源文中没得的情况 for (String nonTransStr : targetMatchList) { if (tgtNonTransData.indexOf(nonTransStr) < 0) { tgtNonTransData.add(nonTransStr); } } return; } public static void main(String[] args) { // String regular = "(?<=\\s+|^)[A-Z]+(?=\\s+|$)"; // String regular = "\\b(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)){3}(:\\d{1,})?\\b"; // String regular = "\\b(abc){1}(?=\\s|$|\\b)"; String regular = "(((http|https|ftp|gopher|wais)://)?(www\\.)?(([^,,\\s@])*(\\.(net|com|cn|org|cc|tv|hk|uk|sg|us|jp|mil|gov|edu|int)))(((:port)|[0-9]{1,3}(:\\d{1,})?)?)([^,,\\s])*)"; // String text = "中国人的什么菏一 THEST 木"; // String text = "an open source community and an ecosystem of complementary products and services.192.168.0.1.2"; // String text = "aiabc"; String text = "2、测试非译元素 [email protected]@[email protected]@qq.com"; Pattern patt = Pattern.compile(regular); // 先匹配源文本里面是否有合适的匹配 Matcher matcher = patt.matcher(text); while(matcher.find()){ System.out.println(matcher.group()); } } }
13,729
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SpaceOfParaCheckQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/SpaceOfParaCheckQA.java
package net.heartsome.cat.ts.ui.qa; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; /** * 段首、段末空格检查 * 是指源文本与目标文本的段首和段末的空格必须一致。 * @author robert 2012-01-17 * @version * @since JDK1.6 */ public class SpaceOfParaCheckQA extends QARealization { private int level; private IPreferenceStore preferenceStore; private boolean hasError; public SpaceOfParaCheckQA(){ preferenceStore = Activator.getDefault().getPreferenceStore(); level = preferenceStore.getInt(QAConstant.QA_PREF_spaceOfPara_TIPLEVEL); } @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } @Override public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } hasError = false; String lineNumber = tuDataBean.getLineNumber(); String qaTypeText = Messages.getString("qa.all.qaItem.SpaceOfParaCheck"); String srcContent = tuDataBean.getSrcContent(); String tgtContent = tuDataBean.getTgtContent(); String rowId = tuDataBean.getRowId(); int srcFirstSpaceNum = getSpaceNumber(srcContent, true); int srcLastSpaceNum = getSpaceNumber(srcContent, false); int tarFirstSpaceNum = getSpaceNumber(tgtContent, true); int tarLastSpaceNum = getSpaceNumber(tgtContent, false); //先处理段首空格的检查 // String errorTip = ""; if (srcFirstSpaceNum > tarFirstSpaceNum) { // errorTip = MessageFormat.format(Messages.getString("qa.SpaceOfParaCheckQA.tip1"), new Object[] { // srcFirstSpaceNum, tarFirstSpaceNum, (srcFirstSpaceNum - tarFirstSpaceNum) }); hasError = true; }else if (srcFirstSpaceNum < tarFirstSpaceNum) { // errorTip = MessageFormat.format(Messages.getString("qa.SpaceOfParaCheckQA.tip2"), new Object[] { // srcFirstSpaceNum, tarFirstSpaceNum, (tarFirstSpaceNum - srcFirstSpaceNum) }); hasError = true; } //如果源文本全是空格,只提示段首空格,不提示段尾 if (srcFirstSpaceNum == srcContent.length()) { return ""; } //处理段末空格的检查 if (srcLastSpaceNum > tarLastSpaceNum) { // errorTip = MessageFormat.format(Messages.getString("qa.SpaceOfParaCheckQA.tip3"), new Object[] { // srcLastSpaceNum, tarLastSpaceNum, (srcLastSpaceNum - tarLastSpaceNum) }); hasError = true; }else if (srcLastSpaceNum < tarLastSpaceNum) { // errorTip = MessageFormat.format(Messages.getString("qa.SpaceOfParaCheckQA.tip4"), new Object[] { // srcLastSpaceNum, tarLastSpaceNum, (tarLastSpaceNum - srcLastSpaceNum) }); hasError = true; } if (hasError) { super.printQAResult(new QAResultBean(level, QAConstant.QA_SPACEOFPARACHECK, qaTypeText, null, tuDataBean.getFileName(), lineNumber, srcContent, tgtContent, rowId)); } String result = ""; if (hasError && level == 0) { result = QAConstant.QA_SPACEOFPARACHECK; } return result; } /** * 获取文本段段首或段尾的空格数 * @param content 要获取空格数的文本 * @param isFirst 是否获取段首的空格数 * @return 空格数; */ public int getSpaceNumber(String content, boolean isFirst){ int spaceNum = 0; if (isFirst) { for (int i = 0; i < content.length(); i++) { if (content.charAt(i) == QAConstant.QA_ONE_SPACE_CHAR) { spaceNum ++; }else { break; } } }else { for (int i = content.length() - 1; i >= 0; i--) { if (content.charAt(i) == QAConstant.QA_ONE_SPACE_CHAR) { spaceNum ++; }else { break; } } } return spaceNum; } }
4,135
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SpellQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/SpellQA.java
package net.heartsome.cat.ts.ui.qa; import java.text.MessageFormat; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import net.heartsome.cat.common.core.Constant; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.core.bean.SingleWord; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.nonTransElement.NonTransElementOperate; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.qa.spell.AspellChecker; import net.heartsome.cat.ts.ui.qa.spell.Hunspell; import net.heartsome.cat.ts.ui.qa.spell.inter.HSSpellChecker; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Display; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 拼写检查, * @author robert 2012-02-03 * @version * @since JDK1.6 */ public class SpellQA extends QARealization { private HSSpellChecker spelling = null; /** 不需用进行拼写检查的目标语言 */ private List<String> nonSpellTarLangList = new ArrayList<String>(); private int level; private IPreferenceStore qaPreferenceStore; private boolean hasError; private boolean isContinue; private StringTokenizer stringToken; /** 拼写检查器类型,是否是 hunspell 拼写词典 */ private boolean isHunspell = false; private NonTransElementOperate nontransOper; /** 是否忽略非译元素 */ private boolean ignoreNontrans; /** 是否忽略单词首字母为数字 */ private boolean ignoreDigitalFirst; /** 是否忽略单词首字母为大写 */ private boolean ignoreUpperCaseFirst; /** 忽略全大写单词 */ private boolean ignoreAllUpperCase; public final static Logger logger = LoggerFactory.getLogger(SpellQA.class.getName()); @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } public SpellQA(){ //确定检查类别 IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); isHunspell = preferenceStore.getBoolean(QAConstant.QA_PREF_isHunspell); ignoreNontrans = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreNontrans); ignoreDigitalFirst = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreDigitalFirst); ignoreUpperCaseFirst = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreUpperCaseFirst); ignoreAllUpperCase = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreAllUpperCase); qaPreferenceStore = Activator.getDefault().getPreferenceStore(); level = qaPreferenceStore.getInt(QAConstant.QA_PREF_spell_TIPLEVEL); //UNDO 拼写检查的信息提示太过专业化,详细化提示。比如:qa.spellCheck.HashDictionary.tip1=词典文件缺少表格大小。 } @Override public String startQA(final QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } if (monitor == null) { monitor = new NullProgressMonitor(); } hasError = false; isContinue = false; //目标语言 final String tgtLang = tuDataBean.getTgtLang(); //若未配置该目标语言的词典,退出程序的执行 if (nonSpellTarLangList.indexOf(tgtLang) != -1) { return ""; } String tgtPureText = TextUtil.resetSpecialString(tuDataBean.getTgtPureText()); String lineNumber = tuDataBean.getLineNumber(); String rowId = tuDataBean.getRowId(); if (spelling == null) { if (isHunspell) { spelling = new Hunspell(model.getShell()); if (ignoreNontrans) { nontransOper = new NonTransElementOperate(); nontransOper.openNonTransDB(); } }else { spelling = new AspellChecker(); } } // 若拼写检查器错误,或者出错,返回 null if (spelling == null || spelling.isError()) { return null; } //如果该拼写检查实例为空,退出执行,并且下次遇到相同目标语言不再检查 if (!spelling.checkLangAvailable(tgtLang)) { nonSpellTarLangList.add(tgtLang); if (!isHunspell) { Display.getDefault().syncExec(new Runnable() { public void run() { String message = Messages.getString("qa.SpellQA.addTip1"); message = MessageFormat.format(message, new Object[]{tgtLang}); isContinue = MessageDialog.openConfirm(model.getShell(), Messages.getString("qa.all.dialog.confirm"), message); } }); if (!isContinue) { monitor.setCanceled(true); } } return ""; } List<SingleWord> errorWords; if (isHunspell) { LinkedList<SingleWord> wordList = new LinkedList<SingleWord>(); getSingleWords(tgtPureText, wordList); errorWords = spelling.getErrorWords(null, wordList, tgtLang); }else { LinkedList<SingleWord> wordList = new LinkedList<SingleWord>(); getSingleWords(tgtPureText, wordList); errorWords = spelling.getErrorWords(tgtPureText, wordList, tgtLang); } if (spelling.isError()) { return null; } //开始输入结果 if (errorWords == null || errorWords.size() == 0) { return ""; } String qaTypeText = Messages.getString("qa.all.qaItem.SpellQA"); // String errorTip = Messages.getString("qa.SpellQA.tip1"); // for (int i = 0; i < errorWords.size(); i++) { // errorTip += "'" + errorWords.get(i).getPureWord() + "' 、"; // } // errorTip = errorTip.substring(0, errorTip.length() - 1); // errorTip += Messages.getString("qa.SpellQA.tip2"); hasError = true; super.printQAResult(new QAResultBean(level, QAConstant.QA_SPELL, qaTypeText, null, tuDataBean.getFileName(), lineNumber, tuDataBean.getSrcContent(), tuDataBean.getTgtContent(), rowId)); String result = ""; if (hasError && level == 0) { result = QAConstant.QA_SPELL; } return result; } /** * 获取单个单词,这里面主要是根据不同的选项。得到要进行拼写检查的单词 */ private void getSingleWords(String pureText, List<SingleWord> tgtWordList) { stringToken = new StringTokenizer(pureText, Constant.SEPARATORS, false); List<Integer[]> ignoreParaList = null; // 如果要处理忽略非译元素,那么执行如下操作 (备注:所有的忽略项。只是针对 hunspell) if (isHunspell && ignoreNontrans) { ignoreParaList = nontransOper.getIgnorePara(pureText, null); } int start = 0; int length = 0; int end = 0; while(stringToken.hasMoreTokens()){ String pureWord = stringToken.nextToken(); start = pureText.indexOf(pureWord, start); length = pureWord.length(); end = start + length; // 经过一系列的判断,从而删除一些不符合标准的单词。将剩下的单词传入拼写检查器中进行检查 if (isHunspell) { // 是否忽略非译元素 if (ignoreNontrans) { boolean needIgnore = false; for(Integer[] ignoreIndexs : ignoreParaList){ if (start >= ignoreIndexs[0] && end <= ignoreIndexs[1] ) { needIgnore = true; break; } } if (needIgnore) { start = start + pureWord.length(); continue; } } // 是否忽略首字母为数字 if (ignoreDigitalFirst && checkDigitalFirst(pureWord)) { start = start + pureWord.length(); continue; } // 是否忽略首字母为大写 if (ignoreUpperCaseFirst && checkUpperCaseFirst(pureWord)) { start = start + pureWord.length(); continue; } //是否忽略全大写单词 if (ignoreAllUpperCase && checkAllUpperCase(pureWord)) { start = start + pureWord.length(); continue; } } tgtWordList.add(new SingleWord(null, pureWord, start, length)); start = start + pureWord.length(); } } /** * 检查单词是否首字母大写 * @return */ private boolean checkDigitalFirst(String pureWord){ return Character.isDigit(pureWord.charAt(0)); } /** * 检查单词是否首字母为数字 * @return */ private boolean checkUpperCaseFirst(String pureWord){ for (int i = 0; i < pureWord.length(); i++) { if (Character.isDigit(pureWord.charAt(i))) { continue; }else { return Character.isUpperCase(pureWord.charAt(i)); } } return true; } /** * 检查单词是否首字母为数字 * @return */ private boolean checkAllUpperCase(String pureWord){ return pureWord.equals(pureWord.toUpperCase()); } }
8,823
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TermConsistenceQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/TermConsistenceQA.java
package net.heartsome.cat.ts.ui.qa; import java.util.Hashtable; import java.util.Vector; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.tb.match.TbMatcher; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Display; /** * 术语一致性检查 * 进度条提示格式为 MessageFormat.format("检查{0}文件,术语一致性检查:术语比较...) * @author robert 2011-11-09 */ public class TermConsistenceQA extends QARealization { private TbMatcher matcher = new TbMatcher(); private int level; private IPreferenceStore preferenceStore; private boolean hasError; private boolean isContinue; public TermConsistenceQA(){ preferenceStore = Activator.getDefault().getPreferenceStore(); level = preferenceStore.getInt(QAConstant.QA_PREF_term_TIPLEVEL); } @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } /** * 如果返回空,则标示未配置术语库 */ @Override public String startQA(final QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } hasError = false; isContinue = false; if (monitor == null) { monitor = new NullProgressMonitor(); } if (!matcher.checkTbMatcher(iFile.getProject())) { Display.getDefault().syncExec(new Runnable() { public void run() { String message = Messages.getString("qa.TermConsistenceQA.addTip1"); isContinue = MessageDialog.openConfirm(model.getShell(), Messages.getString("qa.all.dialog.confirm"), message); } }); if (!isContinue) { monitor.setCanceled(true); } // 未设置术语库,返回 null return null; } //获取操作术语库的操作类,设置新的项目 matcher.setCurrentProject(iFile.getProject()); //现在循环扇历该xliff文件的每一个trans-unit节点,去比较它的术语存在性,monitor推进3格 compareTerms(iFile, xmlHandler, tuDataBean); String result = ""; if (hasError && level == 0) { result = QAConstant.QA_TERM; } return result; } /** * 比较术语 * @param iFile 要检查的文件 * @param handler xml文件操作类 */ private void compareTerms(IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean){ String srcLang = tuDataBean.getSrcLang(); String tgtLang = tuDataBean.getTgtLang(); boolean souTerm_Context = getContext(srcLang); boolean tarTerm_Context = getContext(tgtLang); String sourceText = TextUtil.resetSpecialString(tuDataBean.getSrcPureText()); String targetText = TextUtil.resetSpecialString(tuDataBean.getTgtPureText()); targetText = TextUtil.normalise(targetText, true); // targetText = TextUtil.cleanString(targetText); sourceText = TextUtil.normalise(sourceText, true); // sourceText = TextUtil.cleanString(sourceText); Vector<Hashtable<String, String>> termsVector = matcher.serachTransUnitTerms(sourceText, srcLang, tgtLang, false); String lineNumber = tuDataBean.getLineNumber(); String rowId = tuDataBean.getRowId(); //开始循环术语库中的术语,进行比较 for (int termIndex = 0; termIndex < termsVector.size(); termIndex++) { String sourceTerm = termsVector.get(termIndex).get("srcWord"); String targetTerm = termsVector.get(termIndex).get("tgtWord"); if (containsTerm(sourceText, sourceTerm, souTerm_Context)) { if (!containsTerm(targetText, targetTerm, tarTerm_Context)) { // String errorTip = MessageFormat.format(Messages.getString("qa.TermConsistenceQA.tip1"), // new Object[] { "'" + sourceTerm + "'", "'" + targetTerm + "'" }); hasError = true; String qaTypeText = Messages.getString("qa.all.qaItem.TermConsistenceQA"); super.printQAResult(new QAResultBean(level, QAConstant.QA_TERM, qaTypeText, null, tuDataBean.getFileName(), lineNumber, tuDataBean.getSrcContent(), tuDataBean.getTgtContent(), rowId)); } } } } /** * 比较一个文本段是否包插指定术语,如果包括,返回true * @param context : 是否进行比较上下文,如果是英文,则要进行比较,因为英文每个单词之间有空格, * 如果是中文,就不需要比较上下文 */ private boolean containsTerm(String text, String term, boolean context){ text = resetCleanString(text); //因为查询出的术语已经进行转义了 int idxTerm = text.toLowerCase().indexOf(term.toLowerCase()); boolean exsit = false; while(idxTerm != -1){ char blankChar = ' '; if (idxTerm < 0){ continue; } if (context) { char prevChar = blankChar; char nextChar = blankChar; if (term.charAt(0) == blankChar) { prevChar = blankChar; }else { if (idxTerm > 0){ prevChar = text.charAt(idxTerm -1); } } if (term.charAt(term.length() - 1) == blankChar) { nextChar = blankChar; }else { if (idxTerm + term.length() +1 < text.length()){ nextChar = text.charAt(idxTerm + term.length()); } } exsit = validContainsChar(prevChar) && validContainsChar(nextChar); if (exsit) { return true; } }else { return true; } idxTerm = text.toLowerCase().indexOf(term.toLowerCase(), idxTerm + 1); } return exsit; } private boolean validContainsChar(char ch){ return !(Character.isLetterOrDigit(ch) || ch == '@'); } /** * 判断语言的种类,如果是英语,那么要进行获取上下文进行判断, * 如果是中文,不需要 * @param language * @return */ private boolean getContext(String language){ if (language.matches("zh.*|ja.*|ko.*|th.*|he.*")) { return false; } return true; } private static String resetCleanString(String string){ string = string.replaceAll("&lt;", "<" ); string = string.replaceAll("&gt;", ">"); // string = string.replaceAll("&quot;", "\""); string = string.replaceAll("&amp;", "&"); return string; } @Override public void closeDB(){ matcher.clearResources(); } }
6,740
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TagConsistenceQA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/TagConsistenceQA.java
package net.heartsome.cat.ts.ui.qa; import java.text.MessageFormat; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; /** * 标记一致性检查 * 进度条提示格式为 MessageFormat.format("检查{0}文件,术语一致性检查:术语比较...) * 第一次编写时间:2011-11-18,主要获取所有的标记,在比较时只用比较目标文本中是否有缺时的标记,忽略标记与标记之间的关系。 * @author robert 2011-11-18 * */ public class TagConsistenceQA extends QARealization{ private int level; private IPreferenceStore preferenceStore; private boolean hasError; public TagConsistenceQA(){ preferenceStore = Activator.getDefault().getPreferenceStore(); level = preferenceStore.getInt(QAConstant.QA_PREF_tag_TIPLEVEL); } @Override void setParentQaResult(QAResult qaResult) { super.setQaResult(qaResult); } @Override public String startQA(QAModel model, IProgressMonitor monitor, IFile iFile, QAXmlHandler xmlHandler, QATUDataBean tuDataBean) { if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { return ""; } hasError = false; //获取语言对 String lineNumber = tuDataBean.getLineNumber(); String rowId = tuDataBean.getRowId(); String srcContent = tuDataBean.getSrcContent(); String tgtContent = tuDataBean.getTgtContent(); if (!(srcContent.indexOf("<") >=0 || srcContent.indexOf("</") >=0 || srcContent.indexOf("/>") >= 0) && !(tgtContent.indexOf("<") >=0 || tgtContent.indexOf("</") >=0 || tgtContent.indexOf("/>") >= 0)) { return ""; } String srcContentXml = "<xml>" + srcContent + "</xml>"; String tgtContentXml = "<xml>" + tgtContent + "</xml>"; List<Map<String, String>> sourceTagList = xmlHandler.getTUTag(srcContentXml); List<Map<String, String>> targetTagList = xmlHandler.getTUTag(tgtContentXml); List<String> loseTag = new LinkedList<String>(); List<String> changeTag = new LinkedList<String>(); //开始比较源文本与目标文本标记的不同 for (int sourceIndex = 0; sourceIndex < sourceTagList.size(); sourceIndex++) { Map<String, String> sourceTagMap = sourceTagList.get(sourceIndex); String tagName = sourceTagMap.get(QAConstant.QA_TAGNAME); String tagContent = sourceTagMap.get(QAConstant.QA_TAGCONTENT); boolean hasTag = false; //检查目标文本是否有该标记 boolean tagChanged = false; for (int targetIndex = 0; targetIndex < targetTagList.size(); targetIndex++) { Map<String, String> targetTagMap = targetTagList.get(targetIndex); if (tagName.equals(targetTagMap.get(QAConstant.QA_TAGNAME))) { hasTag = true; if (!tagContent.equals(targetTagMap.get(QAConstant.QA_TAGCONTENT))) { tagChanged = true; }else { targetTagList.remove(targetIndex); tagChanged = false; break; } } } //如果该标记不存在,那么就是目标文本中缺失该标记 if (!hasTag) { loseTag.add(tagName); } //如果有这个标记,但是它的标记内容不正确。 if (hasTag && tagChanged) { changeTag.add(tagName); } } //处理标记缺失的情况 int loseTagSize; if ((loseTagSize = loseTag.size()) > 0) { // String qaTypeText = Messages.getString("qa.TagConsistenceQA.name1"); // String tagLoseTip = ""; // for (int index = 0; index < loseTagSize; index++) { // tagLoseTip += "'" + loseTag.get(index) + "', "; // } // tagLoseTip = tagLoseTip.substring(0, tagLoseTip.length() - 2); // String errorTip = MessageFormat.format(Messages.getString("qa.TagConsistenceQA.tip1"), tagLoseTip); hasError = true; } //处理标记不一致的情况 int changeTagSize; if ((changeTagSize = changeTag.size()) > 0) { // String qaTypeText = Messages.getString("qa.TagConsistenceQA.name2"); // String tagChangeTip = ""; // for (int index = 0; index < changeTagSize; index++) { // tagChangeTip += "'" + changeTag.get(index) + "', "; // } // tagChangeTip = tagChangeTip.substring(0, tagChangeTip.length() - 2); // String errorTip = MessageFormat.format(Messages.getString("qa.TagConsistenceQA.tip2"), tagChangeTip); hasError = true; } // 处理译文标记多出的情况 int moreTagSize; if ((moreTagSize = targetTagList.size()) > 0) { // String qaTypeText = Messages.getString("qa.TagConsistenceQA.addName1"); // String moreTagTip = ""; // for (int index = 0; index < moreTagSize; index++) { // moreTagTip += "'" + targetTagList.get(index).get(QAConstant.QA_TAGNAME) + "', "; // } // moreTagTip = moreTagTip.substring(0, moreTagTip.length() - 2); // String errorTip = MessageFormat.format(Messages.getString("qa.TagConsistenceQA.addTip1"), moreTagTip); hasError = true; } if (hasError) { String qaTypeText = Messages.getString("qa.TagConsistenceQA.name2"); super.printQAResult(new QAResultBean(level, QAConstant.QA_TAG, qaTypeText, null, tuDataBean.getFileName(), lineNumber, srcContent, tgtContent, rowId)); } String result = ""; if (hasError && level == 0) { result = QAConstant.QA_TAG; } return result; } }
5,656
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ExportQAResultDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/export/ExportQAResultDialog.java
package net.heartsome.cat.ts.ui.qa.export; import java.io.File; import java.text.MessageFormat; import net.heartsome.cat.ts.ui.composite.DialogLogoCmp; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.resource.ImageConstant; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; 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.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 导出品质检查结果文件对话框 * @author robert 2013-08-02 */ public class ExportQAResultDialog extends Dialog{ private Image logoImage; private String exportFilePath; private Text pathTxt; public ExportQAResultDialog(Shell parentShell) { super(parentShell); logoImage = Activator.getImageDescriptor(ImageConstant.QA_EXPORTQA_LOG) .createImage(); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("qa.export.ExportQAResultDialog.dialogTitle")); } @Override protected boolean isResizable() { return true; } @Override protected Control createDialogArea(Composite parent) { Composite tparent = (Composite) super.createDialogArea(parent); GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true); parentData.widthHint = 450; parentData.heightHint = 150; tparent.setLayoutData(parentData); GridLayoutFactory.fillDefaults().extendedMargins(-1, -1, -1, 8) .numColumns(1).applyTo(tparent); createLogoArea(tparent); Composite cmp = new Composite(tparent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(cmp); GridLayoutFactory.fillDefaults().extendedMargins(9, 9, 0, 0).numColumns(3).applyTo(cmp); Label label = new Label(cmp, SWT.NONE); label.setText(Messages.getString("qa.export.ExportQAResultDialog.filePathLbl")); pathTxt = new Text(cmp, SWT.BORDER); // pathTxt.setText("/Users/Mac/Desktop/test.xlsx"); exportFilePath = pathTxt.getText(); pathTxt.setEditable(false); GridDataFactory.swtDefaults().grab(true, false).align(SWT.FILL, SWT.CENTER).applyTo(pathTxt); Button browseBtn = new Button(cmp, SWT.NONE); browseBtn.setText(Messages.getString("qa.export.ExportQAResultDialog.browseBtn")); browseBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); FileDialog flg = new FileDialog(getShell(), SWT.SAVE); flg.setText(Messages.getString("qa.export.ExportQAResultDialog.fileDialog.title")); String[] filter = new String[] {"*.xlsx", "*"}; flg.setFilterExtensions(filter); String path = flg.open(); if (path != null) { if (!path.endsWith(".xlsx")) { path += ".xlsx"; } pathTxt.setText(path); } exportFilePath = pathTxt.getText(); } }); return tparent; } /** * 显示图片区 * * @param parent */ public void createLogoArea(Composite parent) { new DialogLogoCmp(parent, SWT.NONE, Messages.getString("qa.export.ExportQAResultDialog.logo.title"), Messages.getString("qa.export.ExportQAResultDialog.logo.message"), logoImage); } public String getExportFilePath() { return exportFilePath; } @Override protected void okPressed() { if (new File(exportFilePath).exists()) { boolean confirm = MessageDialog.openConfirm(getShell(), Messages.getString("qa.all.dialog.confirm"), MessageFormat.format(Messages.getString("qa.export.ExportQAResultDialog.fileExsit"), exportFilePath)); if (!confirm) { return; } } super.okPressed(); } @Override public boolean close() { if (logoImage != null && !logoImage.isDisposed()) { logoImage.dispose(); } return super.close(); } }
4,264
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ExportQAResult.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/export/ExportQAResult.java
package net.heartsome.cat.ts.ui.qa.export; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import net.heartsome.cat.common.innertag.factory.PlaceHolderEditModeBuilder; import net.heartsome.cat.common.innertag.factory.XliffInnerTagFactory; import net.heartsome.cat.common.resources.ResourceUtils; 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.qa.Activator; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.osgi.framework.Bundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 导出品质检查结果视图 * @author robert 2013-07-31 */ public class ExportQAResult { /** 是否合并打开 */ private boolean isMultiFile; private String exportFilePath; private List<String> filePathList = new ArrayList<String>(); public static final Logger LOGGER = LoggerFactory.getLogger(ExportQAResult.class); /** 已经合并的合并 id, 之后遇到不再合并 */ private Set<String> mergedIdSet = new HashSet<String>(); protected PlaceHolderEditModeBuilder placeHolderBuilder = new PlaceHolderEditModeBuilder(); protected XliffInnerTagFactory innerTagFactory = new XliffInnerTagFactory(placeHolderBuilder); public ExportQAResult(){ } public ExportQAResult(boolean isMultiFile, String exportFilePath){ this.isMultiFile = isMultiFile; this.exportFilePath = exportFilePath; } public void beginExport(List<QAResultBean> dataList, List<String> fileLCList, IProgressMonitor monitor){ if (monitor == null) { monitor = new NullProgressMonitor(); } // 分成十份,其中解析文件 1 份,其余 9 份 monitor.beginTask("", 10); monitor.setTaskName(Messages.getString("qa.export.ExportQAResult.monitor.title")); // 将 fileLCList 转换成相对路径 List<File> fileList = new ArrayList<File>(); for (String fileLC : fileLCList) { fileList.add(new File(fileLC)); } for(IFile iFile : ResourceUtils.filesToIFiles(fileList)){ filePathList.add(iFile.getFullPath().toOSString()); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); // UNDO 这里按文件排序给注释了。。。。 // // 先按文件排序 // sort(dataList); // 工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建sheet页 XSSFSheet sheet = workbook.createSheet(); // 设置sheet名称 workbook.setSheetName(0, Messages.getString("qa.export.ExportQAResult.sheet.title")); sheet.setColumnWidth(0, 255*6); sheet.setColumnWidth(1, 255*20); sheet.setColumnWidth(2, 255*30); sheet.setColumnWidth(3, 255*60); sheet.setColumnWidth(4, 255*60); XSSFFont titleFont = workbook.createFont(); titleFont.setColor(IndexedColors.GREY_80_PERCENT.getIndex()); titleFont.setBold(true); titleFont.setFontHeight(20); XSSFFont headerFont = workbook.createFont(); headerFont.setBold(true); headerFont.setFontHeight(14); XSSFFont errorFont = workbook.createFont(); errorFont.setColor(IndexedColors.RED.getIndex()); XSSFCellStyle titleStyle = workbook.createCellStyle(); titleStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); titleStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); titleStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); titleStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); titleStyle.setAlignment(HorizontalAlignment.CENTER); titleStyle.setFont(titleFont); XSSFCellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); headerStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); headerStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); headerStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); headerStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); headerStyle.setFont(headerFont); XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); cellStyle.setWrapText(true); XSSFCellStyle errorCellStyle = workbook.createCellStyle(); errorCellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); errorCellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); errorCellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); errorCellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); errorCellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); errorCellStyle.setWrapText(true); errorCellStyle.setFont(errorFont); // 生成标题行 XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellStyle(titleStyle); cell.setCellValue(Messages.getString("qa.export.ExportQAResult.titleCell")); String[] headers = new String[] { Messages.getString("qa.export.ExportQAResult.header.errorLeavel"), // 级别 Messages.getString("qa.export.ExportQAResult.header.qaType"), // 类型 Messages.getString("qa.export.ExportQAResult.header.location"), // 位置 Messages.getString("qa.export.ExportQAResult.header.srcText"), // 源文 Messages.getString("qa.export.ExportQAResult.header.tgtText") //  译文 }; // 产生表格标题行 row = sheet.createRow(1); for (short i = 0; i < headers.length; i++) { cell = row.createCell(i); cell.setCellStyle(headerStyle); cell.setCellValue(headers[i]); } // 开始生成数据 int index = 1; String rowId = null; // 先处理品质检查结果数据为空的情况 if (dataList.size() <= 0) { if (isMultiFile) { String multiFileStr = getMultiResouce(); index++; row = sheet.createRow(index); for (int i = 0; i < headers.length; i++) { cell = row.createCell(i); cell.setCellStyle(cellStyle); if (i == headers.length - 1) { cell.setCellValue(multiFileStr); } } }else { for (String filePath : this.filePathList) { index++; row = sheet.createRow(index); for (int i = 0; i < headers.length; i++) { cell = row.createCell(i); cell.setCellStyle(cellStyle); if (i == headers.length - 1) { cell.setCellValue(filePath); } } } } sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4)); }else { int interval = 1; if (dataList.size() > 9) { interval = dataList.size() / 9; } int startMergeRow = -1; int endMergeRow = -1; for (int i = 0; i < dataList.size(); i++) { QAResultBean bean = dataList.get(i); index++; System.out.println(index); if (index % interval == 0) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); } row = sheet.createRow(index); // 处理合并 级别 与 类型 两列的行 mergeIF:if (bean.getMergeId() != null) { if (mergedIdSet.contains(bean.getMergeId())) { break mergeIF; } startMergeRow = index; mergeFor:for (int j = i + 1; j < dataList.size(); j++) { if (dataList.get(j).getMergeId() != null && dataList.get(j).getMergeId().equals(bean.getMergeId())) { mergedIdSet.add(bean.getMergeId()); endMergeRow = index + (j - i); }else { break mergeFor; } } if (startMergeRow >= 0 && endMergeRow >= 0) { sheet.addMergedRegion(new CellRangeAddress(startMergeRow, endMergeRow, 0, 0)); sheet.addMergedRegion(new CellRangeAddress(startMergeRow, endMergeRow, 1, 1)); startMergeRow = -1; endMergeRow = -1; } } // 循环当前行的每一列 for (int h = 0; h < headers.length; h++) { cell = row.createCell(h); cell.setCellStyle(cellStyle); String text = null; switch (h) { case 0: if (bean.getLevel() == 0) { text = Messages.getString("qa.export.ExportQAResult.errorLeavel.error"); cell.setCellStyle(errorCellStyle); }else if (bean.getLevel() == 1) { text = Messages.getString("qa.export.ExportQAResult.errorLeavel.warning"); } cell.setCellValue(text); break; case 1: text = bean.getQaTypeText(); cell.setCellValue(text); break; case 2: text = bean.getFileName() + " [" + bean.getLineNumber() + "]"; cell.setCellValue(text); break; case 3: text = bean.getSrcContent(); cell.setCellValue(getDisplayText(text)); break; case 4: text = bean.getTgtContent(); cell.setCellValue(getDisplayText(text)); break; default: break; } } } // // 这是合并 文件路径 // if (isMultiFile) { // sheet.addMergedRegion(new CellRangeAddress(resourceIndex, index, 6, 6)); // }else { // sheet.addMergedRegion(new CellRangeAddress(resourceIndex, index, 6, 6)); // } // sheet.addMergedRegion(new CellRangeAddress(rowidIndex, index, 1, 1)); // sheet.addMergedRegion(new CellRangeAddress(rowidIndex, index, 4, 4)); // sheet.addMergedRegion(new CellRangeAddress(rowidIndex, index, 5, 5)); // 标题行合并(处理未合并完的部份) sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4)); } try { FileOutputStream fileoutputstream = new FileOutputStream(exportFilePath); workbook.write(fileoutputstream); fileoutputstream.close(); Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openInformation( Display.getDefault().getActiveShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.export.ExportQAResult.MSG.exportSuccess")); } }); } catch (Exception e) { Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openInformation( Display.getDefault().getActiveShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.export.ExportQAResult.MSG.exportFail")); } }); LOGGER.error(Messages.getString("qa.export.ExportQAResult.LOG.exportError"), e); } } /** * 根据传入的源文或译文的全文本,获取要显示的文本段内容。 * @param srcOrTgtContent * @return */ private String getDisplayText(String srcOrTgtContent){ innerTagFactory.reset(); String displayText = InnerTagUtil.resolveTag(innerTagFactory.parseInnerTag(srcOrTgtContent)); 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"); } Matcher matcher = PlaceHolderEditModeBuilder.PATTERN.matcher(displayText); int tagIdx = 1; while(matcher.find()){ displayText = matcher.replaceFirst("{" + (tagIdx ++) + "}"); matcher = PlaceHolderEditModeBuilder.PATTERN.matcher(displayText); } return displayText; } // private void sort(List<QAResultBean> dataList){ // //排序 // Collections.sort(dataList, new Comparator<QAResultBean>() { // public int compare(QAResultBean o1, QAResultBean o2) { // return o1.getResource().compareTo(o2.getResource()); // } // }); // } /** * 如果是合并打开,那么返回 * @param datalist * @return */ private String getMultiResouce(){ StringBuffer sb = new StringBuffer(); sb.append(Messages.getString("qa.export.ExportQAResult.multifyOpen")); for(String resource : filePathList){ sb.append(resource).append("\n"); } return sb.toString(); } public static byte[] getImageData(String imgPath){ byte[] arrayByte = null; try { Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID); URL defaultUrl = buddle.getEntry(imgPath); String imagePath = imgPath; imagePath = FileLocator.toFileURL(defaultUrl).getPath(); arrayByte = IOUtils.toByteArray(new FileInputStream(new File(imagePath))); } catch (Exception e) { } return arrayByte; } public static void main(String[] args) { int index = 0; thisIF:if (index < 10) { System.out.println(index); index += 10; if (index > 5) { break thisIF; } System.out.println(index); } } }
14,118
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QAInstalPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/preference/QAInstalPage.java
package net.heartsome.cat.ts.ui.qa.preference; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.resource.ImageConstant; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.nebula.jface.tablecomboviewer.TableComboViewer; import org.eclipse.nebula.widgets.tablecombo.TableCombo; 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.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class QAInstalPage extends PreferencePage implements IWorkbenchPreferencePage, Listener { public static final String ID = "net.heartsome.cat.ts.ui.qa.preference.QAInstalPage"; public final static Logger logger = LoggerFactory.getLogger(QAInstalPage.class.getName()); private IPreferenceStore preferenceStore; private Map<String, HashMap<String, String>> qaItemId_Name_Class; private Button batchTermBtn; private Button batchParaBtn; private Button batchNumberBtn; private Button batchTagBtn; private Button batchNonTransBtn; private Button batchSpaceOfParaBtn; private Button batchParaCompleteBtn; private Button batchTgtLengthLimitBtn; private Button batchSpellBtn; private Button autoTermBtn; //private Button autoParaBtn; private Button autoNumberBtn; private Button autoTagBtn; private Button autoNonTransBtn; private Button autoSpaceOfParaBtn; private Button autoParaCompleteBtn; private Button autoTgtLengthLimitBtn; private Button autoSpellBtn; private TableComboViewer termCmb; private TableComboViewer paraCmb; private TableComboViewer numberCmb; private TableComboViewer tagCmb; private TableComboViewer nonTransCmb; private TableComboViewer spaceOfParaCmb; private TableComboViewer paraCompleteCmb; private TableComboViewer tgtLengthLimitCmb; private TableComboViewer spellCmb; /** 组件是否初始化 */ private boolean isInit = false; /** 批量检查按钮的值--批量检查 */ private static final String CONSTANT_BATCHQA = Messages.getString("qa.preference.QAInstalPage.batchQA"); /** 自动检查按钮的值--自动检查 */ private static final String CONSTANT_AUTOQA = Messages.getString("qa.preference.QAInstalPage.autoQA"); /** 提示级别按钮的值--提示级别 */ private static final String CONSTANT_TIPLEVEL = Messages.getString("qa.preference.QAInstalPage.tipLevel"); private static final String errorTip = Messages.getString("qa.all.tipLevel.error"); private static final String warTip = Messages.getString("qa.all.tipLevel.warning"); private final List<String> CONSTANT_COMBOVALUE = new ArrayList<String>(); private Image errorImg; private Image warnImg; private Button whenApprovalBtn; private Button whenAddToDbBtn; public QAInstalPage() { setTitle(Messages.getString("qa.all.qa")); setPreferenceStore(Activator.getDefault().getPreferenceStore()); preferenceStore = getPreferenceStore(); QAModel qaModel = new QAModel(); qaItemId_Name_Class = qaModel.getQaItemId_Name_Class(); CONSTANT_COMBOVALUE.add(errorTip); CONSTANT_COMBOVALUE.add(warTip); } public void init(IWorkbench workbench) { // TODO Auto-generated method stub } @Override protected Control createContents(Composite parent) { isInit = true; try { String bundlePath = FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.ui.qa").getEntry("")).getPath(); errorImg = new Image(getShell().getDisplay(), bundlePath + "icons/error.png"); warnImg = new Image(getShell().getDisplay(), bundlePath + "icons/warning.png"); } catch (IOException e) { e.printStackTrace(); logger.error(Messages.getString("qa.preference.QAInstalPage.log1"), e); } Composite tparent = new Composite(parent, SWT.NONE); tparent.setLayout(new GridLayout()); tparent.setLayoutData(new GridData(GridData.FILL_BOTH)); Group qaItemInstalGroup = new Group(tparent, SWT.NONE); qaItemInstalGroup.setLayout(new GridLayout()); GridDataFactory.fillDefaults().grab(true, false).hint(600, SWT.DEFAULT).applyTo(qaItemInstalGroup); qaItemInstalGroup.setText(Messages.getString("qa.preference.QAInstalPage.qaInstal")); String tip = Messages.getString("preference.QAInstalPage.itemInstalLbl"); HsImageLabel itemInstalLbl = new HsImageLabel(tip, Activator.getImageDescriptor(ImageConstant.PREFERENCE_QA_instal_itemsChoose)); Composite instalCmp = itemInstalLbl.createControl(qaItemInstalGroup); GridLayoutFactory.fillDefaults().numColumns(4).spacing(20, 2) .applyTo(instalCmp); instalCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout lCmpLayout = new GridLayout(2, false); lCmpLayout.marginWidth = 0; lCmpLayout.marginHeight = 0; GridData separatorLblData = new GridData(SWT.FILL, SWT.CENTER, true, false); separatorLblData.horizontalSpan = 4; // 术语一致性检查 Label termLbl = new Label(instalCmp, SWT.NONE); termLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_TERM).get(QAConstant.QA_ITEM_NAME)); batchTermBtn = new Button(instalCmp, SWT.CHECK); batchTermBtn.setText(CONSTANT_BATCHQA); autoTermBtn = new Button(instalCmp, SWT.CHECK); autoTermBtn.setText(CONSTANT_AUTOQA); Composite levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); termCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(termCmb); Label separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); // 数字一致性检查 Label numberLbl = new Label(instalCmp, SWT.NONE); numberLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_NUMBER).get(QAConstant.QA_ITEM_NAME)); batchNumberBtn = new Button(instalCmp, SWT.CHECK); batchNumberBtn.setText(CONSTANT_BATCHQA); autoNumberBtn = new Button(instalCmp, SWT.CHECK); autoNumberBtn.setText(CONSTANT_AUTOQA); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); numberCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(numberCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); // 标记一致性检查 Label tagLbl = new Label(instalCmp, SWT.NONE); tagLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_TAG).get(QAConstant.QA_ITEM_NAME)); batchTagBtn = new Button(instalCmp, SWT.CHECK); batchTagBtn.setText(CONSTANT_BATCHQA); autoTagBtn = new Button(instalCmp, SWT.CHECK); autoTagBtn.setText(CONSTANT_AUTOQA); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); tagCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(tagCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); // 非译元素检查 Label nonTransLbl = new Label(instalCmp, SWT.NONE); nonTransLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_NONTRANSLATION).get(QAConstant.QA_ITEM_NAME)); batchNonTransBtn = new Button(instalCmp, SWT.CHECK); batchNonTransBtn.setText(CONSTANT_BATCHQA); autoNonTransBtn = new Button(instalCmp, SWT.CHECK); autoNonTransBtn.setText(CONSTANT_AUTOQA); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); nonTransCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(nonTransCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); //段首段末空格检查 Label spaceOfParaLbl = new Label(instalCmp, SWT.NONE); spaceOfParaLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_SPACEOFPARACHECK).get(QAConstant.QA_ITEM_NAME)); batchSpaceOfParaBtn = new Button(instalCmp, SWT.CHECK); batchSpaceOfParaBtn.setText(CONSTANT_BATCHQA); autoSpaceOfParaBtn = new Button(instalCmp, SWT.CHECK); autoSpaceOfParaBtn.setText(CONSTANT_AUTOQA); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); spaceOfParaCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(spaceOfParaCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); //文本段完整性检查 Label paraCompleteLbl = new Label(instalCmp, SWT.NONE); paraCompleteLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_PARACOMPLETENESS).get(QAConstant.QA_ITEM_NAME)); batchParaCompleteBtn = new Button(instalCmp, SWT.CHECK); batchParaCompleteBtn.setText(CONSTANT_BATCHQA); autoParaCompleteBtn = new Button(instalCmp, SWT.CHECK); autoParaCompleteBtn.setText(CONSTANT_AUTOQA); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); paraCompleteCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(paraCompleteCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); //目标文本段长度限制检查 Label tgtLengthLimitLbl = new Label(instalCmp, SWT.NONE); tgtLengthLimitLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_TGTTEXTLENGTHLIMIT).get(QAConstant.QA_ITEM_NAME)); batchTgtLengthLimitBtn = new Button(instalCmp, SWT.CHECK); batchTgtLengthLimitBtn.setText(CONSTANT_BATCHQA); autoTgtLengthLimitBtn = new Button(instalCmp, SWT.CHECK); autoTgtLengthLimitBtn.setText(CONSTANT_AUTOQA); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); tgtLengthLimitCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(tgtLengthLimitCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); //拼写检查 Label spellLbl = new Label(instalCmp, SWT.NONE); spellLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_SPELL).get(QAConstant.QA_ITEM_NAME)); batchSpellBtn = new Button(instalCmp, SWT.CHECK); batchSpellBtn.setText(CONSTANT_BATCHQA); autoSpellBtn = new Button(instalCmp, SWT.CHECK); autoSpellBtn.setText(CONSTANT_AUTOQA); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); spellCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(spellCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); // 文本段一致性检查 Label paraLbl = new Label(instalCmp, SWT.NONE); paraLbl.setText(qaItemId_Name_Class.get(QAConstant.QA_PARAGRAPH).get(QAConstant.QA_ITEM_NAME)); batchParaBtn = new Button(instalCmp, SWT.CHECK); batchParaBtn.setText(CONSTANT_BATCHQA); new Label(instalCmp, SWT.NONE); levelCmp = new Composite(instalCmp, SWT.NONE); levelCmp.setLayout(lCmpLayout); new Label(levelCmp, SWT.NONE).setText(CONSTANT_TIPLEVEL); paraCmb = new TableComboViewer(levelCmp, SWT.READ_ONLY|SWT.BORDER); createTableCombo(paraCmb); separatorLbl = new Label(instalCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); itemInstalLbl.computeSize(); // ---------------------------------自动检查策略设置 Group autoIntalGroup = new Group(tparent, SWT.NONE); autoIntalGroup.setLayout(new GridLayout()); autoIntalGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); autoIntalGroup.setText(Messages.getString("qa.preference.QAInstalPage.autoQaInstal")); // 入库时执行 whenAddToDbBtn = new Button(autoIntalGroup, SWT.CHECK); whenAddToDbBtn.setText(Messages.getString("qa.preference.QAInstalPage.autoQaWhenAddToDb")); whenAddToDbBtn.addListener(SWT.Selection, this); // 批准文本段后执行 whenApprovalBtn = new Button(autoIntalGroup, SWT.CHECK); whenApprovalBtn.setText(Messages.getString("qa.preference.QAInstalPage.autoQaWhenApproval")); whenApprovalBtn.addListener(SWT.Selection, this); initValue(); return parent; } public void handleEvent(Event event) { Widget widge = event.widget; if (widge.equals(whenAddToDbBtn) || widge.equals(whenApprovalBtn)) { setAutoItemSelected(); } } /** * 初始化值 */ public void initValue() { // 默认情况下所有的品质检查项全部选中,在QAInitializer类中初始化 String batchItemsValue = preferenceStore.getString(QAConstant.QA_PREF_BATCH_QAITEMS); List<String> batchItemsValList = new ArrayList<String>(); String[] batchItemsValArray = batchItemsValue.split(","); for (int index = 0; index < batchItemsValArray.length; index++) { batchItemsValList.add(batchItemsValArray[index]); } batchTermBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_TERM) >= 0); batchParaBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_PARAGRAPH) >= 0); batchNumberBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_NUMBER) >= 0); batchTagBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_TAG) >= 0); batchNonTransBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_NONTRANSLATION) >= 0); //段首段末空格检查 batchSpaceOfParaBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_SPACEOFPARACHECK) >= 0); //文本段完整性检查 batchParaCompleteBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_PARACOMPLETENESS) >= 0); batchTgtLengthLimitBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_TGTTEXTLENGTHLIMIT) >= 0); batchSpellBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_SPELL) >= 0); //下面是自动检查的值的初始化情况 String autoItemsValue = preferenceStore.getString(QAConstant.QA_PREF_AUTO_QAITEMS); List<String> autoItemsValList = new ArrayList<String>(); String[] autoItemsValArray = autoItemsValue.split(","); for (int index = 0; index < autoItemsValArray.length; index++) { autoItemsValList.add(autoItemsValArray[index]); } autoTermBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_TERM) >= 0); //autoParaBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_PARAGRAPH) >= 0); autoNumberBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_NUMBER) >= 0); autoTagBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_TAG) >= 0); autoNonTransBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_NONTRANSLATION) >= 0); //段首段末空格检查 autoSpaceOfParaBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_SPACEOFPARACHECK) >= 0); //文本段完整性检查 autoParaCompleteBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_PARACOMPLETENESS) >= 0); autoTgtLengthLimitBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_TGTTEXTLENGTHLIMIT) >= 0); autoSpellBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_SPELL) >= 0); // 下面是设置提示级别 termCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_term_TIPLEVEL)); paraCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_para_TIPLEVEL)); numberCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_number_TIPLEVEL)); tagCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_tag_TIPLEVEL)); nonTransCmb.getTableCombo().select((preferenceStore.getInt(QAConstant.QA_PREF_nonTrans_TIPLEVEL))); spaceOfParaCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_spaceOfPara_TIPLEVEL)); paraCompleteCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_paraComplete_TIPLEVEL)); tgtLengthLimitCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_tgtLengthLimit_TIPLEVEL)); spellCmb.getTableCombo().select(preferenceStore.getInt(QAConstant.QA_PREF_spell_TIPLEVEL)); //等于0时:为从不执行;等于1时,为入库时执行;等于2时,为批准文本段时执行;等于3时,为都进行检查。 int autoTag = preferenceStore.getInt(QAConstant.QA_PREF_AUTO_QARUNTIME); whenAddToDbBtn.setSelection(autoTag == QAConstant.QA_FIRST || autoTag == QAConstant.QA_THREE); whenApprovalBtn.setSelection(autoTag == QAConstant.QA_TWO || autoTag == QAConstant.QA_THREE); setAutoItemSelected(); } @Override protected void performDefaults() { // 默认情况下所有的品质检查项全部选中,在QAInitializer类中初始化 String batchItemsValue = preferenceStore.getDefaultString(QAConstant.QA_PREF_BATCH_QAITEMS); List<String> batchItemsValList = new ArrayList<String>(); String[] batchItemsValArray = batchItemsValue.split(","); for (int index = 0; index < batchItemsValArray.length; index++) { batchItemsValList.add(batchItemsValArray[index]); } batchTermBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_TERM) >= 0); batchParaBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_PARAGRAPH) >= 0); batchNumberBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_NUMBER) >= 0); batchTagBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_TAG) >= 0); batchNonTransBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_NONTRANSLATION) >= 0); //段首段末空格检查 batchSpaceOfParaBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_SPACEOFPARACHECK) >= 0); //文本段完整性检查 batchParaCompleteBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_PARACOMPLETENESS) >= 0); batchTgtLengthLimitBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_TGTTEXTLENGTHLIMIT) >= 0); batchSpellBtn.setSelection(batchItemsValList.indexOf(QAConstant.QA_SPELL) >= 0); //下面是自动检查的值的初始化情况 String autoItemsValue = preferenceStore.getDefaultString(QAConstant.QA_PREF_AUTO_QAITEMS); List<String> autoItemsValList = new ArrayList<String>(); String[] autoItemsValArray = autoItemsValue.split(","); for (int index = 0; index < autoItemsValArray.length; index++) { autoItemsValList.add(autoItemsValArray[index]); } autoTermBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_TERM) >= 0); //autoParaBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_PARAGRAPH) >= 0); autoNumberBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_NUMBER) >= 0); autoTagBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_TAG) >= 0); autoNonTransBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_NONTRANSLATION) >= 0); //段首段末空格检查 autoSpaceOfParaBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_SPACEOFPARACHECK) >= 0); //文本段完整性检查 autoParaCompleteBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_PARACOMPLETENESS) >= 0); autoTgtLengthLimitBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_TGTTEXTLENGTHLIMIT) >= 0); autoSpellBtn.setSelection(autoItemsValList.indexOf(QAConstant.QA_SPELL) >= 0); // 下面是设置提示级别 termCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_term_TIPLEVEL)); paraCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_para_TIPLEVEL)); numberCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_number_TIPLEVEL)); tagCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_tag_TIPLEVEL)); nonTransCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_nonTrans_TIPLEVEL)); spaceOfParaCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_spaceOfPara_TIPLEVEL)); paraCompleteCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_paraComplete_TIPLEVEL)); tgtLengthLimitCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_tgtLengthLimit_TIPLEVEL)); spellCmb.getTableCombo().select(preferenceStore.getDefaultInt(QAConstant.QA_PREF_spell_TIPLEVEL)); //等于0时:为从不执行;等于1时,为入库时执行;等于2时,为批准文本段时执行;等于3时,为都进行检查。 int autoTag = preferenceStore.getDefaultInt(QAConstant.QA_PREF_AUTO_QARUNTIME); whenAddToDbBtn.setSelection(autoTag == QAConstant.QA_FIRST || autoTag == QAConstant.QA_THREE); whenApprovalBtn.setSelection(autoTag == QAConstant.QA_TWO || autoTag == QAConstant.QA_THREE); setAutoItemSelected(); } @Override public boolean performOk() { if (!isInit) { return true; } //先处理批量检查的情况 String batchItemsValue = ""; if (batchTermBtn.getSelection()) { batchItemsValue += QAConstant.QA_TERM + ","; } if (batchParaBtn.getSelection()) { batchItemsValue += QAConstant.QA_PARAGRAPH + ","; } if (batchNumberBtn.getSelection()) { batchItemsValue += QAConstant.QA_NUMBER + ","; } if (batchTagBtn.getSelection()) { batchItemsValue += QAConstant.QA_TAG + ","; } if (batchNonTransBtn.getSelection()) { batchItemsValue += QAConstant.QA_NONTRANSLATION + ","; } if (batchSpaceOfParaBtn.getSelection()) { batchItemsValue += QAConstant.QA_SPACEOFPARACHECK + ","; } if (batchParaCompleteBtn.getSelection()) { batchItemsValue += QAConstant.QA_PARACOMPLETENESS + ","; } if (batchTgtLengthLimitBtn.getSelection()) { batchItemsValue += QAConstant.QA_TGTTEXTLENGTHLIMIT + ","; } if (batchSpellBtn.getSelection()) { batchItemsValue += QAConstant.QA_SPELL ; } //处理自动检查的情况 String autoItemsValue = ""; if (autoTermBtn.getSelection()) { autoItemsValue += QAConstant.QA_TERM + ","; } /*if (autoParaBtn.getSelection()) { autoItemsValue += QAConstant.QA_PARAGRAPH + ","; }*/ if (autoNumberBtn.getSelection()) { autoItemsValue += QAConstant.QA_NUMBER + ","; } if (autoTagBtn.getSelection()) { autoItemsValue += QAConstant.QA_TAG + ","; } if (autoNonTransBtn.getSelection()) { autoItemsValue += QAConstant.QA_NONTRANSLATION + ","; } if (autoSpaceOfParaBtn.getSelection()) { autoItemsValue += QAConstant.QA_SPACEOFPARACHECK + ","; } if (autoParaCompleteBtn.getSelection()) { autoItemsValue += QAConstant.QA_PARACOMPLETENESS + ","; } if (autoTgtLengthLimitBtn.getSelection()) { autoItemsValue += QAConstant.QA_TGTTEXTLENGTHLIMIT + ","; } if (autoSpellBtn.getSelection()) { autoItemsValue += QAConstant.QA_SPELL ; } //等于0时:为从不执行;等于1时,为入库时执行;等于2时,为批准文本段时执行;等于3时,为都执行 int runtime = 0; if (whenAddToDbBtn.getSelection() && whenApprovalBtn.getSelection()) { runtime = 3; }else if (whenAddToDbBtn.getSelection()) { runtime = 1; }else if (whenApprovalBtn.getSelection()) { runtime = 2; } // 储存品质检查项 preferenceStore.setValue(QAConstant.QA_PREF_BATCH_QAITEMS, batchItemsValue); preferenceStore.setValue(QAConstant.QA_PREF_AUTO_QAITEMS, autoItemsValue); preferenceStore.setValue(QAConstant.QA_PREF_AUTO_QARUNTIME, runtime); // 下面是设置提示级别 preferenceStore.setValue(QAConstant.QA_PREF_term_TIPLEVEL, termCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_para_TIPLEVEL, paraCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_number_TIPLEVEL, numberCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_tag_TIPLEVEL, tagCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_nonTrans_TIPLEVEL, nonTransCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_spaceOfPara_TIPLEVEL, spaceOfParaCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_paraComplete_TIPLEVEL, paraCompleteCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_tgtLengthLimit_TIPLEVEL, tgtLengthLimitCmb.getTableCombo().getSelectionIndex()); preferenceStore.setValue(QAConstant.QA_PREF_spell_TIPLEVEL, spellCmb.getTableCombo().getSelectionIndex()); return true; } public static void main(String[] args) { } class QATipsLabelProvider extends LabelProvider implements ITableLabelProvider { private Map<String, Image> imageCache = new HashMap<String, Image>(); public QATipsLabelProvider() { } public Image getColumnImage(Object element, int columnIndex) { if (element instanceof String) { String tip = (String) element; return errorTip.equals(tip) ? errorImg : warnImg; } return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof String) { String array = (String) element; return array; } return null; } public void dispose(){ for (String code : imageCache.keySet()) { Image im = imageCache.get(code); if (im != null && !im.isDisposed()) { im.dispose(); } } imageCache.clear(); super.dispose(); } } private void createTableCombo(TableComboViewer tCmbViewer){ TableCombo tableCombo = tCmbViewer.getTableCombo(); tableCombo.setShowTableLines(false); tableCombo.setShowTableHeader(false); tableCombo.setDisplayColumnIndex(-1); tableCombo.setShowImageWithinSelection(true); tableCombo.setShowColorWithinSelection(false); tableCombo.setShowFontWithinSelection(false); tableCombo.setVisibleItemCount(2); GridDataFactory.swtDefaults().hint(100, SWT.DEFAULT).applyTo(tableCombo); tCmbViewer.setLabelProvider(new QATipsLabelProvider()); tCmbViewer.setContentProvider(new ArrayContentProvider()); tCmbViewer.setInput(CONSTANT_COMBOVALUE); } private void setAutoItemSelected(){ if (!whenApprovalBtn.getSelection() && !whenAddToDbBtn.getSelection()) { setAutoItemEnable(false); }else { setAutoItemEnable(true); } } private void setAutoItemEnable(boolean enable){ autoTermBtn.setEnabled(enable); // autoParaBtn.setEnabled(enable); autoNumberBtn.setEnabled(enable); autoTagBtn.setEnabled(enable); autoNonTransBtn.setEnabled(enable); autoSpaceOfParaBtn.setEnabled(enable); autoParaCompleteBtn.setEnabled(enable); autoTgtLengthLimitBtn.setEnabled(enable); autoSpellBtn.setEnabled(enable); } }
27,661
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QAInitializer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/preference/QAInitializer.java
package net.heartsome.cat.ts.ui.qa.preference; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.Activator; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; /** * 当本产品一打开,初始化品质检查插件中缓存中的值 * @author robert 2011-12-05 */ public class QAInitializer extends AbstractPreferenceInitializer { private boolean isUltimate = CommonFunction.checkEdition("U"); @Override public void initializeDefaultPreferences() { IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); //-------------------------------QAPage中的默认项-------------------- //将不包含上下文匹配的按钮设成默认选中状态 if (isUltimate) { preferenceStore.setDefault(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE, true); } else { preferenceStore.setDefault(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE, false); } preferenceStore.setDefault(QAConstant.QA_PREF_LOCKED_NOTINCLUDE, true); //将相同源文不同译文与相同译文不同源文下的忽略大小写与忽略标记全部勾选 preferenceStore.setDefault(QAConstant.QA_PREF_PARA_SAMESOURCE, true); preferenceStore.setDefault(QAConstant.QA_PREF_PARA_SRC_IGNORCECASE, true); preferenceStore.setDefault(QAConstant.QA_PREF_PARA_SRC_IGNORCETAG, true); preferenceStore.setDefault(QAConstant.QA_PREF_PARA_SAMETARGET, true); preferenceStore.setDefault(QAConstant.QA_PREF_PARA_TAR_IGNORCECASE, true); preferenceStore.setDefault(QAConstant.QA_PREF_PARA_TAR_IGNORCETAG, true); //设置目标文本段长度限制检查的默认值 preferenceStore.setDefault(QAConstant.QA_PREF_isCheckTgtMinLength, false); preferenceStore.setDefault(QAConstant.QA_PREF_isCheckTgtMaxLength, false); preferenceStore.setDefault(QAConstant.QA_PREF_tgtMinLength, "0"); preferenceStore.setDefault(QAConstant.QA_PREF_tgtMaxLength, "0"); //-------------------------------QAPage中的默认项-------------------- //默认情况下所有的品质检查项全部选中,因此先将每个检查项的标识符用","组装起来。(备注:由于现在只开发了五个检查项,因此这里只加了五个,以后每开发完成一个,就加到这里) String defaultItems = QAConstant.QA_PARAGRAPH + "," + QAConstant.QA_NUMBER + "," + QAConstant.QA_TAG + "," + QAConstant.QA_NONTRANSLATION + "," + QAConstant.QA_SPACEOFPARACHECK + "," + QAConstant.QA_PARACOMPLETENESS + "," + QAConstant.QA_SPELL; String autoDefaultItems = QAConstant.QA_NUMBER + "," + QAConstant.QA_TAG + "," + QAConstant.QA_SPELL; //默认情况下所有的品质检查项全部选中,因此先将每个检查项的标识符用","组装起来。 preferenceStore.setDefault(QAConstant.QA_PREF_BATCH_QAITEMS, defaultItems); preferenceStore.setDefault(QAConstant.QA_PREF_AUTO_QAITEMS, autoDefaultItems); //默认为入库时执行 preferenceStore.setDefault(QAConstant.QA_PREF_AUTO_QARUNTIME, QAConstant.QA_FIRST); // 设置默认错误级别 preferenceStore.setDefault(QAConstant.QA_PREF_term_TIPLEVEL, 1); preferenceStore.setDefault(QAConstant.QA_PREF_para_TIPLEVEL, 1); preferenceStore.setDefault(QAConstant.QA_PREF_number_TIPLEVEL, 0); preferenceStore.setDefault(QAConstant.QA_PREF_tag_TIPLEVEL, 0); preferenceStore.setDefault(QAConstant.QA_PREF_nonTrans_TIPLEVEL, 1); preferenceStore.setDefault(QAConstant.QA_PREF_spaceOfPara_TIPLEVEL, 1); preferenceStore.setDefault(QAConstant.QA_PREF_paraComplete_TIPLEVEL, 1); preferenceStore.setDefault(QAConstant.QA_PREF_tgtLengthLimit_TIPLEVEL, 0); preferenceStore.setDefault(QAConstant.QA_PREF_spell_TIPLEVEL, 1); //-------------------------------SpellPage 中的默认项-------------------- preferenceStore.setDefault(QAConstant.QA_PREF_isHunspell, true); preferenceStore.setDefault(QAConstant.QA_PREF_realTimeSpell, true); preferenceStore.setDefault(QAConstant.QA_PREF_ignoreNontrans, false); preferenceStore.setDefault(QAConstant.QA_PREF_ignoreDigitalFirst, false); preferenceStore.setDefault(QAConstant.QA_PREF_ignoreUpperCaseFirst, false); preferenceStore.setDefault(QAConstant.QA_PREF_ignoreAllUpperCase, true); //-------------------------------文件分析首选项值的初始化--------------- preferenceStore.setDefault(QAConstant.FA_PREF_ignoreCase, true); preferenceStore.setDefault(QAConstant.FA_PREF_ignoreTag, true); if (isUltimate) { preferenceStore.setDefault(QAConstant.FA_PREF_contextNum, 1); } else { preferenceStore.setDefault(QAConstant.FA_PREF_contextNum, 0); } preferenceStore.setDefault(QAConstant.FA_PREF_tagPenalty, 2); preferenceStore.setDefault(QAConstant.FA_PREF_interRepeate, true); preferenceStore.setDefault(QAConstant.FA_PREF_interMatch, false); // 等效系数的设置,初始化值,roebrt 2011-12-21 if (isUltimate) { preferenceStore.setDefault(QAConstant.FA_PREF_equivalent, "internalRepeat:0.50;external101:0.50;external100:0.50;95-99:0.60;85-94:0.70;75-84:0.80;50-74:0.90;"); }else { preferenceStore.setDefault(QAConstant.FA_PREF_equivalent, "internalRepeat:0.50;external100:0.50;95-99:0.60;85-94:0.70;75-84:0.80;50-74:0.90;"); } } }
5,313
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QAPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/preference/QAPage.java
package net.heartsome.cat.ts.ui.qa.preference; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.resource.ImageConstant; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; 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.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * 品质检查的首选项设置 * @author robert 2011-11-29 */ public class QAPage extends PreferencePage implements IWorkbenchPreferencePage { public static final String ID = "net.heartsome.cat.ts.ui.qa.preference.QAPage"; private IPreferenceStore preferenceStore; // --------------------------品质检查(针对所有品质检查项)-------------------------------------// private Button contextBtn; private Button fullMatchBtn; private Button lockedBtn; // --------------------------文本段一致性检查-------------------------------------// /** 相同源文不同译文,备注:默认选中 */ private Button sameSourceBtn; /** 相同源文不同译文下的忽略大小写 */ private Button srcIgnorceCaseBtn; /** 相同源文不同译文下的忽略标记 */ private Button srcIgnorceTagBtn; /** 相同译文不同源文 */ private Button sameTargetBtn; /** 相同译文不同源文下的忽略大小写 */ private Button tarIgnorceCaseBtn; /** 相同译文不同源文下的忽略标记 */ private Button tarIgnorceTagBtn; // 以下是目标文本段长度限制的组件 private Button minBtn; private Button maxBtn; private Text minTxt; private Text maxTxt; /** 组件是否初始化 */ private boolean isInit = false; private final static String isNumericRegex = "(^[1-9](\\d{0,2})(\\.\\d+)?$)|(^0(\\.\\d+)?$)"; public QAPage() { setTitle(Messages.getString("qa.preference.QAInstalPage.qaInstal")); setPreferenceStore(Activator.getDefault().getPreferenceStore()); preferenceStore = getPreferenceStore(); } @Override protected Control createContents(Composite parent) { isInit = true; Composite tparent = new Composite(parent, SWT.NONE); tparent.setLayout(new GridLayout()); tparent.setLayoutData(new GridData(GridData.FILL_BOTH)); Group notIncludeGroup = new Group(tparent, SWT.NONE); notIncludeGroup.setLayout(new GridLayout()); notIncludeGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); notIncludeGroup.setText(Messages.getString("qa.preference.QAPage.notInclude")); HsImageLabel notIncludeLbl = new HsImageLabel(Messages.getString("preference.QAPage.notIncludeLbl"), Activator.getImageDescriptor(ImageConstant.PREFERENCE_QA_Page_ignore)); Composite notIncludeCmp = notIncludeLbl.createControl(notIncludeGroup); notIncludeCmp.setLayout(new GridLayout()); notIncludeCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if (CommonFunction.checkEdition("U")) { // 上下文匹配 contextBtn = new Button(notIncludeCmp, SWT.CHECK); contextBtn.setText(Messages.getString("qa.preference.QAPage.content")); } // 完全匹配的文本段 fullMatchBtn = new Button(notIncludeCmp, SWT.CHECK); fullMatchBtn.setText(Messages.getString("qa.preference.QAPage.fullMatch")); // 已锁定的文本段 lockedBtn = new Button(notIncludeCmp, SWT.CHECK); lockedBtn.setText(Messages.getString("qa.preference.QAPage.locked")); notIncludeLbl.computeSize(); // 文本段一致性检查的按钮区 addParaGroup(tparent); addTgtLengthGroup(tparent); setInitValue(); // 初始化事件 initListener(); return parent; } /** * 这是针对文本段一致性检查的按钮区 * @param tparent */ public void addParaGroup(Composite tparent) { Group paragraphGroup = new Group(tparent, SWT.NONE); paragraphGroup.setText(Messages.getString("qa.preference.QAPage.paraConsistence")); paragraphGroup.setLayout(new GridLayout()); paragraphGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); HsImageLabel paraConsisLbl = new HsImageLabel(Messages.getString("preference.QAPage.paraConsisLbl"), Activator.getImageDescriptor(ImageConstant.PREFERENCE_QA_Page_paraConsistence)); Composite paraConsisCmp = paraConsisLbl.createControl(paragraphGroup); paraConsisCmp.setLayout(new GridLayout(3, false)); paraConsisCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout cmpLayout = new GridLayout(1, false); cmpLayout.marginLeft = 30; cmpLayout.marginHeight = 0; // -----------------------------下面是相同源文不同译文的配置----------------------------- sameSourceBtn = new Button(paraConsisCmp, SWT.CHECK); sameSourceBtn.setText(Messages.getString("qa.preference.QAPage.sameSource")); GridDataFactory.fillDefaults().span(3, 1).applyTo(sameSourceBtn); Composite sameSourceCmp = new Composite(paraConsisCmp, SWT.NONE); sameSourceCmp.setLayout(cmpLayout); GridDataFactory.fillDefaults().span(3, 1).applyTo(sameSourceCmp); srcIgnorceCaseBtn = new Button(sameSourceCmp, SWT.CHECK); srcIgnorceCaseBtn.setText(Messages.getString("qa.preference.QAPage.ignoreCase")); srcIgnorceTagBtn = new Button(sameSourceCmp, SWT.CHECK); srcIgnorceTagBtn.setText(Messages.getString("qa.preference.QAPage.ignoreTag")); // -----------------------------下面是相同译文不同源文的配置----------------------------- sameTargetBtn = new Button(paraConsisCmp, SWT.CHECK); sameTargetBtn.setText(Messages.getString("qa.preference.QAPage.sameTarget")); GridDataFactory.fillDefaults().span(3, 1).applyTo(sameTargetBtn); Composite sameTargetCmp = new Composite(paraConsisCmp, SWT.NONE); sameTargetCmp.setLayout(cmpLayout); GridDataFactory.fillDefaults().span(3, 1).applyTo(sameTargetCmp); tarIgnorceCaseBtn = new Button(sameTargetCmp, SWT.CHECK); tarIgnorceCaseBtn.setText(Messages.getString("qa.preference.QAPage.ignoreCase")); tarIgnorceTagBtn = new Button(sameTargetCmp, SWT.CHECK); tarIgnorceTagBtn.setText(Messages.getString("qa.preference.QAPage.ignoreTag")); paraConsisLbl.computeSize(); } /** * 添加目标文本段长度限制检查 * @param tParent */ private void addTgtLengthGroup(Composite tParent) { Group group = new Group(tParent, SWT.NONE); group.setText(Messages.getString("preference.QAPage.group")); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(new GridLayout()); HsImageLabel tgtLengthSetLbl = new HsImageLabel(Messages.getString("preference.QAPage.tgtLengthSetLbl"), Activator.getImageDescriptor(ImageConstant.PREFERENCE_QA_Page_tgtLengthSet)); Composite tgtLengthLblCmp = tgtLengthSetLbl.createControl(group); tgtLengthLblCmp.setLayout(new GridLayout(3, false)); tgtLengthLblCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite tgtLengthSetCmp = new Composite(tgtLengthLblCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).equalWidth(false).numColumns(3) .applyTo(tgtLengthSetCmp); GridDataFactory.fillDefaults().span(3, SWT.DEFAULT).grab(true, true).applyTo(tgtLengthSetCmp); GridData txtData = new GridData(SWT.LEFT, SWT.CENTER, false, false); txtData.widthHint = 200; minBtn = new Button(tgtLengthSetCmp, SWT.CHECK); minBtn.setText(Messages.getString("preference.QAPage.minBtn")); minTxt = new Text(tgtLengthSetCmp, SWT.BORDER); minTxt.setLayoutData(txtData); Label label = new Label(tgtLengthSetCmp, SWT.NONE); label.setText("%"); maxBtn = new Button(tgtLengthSetCmp, SWT.CHECK); maxBtn.setText(Messages.getString("preference.QAPage.maxBtn")); maxTxt = new Text(tgtLengthSetCmp, SWT.BORDER); maxTxt.setLayoutData(txtData); label = new Label(tgtLengthSetCmp, SWT.NONE); label.setText("%"); tgtLengthSetLbl.computeSize(); minTxt.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { validMinValue(isNumericRegex); } }); maxTxt.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { validMaxValue(isNumericRegex); } }); minBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { validMinValue(isNumericRegex); } public void widgetDefaultSelected(SelectionEvent e) { validMinValue(isNumericRegex); } }); maxBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { validMaxValue(isNumericRegex); } public void widgetDefaultSelected(SelectionEvent e) { validMaxValue(isNumericRegex); } }); } /** * 当选中 缩短按钮时,进行的提示信息 * @param isNumericRegex */ private boolean validMinValue(String isNumericRegex){ if (minBtn.getSelection()) { String minNumer = minTxt.getText(); if ("".equals(minNumer)) { minTxt.setFocus(); minBtn.setSelection(false); MessageDialog.openWarning(getShell(), Messages.getString("dialog.TargetLengthSettingDialog.msgTitle"), Messages.getString("preference.QAPage.msg1")); return false; } else if (!minNumer.matches(isNumericRegex)) { minTxt.setFocus(); minBtn.setSelection(false); MessageDialog.openWarning(getShell(), Messages.getString("dialog.TargetLengthSettingDialog.msgTitle"), Messages.getString("preference.QAPage.msg2")); return false; } } return true; } /** * 验证最大数字是否合格 * @param isNumbericRegex */ private boolean validMaxValue(String isNumbericRegex){ if (maxBtn.getSelection()) { String maxNumer = maxTxt.getText(); if ("".equals(maxNumer)) { maxTxt.setFocus(); maxBtn.setSelection(false); MessageDialog.openWarning(getShell(), Messages.getString("dialog.TargetLengthSettingDialog.msgTitle"), Messages.getString("preference.QAPage.msg3")); return false; } else if (!maxNumer.matches(isNumbericRegex)) { maxTxt.setFocus(); maxBtn.setSelection(false); MessageDialog.openWarning(getShell(), Messages.getString("dialog.TargetLengthSettingDialog.msgTitle"), Messages.getString("preference.QAPage.msg4")); return false; } } return true; } private void setInitValue() { // ----------------------------------------针对所有检查项------------------------------------// if (CommonFunction.checkEdition("U")) { // 将不包含上下文匹配(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE)的按钮设成默认选中状态,在QAInitializer类中初始化 if (preferenceStore.getBoolean(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE)) { contextBtn.setSelection(true); } else { contextBtn.setSelection(false); } } if (preferenceStore.getBoolean(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE)) { fullMatchBtn.setSelection(true); } else { fullMatchBtn.setSelection(false); } if (preferenceStore.getBoolean(QAConstant.QA_PREF_LOCKED_NOTINCLUDE)) { lockedBtn.setSelection(true); } else { lockedBtn.setSelection(false); } // -----------------------------------------文本段一致性检查的初始值设置-----------------------------------// // 将相同源文不同译文(QAConstant.QA_PREF_PARA_SAMESOURCE)设成默认,在QAInitializer类中初始化 if (preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SAMESOURCE)) { sameSourceBtn.setSelection(true); } else { sameSourceBtn.setSelection(false); } if (preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SRC_IGNORCECASE)) { srcIgnorceCaseBtn.setSelection(true); } else { srcIgnorceCaseBtn.setSelection(false); } if (preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SRC_IGNORCETAG)) { srcIgnorceTagBtn.setSelection(true); } else { srcIgnorceTagBtn.setSelection(false); } if (preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_SAMETARGET)) { sameTargetBtn.setSelection(true); } else { sameTargetBtn.setSelection(false); } if (preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_TAR_IGNORCECASE)) { tarIgnorceCaseBtn.setSelection(true); } else { tarIgnorceCaseBtn.setSelection(false); } if (preferenceStore.getBoolean(QAConstant.QA_PREF_PARA_TAR_IGNORCETAG)) { tarIgnorceTagBtn.setSelection(true); } else { tarIgnorceTagBtn.setSelection(false); } // -------------------------目标文本段长度限制设置 minBtn.setSelection(preferenceStore.getBoolean(QAConstant.QA_PREF_isCheckTgtMinLength)); maxBtn.setSelection(preferenceStore.getBoolean(QAConstant.QA_PREF_isCheckTgtMaxLength)); minTxt.setText(preferenceStore.getString(QAConstant.QA_PREF_tgtMinLength)); maxTxt.setText(preferenceStore.getString(QAConstant.QA_PREF_tgtMaxLength)); } @Override protected void performDefaults() { if (CommonFunction.checkEdition("U")) { // 默认情况下,不包含上下文匹配的按钮为选中状态 contextBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE)); } fullMatchBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE)); lockedBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_LOCKED_NOTINCLUDE)); // ----------------------文本段一致性检查的灰复默认值-----------------------------------// // 默认情况下,不包含上下文匹配的按钮为选中状态 sameSourceBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_PARA_SAMESOURCE)); srcIgnorceCaseBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_PARA_SRC_IGNORCECASE)); srcIgnorceTagBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_PARA_SRC_IGNORCETAG)); sameTargetBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_PARA_SAMETARGET)); tarIgnorceCaseBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_PARA_TAR_IGNORCECASE)); tarIgnorceTagBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_PARA_TAR_IGNORCETAG)); // -------------------------目标文本段长度限制设置 minBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_isCheckTgtMinLength)); maxBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_isCheckTgtMaxLength)); minTxt.setText(preferenceStore.getDefaultString(QAConstant.QA_PREF_tgtMinLength)); maxTxt.setText(preferenceStore.getDefaultString(QAConstant.QA_PREF_tgtMaxLength)); } public void init(IWorkbench workbench) { } @Override public boolean performOk() { if (!isInit) { return true; } if (!validMinValue(isNumericRegex) || !validMaxValue(isNumericRegex)) { return false; } if (CommonFunction.checkEdition("U")) { // 不包含上下文匹配的文本段 if (contextBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE, false); } } // 不包含完全匹配的文本段 if (fullMatchBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE, false); } // 不包含已锁定的文本段 if (lockedBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_LOCKED_NOTINCLUDE, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_LOCKED_NOTINCLUDE, false); } // ------------------------------文本段一致性检查的确定按钮点击所触发的事件 if (sameSourceBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SAMESOURCE, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SAMESOURCE, false); } if (srcIgnorceCaseBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SRC_IGNORCECASE, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SRC_IGNORCECASE, false); } if (srcIgnorceTagBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SRC_IGNORCETAG, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SRC_IGNORCETAG, false); } if (sameTargetBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SAMETARGET, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_PARA_SAMETARGET, false); } if (tarIgnorceCaseBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_PARA_TAR_IGNORCECASE, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_PARA_TAR_IGNORCECASE, false); } if (tarIgnorceTagBtn.getSelection()) { preferenceStore.setValue(QAConstant.QA_PREF_PARA_TAR_IGNORCETAG, true); } else { preferenceStore.setValue(QAConstant.QA_PREF_PARA_TAR_IGNORCETAG, false); } preferenceStore.setValue(QAConstant.QA_PREF_isCheckTgtMinLength, minBtn.getSelection()); preferenceStore.setValue(QAConstant.QA_PREF_isCheckTgtMaxLength, maxBtn.getSelection()); preferenceStore.setValue(QAConstant.QA_PREF_tgtMinLength, minTxt.getText()); preferenceStore.setValue(QAConstant.QA_PREF_tgtMaxLength, maxTxt.getText()); return true; } public void initListener() { // 勾选相同源文不同译文时,将属于它的两个小项“忽略标记与忽略大小写”也选中。 sameSourceBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { srcIgnorceCaseBtn.setSelection(sameSourceBtn.getSelection()); srcIgnorceTagBtn.setSelection(sameSourceBtn.getSelection()); } }); // 勾选相同译文不同源文时,将属于它的两个小项“忽略标记与忽略大小写”也选中。 sameTargetBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { tarIgnorceCaseBtn.setSelection(sameTargetBtn.getSelection()); tarIgnorceTagBtn.setSelection(sameTargetBtn.getSelection()); } }); srcIgnorceCaseBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (srcIgnorceCaseBtn.getSelection()) { sameSourceBtn.setSelection(true); } } }); srcIgnorceTagBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (srcIgnorceTagBtn.getSelection()) { sameSourceBtn.setSelection(true); } } }); tarIgnorceCaseBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (tarIgnorceCaseBtn.getSelection()) { sameTargetBtn.setSelection(true); } } }); tarIgnorceTagBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (tarIgnorceTagBtn.getSelection()) { sameTargetBtn.setSelection(true); } } }); } }
19,555
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NonTranslationQAPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/preference/NonTranslationQAPage.java
package net.heartsome.cat.ts.ui.qa.preference; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.dialogs.AddOrEditNontransElementDialog; import net.heartsome.cat.ts.ui.qa.model.NontransElementBean; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.nonTransElement.NonTransElementOperate; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.resource.ImageConstant; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; 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.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * 非译元素的首选项设置 * @author robert 2011-11-30 */ public class NonTranslationQAPage extends PreferencePage implements IWorkbenchPreferencePage { public static final String ID = "net.heartsome.cat.ts.ui.qa.preference.NonTranslationQAPage"; private Button addBtn; private Button editBtn; private Button deleteBtn; private TableViewer tableViewer; private ComboViewer comboViewer; private NonTransElementOperate operate; /** 内置非译元素,从QAMolde中获取 */ private List<NontransElementBean> internalElementList = new ArrayList<NontransElementBean>(); private List<NontransElementBean> defaultTipList = new ArrayList<NontransElementBean>(); /** 从非译元素库中取出的非译元素的集合 */ private List<NontransElementBean> dataList; private boolean isInit = false; public NonTranslationQAPage() { setTitle(Messages.getString("qa.preference.NonTranslationQAPage.nonTransElement")); initValue(); } /** * 初始化相关数据 */ public void initValue() { operate = new NonTransElementOperate(); operate.openNonTransDB(); internalElementList = QAModel.getInterNonTransElements(); defaultTipList.add(new NontransElementBean(null, Messages.getString("qa.preference.NonTranslationQAPage.addInterElement"), null, null)); dataList = operate.getNonTransElements(); } public void init(IWorkbench workbench) { } @Override protected Control createContents(Composite parent) { isInit = true; Composite tparent = new Composite(parent, SWT.NONE); tparent.setLayout(new GridLayout()); GridDataFactory.fillDefaults().grab(true, true).hint(550, 400).applyTo(tparent); Group instalGroup = new Group(tparent, SWT.NONE); instalGroup.setLayout(new GridLayout()); instalGroup.setLayoutData(new GridData(GridData.FILL_BOTH)); instalGroup.setText(Messages.getString("qa.preference.NonTranslationQAPage.nonTransElementInstal")); String tip = Messages.getString("preference.NonTranslationQAPage.instalLbl"); HsImageLabel instalLbl = new HsImageLabel(tip, Activator.getImageDescriptor(ImageConstant.PREFERENCE_QA_nontrans_nontransInstal)); Composite instalCmp = instalLbl.createControl(instalGroup); instalCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // 一排按钮 Composite buttonCmp = new Composite(instalGroup, SWT.NONE); GridLayoutFactory.fillDefaults().margins(0, 0).numColumns(4).applyTo(buttonCmp); GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonCmp); addBtn = new Button(buttonCmp, SWT.NONE); addBtn.setText(Messages.getString("qa.preference.NonTranslationQAPage.add")); editBtn = new Button(buttonCmp, SWT.NONE); editBtn.setText(Messages.getString("qa.preference.NonTranslationQAPage.editBtn")); editBtn.setEnabled(false); deleteBtn = new Button(buttonCmp, SWT.NONE); deleteBtn.setText(Messages.getString("qa.preference.NonTranslationQAPage.delete")); deleteBtn.setEnabled(false); Point addPoint = addBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); Point editPoint = editBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); Point delPoint = deleteBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); GridData btnData = new GridData(); int width = Math.max(addPoint.x, Math.max(editPoint.x, delPoint.x)); btnData.widthHint = width + 10; addBtn.setLayoutData(btnData); editBtn.setLayoutData(btnData); deleteBtn.setLayoutData(btnData); Map<String, String> comboTip = new HashMap<String, String>(); comboTip.put(QAConstant.QA_NONTRANS_NAME, Messages.getString("qa.preference.NonTranslationQAPage.addInterElement")); comboViewer = new ComboViewer(buttonCmp, SWT.NONE); comboViewer.setContentProvider(new ArrayContentProvider()); comboViewer.setLabelProvider(new NonTransElementCmbProvider()); comboViewer.getCombo().setToolTipText(Messages.getString("qa.preference.NonTranslationQAPage.addInterElement")); comboViewer.setInput(internalElementList); comboViewer.getCombo().setText(Messages.getString("qa.preference.NonTranslationQAPage.addInterElement")); GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).grab(false, false).applyTo(comboViewer.getCombo()); // ---------------------下面是非译元素展示框--------------------------------- tableViewer = new TableViewer(instalGroup, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); final Table table = tableViewer.getTable(); table.setLinesVisible(true); table.setHeaderVisible(true); ColumnViewerToolTipSupport.enableFor(tableViewer,ToolTip.NO_RECREATE); String[] columnNames = new String[] {Messages.getString("qa.preference.NonTranslationQAPage.tipColumn"), Messages.getString("qa.preference.NonTranslationQAPage.contentColumn"), Messages.getString("qa.preference.NonTranslationQAPage.regularColumn")}; tableViewer.setLabelProvider(new NonTransElementTableProvider()); int[] columnAlignments = new int[] { SWT.LEFT, SWT.LEFT, SWT.LEFT}; for (int i = 0; i < columnNames.length; i++) { TableViewerColumn column = new TableViewerColumn(tableViewer, columnAlignments[i]); column.getColumn().setText(columnNames[i]); column.getColumn().setWidth(50); column.setLabelProvider(new NonTransElementTableProvider(i)); if (i == 0) { column.getColumn().addSelectionListener(new SelectionAdapter() { boolean asc = true; public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? TableSorter.name_ASC : TableSorter.name_DESC); asc = !asc; } }); } if (i == 1) { column.getColumn().addSelectionListener(new SelectionAdapter() { boolean asc = true; public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? TableSorter.content_ASC : TableSorter.content_DESC); asc = !asc; } }); } } tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH)); tableViewer.setInput(dataList); GridDataFactory.fillDefaults().grab(true, true).applyTo(table); // 让列表列宽动态变化 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.2, 0.2, 0.58}; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); instalLbl.computeSize(); initListener(); return parent; } /** * 一些事件的添加 */ public void initListener() { // 非译元素的添加事件 addBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { addNonTransElement(); } public void widgetDefaultSelected(SelectionEvent e) { addNonTransElement(); } }); editBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { editNontransElement(); } public void widgetDefaultSelected(SelectionEvent arg0) { editNontransElement(); } }); // 删除按钮的点击操作 deleteBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { deleteElement(); } public void widgetDefaultSelected(SelectionEvent e) { deleteElement(); } }); // 给comboViewer添加事件,同时传入内置元素 comboViewer.getCombo().addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { addInternalElement(); comboViewer.getCombo().setText(Messages.getString("qa.preference.NonTranslationQAPage.addInterElement")); } public void widgetDefaultSelected(SelectionEvent e) { addInternalElement(); comboViewer.getCombo().setText(Messages.getString("qa.preference.NonTranslationQAPage.addInterElement")); } }); // 非译元素列表的点击事件 tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (structuredSelection.getFirstElement() instanceof NontransElementBean) { if (structuredSelection.size() == 1 && !validIsInternalElementNonTip((NontransElementBean)structuredSelection.getFirstElement())) { editBtn.setEnabled(true); }else { editBtn.setEnabled(false); } deleteBtn.setEnabled(true); }else { setAddModel(); } }else { setAddModel(); } } }); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent arg0) { editNontransElement(); } }); } /** * 设置添加模式 */ private void setAddModel(){ editBtn.setEnabled(false); deleteBtn.setEnabled(false); } /** * 验证是否是内置非译元素 * @return */ private boolean validIsInternalElementNonTip(NontransElementBean curElement){ String selectedElementId = curElement.getId(); if ("qaInternalNonTrans_ip".equals(selectedElementId) || "qaInternalNonTrans_email".equals(selectedElementId) || "qaInternalNonTrans_web".equals(selectedElementId)) { return true; } return false; } /** * 添加非译元素 */ public void addNonTransElement() { NontransElementBean bean = new NontransElementBean(); AddOrEditNontransElementDialog dialog = new AddOrEditNontransElementDialog(getShell(), true, tableViewer, bean); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { // 先添加到listViewer中 dataList.add(bean); tableViewer.refresh(); tableViewer.setSelection(new StructuredSelection(bean)); } } /** * 编辑非译元素 */ private void editNontransElement(){ NontransElementBean bean = null; ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (structuredSelection.getFirstElement() instanceof NontransElementBean) { bean = (NontransElementBean) structuredSelection.getFirstElement(); if (validIsInternalElementNonTip(bean)) { return; } AddOrEditNontransElementDialog dialog = new AddOrEditNontransElementDialog(getShell(), false, tableViewer, bean); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { tableViewer.refresh(); } } } } /** * 删除列表中的非译元素 */ @SuppressWarnings("unchecked") public void deleteElement() { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { boolean confirm = MessageDialog.openConfirm(getShell(), Messages.getString("qa.preference.NonTranslationQAPage.enter"), Messages.getString("qa.preference.NonTranslationQAPage.enterDelete")); if (!confirm) { return; } IStructuredSelection structuredSelection = (IStructuredSelection) selection; Iterator<NontransElementBean> iter = structuredSelection.iterator(); while (iter.hasNext()) { NontransElementBean selectElement = iter.next(); dataList.remove(selectElement); } tableViewer.refresh(); } } /** * 如果点击默认,那么重新从非译元素的库中取值,再删除之前所添加或删除的非译元素 */ @Override protected void performDefaults() { dataList = QAModel.getInterNonTransElements(); tableViewer.setInput(dataList); setAddModel(); } @Override public boolean performOk() { if (!isInit) { return true; } // 遍历列表,获取出要添加的数据 List<NontransElementBean> addElementList = new ArrayList<NontransElementBean>(); NontransElementBean listViewerBean; int listViewerNum = tableViewer.getTable().getItemCount(); for (int i = 0; i < listViewerNum; i++) { if (tableViewer.getElementAt(i) instanceof NontransElementBean) { listViewerBean = (NontransElementBean)tableViewer.getElementAt(i); addElementList.add(listViewerBean); } } // 删除所有非译元素 operate.deleteAllElement(); // 再进行相关操作,先添加 if (addElementList.size() > 0) { operate.addNonTransElement(addElementList); } IPreferenceStore store = Activator.getDefault().getPreferenceStore(); int oldValue = store.getInt(QAConstant.QA_PREF_nonTrans_changeTag); store.setValue(QAConstant.QA_PREF_nonTrans_changeTag, ++oldValue); return true; } /** * 给comboViewer初始化内置元素 */ public void initInternalValue() { comboViewer.getCombo().removeAll(); comboViewer.setInput(internalElementList); comboViewer.refresh(); } /** * 添加内置非译元素 */ public void addInternalElement() { ISelection selection = comboViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; NontransElementBean interBean = (NontransElementBean) structuredSelection.getFirstElement(); if (interBean.getId() == null) { return; } int eleSum = tableViewer.getTable().getItemCount(); for (int i = 0; i < eleSum; i++) { NontransElementBean curBean = new NontransElementBean(); if (tableViewer.getElementAt(i) instanceof NontransElementBean) { curBean = (NontransElementBean) tableViewer.getElementAt(i); if (curBean.getId().equals(interBean.getId())) { MessageDialog.openWarning(getShell(), Messages.getString("qa.all.dialog.warning"), MessageFormat .format(Messages.getString("qa.preference.NonTranslationQAPage.tip5"), interBean.getName())); return; } } } dataList.add(interBean); tableViewer.refresh(); } } /** * tableViewer的标签提供器 * @author robert */ class NonTransElementTableProvider extends CellLabelProvider implements ITableLabelProvider { private int index; public NonTransElementTableProvider(){} public NonTransElementTableProvider(int index){ this.index = index; } public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof NontransElementBean) { NontransElementBean bean = (NontransElementBean)element; switch (columnIndex) { case 0: return bean.getName(); case 1: return isNull(bean.getContent()) ? "" : bean.getContent(); case 2: return isNull(bean.getRegular()) ? "" : bean.getRegular(); default: return null; } } return null; } @Override public void update(ViewerCell cell) { cell.setText(getColumnText(cell.getElement(), index)); } @Override public String getToolTipText(Object element) { if (element instanceof NontransElementBean) { NontransElementBean bean = (NontransElementBean)element; switch (index) { case 0: return bean.getName(); case 1: return isNull(bean.getContent()) ? "" : bean.getContent(); case 2: return isNull(bean.getRegular()) ? "" : bean.getRegular(); default: return null; } } return null; } @Override public Point getToolTipShift(Object object) { return new Point(5, 5); } } /** * 非译元素列表的标签提供类 * @author robert 2011-11-30 */ class NonTransElementCmbProvider extends LabelProvider { @Override public String getText(Object element) { if (element instanceof NontransElementBean) { return ((NontransElementBean)element).getName(); } return ""; } } @Override public void dispose() { super.dispose(); } /** * 非译元素的所显示的列中的排序类 * @version * @since JDK1.6 */ static class TableSorter extends ViewerSorter { private static final int name_ID = 1; //非译元素名称 private static final int content_ID = 2; //非译元素内容 public static final TableSorter name_ASC = new TableSorter(name_ID); public static final TableSorter name_DESC = new TableSorter(-name_ID); public static final TableSorter content_ASC = new TableSorter(content_ID); public static final TableSorter content_DESC = new TableSorter(-content_ID); private int sortType; private TableSorter(int sortType) { this.sortType = sortType; } @Override public int compare(Viewer viewer, Object e1, Object e2) { NontransElementBean bean1 = (NontransElementBean) e1; NontransElementBean bean2 = (NontransElementBean) e2; switch (sortType) { case name_ID: { String name1 = bean1.getName(); String name2 = bean2.getName(); return name1.compareToIgnoreCase(name2); } case -name_ID: { String name1 = bean1.getName(); String name2 = bean2.getName(); return name2.compareToIgnoreCase(name1); } case content_ID: { String content1 = bean1.getContent(); String content2 = bean2.getContent(); return content1.compareToIgnoreCase(content2); } case -content_ID: { String content1 = bean1.getContent(); String content2 = bean2.getContent(); return content2.compareToIgnoreCase(content1); } } return 0; } } /** * 判断是否为空 * @param str * @return */ public static boolean isNull(String str){ if (str == null || "".equals(str)) { return true; } return false; } public static void main(String[] args) { String regular = "(?i)this is a regular"; if (regular.contains("\\b")) { System.out.println("------------"); } } }
20,683
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SpellPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/preference/SpellPage.java
package net.heartsome.cat.ts.ui.qa.preference; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Vector; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.common.locale.LocaleService; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.composite.LanguageLabelProvider; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.resource.ImageConstant; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.FileLocator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.nebula.jface.tablecomboviewer.TableComboViewer; import org.eclipse.nebula.widgets.tablecombo.TableCombo; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 拼写检查设置首选项界面 * @author robert 2013-01-30 */ public class SpellPage extends PreferencePage implements IWorkbenchPreferencePage { public final static String ID = "net.heartsome.cat.ts.ui.qa.preference.SpellPage"; private IPreferenceStore preferenceStore; private static final Logger LOGGER = LoggerFactory.getLogger(SpellPage.class.getName()); /** 组件是否初始化 */ private boolean isInit = false; /** 拼写检查器 > Aspell单选按钮 */ private Button aspellBtn; /** 拼写检查器 > 内置拼写检查器 hunspell 单选按钮 */ private Button hunspellBtn; /** 是否实时检查 */ private Button realTimeSpellBtn; /** 装载 hunspell 与 aspell 设置的 tab folder */ private TabFolder tabFolder; private TabItem hunspellTabItem; private TabItem aspellTabItem; //----------------- 下面是 hunspell 设置组件 --------------------------// /** 忽略非译元素 */ private Button ignoreNontransBtn; /** 忽略单词首字母为数字 */ private Button ignoreDigitalFirstBtn; /** 忽略单词首字母为大写 */ private Button ignoreUpperCaseFirstBtn; /** 忽略所有都是大写的单词 */ private Button ignoreAllUpperCaseBtn; //------------------ 下面是 aspell 设置的组件 --------------------------// /** 语言集合 */ private List<Language> languages; /** Aspell 配置文件路径 */ private String configFilePath; /** Aspell 命令文本框 */ private Text txtCommandPath; /** 浏览按钮 */ private Button btnBrowse; /** 是否使用 UTF-8 复选框 */ private Button btnUTF8; /** 刷新按钮 */ private Button btnRefresh; /** 语言下拉框 */ private TableComboViewer cmbLang; /** 默认词典下拉框 */ private ComboViewer cmbDefaultDic; /** 添加到列表按钮 */ private Button btnAdd; /** 从列表删除按钮 */ private Button btnRemove; /** 词典表格 */ private Table table; private Map<String, Language> langMap = null; private String bundlePath; private QAXmlHandler xmlHandler; public SpellPage() { setTitle("拼写检查"); setPreferenceStore(Activator.getDefault().getPreferenceStore()); preferenceStore = getPreferenceStore(); try { bundlePath = FileLocator.toFileURL(net.heartsome.cat.ts.ui.Activator.getDefault().getBundle().getEntry("")).getPath(); } catch (IOException e) { LOGGER.error(Messages.getString("qa.preference.SpellPage.LOG1"), e); } langMap = LocaleService.getDefaultLanguage(); languages = new ArrayList<Language>(langMap.values()); Collections.sort(languages, new Comparator<Language>() { public int compare(Language o1, Language o2) { return o1.toString().compareTo(o2.toString()); } }); checkAspellConfigureFile(); } public void init(IWorkbench workbench) { } @Override protected Control createContents(Composite parent) { isInit = true; Composite tParent = new Composite(parent, SWT.BORDER); tParent.setLayoutData(new GridData(GridData.FILL_BOTH)); tParent.setLayout(new GridLayout()); addSpellInstalGroup(tParent); tabFolder = new TabFolder(tParent, SWT.NONE); tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); hunspellTabItem = new TabItem(tabFolder, SWT.NONE); hunspellTabItem.setText(Messages.getString("qa.preference.SpellPage.hunspellTab")); aspellTabItem = new TabItem(tabFolder, SWT.NONE); aspellTabItem.setText(Messages.getString("qa.preference.SpellPage.aspellTab")); createHunspellCmp(); createAspellCmp(); initData(); return parent; } /** * 创建 aspell 的初始化数据 */ private void checkAspellConfigureFile(){ // 先检查首选项目录是否存在 String preferencePath = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(QAConstant.QA_SPELL_preferenceFolder).toOSString(); File preferenceFolder = new File(preferencePath); if (!preferenceFolder.exists() || preferenceFolder.isFile()) { preferenceFolder.mkdirs(); } configFilePath = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(QAConstant.QA_SPELL_ASPELLCONFIGFILE).toOSString(); File configureFile = new File(configFilePath); if (!configureFile.exists() || configureFile.isDirectory()) { try { FileOutputStream fos = new FileOutputStream(configureFile); BufferedOutputStream bos = new BufferedOutputStream(fos); StringBuffer bf = new StringBuffer(); bf.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); bf.append("<aspell>\n"); bf.append("</aspell>"); bos.write(bf.toString().getBytes()); bos.close(); fos.close(); } catch (IOException e) { LOGGER.error(Messages.getString("qa.preference.SpellPage.LOG2"), e); MessageDialog.openInformation(getShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.preference.SpellPage.LOG3")); } } } /** * 拼写检查词典设置 * @param tParent */ private void addSpellInstalGroup(Composite tParent) { Group groupSpellCheck = new Group(tParent, SWT.NONE); groupSpellCheck.setLayout(new GridLayout()); groupSpellCheck.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); groupSpellCheck.setText(Messages.getString("qa.preference.SpellPage.groupSpellCheck")); HsImageLabel imageLabel2 = new HsImageLabel(Messages.getString("qa.preference.SpellPage.imageLabel2"), Activator.getImageDescriptor(ImageConstant.PREFERENCE_SYS_DICTIONARY)); Composite cmpSpellCheck = imageLabel2.createControl(groupSpellCheck); cmpSpellCheck.setLayout(new GridLayout(2, false)); cmpSpellCheck.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); hunspellBtn = new Button(cmpSpellCheck, SWT.RADIO); hunspellBtn.setText(Messages.getString("qa.preference.SpellPage.hunspellBtn")); hunspellBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); aspellBtn = new Button(cmpSpellCheck, SWT.RADIO); aspellBtn.setText(Messages.getString("qa.preference.SpellPage.aspellBtn")); aspellBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); realTimeSpellBtn = new Button(cmpSpellCheck, SWT.CHECK); realTimeSpellBtn.setText(Messages.getString("qa.preference.SpellPage.realTimeSpellBtn")); realTimeSpellBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); imageLabel2.computeSize(); hunspellBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { tabFolder.setSelection(hunspellTabItem); } }); aspellBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { tabFolder.setSelection(aspellTabItem); } }); } /** * 创建 hunspell 的界面 */ private void createHunspellCmp() { Composite composite = new Composite(tabFolder, SWT.NONE); composite.setLayout(new GridLayout()); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); HsImageLabel imageLabel = new HsImageLabel(Messages.getString("qa.preference.SpellPage.hunspellTab.label"), Activator.getImageDescriptor(ImageConstant.PREFERENCE_SYS_IN_DIC)); Composite cmp = imageLabel.createControl(composite); ignoreNontransBtn = new Button(cmp, SWT.CHECK); ignoreNontransBtn.setText(Messages.getString("qa.preference.SpellPage.ignoreNontransBtn")); ignoreDigitalFirstBtn = new Button(cmp, SWT.CHECK); ignoreDigitalFirstBtn.setText(Messages.getString("qa.preference.SpellPage.ignoreDigitalFirstBtn")); ignoreUpperCaseFirstBtn = new Button(cmp, SWT.CHECK); ignoreUpperCaseFirstBtn.setText(Messages.getString("qa.preference.SpellPage.ignoreUpperCaseFirstBtn")); ignoreAllUpperCaseBtn = new Button(cmp, SWT.CHECK); ignoreAllUpperCaseBtn.setText(Messages.getString("qa.preference.SpellPage.ignoreAllUpperBtn")); imageLabel.computeSize(); hunspellTabItem.setControl(composite); } /** * 创建 aspell 的配置界面 */ private void createAspellCmp() { isInit = true; Composite groupParent = new Composite(tabFolder, SWT.NONE); groupParent.setLayout(new GridLayout()); groupParent.setLayoutData(new GridData(GridData.FILL_BOTH)); // Group groupParent = new Group(tparent, SWT.None); // groupParent.setLayout(new GridLayout()); // groupParent.setLayoutData(new GridData(GridData.FILL_BOTH)); // groupParent.setText(Messages.getString("qa.preference.SpellPage.groupParent")); HsImageLabel imageLabel = new HsImageLabel( Messages.getString("qa.preference.SpellPage.imageLabel"), Activator.getImageDescriptor(ImageConstant.PREFERENCE_SYS_ASPELL_DIC)); Composite cmp = imageLabel.createControl(groupParent); cmp.setLayout(new GridLayout()); Composite cmpTemp = (Composite) imageLabel.getControl(); cmpTemp.setLayoutData(new GridData(GridData.FILL_BOTH)); Composite cmpContent = new Composite(cmpTemp, SWT.None); cmpContent.setLayout(new GridLayout(3, false)); GridData data = new GridData(GridData.FILL_BOTH); data.horizontalSpan = 2; cmpContent.setLayoutData(data); Label lbl = new Label(cmpContent, SWT.NONE); lbl.setText(Messages.getString("qa.preference.SpellPage.lblPath")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lbl); txtCommandPath = new Text(cmpContent, SWT.BORDER); txtCommandPath.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); txtCommandPath.setEditable(false); btnBrowse = new Button(cmpContent, SWT.NONE); btnBrowse.setText(Messages.getString("qa.preference.SpellPage.btnBrowse")); // GridData btnData = new GridData(); // btnData.widthHint = 70; // btnBrowse.setLayoutData(btnData); new Label(cmpContent, SWT.NONE); btnUTF8 = new Button(cmpContent, SWT.CHECK); btnUTF8.setText(Messages.getString("qa.preference.SpellPage.btnUTF8")); new Label(cmpContent, SWT.NONE); lbl = new Label(cmpContent, SWT.NONE); lbl.setText(Messages.getString("qa.preference.SpellPage.lblDic")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lbl); cmbDefaultDic = new ComboViewer(cmpContent); cmbDefaultDic.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnRefresh = new Button(cmpContent, SWT.NONE); btnRefresh.setText(Messages.getString("qa.preference.SpellPage.btnRefresh")); lbl = new Label(cmpContent, SWT.NONE); lbl.setText(Messages.getString("qa.preference.SpellPage.lblLang")); GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lbl); cmbLang = new TableComboViewer(cmpContent, SWT.READ_ONLY | SWT.BORDER); TableCombo tableCombo = cmbLang.getTableCombo(); tableCombo.setShowTableLines(false); tableCombo.setShowTableHeader(false); tableCombo.setDisplayColumnIndex(-1); tableCombo.setShowImageWithinSelection(true); tableCombo.setShowColorWithinSelection(false); tableCombo.setShowFontWithinSelection(false); tableCombo.setVisibleItemCount(20); cmbLang.getTableCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); cmbLang.setLabelProvider(new LanguageLabelProvider()); cmbLang.setContentProvider(new ArrayContentProvider()); cmbLang.setInput(languages); cmbLang.getTableCombo().select(0); new Label(cmpContent, SWT.NONE); Composite cmpTableBtn = new Composite(cmpContent, SWT.NONE); GridLayout btnLayout = new GridLayout(2, false); btnLayout.marginWidth = 0; cmpTableBtn.setLayout(btnLayout); GridData btnData1 = new GridData(GridData.FILL_BOTH); btnData1.horizontalSpan = 3; cmpTableBtn.setLayoutData(btnData1); btnAdd = new Button(cmpTableBtn, SWT.NONE); btnAdd.setText(Messages.getString("qa.preference.SpellPage.btnAdd")); btnRemove = new Button(cmpTableBtn, SWT.NONE); btnRemove.setText(Messages.getString("qa.preference.SpellPage.btnRemove")); Point browsePoint = btnBrowse.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); Point refreshPoint = btnRefresh.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); Point addPoint = btnAdd.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); Point remPoint = btnRemove.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); GridData btnData = new GridData(); int width = Math.max(refreshPoint.x, Math.max(browsePoint.x, Math.max(addPoint.x, remPoint.x))); btnData.widthHint = width + 10; btnBrowse.setLayoutData(btnData); btnRefresh.setLayoutData(btnData); btnAdd.setLayoutData(btnData); btnRemove.setLayoutData(btnData); table = new Table(cmpTableBtn, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); String[] arrTableHeader = new String[] { Messages.getString("qa.preference.SpellPage.arrTableHeader1"), "", Messages.getString("qa.preference.SpellPage.arrTableHeader2") }; int[] arrWidth = new int[] { 195, 40, 195 }; for (int i = 0; i < arrTableHeader.length; i++) { int style = SWT.NONE; if (i == 1) { style = SWT.CENTER; } TableColumn col = new TableColumn(table, style); col.setText(arrTableHeader[i]); col.setWidth(arrWidth[i]); } GridData dataTable = new GridData(GridData.FILL_BOTH); dataTable.horizontalSpan = 2; table.setLayoutData(dataTable); table.setHeaderVisible(true); table.setLinesVisible(true); initProperty(); initListener(); imageLabel.computeSize(); aspellTabItem.setControl(groupParent); } private void initProperty() { xmlHandler = new QAXmlHandler(); Map<String, Object> openResultMap = xmlHandler.openFile(configFilePath); if (openResultMap != null && QAConstant.RETURNVALUE_RESULT_RETURN.equals(openResultMap.get(QAConstant.RETURNVALUE_RESULT))) { return; } if (openResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) openResultMap .get(QAConstant.RETURNVALUE_RESULT)) { // 针对文件解析出错 boolean response = MessageDialog.openConfirm(getShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.preference.SpellPage.aspellLogCheck")); if (response) { checkAspellConfigureFile(); }else { return; } } String commandPath = xmlHandler.getNodeText(configFilePath, "/aspell/commandLine", ""); txtCommandPath.setText(commandPath == null ? "" : commandPath); cmbDefaultDic.getCombo().setItems(getDictionaries(commandPath)); cmbDefaultDic.getCombo().select(0); String utf8 = xmlHandler.getNodeText(configFilePath, "/aspell/utf8", ""); btnUTF8.setSelection(utf8 != null && utf8.equals("yes")); List<String[]> aspellDicList = null; try { aspellDicList = xmlHandler.getAspellDicConfig(configFilePath); addLangAndDicToTable(aspellDicList); } catch (Exception e) { LOGGER.error(Messages.getString("qa.preference.SpellPage.LOG4"), e); } } private void initListener() { btnBrowse.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog flg = new FileDialog(btnBrowse.getShell(), SWT.OPEN); flg.setText(Messages.getString("qa.preference.SpellPage.btnBrowse.Title")); String[] filter = new String[] { "*" }; flg.setFilterExtensions(filter); if (txtCommandPath.getText() == null || txtCommandPath.getText().trim().equals("")) { flg.setFilterPath(System.getProperty("user.home")); } else { String path = txtCommandPath.getText(); if (path.endsWith(" --encoding=utf-8")) { path = path.substring(0, path.indexOf(" --encoding=utf-8")); } flg.setFilterPath(path.substring(0, path.lastIndexOf(System.getProperty("file.separator")))); flg.setFileName(path.substring(path.lastIndexOf(System.getProperty("file.separator")) + 1)); } String stropen = flg.open(); String commandLine = stropen == null ? "" : stropen; if (commandLine.equals("")) { return; } else { boolean blnUseUTF8 = btnUTF8.getSelection(); if (blnUseUTF8 && !commandLine.endsWith(" --encoding=utf-8")) { commandLine += " --encoding=utf-8"; } if (!blnUseUTF8 && commandLine.endsWith(" --encoding=utf-8")) { commandLine = commandLine.substring(0, commandLine.indexOf(" --encoding=utf-8")); } txtCommandPath.setText(commandLine); cmbDefaultDic.getCombo().removeAll(); cmbDefaultDic.getCombo().setItems(getDictionaries(commandLine)); cmbDefaultDic.getCombo().select(0); } filter = null; } }); btnUTF8.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { boolean blnUseUTF8 = btnUTF8.getSelection(); String commandLine = txtCommandPath.getText(); if (blnUseUTF8 && !commandLine.endsWith(" --encoding=utf-8") && !commandLine.equals("")) { commandLine += " --encoding=utf-8"; } if (!blnUseUTF8 && commandLine.endsWith(" --encoding=utf-8")) { commandLine = commandLine.substring(0, commandLine.indexOf(" --encoding=utf-8")); } txtCommandPath.setText(commandLine); } }); btnRefresh.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String commandLine = txtCommandPath.getText(); cmbDefaultDic.getCombo().removeAll(); cmbDefaultDic.getCombo().setItems(getDictionaries(commandLine)); cmbDefaultDic.getCombo().select(0); } }); btnAdd.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (cmbLang.getTableCombo().getSelectionIndex() >= 0 && cmbDefaultDic.getCombo().getSelectionIndex() >= 0) { String lang = TextUtil.getLanguageCode(cmbLang.getTableCombo().getItem( cmbLang.getTableCombo().getSelectionIndex())); String fileName = cmbDefaultDic.getCombo().getItem(cmbDefaultDic.getCombo().getSelectionIndex()); TableItem[] items = table.getItems(); boolean blnIsUpdate = false; for (int i = 0; i < items.length; i++) { String itemLang = TextUtil.getLanguageCode(items[i].getText(0)); if (lang.equals(itemLang)) { if (fileName.equals(items[i].getText(2))) { return; } blnIsUpdate = true; break; } } List<String[]> dicList = new ArrayList<String[]>(); dicList.add(new String[]{lang, fileName}); addLangAndDicToTable(dicList); try { xmlHandler.addAspellConfig(configFilePath, lang, fileName, blnIsUpdate); } catch (Exception e) { LOGGER.error(Messages.getString("qa.preference.SpellPage.LOG5"), e); } } } }); btnRemove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (table.getSelectionCount() == 0) { MessageDialog.openInformation(getShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.preference.SpellPage.msg1")); return; } Rectangle rect = table.getBounds(); for (TableItem item : table.getSelection()) { String lang = TextUtil.getLanguageCode(item.getText(0)); try { xmlHandler.removeAspellConfig(configFilePath, lang); } catch (Exception e) { LOGGER.error(Messages.getString("qa.preference.SpellPage.LOG6"), e); } table.remove(table.indexOf(item)); } table.pack(); table.setHeaderVisible(true); table.setBounds(rect); } }); } /** * 根据传入的 命令 从 aspell 中读取所有的词典 * @param command * @return */ public String[] getDictionaries(String command) { String response; Process spellProcess; Runtime runtime = Runtime.getRuntime(); try { spellProcess = runtime.exec(command + " dump dicts --encoding=utf-8"); BufferedReader spellReader = new BufferedReader(new InputStreamReader(spellProcess.getInputStream())); response = spellReader.readLine(); Vector<String> result = new Vector<String>(); while (response != null && !response.equals("")) { result.add(response); response = spellReader.readLine(); } String[] dicts = new String[result.size()]; for (int i = 0; i < result.size(); i++) { dicts[i] = result.get(i); } return dicts; } catch (IOException e) { return new String[0]; } } /** * 将语言与词典对进行加载到列表中, * @param aspellDicList 第一个数据为 语言, 第二个数据为 词典 */ private void addLangAndDicToTable(List<String[]> aspellDicList) { for(String[] dicArray : aspellDicList){ String lang = dicArray[0]; String dic = dicArray[1]; TableItem item = null; for (int i = 0; i < table.getItemCount(); i++) { TableItem currItem = table.getItem(i); if (TextUtil.getLanguageCode(currItem.getText(0)).equals(lang)) { item = currItem; } } if (item == null) { item = new TableItem(table, 0); } String[] data = { TextUtil.getLanguageName(lang), "->", dic }; //$NON-NLS-1$ String imgPath = langMap.get(lang).getImagePath(); if (imgPath != null && !imgPath.equals("")) { imgPath = bundlePath + imgPath; Image image = new Image(getShell().getDisplay(), imgPath); if (image != null) { ImageData imgData = image.getImageData().scaledTo(16, 12); image = new Image(getShell().getDisplay(), imgData); item.setImage(0, image); } } item.setText(data); } } /** * 初始化数据 */ private void initData(){ if (preferenceStore.getBoolean(QAConstant.QA_PREF_isHunspell)) { hunspellBtn.setSelection(true); }else { aspellBtn.setSelection(true); } realTimeSpellBtn.setSelection(preferenceStore.getBoolean(QAConstant.QA_PREF_realTimeSpell)); ignoreNontransBtn.setSelection(preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreNontrans)); ignoreDigitalFirstBtn.setSelection(preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreDigitalFirst)); ignoreUpperCaseFirstBtn.setSelection(preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreUpperCaseFirst)); ignoreAllUpperCaseBtn.setSelection(preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreAllUpperCase)); if (hunspellBtn.getSelection()) { tabFolder.setSelection(hunspellTabItem); } if (aspellBtn.getSelection()) { tabFolder.setSelection(aspellTabItem); } } @Override protected void performDefaults() { if (preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_isHunspell)) { hunspellBtn.setSelection(true); aspellBtn.setSelection(false); }else { hunspellBtn.setSelection(false); aspellBtn.setSelection(true); } realTimeSpellBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_realTimeSpell)); ignoreNontransBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_ignoreNontrans)); ignoreDigitalFirstBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_ignoreDigitalFirst)); ignoreUpperCaseFirstBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_ignoreUpperCaseFirst)); ignoreAllUpperCaseBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.QA_PREF_ignoreAllUpperCase)); if (hunspellBtn.getSelection()) { tabFolder.setSelection(hunspellTabItem); } if (aspellBtn.getSelection()) { tabFolder.setSelection(aspellTabItem); } } @Override public boolean performOk() { if (!isInit) { return true; } preferenceStore.setValue(QAConstant.QA_PREF_isHunspell, hunspellBtn.getSelection()); preferenceStore.setValue(QAConstant.QA_PREF_realTimeSpell, realTimeSpellBtn.getSelection()); preferenceStore.setValue(QAConstant.QA_PREF_ignoreNontrans, ignoreNontransBtn.getSelection()); preferenceStore.setValue(QAConstant.QA_PREF_ignoreDigitalFirst, ignoreDigitalFirstBtn.getSelection()); preferenceStore.setValue(QAConstant.QA_PREF_ignoreUpperCaseFirst, ignoreUpperCaseFirstBtn.getSelection()); preferenceStore.setValue(QAConstant.QA_PREF_ignoreAllUpperCase, ignoreAllUpperCaseBtn.getSelection()); String commandLine = txtCommandPath.getText(); try { xmlHandler.saveAspellConfig(configFilePath, commandLine, btnUTF8.getSelection()); int oldValue = preferenceStore.getInt(QAConstant.QA_PREF_aspellConfig_changeTag); preferenceStore.setValue(QAConstant.QA_PREF_aspellConfig_changeTag, ++ oldValue); } catch (Exception e) { LOGGER.error(Messages.getString("qa.preference.SpellPage.LOG5"), e); } return true; } }
26,403
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
EquivalentPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/preference/EquivalentPage.java
package net.heartsome.cat.ts.ui.qa.preference; import java.text.MessageFormat; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.resource.ImageConstant; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; 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.Spinner; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * 等效系统的首选项设置 存储在PreferenceStore中的格式为"internalRepeat:0.50;external101:0.50;external100:0.50;95-99:0.60;85-94:0.70;" * @author robert 2011-12-17 加权字数 Weighted Word Count 加权系数 Weighted factor 等效字数 Equivalent wordcount to be paid at full word rate 等效系数 Percentage Payment of Full Word Rate */ public class EquivalentPage extends PreferencePage implements IWorkbenchPreferencePage { public static final String ID = "net.heartsome.cat.ts.ui.qa.preference.EquivalentPage"; IPreferenceStore preferenceStore; private int defaultValue = 95; private Image addImage; private Image deleteimage; private int index = 1; private int selectionvalue = 0; private int space_Number = 10; private GridData btn_data; private GridData spinnerdata; private GridData cmpData; /** 匹配区间所在的父面板 */ private Composite matchParent; /** 重复文本段的加权系数设置所在的面板 */ private Composite repeatCmp; private Composite equiCmp; private GridData equiTxtData; private GridData phLblData; /** 两个按钮所在小面板的长度 */ private int btnCmpWidth = 100; /** 组件是否初始化 */ private boolean isInit = false; private boolean isUltimate = CommonFunction.checkEdition("U"); /** 最低匹配率常量,可以修改 */ private static final int MINRATE = 1; public void init(IWorkbench workbench) { } public EquivalentPage() { setTitle(Messages.getString("preference.EquivalentPage.title")); setPreferenceStore(Activator.getDefault().getPreferenceStore()); preferenceStore = getPreferenceStore(); spinnerdata = new GridData(); spinnerdata.widthHint = 30; equiTxtData = new GridData(SWT.CENTER, SWT.CENTER, false, false); equiTxtData.widthHint = 50; phLblData = new GridData(SWT.FILL, SWT.CENTER, true, false); addImage = Activator.getImageDescriptor("images/addSign.png").createImage(); deleteimage = Activator.getImageDescriptor("images/deleteSign.png").createImage(); } @Override protected Control createContents(Composite parent) { isInit = true; Composite tparent = new Composite(parent, SWT.NONE); tparent.setLayout(new GridLayout()); tparent.setLayoutData(new GridData(GridData.FILL_BOTH)); Group group = new Group(tparent, SWT.NONE); group.setText(Messages.getString("preference.EquivalentPage.group")); group.setLayout(new GridLayout(1, false)); GridData groupData = new GridData(GridData.FILL_BOTH); groupData.widthHint = 500; groupData.heightHint = 460; group.setLayoutData(groupData); String tip = Messages.getString("preference.EquivalentPage.equiImgLbl"); HsImageLabel equiImgLbl = new HsImageLabel(tip, Activator.getImageDescriptor(ImageConstant.PREFERENCE_FA_equivalent)); equiCmp = equiImgLbl.createControl(group); equiCmp.setLayout(new GridLayout()); equiCmp.setLayoutData(new GridData(GridData.FILL_BOTH)); equiImgLbl.computeSize(); // 设置重复文本段的加权系统 createRepeatCmp(); // 内部匹配加权系数 createEqui(equiCmp); createMatchEqui(preferenceStore.getString(QAConstant.FA_PREF_equivalent)); // scroll.setSize(scroll.computeSize(SWT.DEFAULT, SWT.DEFAULT)); return parent; } private void createRepeatCmp(){ repeatCmp = new Composite(equiCmp, SWT.NONE); repeatCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayoutFactory.fillDefaults().margins(0, 0).numColumns(1).equalWidth(false).applyTo(repeatCmp); GridData btnPhLblData = new GridData(SWT.CENTER, SWT.CENTER, false, false); btnPhLblData.widthHint = btnCmpWidth; // 内部重复面板 Composite internalRepeatCmp = new Composite(repeatCmp, SWT.NONE); internalRepeatCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayoutFactory.fillDefaults().margins(0, 0).numColumns(4).equalWidth(false).applyTo(internalRepeatCmp); Label matchLbl = new Label(internalRepeatCmp, SWT.NONE); matchLbl.setText(Messages.getString("preference.EquivalentPage.msg2")); Label phLbl = new Label(internalRepeatCmp, SWT.NONE); // 这个label 是占位用的 phLbl.setLayoutData(phLblData); Text equiTxt = new Text(internalRepeatCmp, SWT.BORDER); equiTxt.setLayoutData(equiTxtData); validEquiTxt(equiTxt); Label btnPhLbl = new Label(internalRepeatCmp, SWT.NONE); // 为了与下面的对齐,这里是两个按钮的占位。 btnPhLbl.setLayoutData(btnPhLblData); // 外部 101% 匹配面板 if (isUltimate) { Composite exter101Cmp = new Composite(repeatCmp, SWT.NONE); exter101Cmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayoutFactory.fillDefaults().margins(0, 0).numColumns(4).equalWidth(false).applyTo(exter101Cmp); matchLbl = new Label(exter101Cmp, SWT.NONE); matchLbl.setText(Messages.getString("preference.EquivalentPage.msg3")); phLbl = new Label(exter101Cmp, SWT.NONE); // 这个label 是占位用的 phLbl.setLayoutData(phLblData); equiTxt = new Text(exter101Cmp, SWT.BORDER); equiTxt.setLayoutData(equiTxtData); validEquiTxt(equiTxt); btnPhLbl = new Label(exter101Cmp, SWT.NONE); btnPhLbl.setLayoutData(btnPhLblData); } // 外部 100% 匹配面板 Composite exter100Cmp = new Composite(repeatCmp, SWT.NONE); exter100Cmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayoutFactory.fillDefaults().margins(0, 0).numColumns(4).equalWidth(false).applyTo(exter100Cmp); matchLbl = new Label(exter100Cmp, SWT.NONE); matchLbl.setText(Messages.getString("preference.EquivalentPage.msg4")); phLbl = new Label(exter100Cmp, SWT.NONE); // 这个label 是占位用的 phLbl.setLayoutData(phLblData); equiTxt = new Text(exter100Cmp, SWT.BORDER); equiTxt.setLayoutData(equiTxtData); validEquiTxt(equiTxt); btnPhLbl = new Label(exter100Cmp, SWT.NONE); btnPhLbl.setLayoutData(btnPhLblData); GridData separatorLblData = new GridData(SWT.FILL, SWT.CENTER, true, false); separatorLblData.horizontalSpan = 4; Label separatorLbl = new Label(repeatCmp, SWT.SEPARATOR | SWT.HORIZONTAL); separatorLbl.setLayoutData(separatorLblData); } /** * 验证用户输入的加权系数的正确性 * @param equiTxt */ private void validEquiTxt(final Text equiTxt){ final String defaultStr = "0.50"; equiTxt.setText(defaultStr); equiTxt.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { String textStr = equiTxt.getText().trim(); if (textStr == null || textStr.trim().length() == 0) { equiTxt.setText(defaultStr); }else { String regular = "1\\.(0){0,2}|0\\.\\d{0,2}"; if (!textStr.matches(regular)) { MessageDialog.openInformation(getShell(), Messages.getString("preference.EquivalentPage.msgTitle"), Messages.getString("preference.EquivalentPage.msg5")); equiTxt.setText(defaultStr); } } } }); } public void createEqui(Composite equiCmp) { cmpData = new GridData(GridData.FILL_HORIZONTAL); cmpData.widthHint = 570; matchParent = new Composite(equiCmp, SWT.NONE); matchParent.setLayoutData(new GridData(GridData.FILL_BOTH)); GridLayoutFactory.fillDefaults().margins(0, 0).spacing(0, 2).applyTo(matchParent); Composite match = new Composite(matchParent, SWT.NONE); match.setLayoutData(cmpData); GridLayoutFactory.fillDefaults().margins(0, 0).numColumns(8).equalWidth(false).applyTo(match); Spinner mininSpinner = new Spinner(match, SWT.BORDER); int minSpinnerIndex = 55; while (minSpinnerIndex <= 95) { mininSpinner.setSelection(minSpinnerIndex); minSpinnerIndex = minSpinnerIndex + 5; } mininSpinner.setMinimum(35); mininSpinner.setMaximum(99); mininSpinner.setIncrement(5); mininSpinner.setSelection(defaultValue); mininSpinner.setLayoutData(spinnerdata); mininSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { selected(e); } }); Label perLabel1 = new Label(match, SWT.NONE); perLabel1.setText("%"); Label waveLabel = new Label(match, SWT.NONE); waveLabel.setText("~"); Spinner maxSpinner = new Spinner(match, SWT.BORDER); maxSpinner.setSelection(99); maxSpinner.setEnabled(false); maxSpinner.setLayoutData(spinnerdata); Label perLabel2 = new Label(match, SWT.NONE); perLabel2.setText("%"); Label phLbl = new Label(match, SWT.NONE); phLbl.setLayoutData(phLblData); Text equiTxt = new Text(match, SWT.BORDER); equiTxt.setLayoutData(equiTxtData); validEquiTxt(equiTxt); btn_data = new GridData(); btn_data.widthHint = 40; btn_data.heightHint = 26; btn_data.horizontalIndent = 5; Composite btnCmp = new Composite(match, SWT.NONE); GridLayoutFactory.swtDefaults().numColumns(2).margins(0, 0).applyTo(btnCmp); GridDataFactory.swtDefaults().hint(btnCmpWidth, SWT.DEFAULT).applyTo(btnCmp); Button addBtn = new Button(btnCmp, SWT.NONE); addBtn.setLayoutData(btn_data); addBtn.setImage(addImage); addBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (index < 11) { addEquiCmp(e, null); } } }); Label spaceLbl = new Label(btnCmp, SWT.NONE); spaceLbl.setLayoutData(btn_data); match.getParent().setData(String.valueOf(index), match); match.setData("index", index); match.pack(); match.layout(); match.redraw(); } /** * 点击添加按钮时,添加加权系数匹配面板 * @param e */ public void addEquiCmp(SelectionEvent e, Button button) { Composite cp; if (button == null) { Button btn = (Button) e.getSource(); cp = btn.getParent().getParent(); } else { cp = button.getParent().getParent(); } // 获取加权系数面板的父面板,即group Composite cp_parent = cp.getParent(); int temp_index = cp_parent.getChildren().length; Composite temp_cp = (Composite) cp_parent.getData(String.valueOf(temp_index)); Control[] ctrls = temp_cp.getChildren(); // 获取最小匹配率 Spinner tempMinSp = (Spinner) ctrls[0]; selectionvalue = tempMinSp.getSelection() - 1; if (selectionvalue < MINRATE) { MessageDialog.openInformation(tempMinSp.getShell(), Messages.getString("preference.EquivalentPage.msgTitle"), MessageFormat.format(Messages.getString("preference.EquivalentPage.msg1"), MINRATE)); return; } Composite new_cp = new Composite(cp_parent, SWT.NONE); new_cp.setLayoutData(cmpData); GridLayoutFactory.fillDefaults().margins(0, 0).numColumns(8).equalWidth(false).applyTo(new_cp); Spinner minSp = new Spinner(new_cp, SWT.BORDER); minSp.setMinimum(0); minSp.setMaximum(selectionvalue); minSp.setIncrement(5); minSp.setLayoutData(spinnerdata); minSp.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { selected(e); } }); if (tempMinSp.getSelection() - space_Number >= 0) { minSp.setSelection(tempMinSp.getSelection() - space_Number); } else { minSp.setSelection(0); } Label perLabel1 = new Label(new_cp, SWT.NONE); perLabel1.setText("%"); Label waveLabel = new Label(new_cp, SWT.NONE); waveLabel.setText("~"); Spinner maxSp = new Spinner(new_cp, SWT.BORDER); maxSp.setSelection(tempMinSp.getSelection() - 1); maxSp.setEnabled(false); maxSp.setLayoutData(spinnerdata); Label perLabel2 = new Label(new_cp, SWT.NONE); perLabel2.setText("%"); Label phLbl = new Label(new_cp, SWT.NONE); phLbl.setLayoutData(phLblData); Text equiTxt = new Text(new_cp, SWT.BORDER); equiTxt.setLayoutData(equiTxtData); validEquiTxt(equiTxt); Composite btnCmp = new Composite(new_cp, SWT.NONE); GridLayoutFactory.swtDefaults().numColumns(2).margins(0, 0).applyTo(btnCmp); GridDataFactory.swtDefaults().hint(btnCmpWidth, SWT.DEFAULT).applyTo(btnCmp); // 增加加权系数面板的按钮及其事件 Button addBtn = new Button(btnCmp, SWT.NONE); addBtn.setImage(addImage); addBtn.setLayoutData(btn_data); addBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (index < 11) { addEquiCmp(e, null); } } }); // 删除加权系数的按钮及其事件 Button deleteBtn = new Button(btnCmp, SWT.NONE); deleteBtn.setImage(deleteimage); deleteBtn.setLayoutData(btn_data); deleteBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { deleteEquiCmp(e); } }); index = index + 1; cp_parent.setData(String.valueOf(index), new_cp); new_cp.setData("index", String.valueOf(index)); //$NON-NLS-1$ // new_cp.pack(); // new_cp.layout(); // cp_parent.layout(); // equiCmp.getParent().layout(); // equiCmp.getParent().getParent().layout(); equiCmp.getParent().getParent().getParent().layout(); } /** * 删除加权系数面板 * @param e */ public void deleteEquiCmp(SelectionEvent e) { Button deleteBtn = (Button) e.getSource(); Composite cp = deleteBtn.getParent().getParent(); Composite cp_parent = cp.getParent(); Control[] ctr_cp = cp_parent.getChildren(); Composite currentCp; Composite nextCp; Control[] currentCtrls; Control[] nextCtrls; Spinner cuSp; Spinner nextSp; int next = 0; int current = 0; int uplimit = 0; // get current rows index,we can get Composite by current rows index current = Integer.parseInt(cp.getData("index").toString()); // if current composite is not the last Component if (current < ctr_cp.length) { next = current + 1; currentCp = (Composite) ctr_cp[current - 1]; nextCp = (Composite) ctr_cp[next - 1]; currentCtrls = currentCp.getChildren(); nextCtrls = nextCp.getChildren(); cuSp = (Spinner) currentCtrls[3]; nextSp = (Spinner) nextCtrls[3]; cuSp.setEnabled(true); nextSp.setEnabled(true); nextSp.setSelection(cuSp.getSelection()); nextSp.setEnabled(false); } ctr_cp[current - 1].dispose(); // delete current composite // reset index of whole container uplimit = ctr_cp.length; for (int j = current; j < uplimit; j++) { Composite tempcp = (Composite) ctr_cp[j]; tempcp.setData("index", String.valueOf(j)); //$NON-NLS-1$ cp_parent.setData(String.valueOf(j), tempcp); } index = ctr_cp.length - 1; // 设置每一个匹配区间的最小匹配率 for (int i = 1; i < matchParent.getChildren().length; i++) { Composite _cmp = (Composite) matchParent.getChildren()[i]; Spinner _minSp = (Spinner) _cmp.getChildren()[0]; _minSp.setMinimum(matchParent.getChildren().length - i - 1); Spinner _maxSp = (Spinner) _cmp.getChildren()[3]; _minSp.setMaximum(Integer.parseInt(_maxSp.getText())); } // cp_parent.pack(); // cp_parent.layout(); // cp_parent.getParent().layout(); // equiCmp.getParent().layout(); // equiCmp.getParent().getParent().layout(); equiCmp.getParent().getParent().getParent().layout(); } /** * 改变相对最小匹配率的大小时,动态改变下一行相对最大匹配率的大小 * @param arg0 */ private void selected(SelectionEvent e) { Composite currentCp, nextCp, parentCp; int currentIndex = 0; int currentValue = 0; int upValue = 0; int nextMinValue = 0; Control[] paCtrls; Control[] cuCtrls; Control[] nextCtrls; Spinner sp3 = (Spinner) e.getSource(); // 当前相对最小匹配值 currentValue = sp3.getSelection(); currentCp = sp3.getParent(); parentCp = currentCp.getParent(); paCtrls = parentCp.getChildren(); cuCtrls = currentCp.getChildren(); Spinner cuMinSp = (Spinner) cuCtrls[0]; cuMinSp.setSelection(currentValue); Spinner cuMaxSp = (Spinner) cuCtrls[3]; upValue = cuMaxSp.getSelection(); currentIndex = Integer.parseInt(currentCp.getData("index").toString()); cuMinSp.setMinimum(paCtrls.length - currentIndex + MINRATE); if (currentIndex >= paCtrls.length) { if (currentValue > upValue) { cuMinSp.setSelection(upValue); } parentCp.layout(); parentCp.redraw(); return; } // 从当前加权设置的下一条设置开始,直到结束, for (int i = currentIndex + 1; i <= paCtrls.length; i++) { int remain = paCtrls.length - i + MINRATE; // 获取下一个加权设置面板 nextCp = (Composite) paCtrls[i - 1]; nextCtrls = nextCp.getChildren(); Spinner nextMinSp = (Spinner) nextCtrls[0]; // 最低值不能小于这个匹配之下所有匹配区间的总数 nextMinSp.setMinimum(remain); nextMinValue = nextMinSp.getSelection(); Spinner nextMaxSp = (Spinner) nextCtrls[3]; // 如果当前循环的相对最小匹配值小于它的最大值,设成等于最大值 if (nextMinValue > (currentValue - 1)) { nextMinSp.setSelection(currentValue - 1); } nextMaxSp.setSelection(currentValue - 1); nextMinSp.setMaximum(nextMaxSp.getSelection()); currentValue = nextMinSp.getSelection(); } parentCp.layout(); parentCp.redraw(); } @Override protected void performDefaults() { String equivalStr = preferenceStore.getDefaultString(QAConstant.FA_PREF_equivalent); createMatchEqui(equivalStr); } @Override public boolean performOk() { if (!isInit) { return true; } StringBuffer equivalSB = new StringBuffer(); // 先获取重复文本段的加权系数 Composite interRepeatCmp = (Composite) repeatCmp.getChildren()[0]; Text text = (Text) interRepeatCmp.getChildren()[2]; equivalSB.append(QAConstant._InternalRepeat + ":" + text.getText() + ";"); if (isUltimate) { Composite exter101Cmp = (Composite) repeatCmp.getChildren()[1]; text = (Text) exter101Cmp.getChildren()[2]; equivalSB.append(QAConstant._External101 + ":" + text.getText() + ";"); } Composite exter100Cmp = (Composite) repeatCmp.getChildren()[2 - (isUltimate ? 0 : 1)]; text = (Text) exter100Cmp.getChildren()[2]; equivalSB.append(QAConstant._External100 + ":" + text.getText() + ";"); for (int i = 0; i < matchParent.getChildren().length; i++) { Composite cmp = (Composite) matchParent.getChildren()[i]; Control[] ctr_cmp = cmp.getChildren(); text = (Text) ctr_cmp[6]; Spinner minSp = (Spinner) ctr_cmp[0]; Spinner maxSp = (Spinner) ctr_cmp[3]; equivalSB.append(minSp.getSelection() + "-" + maxSp.getSelection() + ":" + text.getText() + ";"); } preferenceStore.setValue(QAConstant.FA_PREF_equivalent, equivalSB.toString()); return true; } /** * 创建加权系统设置区间 */ public void createMatchEqui(String equivalStr) { boolean isDelete = false; String[] equivalArray = equivalStr.split(";"); for (int i = 0; i < equivalArray.length; i++) { String equival = equivalArray[i]; String matchStr = equival.substring(0, equival.indexOf(":")); String equiValue = equival.substring(equival.indexOf(":") + 1, equival.length()); // 先处理所有重复加权系数 if (QAConstant._InternalRepeat.equals(matchStr)) { Composite interRepeatCmp = (Composite) repeatCmp.getChildren()[0]; Text text = (Text) interRepeatCmp.getChildren()[2]; text.setText(equiValue); }else if (QAConstant._External101.equals(matchStr)) { if (isUltimate) { Composite exter101Cmp = (Composite) repeatCmp.getChildren()[1]; Text text = (Text) exter101Cmp.getChildren()[2]; text.setText(equiValue); } }else if (QAConstant._External100.equals(matchStr)) { Composite exter100Cmp = (Composite) repeatCmp.getChildren()[2 - (isUltimate ? 0 : 1)]; Text text = (Text) exter100Cmp.getChildren()[2]; text.setText(equiValue); }else { int minMacth = Integer.parseInt(equival.substring(0, equival.indexOf("-"))); int maxMatch = Integer.parseInt(equival.substring(equival.indexOf("-") + 1, equival.indexOf(":"))); if (maxMatch == 99) { // 如果最大匹配率是99,那么就是模糊匹配的第一个设置 Composite macthCmp = (Composite) matchParent.getChildren()[0]; Control[] ctls = macthCmp.getChildren(); Text text = (Text) ctls[6]; Spinner minSp = (Spinner) ctls[0]; Spinner maxSp = (Spinner) ctls[3]; text.setText(equiValue); minSp.setSelection(minMacth); maxSp.setSelection(maxMatch); } else { if (!isDelete) { // 若模糊匹配区间有两个或两个以上的匹配,那么先删除所有除第一个以外的其他设置 if (matchParent.getChildren().length > 1) { for (int j = matchParent.getChildren().length - 1; j >= 1; j--) { Control[] ctls = matchParent.getChildren(); ctls[j].dispose(); } index = 1; } // 创建除第一个模糊匹配之外的其他匹配段 int fixItemNum = equivalStr.indexOf("external101") == -1 ? 3 : 4; for (int j = 0; j < equivalStr.split(";").length - fixItemNum; j++) { Composite cmp = (Composite) ((Composite) matchParent.getChildren()[j]).getChildren()[7]; Button addBtn = (Button) cmp.getChildren()[0]; addEquiCmp(null, addBtn); } isDelete = true; } int fixItemNum = equivalStr.indexOf("external101") == -1 ? 2 : 3; Composite macthCmp = (Composite) matchParent.getChildren()[i - fixItemNum]; Control[] ctls = macthCmp.getChildren(); Text text = (Text) ctls[6]; Spinner minSp = (Spinner) ctls[0]; Spinner maxSp = (Spinner) ctls[3]; text.setText(equiValue); minSp.setSelection(minMacth); maxSp.setSelection(maxMatch); } } } // matchParent.pack(); matchParent.layout(); // matchParent.getParent().pack(); // matchParent.getParent().layout(); } @Override public void dispose() { if(addImage != null && !addImage.isDisposed()){ addImage.dispose(); } if(deleteimage != null && !deleteimage.isDisposed()){ deleteimage.dispose(); } super.dispose(); } }
23,075
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FileAnalysisInstalPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/preference/FileAnalysisInstalPage.java
package net.heartsome.cat.ts.ui.qa.preference; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.resource.ImageConstant; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; 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.Spinner; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * 文件分析的参数设置,针对于字数分析 * @author robert 2012-05-04 * @version * @since JDK1.6 */ public class FileAnalysisInstalPage extends PreferencePage implements IWorkbenchPreferencePage { public static final String ID = "net.heartsome.cat.ts.ui.qa.preference.FileAnalysisInstalPage"; private IPreferenceStore preferenceStore; /** 是否忽略大小写 */ private Button ignoreCaseBtn; /** 是否忽略标记 */ private Button ignoreTagBtn; /** 上下文个数 */ private Spinner contextSpinner; private Label tagPenaltyLbl; private Spinner tagPenaltySpi; /** 是否进行内部重复 */ private Button interRepateBtn; /** 是否进行内部匹配 */ private Button interMatchBtn; private boolean isInit = false; public void init(IWorkbench workbench) { } public FileAnalysisInstalPage() { setTitle(Messages.getString("preference.FileAnalysisInstalPage.title")); setPreferenceStore(Activator.getDefault().getPreferenceStore()); preferenceStore = getPreferenceStore(); } @Override protected Control createContents(Composite parent) { isInit = true; Composite tparent = new Composite(parent, SWT.NONE); tparent.setLayout(new GridLayout()); tparent.setLayoutData(new GridData(GridData.FILL_BOTH)); Group faGroup = new Group(tparent, SWT.NONE); faGroup.setLayout(new GridLayout()); faGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); faGroup.setText(Messages.getString("preference.FileAnalysisInstalPage.faGroup")); String tip = Messages.getString("preference.FileAnalysisInstalPage.faImgLbl"); HsImageLabel faImgLbl = new HsImageLabel(tip, Activator.getImageDescriptor(ImageConstant.PREFERENCE_FA_analysis)); Composite faLblCmp = faImgLbl.createControl(faGroup); faLblCmp.setLayout(new GridLayout()); faLblCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); ignoreCaseBtn = new Button(faLblCmp, SWT.CHECK); ignoreCaseBtn.setText(Messages.getString("preference.FileAnalysisInstalPage.ignoreCaseBtn")); ignoreTagBtn = new Button(faLblCmp, SWT.CHECK); ignoreTagBtn.setText(Messages.getString("preference.FileAnalysisInstalPage.ignoreTagBtn")); ignoreTagBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { setTagPenaltyEnable(); } public void widgetDefaultSelected(SelectionEvent e) { setTagPenaltyEnable(); } }); GridData spinnerData = new GridData(30, SWT.DEFAULT); // 罚分制度 Composite tagPenaltyCmp = new Composite(faLblCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).applyTo(tagPenaltyCmp); tagPenaltyCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); tagPenaltyLbl = new Label(tagPenaltyCmp, SWT.NONE); tagPenaltyLbl.setText(Messages.getString("preference.FileAnalysisInstalPage.tagPenalty")); tagPenaltySpi = new Spinner(tagPenaltyCmp, SWT.BORDER); tagPenaltySpi.setLayoutData(spinnerData); GridLayout pGl = new GridLayout(2, false); pGl.marginHeight = 0; pGl.marginWidth = 0; tagPenaltySpi.setMinimum(1); tagPenaltySpi.setMaximum(100); if (CommonFunction.checkEdition("U")) { // 上下文个数 Composite contextCmp = new Composite(faLblCmp, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).numColumns(3).applyTo(contextCmp); contextCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Label contextLbl = new Label(contextCmp, SWT.NONE); contextLbl.setText(Messages.getString("preference.FileAnalysisInstalPage.contextLbl")); contextSpinner = new Spinner(contextCmp, SWT.BORDER); contextSpinner.setLayoutData(spinnerData); contextSpinner.setMinimum(1); contextSpinner.setMaximum(100); contextSpinner.setIncrement(1); // 步值为1 contextSpinner.setSelection(1); Label unitLbl = new Label(contextCmp, SWT.NONE); unitLbl.setText(Messages.getString("preference.FileAnalysisInstalPage.unitLbl")); } faImgLbl.computeSize(); // 分析文件设置 Group faFileGroup = new Group(tparent, SWT.NONE); faFileGroup.setLayout(new GridLayout()); faFileGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); faFileGroup.setText(Messages.getString("preference.FileAnalysisInstalPage.faFileGroup")); String faFileTip = Messages.getString("preference.FileAnalysisInstalPage.faFileTip"); HsImageLabel faFileImgLbl = new HsImageLabel(faFileTip, Activator.getImageDescriptor(ImageConstant.PREFERENCE_FA_fileAnalysis)); Composite faFileLblCmp = faFileImgLbl.createControl(faFileGroup); faFileLblCmp.setLayout(new GridLayout()); faFileLblCmp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); interRepateBtn = new Button(faFileLblCmp, SWT.CHECK); interRepateBtn.setText(Messages.getString("preference.FileAnalysisInstalPage.faFileInterRepeate")); interMatchBtn = new Button(faFileLblCmp, SWT.CHECK); interMatchBtn.setText(Messages.getString("preference.FileAnalysisInstalPage.faFileInterMatch")); faFileImgLbl.computeSize(); initListener(); initValue(); return parent; } private void initListener(){ interRepateBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { if (interRepateBtn.getSelection()) { interMatchBtn.setEnabled(true); }else { interMatchBtn.setSelection(false); interMatchBtn.setEnabled(false); } } public void widgetDefaultSelected(SelectionEvent arg0) { if (interRepateBtn.getSelection()) { interMatchBtn.setEnabled(true); }else { interMatchBtn.setSelection(false); interMatchBtn.setEnabled(false); } } }); } private void initValue() { ignoreCaseBtn.setSelection(preferenceStore.getBoolean(QAConstant.FA_PREF_ignoreCase)); ignoreTagBtn.setSelection(preferenceStore.getBoolean(QAConstant.FA_PREF_ignoreTag)); if (CommonFunction.checkEdition("U")) { contextSpinner.setSelection(preferenceStore.getInt(QAConstant.FA_PREF_contextNum)); } tagPenaltySpi.setSelection(preferenceStore.getInt(QAConstant.FA_PREF_tagPenalty)); interRepateBtn.setSelection(preferenceStore.getBoolean(QAConstant.FA_PREF_interRepeate)); interMatchBtn.setSelection(preferenceStore.getBoolean(QAConstant.FA_PREF_interMatch)); if (interRepateBtn.getSelection()) { interMatchBtn.setEnabled(true); }else { interMatchBtn.setSelection(false); interMatchBtn.setEnabled(false); } setTagPenaltyEnable(); } private void setTagPenaltyEnable(){ boolean ignoreTag = ignoreTagBtn.getSelection(); tagPenaltyLbl.setEnabled(!ignoreTag); tagPenaltySpi.setEnabled(!ignoreTag); } @Override protected void performDefaults() { ignoreCaseBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.FA_PREF_ignoreCase)); ignoreTagBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.FA_PREF_ignoreTag)); if (CommonFunction.checkEdition("U")) { contextSpinner.setSelection(preferenceStore.getDefaultInt(QAConstant.FA_PREF_contextNum)); } tagPenaltySpi.setSelection(preferenceStore.getDefaultInt(QAConstant.FA_PREF_tagPenalty)); interRepateBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.FA_PREF_interRepeate)); interMatchBtn.setSelection(preferenceStore.getDefaultBoolean(QAConstant.FA_PREF_interMatch)); setTagPenaltyEnable(); } @Override public boolean performOk() { if (!isInit) { return true; } preferenceStore.setValue(QAConstant.FA_PREF_ignoreCase, ignoreCaseBtn.getSelection()); preferenceStore.setValue(QAConstant.FA_PREF_ignoreTag, ignoreTagBtn.getSelection()); if (CommonFunction.checkEdition("U")) { preferenceStore.setValue(QAConstant.FA_PREF_contextNum, contextSpinner.getSelection()); } preferenceStore.setValue(QAConstant.FA_PREF_tagPenalty, tagPenaltySpi.getSelection()); preferenceStore.setValue(QAConstant.FA_PREF_interRepeate, interRepateBtn.getSelection()); preferenceStore.setValue(QAConstant.FA_PREF_interMatch, interMatchBtn.getSelection()); return true; } }
9,059
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
QAResultViewPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/views/QAResultViewPart.java
package net.heartsome.cat.ts.ui.qa.views; import static net.heartsome.cat.ts.ui.Constants.SEGMENT_LINE_SPACING; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; 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.resources.ResourceUtils; import net.heartsome.cat.common.ui.innertag.InnerTagRender; import net.heartsome.cat.common.ui.utils.InnerTagUtil; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.Constants; import net.heartsome.cat.ts.ui.bean.XliffEditorParameter; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.export.ExportQAResult; import net.heartsome.cat.ts.ui.qa.export.ExportQAResultDialog; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.util.MultiFilesOper; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseWheelListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.GlyphMetrics; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.ViewPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.kupzog.ktable.KTable; import de.kupzog.ktable.KTableCellEditor; import de.kupzog.ktable.KTableCellRenderer; import de.kupzog.ktable.KTableCellResizeListener; import de.kupzog.ktable.KTableDefaultModel; import de.kupzog.ktable.KTableModel; import de.kupzog.ktable.SWTX; import de.kupzog.ktable.renderers.FixedCellRenderer; import de.kupzog.ktable.renderers.TextCellRenderer; /** * 品质检查结果视图 * @author robert 2011-11-12 */ public class QAResultViewPart extends ViewPart implements PropertyChangeListener { /** 常量,视图ID。 */ public static final String ID = "net.heartsome.cat.ts.ui.qa.views.QAResultViewPart"; private Composite parent; private KTable table; private KtableModel tableModel; private List<QAResultBean> dataList = new ArrayList<QAResultBean>(); private QAResult qaResult; private IWorkbenchWindow window; private Image exportImg; private boolean isMultiFile; private MultiFilesOper oper; private final static String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; public final static Logger logger = LoggerFactory.getLogger(QAResultViewPart.class.getName()); /** 标识当前品质检查结果视图所处理的文件路径的集合 */ private List<String> filePathList = null; private MenuItem exportItem; /** 标志品质检查是否结束,若没有结束,导出品质检查结果视图时,需等待 */ private boolean isQAEnd = true; private Image errorImg; private Image warningImg; private Image deleteImage; public QAResultViewPart() { errorImg = Activator.getImageDescriptor("icons/error.png").createImage(); warningImg = Activator.getImageDescriptor("icons/warning.png").createImage(); exportImg = Activator.getImageDescriptor("images/export.png").createImage(); deleteImage = Activator.getImageDescriptor("images/delete.png").createImage(); } @Override public void createPartControl(Composite parent) { this.parent = parent; window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); createTable(); } @Override public void setFocus() { // TODO Auto-generated method stub } @Override public void dispose() { if (qaResult != null) { qaResult.listeners.removePropertyChangeListener(this); } if (errorImg != null && !errorImg.isDisposed()) { errorImg.dispose(); } if (warningImg != null && !warningImg.isDisposed()) { warningImg.dispose(); } if (deleteImage != null && !deleteImage.isDisposed()) { deleteImage.dispose(); } if (exportImg != null && !exportImg.isDisposed()) { exportImg.dispose(); } super.dispose(); } public void createTable() { table = new KTable(parent, SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWTX.FILL_WITH_LASTCOL | SWT.WRAP); tableModel = new KtableModel(); table.setModel(tableModel); table.setLayoutData(new GridData(GridData.FILL_BOTH)); table.setColorRightBorder(Display.getCurrent().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); table.setColorLeftBorder(Display.getCurrent().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); table.setColorTopBorder(Display.getCurrent().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); table.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); table.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { locationRow(); } }); table.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == QAConstant.QA_CENTERKEY_1 || e.keyCode == QAConstant.QA_CENTERKEY_2) { locationRow(); } } }); table.addCellResizeListener(new KTableCellResizeListener() { public void rowResized(int arg0, int arg1) { tableModel.textRenderer.clearRowHeiMap(); table.redraw(); } public void columnResized(int arg0, int arg1) { tableModel.textRenderer.clearRowHeiMap(); table.redraw(); } }); table.addControlListener(new ControlAdapter() { @Override public void controlResized(ControlEvent e) { tableModel.textRenderer.clearRowHeiMap(); table.redraw(); } }); table.addMouseWheelListener(new MouseWheelListener() { public void mouseScrolled(MouseEvent e) { tableModel.textRenderer.clearRowHeiMap(); table.redraw(); } }); createPropMenu(); } /** * 创建右键参数 */ private void createPropMenu() { Menu propMenu = new Menu(table); table.setMenu(propMenu); MenuItem deletWarnItem = new MenuItem(propMenu, SWT.NONE); deletWarnItem.setText(Messages.getString("views.QAResultViewPart.deletWarnItem")); deletWarnItem.setImage(deleteImage); deletWarnItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { QAResultBean bean; for (int i = 0; i < dataList.size(); i++) { bean = dataList.get(i); // 0为错误,1为警告 if (1 == bean.getLevel()) { dataList.remove(bean); i--; } } tableModel.textRenderer.clearRowHeiMap(); table.redraw(); } }); MenuItem deleteAllItem = new MenuItem(propMenu, SWT.NONE); deleteAllItem.setText(Messages.getString("views.QAResultViewPart.deleteAllItem")); deleteAllItem.setImage(deleteImage); deleteAllItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { dataList.clear(); tableModel.textRenderer.clearRowHeiMap(); table.redraw(); } }); // 导出品质检查报告 exportItem = new MenuItem(propMenu, SWT.NONE); exportItem.setText(Messages.getString("qa.views.QAResultViewPart.exportPopMenu")); exportItem.setImage(exportImg); exportItem.setEnabled(false); exportItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ExportQAResultDialog dialog = new ExportQAResultDialog(getSite().getShell()); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { final String exportFilePath = dialog.getExportFilePath(); if (exportFilePath == null || exportFilePath.isEmpty()) { MessageDialog.openInformation(getSite().getShell(), Messages.getString("qa.all.dialog.info"), Messages.getString("qa.views.QAResultViewPart.msg.nullFilePath")); return; } IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("", 1); while(!isQAEnd){ try { Thread.sleep(500); } catch (Exception e2) { logger.error("", e2); } if (monitor.isCanceled()) { return; } } List<QAResultBean> exportDataList = new ArrayList<QAResultBean>(); exportDataList.addAll(dataList); ExportQAResult export = new ExportQAResult(isMultiFile, exportFilePath); export.beginExport(dataList, filePathList, monitor); monitor.done(); } }; try { new ProgressMonitorDialog(getSite().getShell()).run(true, true, runnable); } catch (Exception e1) { logger.error("", e1); } } } }); propMenu.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if(deleteImage!= null && !deleteImage.isDisposed()){ deleteImage.dispose(); } } }); } public void propertyChange(final PropertyChangeEvent evt) { /* * 备注,传过来的数据是一个 ArrayList<QAResultBean>, 每组数据都是相同的 rowId */ if ("printData".equals(evt.getPropertyName())) { try { Display.getDefault().syncExec(new Runnable() { @SuppressWarnings("unchecked") public void run() { Object obj = evt.getNewValue(); if (obj instanceof List) { List<QAResultBean> objList = (List<QAResultBean>) obj; if (objList.size() <= 0) { return; } isQAEnd = false; String rowId = objList.get(0).getRowId(); // 如果是自动检查。那么要删除之前的记录 int addIndex = -1; if (qaResult.isAutoQA()) { if (qaResult.isSameOperObjForAuto()) { for(int i = 0; i < dataList.size(); i ++){ QAResultBean bean = dataList.get(i); if (rowId.equals(bean.getRowId())) { dataList.remove(bean); addIndex = i; i --; } } if (addIndex == -1) { addIndex = 0; } dataList.addAll(addIndex, objList); tableModel.textRenderer.clearRowHeiMap(); table.redraw(); }else { dataList.clear(); tableModel.textRenderer.clearRowHeiMap(); table.redraw(); filePathList = qaResult.getFilePathList(); qaResult.setSameOperObjForAuto(true); } }else { dataList.addAll(objList); table.redraw(); } if (qaResult.isAutoQA()) { if (addIndex > 0) { table.setSelection(0, addIndex + 1, true); } } }else if (obj instanceof String) { // 这是针对自动品质检查,若一个文本段没有错误,那么就将这个文本段之前的提示进行清除 if (qaResult.isAutoQA()) { if (qaResult.isSameOperObjForAuto()) { String rowId = (String) obj; for(int i = 0; i < dataList.size(); i ++){ QAResultBean bean = dataList.get(i); if (rowId.equals(bean.getRowId())) { dataList.remove(bean); i --; } } }else { dataList.clear(); tableModel.textRenderer.clearRowHeiMap(); table.redraw(); filePathList = qaResult.getFilePathList(); qaResult.setSameOperObjForAuto(true); } } table.redraw(); } } }); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log1"), e); } } else if ("isMultiFiles".equals(evt.getPropertyName())) { try { Display.getCurrent().syncExec(new Runnable() { public void run() { isMultiFile = (Boolean) ((Object[]) evt.getNewValue())[0]; if (isMultiFile) { oper = (MultiFilesOper) ((Object[]) evt.getNewValue())[1]; }else { oper = null; } } }); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log1"), e); } }else if ("informQAEndFlag".equals(evt.getPropertyName())) { // 通知品质检查已经结束 isQAEnd = true; } } public void registLister(QAResult qaResult) { this.qaResult = qaResult; this.qaResult.listeners.addPropertyChangeListener(this); if (filePathList != null && filePathList.size() > 0) { // 自动品质检查这里是不能保存相关信息的 if (!qaResult.isAutoQA()) { filePathList = this.qaResult.getFilePathList(); }else { boolean isSameOperObj = true; List<String> curFilePathList = this.qaResult.getFilePathList(); if (curFilePathList.size() == filePathList.size()) { for(String filePath : filePathList){ if (curFilePathList.contains(filePath)) { curFilePathList.remove(filePath); }else { isSameOperObj = false; break; } } }else { isSameOperObj = false; } this.qaResult.setSameOperObjForAuto(isSameOperObj); } }else { filePathList = this.qaResult.getFilePathList(); } if (dataList.size() > 0 || (filePathList != null && filePathList.size() > 0)) { exportItem.setEnabled(true); }else { exportItem.setEnabled(false); } isQAEnd = false; } /** * 双击或按回车键,将品质检查结果中的数据定位到翻译界面上去。 */ public void locationRow() { int[] selectRow = table.getRowSelection(); if (selectRow.length <= 0) { return; } // 获取第一行选择的值 QAResultBean bean = dataList.get(selectRow[0] - 1); // 如果是合并打开的文件 if (isMultiFile) { IXliffEditor xliffEditor = openMultiFilesEditor(); if (xliffEditor == null) { return; } int lineNumber = xliffEditor.getXLFHandler().getRowIndex(bean.getRowId()); // 跳转到错误行 xliffEditor.setFocus(); xliffEditor.jumpToRow(lineNumber, true); return; } else { // 检查该文件是否已经打开,如果没有打开,就在界面上打开,再返回这个 IXliffEditor xliffEditor = openEditor(RowIdUtil.getFileNameByRowId(bean.getRowId())); if (xliffEditor == null) { return; } int lineNumber = xliffEditor.getXLFHandler().getRowIndex(bean.getRowId()); // 跳转到错误行 xliffEditor.setFocus(); xliffEditor.jumpToRow(lineNumber, false); } } public IXliffEditor openEditor(String filePath) { IFile ifile = ResourceUtils.fileToIFile(filePath); FileEditorInput fileInput = new FileEditorInput(ifile); IEditorReference[] editorRefer = window.getActivePage().findEditors(fileInput, XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); IEditorPart editorPart = null; IXliffEditor xliffEditor = null; if (editorRefer.length >= 1) { editorPart = editorRefer[0].getEditor(true); xliffEditor = (IXliffEditor) editorPart; // 若该文件未激活,激活此文件 if (window.getActivePage().getActiveEditor() != editorPart) { window.getActivePage().activate(editorPart); } // 对于已经打开过的文件,进行重排序 xliffEditor.resetOrder(); } else { // 如果文件没有打开,那么先打开文件 try { if(!validateXliffCanOpen(ifile)){ return null; } xliffEditor = (IXliffEditor) window.getActivePage().openEditor(fileInput, XLIFF_EDITOR_ID, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); } catch (PartInitException e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log2"), e); } } return xliffEditor; } /** * 处理合并打开文件 nattable editor的相关问题 * @return ; */ public IXliffEditor openMultiFilesEditor() { IXliffEditor xliffEditor = null; FileEditorInput fileInput = new FileEditorInput(oper.getCurMultiTempFile()); IEditorReference[] editorRefer = window.getActivePage().findEditors(fileInput, XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); IEditorPart editorPart = null; if (editorRefer.length >= 1) { editorPart = editorRefer[0].getEditor(true); xliffEditor = (IXliffEditor) editorPart; // 若该文件未激活,激活此文件 if (window.getActivePage().getActiveEditor() != editorPart) { window.getActivePage().activate(editorPart); } // 对于已经打开过的文件,进行重排序 xliffEditor.resetOrder(); } else { // 如果文件没有打开,那么先打开文件 try { // 如果保存合并打开所有信息的临时文件已经被删除,那么,重新生成临时文件 if (!oper.getCurMultiTempFile().getLocation().toFile().exists()) { // 检查这两个文件是否重新进行合并打开了的。 IFile findMultiTempIfile = oper.getMultiFilesTempIFile(true); if (findMultiTempIfile != null) { fileInput = new FileEditorInput(findMultiTempIfile); oper.setCurMultiTempFile(findMultiTempIfile); } else { //先验证这些所处理的文件是否有已经被打开的 List<IFile> openedFileList = oper.getOpenedIfile(); if (openedFileList.size() > 0) { String openFileStr = ""; for(IFile ifile : openedFileList){ openFileStr += "\t" + ifile.getFullPath().toOSString() + "\n"; } MessageDialog.openInformation(getSite().getShell(), Messages.getString("views.QAResultViewPart.msgTitle"), MessageFormat.format(Messages.getString("qa.views.QAResultViewPart.addTip1"), openFileStr)); return null; } // 如果选中的文件没有合并打开,那么就重新打开它们 IFile multiIFile = oper.createMultiTempFile(); if (multiIFile != null && multiIFile.exists()) { fileInput = new FileEditorInput(multiIFile); oper.setCurMultiTempFile(multiIFile); } else { MessageDialog.openInformation(getSite().getShell(), Messages.getString("views.QAResultViewPart.msgTitle"), Messages.getString("views.QAResultViewPart.msg1")); return null; } xliffEditor = (IXliffEditor) window.getActivePage().openEditor(fileInput, XLIFF_EDITOR_ID, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); } } } catch (PartInitException e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log2"), e); } } return xliffEditor; } /** * 验证当前要单个打开的文件是否已经被合并打开,针对单个文件的品质检查点击结果进行定位 * @return */ public boolean validateXliffCanOpen(IFile iFile){ IEditorReference[] editorRes = window.getActivePage().getEditorReferences(); for (int i = 0; i < editorRes.length; i++) { IXliffEditor editor = (IXliffEditor) editorRes[i].getEditor(true); if (editor.isMultiFile()) { if (editor.getMultiFileList().indexOf(iFile.getLocation().toFile()) != -1) { MessageDialog.openInformation(getSite().getShell(), Messages.getString("views.QAResultViewPart.msgTitle"), MessageFormat.format(Messages.getString("qa.views.QAResultViewPart.addTip2"), iFile.getFullPath().toOSString())); return false; } } } return true; } /** * 清除结果显示视图的列表中的数据 */ public void clearTableData() { dataList.clear(); tableModel.textRenderer.clearRowHeiMap(); table.redraw(); } /** * 控制 ktable 的数据显示 * @author robert * */ private class KtableModel extends KTableDefaultModel{ private static final int levelColWidth = 35; private Map<String, Integer> belongMap = new HashMap<String, Integer>(); private final FixedCellRenderer fixedRenderer = new FixedCellRenderer( FixedCellRenderer.STYLE_FLAT | TextCellRenderer.INDICATION_FOCUS_ROW); public final TextRenderer textRenderer = new TextRenderer(); public KtableModel() { initialize(); } public int getFixedHeaderColumnCount() { return 0; } public int getFixedHeaderRowCount() { return 1; } public int getFixedSelectableColumnCount() { return 0; } public int getFixedSelectableRowCount() { return 0; } public int getRowHeightMinimum() { return 20; } public boolean isColumnResizable(int col) { // 第一列不允许更改列宽 return !(col == 0); } public boolean isRowResizable(int arg0) { return false; } public KTableCellEditor doGetCellEditor(int arg0, int arg1) { return null; } public int getInitialRowHeight(int row) { if (row==0) { return 22; }else { return 50; } } public KTableCellRenderer doGetCellRenderer(int col, int row) { if (isFixedCell(col, row)) { return fixedRenderer; } else { return textRenderer; } } public void doSetContentAt(int arg0, int arg1, Object arg2) { // do nothing } public int doGetColumnCount() { return 5; } public Object doGetContentAt(int col, int row) { if (row == 0) { switch (col) { case 0: return Messages.getString("qa.views.QAResultViewPart.columnTipLevel"); case 1: return Messages.getString("qa.views.QAResultViewPart.columnQAType"); case 2: return Messages.getString("qa.views.QAResultViewPart.location"); case 3: return Messages.getString("qa.views.QAResultViewPart.source"); case 4: return Messages.getString("qa.views.QAResultViewPart.target"); default: return ""; } }else { if (dataList.size() > 0) { QAResultBean bean = dataList.get(row - 1); switch (col) { case 0: if (0 == bean.getLevel()) { return errorImg; } else if (1 == bean.getLevel()) { return warningImg; } case 1: return bean.getQaTypeText(); case 2: return bean.getFileName() + " [" + bean.getLineNumber() + "]"; case 3: return bean.getSrcContent() == null ? "" : bean.getSrcContent(); case 4: return bean.getTgtContent() == null ? "" : bean.getTgtContent(); default: return ""; } }else { return ""; } } } @Override public int doGetRowCount() { return dataList.size() + 1; } @Override public int getInitialColumnWidth(int col) { table.getVerticalBar().getSize(); int lastWidth = table.getBounds().width - levelColWidth - table.getVerticalBar().getSize().x; switch (col) { case 0: return levelColWidth; case 1: return (int)(lastWidth * 0.08); case 2: return (int)(lastWidth * 0.12); case 3: return (int)(lastWidth * 0.4); case 4: return (int)(lastWidth * 0.4); default: return 0; } } @Override public Point doBelongsToCell(int col, int row) { if (isFixedCell(col, row)){ return new Point(col, row); } QAResultBean bean = dataList.get(row - 1); if (bean.getMergeId() != null && !bean.getMergeId().isEmpty()) { if (belongMap.get(bean.getMergeId()) != null) { if (col <= 1) { if (row <= belongMap.get(bean.getMergeId())) { belongMap.put(bean.getMergeId(), row); }else { return new Point(col, belongMap.get(bean.getMergeId())); } } }else { belongMap.put(bean.getMergeId(), row); } } return new Point(col, row); } } /** * 级别列的 renderer,主要用于绘画图片。 * @author robert 2013-10-24 */ private class TextRenderer implements KTableCellRenderer { protected Display display; protected PlaceHolderEditModeBuilder placeHolderBuilder = new PlaceHolderEditModeBuilder(); protected XliffInnerTagFactory innerTagFactory = new XliffInnerTagFactory(placeHolderBuilder); protected InnerTagRender tagRender = new InnerTagRender(); private final int topPadding = 2; private final int rightPadding = 2; private final int bottomPadding = 2; private final int leftPadding = 2; private Map<Integer, Integer> rowHeightMap = new HashMap<Integer, Integer>(); public TextRenderer() { display = Display.getCurrent(); } public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed, KTableModel model) { // UNDO 这个方法有什么用?到现在为止还不晓得,我哪个去。 // if (col == 2) { // System.out.println(Math.max(gc.stringExtent(content.toString()).x + 8, 20)); // // String text = SWTX.wrapText(gc, content.toString(), model.getRowHeight(row)-6); // int w = SWTX.getCachedStringExtent(gc, text).y; // w+=6; // System.out.println(w); // return w; // // } // return Math.max(gc.stringExtent(content.toString()).x + 8, 20); return 100; } public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model) { Color backColor; Color borderColor = display.getSystemColor(SWT.COLOR_GRAY); Color oldForgeColor = gc.getForeground(); if (focus) { backColor = display.getSystemColor(SWT.COLOR_LIST_SELECTION); } else { backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); } if (col == 0) { gc.setBackground(backColor); gc.fillRectangle(rect); gc.drawImage(((Image) content), rect.x, rect.y + (rect.height - ((Image) content).getBounds().height) / 2); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.height + rect.y); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(oldForgeColor); }else { if (col == 3 || col == 4) { innerTagFactory.reset(); TextLayout layout = new TextLayout(display); layout.setWidth(model.getColumnWidth(col) - leftPadding - rightPadding); String displayText = InnerTagUtil.resolveTag(innerTagFactory.parseInnerTag((String) content)); 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"); } gc.setBackground(backColor); gc.setForeground(borderColor); gc.fillRectangle(rect); if (col == 3) { gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.height + rect.y); } gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(oldForgeColor); 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 point = tagRender.calculateTagSize(innerTagBean); style.metrics = new GlyphMetrics(point.y, 0, point.x + SEGMENT_LINE_SPACING * 2); layout.setStyle(style, start, start + placeHolder.length() - 1); } layout.draw(gc, rect.x + leftPadding, rect.y + topPadding); int curHeight = layout.getBounds().height + topPadding + bottomPadding; if (rowHeightMap.get(row) == null || (rowHeightMap.get(row) != null && curHeight > rowHeightMap.get(row))) { rowHeightMap.put(row, curHeight); } // UNDO 这里控制自动换行的,还需要更好的设计模式。 if (col == 4) { if (rowHeightMap.get(row) != model.getRowHeight(row)) { model.setRowHeight(row, rowHeightMap.get(row)); table.redraw(); } } 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 = rect.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 = rect.y + p.y + topPadding + r.height / 2 - tagSize.y / 2; tagRender.draw(gc, innerTagBean, x, y); } layout.dispose(); }else { gc.setBackground(backColor); gc.fillRectangle(rect); gc.setForeground(borderColor); gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.height + rect.y); gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); gc.setForeground(oldForgeColor); String text = SWTX.wrapText(gc, content.toString(), model.getColumnWidth(col) - leftPadding - rightPadding); int textHeight = gc.textExtent(text).y; gc.drawText(text, rect.x + leftPadding, rect.y + (rect.height - textHeight) / 2, true); int curHeight = textHeight + topPadding + bottomPadding; if (rowHeightMap.get(row) == null || (rowHeightMap.get(row) != null && curHeight > rowHeightMap.get(row))) { rowHeightMap.put(row, curHeight); } } } } public void clearRowHeiMap(){ rowHeightMap.clear(); } } public static void main(String[] args) { String text = "this 1 is 5 a 6 test 7 for 8 match."; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); text = matcher.replaceFirst("{" + "a" + "}"); System.out.println(text); matcher = pattern.matcher(text); } } }
31,480
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NonTransElementOperate.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/nonTransElement/NonTransElementOperate.java
package net.heartsome.cat.ts.ui.qa.nonTransElement; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.NontransElementBean; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 非译元素处理类,包括获取相关数据,新建非译元素库(xml)等。 * 默认非译元素库的库名为 .nonTransElement,保存在工作空间下 * 其结构为 * <nonTrans> //这是根节点 * <element id='152054313205'> //id为毫秒 * <name> //非译元素的名字,对应界面上的说明 * ip地址 * </name> * <content> //非译元素的内容 * http://.... * </content> * <regular> //非译元素的正则表达式 * \\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+ * </regular> * </element> * </nonTrans> * @author robert 2011-11-31 */ public class NonTransElementOperate { private String fileName = ".nonTransElement"; private QAXmlHandler handler; private String path; public final static Logger logger = LoggerFactory.getLogger(NonTransElementOperate.class.getName()); public NonTransElementOperate(){ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); handler = new QAXmlHandler(); path = root.getLocation().append(fileName).toOSString(); validExist(); } /** * 首先验证.nonTransElement是否存在,若不存在,则进行创建, */ public void validExist(){ File file = new File(path); if (!file.exists()) { FileOutputStream output; try { output = new FileOutputStream(path); output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes("UTF-8")); output.write("<nonTrans>\n</nonTrans>".getBytes("UTF-8")); output.close(); openNonTransDB(); addNonTransElement(QAModel.getInterNonTransElements()); } catch (FileNotFoundException e) { e.printStackTrace(); logger.error(Messages.getString("qa.preference.NonTranslationQAPage.log1"), e); } catch (UnsupportedEncodingException e) { e.printStackTrace(); logger.error(Messages.getString("qa.preference.NonTranslationQAPage.log2"), e); } catch (IOException e) { e.printStackTrace(); logger.error(Messages.getString("qa.preference.NonTranslationQAPage.log3"), e); } } } /** * 打开非译元素库,即解析非译元素所在的xml文件 * @return */ public boolean openNonTransDB(){ Map<String, Object> newResultMap = handler.openFile(path); if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap.get(QAConstant.RETURNVALUE_RESULT)) { Display.getDefault().asyncExec(new Runnable() { public void run() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); Assert.isNotNull(window); Shell shell = window.getShell(); MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), MessageFormat.format( Messages.getString("qa.all.log.openThisXmlError"), new Object[] { path })); } }); return false; } return true; } public List<NontransElementBean> getNonTransElements(){ List<NontransElementBean> result = new ArrayList<NontransElementBean>(); List<Map<String, String>> elementList = handler.getNonTransElements(path, "/nonTrans/element"); for(Map<String, String> element : elementList){ String id = element.get("id"); String name = element.get("name"); String content = element.get("content"); String regular = TextUtil.resetSpecialString(element.get("regular")); result.add(new NontransElementBean(id, name, content, regular)); } return result; } /** * 只获取非译元素的 正则表达式 */ public List<String> getNontransElementRegex(){ List<String> regexList = new ArrayList<String>(); regexList = handler.getNonTransElementsRegex(path); return regexList; } /** * 添加非译元素 * @return */ public boolean addNonTransElement(List<NontransElementBean> elementList){ StringBuffer dataSB = new StringBuffer(); for(NontransElementBean bean : elementList){ dataSB.append("\t<element id='"+ bean.getId() +"'>\n") ; dataSB.append("\t\t<name>" + bean.getName() + "</name>\n") ; dataSB.append( "\t\t<content>" + bean.getContent() + "</content>\n"); dataSB.append( "\t\t<regular>" + TextUtil.cleanSpecialString(bean.getRegular()) + "</regular>\n"); dataSB.append("\t</element>\n") ; } if (elementList.size() > 0) { return handler.addDataToXml(path, "/nonTrans", dataSB.substring(0, dataSB.length() - 1)); } return false; } /** * 根据配置的map值获取String类型的数据 * @param configList * @return */ private String getConfig(List<Map<String, String>> configList){ StringBuffer configSB = new StringBuffer(); configSB.append("<configs>\n"); for (Map<String, String> configMap : configList) { String position = configMap.get("position"); String operate = configMap.get("operate"); String value = configMap.get("value"); configSB.append(MessageFormat.format("\t\t\t<config position=\"{0}\" operate=\"{1}\" value=\"{2}\"></config>\n", new Object[] { position, operate, value })); } configSB.append("\t\t</configs>\n"); return configSB.toString(); } /** * 从非译元素库时面删除非译元素 * @param idList * @return */ public void deleteElement(List<String> idList){ for (int i = 0; i < idList.size(); i++) { String nodeXpath = "/nonTrans/element[@id='" + idList.get(i) + "']"; handler.deleteNode(path, nodeXpath); } } /** * 删除所有的非译元素 */ public void deleteAllElement(){ String nodeXpath = "/nonTrans/element"; handler.deleteAllNode(path, nodeXpath); } /** * 获取忽略非译元素的文本片段的起始与结束的标记 * @param List<Integer[]> 第一个数为 start index, 第二个数为 end index * @return */ public List<Integer[]> getIgnorePara(String text, List<Integer> tagPositionList){ List<Integer[]> ignoreParaList = new LinkedList<Integer[]>(); List<String> regexList = getNontransElementRegex(); Matcher matcher = null; for (String regex : regexList) { matcher = Pattern.compile(regex).matcher(text); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); int startAdd = 0; int endAdd = 0; // 将标记放回去,使每个非译片段回复之前未去标记的状态 if (tagPositionList != null) { for(Integer tagIndex : tagPositionList){ if (start >= tagIndex) { startAdd ++; } if (end >= tagIndex) { endAdd ++; } } } ignoreParaList.add(new Integer[]{start + startAdd, end + endAdd}); } } return ignoreParaList; } }
7,652
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TranslationProgressFA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/fileAnalysis/TranslationProgressFA.java
package net.heartsome.cat.ts.ui.qa.fileAnalysis; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.core.qa.FAModel; import net.heartsome.cat.ts.core.qa.FileAnalysis; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.TransProgressFAResult; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 翻译进度分析 monitor进度提示语句: 翻译进度分析: 文件{0}翻译进度分析 ... ... * @author robert 2011-12-13 */ public class TranslationProgressFA extends FileAnalysis { private FAModel model; /** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格 */ private static int workInterval = 4; /** 翻译进度分析结果,key为文件的绝对路径,值为已翻译文本段等值的pojo类 */ private Map<String, TransProgressFAResult> transProgFAResultMap; /** 所有包括分析文件的容器 */ private List<IContainer> allFolderList; public final static Logger logger = LoggerFactory.getLogger(TranslationProgressFA.class.getName()); @Override public int beginAnalysis(FAModel model, IProgressMonitor monitor, QAXmlHandler handler) { this.model = model; super.setModel(model); transProgFAResultMap = new HashMap<String, TransProgressFAResult>(); if (monitor == null) { monitor = new NullProgressMonitor(); } // 要分析的文件的所有 int allTUSize = model.getAllTuSize(); int traversalTuIndex = 0; int totalWork = allTUSize % workInterval == 0 ? (allTUSize / workInterval) : (allTUSize / workInterval) + 1; monitor.beginTask("", totalWork); for (int index = 0; index < model.getAnalysisIFileList().size(); index++) { IFile iFile = model.getAnalysisIFileList().get(index); monitor.setTaskName(MessageFormat.format(Messages.getString("qa.fileAnalysis.TranslationProgressFA.tip1"), iFile.getFullPath().toOSString())); String iFilePath = iFile.getLocation().toOSString(); // 获取单个文件的翻译进度的数据 Map<String, Integer> transProgMap = handler.getTransProgressData(iFilePath, monitor, workInterval, traversalTuIndex); // 如果获取的结果为null,则表示用户退出程序 if (transProgMap == null) { return QAConstant.QA_ZERO; } traversalTuIndex += handler.getTuSizeMap().get(iFilePath); int notTransPara = transProgMap.get("notTransPara"); int translatedPara = transProgMap.get("translatedPara"); int notTransWords = transProgMap.get("notTransWords"); int translatedWords = transProgMap.get("translatedWords"); int lockedWords = transProgMap.get("lockedWords"); int lockedPara = transProgMap.get("lockedPara"); TransProgressFAResult transResult = new TransProgressFAResult( notTransPara, translatedPara, lockedPara, notTransWords, translatedWords, lockedWords ); transProgFAResultMap.put(iFilePath, transResult); } if (!handler.monitorWork(monitor, traversalTuIndex, workInterval, true)) { return QAConstant.QA_ZERO; } // 开始填充数据 printTransProgFAReslut(); return QAConstant.QA_FIRST; } public void printTransProgFAReslut() { String htmlPath = createFAResultHtml(); try { model.getAnalysisIFileList().get(0).getProject().getFolder("Intermediate").getFolder("Report").refreshLocal(IResource.DEPTH_ONE, null); } catch (CoreException e1) { e1.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.TranslationProgressFA.log1"), e1); } final FileEditorInput input = new FileEditorInput(ResourceUtils.fileToIFile(htmlPath)); Display.getDefault().asyncExec(new Runnable() { public void run() { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(input, QAConstant.FA_HtmlBrowserEditor, true); } catch (PartInitException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.TranslationProgressFA.log2"), e); } } }); } public String createFAResultHtml() { allFolderList = new LinkedList<IContainer>(); Date createDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String createTime = formatter.format(createDate); formatter = new SimpleDateFormat("yyyyMMdd-HHmmss"); String htmlNameTime = formatter.format(createDate); IProject curProject = model.getAnalysisIFileList().get(0).getProject(); String htmlName = "TRLog" + htmlNameTime + ".html"; String htmlPath = curProject.getLocation().append("Intermediate").append("Report").append(htmlName).toOSString(); File htmlFile = new File(htmlPath); if (!htmlFile.getParentFile().exists()) { htmlFile.getParentFile().mkdirs(); } FileOutputStream output; try { output = new FileOutputStream(htmlPath); output.write(QAConstant.FA_HtmlDoctype.getBytes("UTF-8")); output.write("<html>\n".getBytes("UTF-8")); String headerNode = QAConstant.FA_htmlHeader; headerNode = headerNode.replace("###Title###", Messages.getString("qa.fileAnalysis.TranslationProgressFA.name1")); output.write(headerNode.getBytes("UTF-8")); output.write("\t<body>\n".getBytes("UTF-8")); output.write(("<p class=\"title\">" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.TransProgresFA") + "</p>") .getBytes("UTF-8")); // ----------------<<<<<<start-- 下面是相关信息提示部份--------------------- output.write("\t<div>\n".getBytes("UTF-8")); output.write("\t\t<table class=\"infoTableStyle\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n".getBytes("UTF-8")); // 分析文件总数 String title = Messages.getString("qa.fa.info.fileSum"); String content = "" + model.getSubFileNum(); String infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", content); output.write(infoStr.getBytes("UTF-8")); // 分析失败文件 title = Messages.getString("qa.fa.info.errorFiles"); StringBuffer errorFileSB = new StringBuffer(); errorFileSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); errorFileSB.append(model.getErrorIFileList().size()); errorFileSB.append("</div>"); for(IFile iFile : model.getErrorIFileList()){ errorFileSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); errorFileSB.append(iFile.getFullPath().toOSString()); errorFileSB.append("</div>"); } infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", errorFileSB.toString()); output.write(infoStr.getBytes("UTF-8")); // 报告生成时间 title = Messages.getString("qa.fa.info.createTime"); infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", createTime); output.write(infoStr.getBytes("UTF-8")); output.write("</table></div><br>\n".getBytes("UTF-8")); // ---------------->>>>>>end-- 报表信息提示部分结束--------------------- // --------------字数--------------------- output.write(("\t\t<div class=\"legendStyle\"><b>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.words") + "</b></div>") .getBytes("UTF-8")); StringBuffer wordsFAdata = new StringBuffer(); getAllFolder(curProject, allFolderList); setDataToFolder(curProject); // 创建一个表 wordsFAdata.append("\t<table class='tableStyle' cellpadding='0' cellspacing='1'> \n"); // 表头 wordsFAdata.append("\t\t<tr>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='22%'>" + Messages.getString("qa.all.fa.fileName") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.nonTrans") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.translated") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.lockedWords") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.wordsSum") + "</td>\n"); wordsFAdata.append("\t\t</tr>\n"); wordsFAdata.append("\t\t<tr>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transWords") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transWordsProp") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transWords") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transWordsProp") + "</td>\n"); wordsFAdata.append("\t\t</tr>\n"); // 首先写下项目 TransProgressFAResult proFaResult = transProgFAResultMap.get(curProject.getLocation().toOSString()); int paddLeft = 6; String folderId = curProject.getFullPath().toOSString(); wordsFAdata.append("<tr onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' style='padding-left: 6'>\n" + "<a href='javascript:void(0)' id='" + folderId + "' name='words' class='link' title='" + Messages.getString("qa.all.fa.clickToShrink") + "' " + " onclick='clickFolder(id, name)' ><span id='" + folderId + "_span'>-</span> " + curProject.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotTransWords() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotTransWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTranslatedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTransWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getLockedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTotalWords() + "</td>\n" + "</tr>"); wordsSetInputData(curProject, wordsFAdata, paddLeft); wordsFAdata.append("\t</table>\n"); output.write(wordsFAdata.toString().getBytes("UTF-8")); output.write("<br/>\n".getBytes("UTF-8")); // --------------文本段--------------------- output.write(("\t\t<div class=\"legendStyle\"><b>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.paragraph") + "</b></div>") .getBytes("UTF-8")); StringBuffer paraFAdata = new StringBuffer(); // 创建一个表 paraFAdata.append("\t<table class='tableStyle' cellpadding='0' cellspacing='1'> \n"); // 表头 paraFAdata.append("\t\t<tr>\n"); paraFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='22%'>" + Messages.getString("qa.all.fa.fileName") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.nonTrans") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.translated") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.lockedParasNum") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.parasSum") + "</td>\n"); paraFAdata.append("\t\t</tr>\n"); paraFAdata.append("\t\t<tr>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transParasNum") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transWordsProp") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transParasNum") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.TranslationProgressFA.transWordsProp") + "</td>\n"); paraFAdata.append("\t\t</tr>\n"); // 首先写下项目 paddLeft = 6; paraFAdata.append("<tr onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' style='padding-left: 6'>\n" + "<a href='javascript:void(0)' id='" + folderId + "' name='paras' class='link' title='" + Messages.getString("qa.all.fa.clickToShrink") + "' " + " onclick='clickFolder(id, name)' ><span id='" + folderId + "_span'>-</span> " + curProject.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotTransPara() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotTransParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTranslatedPara() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTransParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getLockedPara() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTotalParas() + "</td>\n" + "</tr>"); paraSetInputData(curProject, paraFAdata, paddLeft); paraFAdata.append("\t</table>\n"); output.write(paraFAdata.toString().getBytes("UTF-8")); // output.write("\t\t</fieldset><br/>\n".getBytes("UTF-8")); // -----------文本段结束-------------- /* String htmlPathDiv = "<div style='width:100%;font-size:14;color:blue;'>" + Messages.getString("qa.all.fa.fileLocation") + curProject.getFullPath().append("Report").append(htmlName).toOSString() + "</div>"; output.write(htmlPathDiv.getBytes("UTF-8"));*/ output.write("\t</body>\n".getBytes("UTF-8")); output.write("</html>".getBytes("UTF-8")); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.TranslationProgressFA.log3"), e); } catch (UnsupportedEncodingException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.TranslationProgressFA.log4"), e); } catch (IOException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.TranslationProgressFA.log5"), e); } return htmlPath; } /** * 将文件下所有的子文件(直接或间接子文件)的值加到文件夹中 */ public void setDataToFolder(IProject curProject) { // 先存放项目相关的信息,所有的文件都存放在该项目中的,因此直接遍历所有的文件 TransProgressFAResult proFaResult = new TransProgressFAResult(); for (int i = 0; i < model.getAnalysisIFileList().size(); i++) { IFile ifile = model.getAnalysisIFileList().get(i); TransProgressFAResult faResult = transProgFAResultMap.get(ifile.getLocation().toOSString()); proFaResult.setNotTransPara(faResult.getNotTransPara()); proFaResult.setTranslatedPara(faResult.getTranslatedPara()); proFaResult.setLockedPara(faResult.getLockedPara()); proFaResult.setNotTransWords(faResult.getNotTransWords()); proFaResult.setTranslatedWords(faResult.getTranslatedWords()); proFaResult.setLockedWords(faResult.getLockedWords()); } transProgFAResultMap.put(curProject.getLocation().toOSString(), proFaResult); // 先遍历所有的文件夹 for (int index = 0; index < allFolderList.size(); index++) { IContainer container = allFolderList.get(index); TransProgressFAResult folderFaResult = new TransProgressFAResult(); // 循环所有的已经分析完的文件 for (int i = 0; i < model.getAnalysisIFileList().size(); i++) { IFile ifile = model.getAnalysisIFileList().get(i); IContainer iFileParent = ifile.getParent(); while (iFileParent != null) { if (iFileParent.equals(container)) { TransProgressFAResult faResult = transProgFAResultMap.get(ifile.getLocation().toOSString()); folderFaResult.setNotTransPara(faResult.getNotTransPara()); folderFaResult.setTranslatedPara(faResult.getTranslatedPara()); folderFaResult.setLockedPara(faResult.getLockedPara()); folderFaResult.setNotTransWords(faResult.getNotTransWords()); folderFaResult.setTranslatedWords(faResult.getTranslatedWords()); folderFaResult.setLockedWords(faResult.getLockedWords()); break; } else { iFileParent = iFileParent.getParent(); } } } transProgFAResultMap.put(container.getLocation().toOSString(), folderFaResult); } } /** * 向字数分析的字数展示模块填充数据 * @param curContainer * @param wordsFAdata */ public void wordsSetInputData(IContainer curContainer, StringBuffer wordsFAdata, int paddLeft) { paddLeft += 10; // 先判断该容器中是否有直接子文件为本次分析文件 if (hasFAIFiles(curContainer)) { // 每个文件的具体数据 for (int fIndex = 0; fIndex < model.getAnalysisIFileList().size(); fIndex++) { IFile curIFile = model.getAnalysisIFileList().get(fIndex); if (curIFile.getParent().equals(curContainer)) { TransProgressFAResult faResult = transProgFAResultMap.get(curIFile.getLocation().toOSString()); wordsFAdata.append("\t\t<tr id='" + curContainer.getFullPath().toOSString() + "' name='words' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n"); wordsFAdata.append("\t\t\t<td class='fileTd' style='padding-left: " + paddLeft + "'>" + curIFile.getName() + "</td>\n");// 文件名 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotTransWords() + "</td>\n"); // 未翻译字数 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotTransWordsRatio() + "</td>\n"); // 未翻译字数比例 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTranslatedWords() + "</td>\n"); // 已翻译字数 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTransWordsRatio() + "</td>\n"); // 已翻译字数比例 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getLockedWords() + "</td>\n"); // 锁定字数 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTotalWords() + "</td>\n"); // 总字数 wordsFAdata.append("\t\t</tr>\n"); } } } // 遍历所有含有分析文件的容器,找出当前容器的子容器, for (int index = 0; index < allFolderList.size(); index++) { IContainer childContainer = allFolderList.get(index); if (childContainer.getParent().equals(curContainer)) { TransProgressFAResult faResult = transProgFAResultMap.get(childContainer.getLocation().toOSString()); String folderId = childContainer.getFullPath().toOSString(); wordsFAdata.append("<tr id='" + curContainer.getFullPath().toOSString() + "' name='words' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' ><a href='javascript:void(0)' id='" + folderId + "' name='words' class='link' style='padding-left: " + paddLeft + "'" + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)'>" + "<span id='" + folderId + "_span'>-</span> " + childContainer.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotTransWords() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotTransWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTranslatedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTransWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getLockedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTotalWords() + "</td>\n" + "</tr>\n"); wordsSetInputData(childContainer, wordsFAdata, paddLeft); } } } public void paraSetInputData(IContainer curContainer, StringBuffer paraFAdata, int paddLeft) { paddLeft += 10; // 先判断该容器中是否有直接子文件为本次分析文件 if (hasFAIFiles(curContainer)) { // 每个文件的具体数据 for (int fIndex = 0; fIndex < model.getAnalysisIFileList().size(); fIndex++) { IFile curIFile = model.getAnalysisIFileList().get(fIndex); if (curIFile.getParent().equals(curContainer)) { TransProgressFAResult faResult = transProgFAResultMap.get(curIFile.getLocation().toOSString()); paraFAdata.append("\t\t<tr id='" + curContainer.getFullPath().toOSString() + "' name='paras' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n"); paraFAdata.append("\t\t\t<td class='fileTd' style='padding-left: " + paddLeft + "'>" + curIFile.getName() + "</td>\n");// 文件名 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotTransPara() + "</td>\n"); // 未翻译文本段数 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotTransParasRatio() + "</td>\n"); // 未翻译文本段比例 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTranslatedPara() + "</td>\n"); // 已翻译文本段数 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTransParasRatio() + "</td>\n"); // 已翻译文本段比例 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getLockedPara() + "</td>\n"); // 锁定文本段 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTotalParas() + "</td>\n"); // 总段数 paraFAdata.append("\t\t</tr>\n"); } } } // 遍历所有含有分析文件的容器,找出当前容器的子容器, for (int index = 0; index < allFolderList.size(); index++) { IContainer childContainer = allFolderList.get(index); if (childContainer.getParent().equals(curContainer)) { TransProgressFAResult faResult = transProgFAResultMap.get(childContainer.getLocation().toOSString()); String folderId = childContainer.getFullPath().toOSString(); paraFAdata.append("<tr id='" + curContainer.getFullPath().toOSString() + "' name='paras' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' >\n" + "<a href='javascript:void(0)' id='" + folderId + "' name='paras' class='link' style='padding-left: " + paddLeft + "'" + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)'>" + "<span id='" + folderId + "_span'>-</span> " + childContainer.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotTransPara() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotTransParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTranslatedPara() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTransParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getLockedPara() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTotalParas() + "</td>\n" + "</tr>\n"); paraSetInputData(childContainer, paraFAdata, paddLeft); } } } }
24,775
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
WordsFA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/fileAnalysis/WordsFA.java
package net.heartsome.cat.ts.ui.qa.fileAnalysis; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.common.bean.DatabaseModelBean; import net.heartsome.cat.common.bean.TranslationUnitAnalysisResult; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.common.tm.MatchQuality; import net.heartsome.cat.ts.core.file.ProjectConfiger; import net.heartsome.cat.ts.core.file.ProjectConfigerFactory; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.core.qa.CountWord; import net.heartsome.cat.ts.core.qa.FAModel; import net.heartsome.cat.ts.core.qa.FileAnalysis; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.core.qa.WordsFABean; import net.heartsome.cat.ts.tm.bean.TransUnitInfo2TranslationBean; import net.heartsome.cat.ts.tm.match.TmMatcher; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.model.WordsFAResult; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 字数分析,包括统计内部重复,内部匹配,外部重复,外部匹配,以及新字数的字数统计, 结果展示为字数统计,文本段统计。 monitor进度提示语句: 字数分析: 获取文件{0}所有源文本 ... ... * 备注:所分析的文件必须在一个项目内 * @author robert 2011-12-08 * * 备注-robert ,此处还待优化,优化内容为重新写一个查询数据库的方法,待jason优化findmatch方法之后,优化的方面是,只查询我所需要的东西 2012-01-04 */ public class WordsFA extends FileAnalysis { private FAModel model; private QAXmlHandler handler; /** 是否忽略标记 */ private boolean ignoreTag = false; /** 是否忽略大小写,从记忆库首选项中获取 */ private boolean ignoreCase = false; /** 罚分制度 */ private int tagPenalty; /** 是否检查内部重复 */ private boolean interRepeat; /** 是否检查内部匹配 */ private boolean interMatch; /** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格,针对匹配 */ private int workInterval = 1; /** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格,针对获取源文本 */ private int getSrcTextWorkInterval = workInterval * 100; /** * 存储所选文件的所有trans-unit节点的源文本 Map<文件名, Map<trans-unit唯一标识符, * Map<source节点的内容或纯文本(QAConstant.FA_SRC_CONTENT/QAConstant.FA_SRC_PURE_TEXT), 值>>> */ private Map<String, Map<String, WordsFABean>> allSrcTextsMap = new HashMap<String, Map<String, WordsFABean>>(); /** 新字数的最大匹配率,从首选项的记忆库设置中获取,也就是匹配率低于这个值就是新字数 */ private int newWordsMaxMatchRate; /** 一个存放每个文件分析结果的集合,key值为一个文件的绝对路径(IFile.getLocation.toOSString) */ private Map<String, WordsFAResult> WordsFAResultMap; /** 所有包括分析文件的容器,但不包括项目 */ private List<IContainer> allFolderList; /** 上下文的个数,从首选项中获取(记忆库) */ private int contextSum = 0; private IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); /** 加权系数字符串,如internalRepeat:0.50;external101:0.50;external100:0.50;95-99:0.60; */ private String equivStr; private TmMatcher tmMatcher = new TmMatcher(); private TransUnitInfo2TranslationBean tuInfoBean; private IProject curProject; private List<String> needLockRowIdList = new ArrayList<String>(); /** 保存内部重复的数据,以便锁定内部重复 */ private XLIFFEditorImplWithNatTable nattble; private boolean isOpened; public final static Logger logger = LoggerFactory.getLogger(WordsFA.class.getName()); @Override public int beginAnalysis(FAModel model, IProgressMonitor monitor, QAXmlHandler handler) { this.model = model; this.handler = handler; super.setModel(model); ignoreTag = preferenceStore.getBoolean(QAConstant.FA_PREF_ignoreTag); ignoreCase = preferenceStore.getBoolean(QAConstant.FA_PREF_ignoreCase); contextSum = preferenceStore.getInt(QAConstant.FA_PREF_contextNum); equivStr = preferenceStore.getString(QAConstant.FA_PREF_equivalent); tagPenalty = preferenceStore.getInt(QAConstant.FA_PREF_tagPenalty); initNewWordsMaxMatchRateFromWeightPage(); interRepeat = preferenceStore.getBoolean(QAConstant.FA_PREF_interRepeate); interMatch = preferenceStore.getBoolean(QAConstant.FA_PREF_interMatch); // 备注,这里的是否忽略大小写,传到记忆库匹配时是必须变成它的相反值的,因为记忆库里的参数为是否区分大小写。 tmMatcher.setCustomeMatchParameters(1, ignoreTag, newWordsMaxMatchRate, !ignoreCase, contextSum, tagPenalty); if (monitor == null) { monitor = new NullProgressMonitor(); } if (model.getAnalysisIFileList().size() <= 0) { return QAConstant.QA_ZERO; } // 字数分析的进度条分为两大块,1:获取项目下所有源文本,共花一格,2:分析文件,共花四格 int allTUSize = model.getAllTuSize(); curProject = model.getAnalysisIFileList().get(0).getProject(); // UNDO 所有的这里都要对进度条进行处理。 if (allTUSize > 500) { workInterval = allTUSize / 500; } int matchWorkUnit = allTUSize % workInterval == 0 ? (allTUSize / workInterval) : (allTUSize / workInterval) + 1; monitor.beginTask("", matchWorkUnit); // 开始进行内部与外部匹配 WordsFAResultMap = matching(monitor); tmMatcher.clearResources(); // 关闭数据库,释放资源 if (WordsFAResultMap == null) { return QAConstant.QA_ZERO; } // 输出结果 printWordsFAReslut(); return QAConstant.QA_FIRST; } /** * 根据加权字数字符串获取最低匹配率 * @return */ private void initNewWordsMaxMatchRateFromWeightPage(){ int minRate = 100; //internalRepeat:0.50;external101:0.50;external100:0.50;95-99:0.60; String[] equivArray = equivStr.split(";"); for(String singleEquiv : equivArray){ if (singleEquiv.indexOf("internalRepeat") != -1 || singleEquiv.indexOf("external101") != -1 || singleEquiv.indexOf("external100") != -1) { continue; } String matchPair = singleEquiv.substring(0, singleEquiv.indexOf(":") ); String minRateStr = matchPair.split("-")[0]; if (minRateStr != null && minRateStr.matches("\\d{0,2}")) { if (minRate > Integer.parseInt(minRateStr)) { minRate = Integer.parseInt(minRateStr); } } } newWordsMaxMatchRate = minRate; if (newWordsMaxMatchRate <=0 ) { newWordsMaxMatchRate = 1; } } /** * 获取要分析的所有xliff文件的所有源文本 其值为一个键值对,rowId --> 该节点的源文本 * @return : Map<文件名, Map<trans-unit唯一标识符, * Map<source节点的内容或纯文本(QAConstant.FA_SRC_CONTENT/QAConstant.FA_SRC_PURE_TEXT), 值>>> 如果返回为null,则标志退出程序操作 */ public Map<String, Map<String, WordsFABean>> getAllXlfSrcTexts(String srcLang, String tgtLang) { return handler.getAllSrcText(getSrcTextWorkInterval, ignoreTag, contextSum, srcLang, tgtLang); } /** * 开始处理匹配操作 如果返回null,则是用户点击退出按钮,执行退出操作 */ public Map<String, WordsFAResult> matching(IProgressMonitor monitor) { int matchTravelTuIndex = 0; // 字数统计的结果集合 Map<String, WordsFAResult> wordsFAResultMap = new LinkedHashMap<String, WordsFAResult>(); Map<String, ArrayList<String>> languages = handler.getLanguages(); //先对每个文件存放一个结果集 for(IFile iFile : model.getAnalysisIFileList()){ String filePath = iFile.getLocation().toOSString(); wordsFAResultMap.put(filePath, new WordsFAResult()); } WordsFAResult wordFaResult; //针对每一个文件的结果集 for (Entry<String, ArrayList<String>> langEntry : languages.entrySet()) { String srcLanguage = langEntry.getKey(); for (String tgtLanguage : langEntry.getValue()) { //针对每个文件,每种语言对获取其内容 allSrcTextsMap = getAllXlfSrcTexts(srcLanguage.toUpperCase(), tgtLanguage.toUpperCase()); // 如果返回的值为空,则标志用户点击了退出操作,那么退出程序 if (allSrcTextsMap == null) { continue; } WordsFABean bean; List<TranslationUnitAnalysisResult> exterMatchResult = null; // 字数统计的结果集合 for(Entry<String, Map<String, WordsFABean>> textEntry : allSrcTextsMap.entrySet()){ String filePath = textEntry.getKey(); IFile iFile = ResourceUtils.fileToIFile(filePath); // 存储匹配结果的pojo类 wordFaResult = wordsFAResultMap.get(filePath); Map<String, WordsFABean> fileSrcTextMap = textEntry.getValue(); monitor.setTaskName(MessageFormat.format(Messages.getString("qa.fileAnalysis.WordsFA.tip1"), iFile .getFullPath().toOSString())); Iterator<Entry<String, WordsFABean>> it = fileSrcTextMap.entrySet().iterator(); while (it.hasNext()) { Entry<String, WordsFABean> entry = (Entry<String, WordsFABean>) it.next(); matchTravelTuIndex++; String rowId = entry.getKey(); bean = entry.getValue(); String srcPureText = bean.getSrcPureText(); int textLength = bean.getSrcLength(); String preTextHash = bean.getPreHash(); String nextTextHash = bean.getNextHash(); boolean isLocked = bean.isLocked(); String tagStr = bean.getTagStr(); int wordsCount = CountWord.wordCount(srcPureText, srcLanguage); //若处于锁定状态,则添加到已锁定字数,然后跳出,执行下一文本段 if (isLocked) { wordFaResult.setLockedPara(QAConstant.QA_FIRST); wordFaResult.setLockedWords(wordsCount); //删除该文本段,不再进行比较 fileSrcTextMap.remove(rowId); it = fileSrcTextMap.entrySet().iterator(); continue; } // UNDO 应先判断数据库是否可用。 // 第一步,进行外部匹配,先封装参数。 tuInfoBean = new TransUnitInfo2TranslationBean(); tuInfoBean.setNextContext(bean.getNextHash()); tuInfoBean.setPreContext(bean.getPreHash()); tuInfoBean.setSrcFullText(bean.getSrcContent()); tuInfoBean.setSrcLanguage(srcLanguage); tuInfoBean.setSrcPureText(bean.getSrcPureText()); tuInfoBean.setTgtLangugage(tgtLanguage); exterMatchResult = tmMatcher.analysTranslationUnit(curProject, tuInfoBean); int exterMatchRate = 0; if (exterMatchResult != null && exterMatchResult.size() > 0) { exterMatchRate = exterMatchResult.get(0).getSimilarity(); } if (exterMatchRate == 100) { // 如果锁定外部 100% 匹配,那么这些字数将被添加到锁定字数,而非外部 100% 匹配,外部101% 一样 if (model.isLockExter100()) { wordFaResult.setLockedPara(QAConstant.QA_FIRST); wordFaResult.setLockedWords(wordsCount); needLockRowIdList.add(rowId); }else { wordFaResult.setExterRepeatPara(QAConstant.QA_FIRST); wordFaResult.setExterMatchWords(wordsCount); wordFaResult.setAllExterMatchWords(exterMatchRate, wordsCount); } //删除该文本段,不再进行比较 fileSrcTextMap.remove(rowId); it = fileSrcTextMap.entrySet().iterator(); if (!handler.monitorWork(monitor, matchTravelTuIndex, workInterval, false)) { return null; } continue; } if (exterMatchRate == 101) { if (model.isLockExter101()) { wordFaResult.setLockedPara(QAConstant.QA_FIRST); wordFaResult.setLockedWords(wordsCount); needLockRowIdList.add(rowId); }else { wordFaResult.setExterRepeatPara(QAConstant.QA_FIRST); wordFaResult.setExterMatchWords(wordsCount); wordFaResult.setAllExterMatchWords(exterMatchRate, wordsCount); } //删除该文本段,不再进行比较 fileSrcTextMap.remove(rowId); it = fileSrcTextMap.entrySet().iterator(); if (!handler.monitorWork(monitor, matchTravelTuIndex, workInterval, false)) { return null; } continue; } // 第二步,进行内部匹配 int inteMatchRate = 0; // 如果要检查内部重复,那么就查找内部匹配 if (interRepeat) { // 如果不进行内部模糊匹配,那么直接 int interNewWordsMaxMatchRate = interMatch ? newWordsMaxMatchRate : 100; internalMatching(rowId, srcPureText, tagStr, textLength, preTextHash, nextTextHash, interNewWordsMaxMatchRate); } inteMatchRate = bean.getThisMatchRate() > inteMatchRate ? bean.getThisMatchRate() : inteMatchRate; int maxMacthRate = exterMatchRate > inteMatchRate ? exterMatchRate : inteMatchRate; if (inteMatchRate == 100 || inteMatchRate == 101) { if (model.isLockInterRepeat()) { wordFaResult.setLockedPara(QAConstant.QA_FIRST); wordFaResult.setLockedWords(wordsCount); needLockRowIdList.add(rowId); }else { wordFaResult.setInterRepeatPara(QAConstant.QA_FIRST); wordFaResult.setInterMatchWords(wordsCount); wordFaResult.setAllInterMatchWords(inteMatchRate, wordsCount); } }else if (maxMacthRate < newWordsMaxMatchRate ) { //最大匹配小于最小匹配时,就为新字数 wordFaResult.setNewPara(QAConstant.QA_FIRST); wordFaResult.setNewWords(wordsCount); }else { if (inteMatchRate > exterMatchRate) { // 内部匹配 wordFaResult.setInterMatchPara(QAConstant.QA_FIRST); wordFaResult.setInterMatchWords(wordsCount); wordFaResult.setAllInterMatchWords(inteMatchRate, wordsCount); }else { //外部匹配 wordFaResult.setExterMatchPara(QAConstant.QA_FIRST); wordFaResult.setExterMatchWords(wordsCount); wordFaResult.setAllExterMatchWords(exterMatchRate, wordsCount); } } //删除该文本段,不再进行比较 fileSrcTextMap.remove(rowId); it = fileSrcTextMap.entrySet().iterator(); if (!handler.monitorWork(monitor, matchTravelTuIndex, workInterval, false)) { return null; } } wordsFAResultMap.put(filePath, wordFaResult); } if (!handler.monitorWork(monitor, matchTravelTuIndex, workInterval, false)) { return null; } } } lockRepeatTU(wordsFAResultMap); return wordsFAResultMap; } /** * 内部匹配 备注,是将一个source节点拿去跟所有的source节点进行匹配,并称这个source节点为比较者,其他所有的source节点为被比较者 * 关于上下文匹配,在获取分割xliff文件时就没有必要去做了,故在获取加权系数时,传入两个空值即可 * @param rowId * : 被比较者的trans-unit节点的唯一标识符 * @param srcContent * : 被比较者的trans-unit节点的source子节点的完整内容(包括标记) * @param srcPureText * : 被比较者的trans-unit节点的source子节点的纯文本 * @param preTextHash * 上文的hash值 * @param nextTexthash * 下文的hash值 */ public int internalMatching(String rowId, String srcPureText, String tagStr, int textLength, String preTextHash, String nextTexthash, int interNewWordsMaxMatchRate) { int matchRate = 0; // 匹配率 // System.out.println("长度为="+srcContent.length()); //System.out.println("rowId = " + rowId); //System.out.println("ignoreTag = " + ignoreTag); int fileSize = model.getAnalysisIFileList().size(); List<IFile> fileList = model.getAnalysisIFileList(); for (int fileIndex = 0; fileIndex < fileSize; fileIndex++) { IFile iFile = fileList.get(fileIndex); String filePath = iFile.getLocation().toOSString(); Map<String, WordsFABean> fileSrcTextMap = allSrcTextsMap.get(filePath); Iterator<Entry<String, WordsFABean>> it = fileSrcTextMap.entrySet().iterator(); WordsFABean curBean; while (it.hasNext()) { Entry<String, WordsFABean> entry = (Entry<String, WordsFABean>) it.next(); String curRowId = entry.getKey(); // 比较者不与自己进行比较 if (rowId.equals(curRowId)) { continue; } curBean = entry.getValue(); String curSrcPureText = curBean.getSrcPureText(); if (!checkIsideal(ignoreCase ? srcPureText.toLowerCase() : srcPureText, ignoreCase ? curSrcPureText.toLowerCase() : curSrcPureText, interNewWordsMaxMatchRate)) { continue; } // long time2 = System.currentTimeMillis(); int curMatchRate = 0; curMatchRate = MatchQuality.similarity(ignoreCase ? srcPureText.toLowerCase() : srcPureText, ignoreCase ? curSrcPureText.toLowerCase() : curSrcPureText); if (!ignoreTag) { String curTagStr = curBean.getTagStr(); if (!curTagStr.equals(tagStr)) { curMatchRate -= tagPenalty; } } if (curMatchRate > matchRate) { matchRate = curMatchRate; } //如果当前文本段的匹配率小于本次所比较的匹配率,则重新刷新匹配率 curBean.setThisMatchRate(curMatchRate); // System.out.println("比较时= " + (System.currentTimeMillis() - time2)); } } return matchRate; } /** * 执行锁定重复文本段 */ private void lockRepeatTU(Map<String, WordsFAResult> wordsFAResultMap) { final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; // 首先,判断当前所处理的文件是否合并打开 if (model.isMultiFile()) { if (needLockRowIdList.size() <= 0) { return; } Display.getDefault().asyncExec(new Runnable() { public void run() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IEditorInput input = new FileEditorInput(model.getMultiTempIFile()); IEditorReference[] reference = window.getActivePage().findEditors(input,XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); nattble = (XLIFFEditorImplWithNatTable) reference[0].getEditor(true); XLFHandler thisHandler = nattble.getXLFHandler(); thisHandler.lockFaTU(needLockRowIdList); nattble.redraw(); } }); }else { //针对已经打开的文件进行锁定 if (needLockRowIdList.size() <= 0) { return; } final Map<String, List<String>> rowIdMap = RowIdUtil.groupRowIdByFileName(needLockRowIdList); for(final IFile iFile : model.getAnalysisIFileList() ){ isOpened = false; final String filePath = iFile.getLocation().toOSString(); if (rowIdMap.get(filePath) == null || rowIdMap.get(filePath).size() <= 0) { continue; } Display.getDefault().syncExec(new Runnable() { public void run() { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IEditorInput input = new FileEditorInput(iFile); IEditorReference[] reference = window.getActivePage() .findEditors(input,XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); if (reference.length > 0) { isOpened = true; nattble = (XLIFFEditorImplWithNatTable) reference[0] .getEditor(true); XLFHandler thisHandler = nattble.getXLFHandler(); thisHandler.lockFaTU(rowIdMap.get(filePath)); nattble.redraw(); } } }); if (!isOpened) { for(String rowId : rowIdMap.get(filePath)){ handler.lockedTU(rowId); } } } } } /** * 检查两个句子是否理想匹配,如果不是理想匹配,返回 false * @return */ private static boolean checkIsideal(String x, String y, int newMatch){ // 求匹配的算法,必须要去掉首尾的空格。 x = x.trim(); y = y.trim(); // x 换成短句,y变成长句 String temp = ""; if (x.length() > y.length()) { temp = x; x = y; y = temp; } int maxLength = y.length(); if (maxLength == 0) { return false; } if ((100 * x.length() / maxLength) < newMatch) { return false; } if (newMatch >= 100) { if (!x.equals(y)) { return false; } } // 如果最大长度小于 10 ,那么 MatchQuality 类的所耗时间并不长,不需要求 字符相似度 // if (maxLength < 10) { // return true; // } // 下面是切段理想匹配 Map<Character, Integer> xMap = new HashMap<Character, Integer>(); for(char _char : x.toCharArray()){ if (xMap.containsKey(_char)) { xMap.put(_char, xMap.get(_char) + 1); }else { xMap.put(_char, 1); } } int repeatSum = 0; for (char _char : y.toCharArray()) { if (xMap.containsKey(_char)) { if (xMap.get(_char) <= 1) { xMap.remove(_char); }else { xMap.put(_char, xMap.get(_char) - 1); } repeatSum ++; } } int idealMath = 100*repeatSum / maxLength; if (idealMath < newMatch) { return false; } return true; } //-------------------------------------------------------------------------------------------// //---------------------------------下面的代码主要是报表部份---------------------------------------// //-------------------------------------------------------------------------------------------// /** * 输出字数统计结果到结果窗体中 * @param WordsFAResultMap */ public void printWordsFAReslut() { String htmlPath = createFAResultHtml(); try { model.getAnalysisIFileList().get(0).getProject().getFolder("Intermediate").getFolder("Report").refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e1) { e1.printStackTrace(); } final FileEditorInput input = new FileEditorInput(ResourceUtils.fileToIFile(htmlPath)); if (PlatformUI.getWorkbench().isClosing()) { return; } Display.getDefault().asyncExec(new Runnable() { public void run() { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(input, QAConstant.FA_HtmlBrowserEditor, true); } catch (PartInitException e) { logger.error(Messages.getString("qa.fileAnalysis.WordsFA.log5"), e); e.printStackTrace(); } } }); } /** * 生成字数分析结果html文件 * @return html文件的路径 */ public String createFAResultHtml() { allFolderList = new LinkedList<IContainer>(); Date createDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String createTime = formatter.format(createDate); formatter = new SimpleDateFormat("yyyyMMdd-HHmmss"); String htmlNameTime = formatter.format(createDate); IProject curProject = model.getAnalysisIFileList().get(0).getProject(); String htmlName = "WordLog" + htmlNameTime + ".html"; String htmlPath = curProject.getLocation().append("Intermediate").append("Report").append(htmlName).toOSString(); File htmlFile = new File(htmlPath); if (!htmlFile.getParentFile().exists()) { htmlFile.getParentFile().mkdirs(); } FileOutputStream output; try { output = new FileOutputStream(htmlPath); output.write(QAConstant.FA_HtmlDoctype.getBytes("UTF-8")); output.write("<html>\n".getBytes("UTF-8")); String headerNode = QAConstant.FA_htmlHeader; headerNode = headerNode.replace("###Title###", Messages.getString("qa.fileAnalysis.WordsFA.name1")); output.write(headerNode.getBytes("UTF-8")); output.write("\t<body>\n".getBytes("UTF-8")); output.write(("<p class=\"title\">"+Messages.getString("qa.all.fa.WordsFA")+"</p>").getBytes("UTF-8")); // ----------------<<<<<<start-- 下面是相关信息提示部份--------------------- output.write("\t<div>\n".getBytes("UTF-8")); output.write("\t\t<table class=\"infoTableStyle\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n".getBytes("UTF-8")); // 记忆库 String title = Messages.getString("qa.fa.info.tm"); ProjectConfiger projectConfiger = ProjectConfigerFactory.getProjectConfiger(curProject); List<DatabaseModelBean> tmBeanList = projectConfiger.getAllTmDbs(); StringBuffer tmInfoSB = new StringBuffer(); if (tmBeanList.size() > 0) { for(DatabaseModelBean bean : tmBeanList){ tmInfoSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); String dbType = bean.getDbType(); if("MySQL 5.x".equals(dbType)){ dbType = "MySQL"; } else if ("MsSQL2005".equals(dbType)){ dbType = "SQL Server"; } tmInfoSB.append(dbType); String location = ""; if ("Internal DB".equals(dbType) || "SQLite".equals(dbType)) { location = bean.getItlDBLocation(); }else { location = bean.getHost() + ":" + bean.getPort(); if (":".equals(location)) { location = ""; } } if (location != null && !"".equals(location.trim()) && !" : ".equals(location)) { tmInfoSB.append(" ( " + location + " ) "); } tmInfoSB.append(": "); tmInfoSB.append(MessageFormat.format("{0}" + bean.getDbName() + "{1}", new Object[]{bean.isDefault() ? "<b>" : "", bean.isDefault() ? "</b>" : ""})); tmInfoSB.append("</div>\n"); } }else { tmInfoSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); tmInfoSB.append("N/A"); tmInfoSB.append("</div>\n"); } String infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", tmInfoSB.toString()); output.write(infoStr.getBytes("UTF-8")); // 最底匹配率 title = Messages.getString("qa.fa.info.newWordMatch"); String content = newWordsMaxMatchRate + "%"; infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", content); output.write(infoStr.getBytes("UTF-8")); // 分析文件总数 title = Messages.getString("qa.fa.info.fileSum"); content = "" + model.getSubFileNum(); infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", content); output.write(infoStr.getBytes("UTF-8")); // 分析失败文件 title = Messages.getString("qa.fa.info.errorFiles"); StringBuffer errorFileSB = new StringBuffer(); errorFileSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); errorFileSB.append(model.getErrorIFileList().size()); errorFileSB.append("</div>"); for(IFile iFile : model.getErrorIFileList()){ errorFileSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); errorFileSB.append(iFile.getFullPath().toOSString()); errorFileSB.append("</div>"); } infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", errorFileSB.toString()); output.write(infoStr.getBytes("UTF-8")); // 报告生成时间 title = Messages.getString("qa.fa.info.createTime"); infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", createTime); output.write(infoStr.getBytes("UTF-8")); output.write("</table></div><br>\n".getBytes("UTF-8")); // ---------------->>>>>>end-- 报表信息提示部分结束--------------------- int paddLeft = 6; String folderId = curProject.getFullPath().toOSString(); getAllFolder(curProject, allFolderList); // 向所有的文件夹传值 setDataToFolder(curProject); // 首先写下项目 WordsFAResult proFaResult = WordsFAResultMap.get(curProject.getLocation().toOSString()); // --------------数据库匹配率区间--------------------- output.write(("\t\t<div class=\"legendStyle\"><b>" + Messages.getString("qa.fileAnalysis.WordsFA.wordsFA") + "</b></div>").getBytes("UTF-8")); StringBuffer exterFAdata = new StringBuffer(); //"100-101:0.5;89-99:0.4" String[] equivArray = equivStr.split(";"); int length = equivArray.length; // 是否有 上下文匹配 boolean hasExter101 = equivStr.indexOf("external101") != -1; int interMathNum = 0; if (interRepeat && !interMatch) { interMathNum = 1; }else if(interRepeat && interMatch) { interMathNum = length - (hasExter101 ? 2 : 1); } int columLength = length - 1 + interMathNum + 3 + 4; //要显示列的总数(文件列是普通列的三倍) float width = (float)100 / columLength; //开始创建表头 exterFAdata.append("\t<table class='tableStyle' cellpadding='0' cellspacing='1'> \n"); // 表头 exterFAdata.append("\t\t<tr>\n"); exterFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='" + 3 * width + "%'>" + Messages.getString("qa.all.fa.fileName") + "</td>\n"); exterFAdata.append("\t\t\t<td class='headerTd' colSpan='" + (length - 1) + "' width='" + (length - 1) * width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.exterMatch") + "</td>\n"); if (interRepeat) { exterFAdata.append("\t\t\t<td class='headerTd' colSpan='" + interMathNum + "' width='" + interMathNum * width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.interMatch") + "</td>\n"); } exterFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='" + width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.newWordsNum") + "</td>\n"); exterFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='" + width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.equivWordsNum") + "</td>\n"); exterFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='" + width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.lockWordsNum") + "</td>\n"); exterFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='" + width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.wordsSum") + "</td>\n"); exterFAdata.append("\t\t</tr>\n"); exterFAdata.append("\t\t<tr>\n"); //这是创建显示结果的外部匹配部份 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "headerTd"; if (QAConstant._External101.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' width='" + width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.contentMath") + "</td>\n"); }else if (QAConstant._External100.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' width='"+width+"%'>"+ "100%" +"</td>\n"); }else if (!QAConstant._InternalRepeat.equals(matchPair)) { matchPair = matchPair.substring(0, matchPair.indexOf("-")) + "%" + matchPair.substring(matchPair.indexOf("-"), matchPair.length()) + "%"; exterFAdata.append("\t\t\t<td class='" + className + "' width='"+width+"%'>"+ matchPair +"</td>\n"); } } //这是创建显示结果的内部匹配部份 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "headerTd"; if (interRepeat && QAConstant._InternalRepeat.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' width='" + width + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.contentRepeat") + "</td>\n"); }else if (interMatch && matchPair.indexOf("external") == -1) { matchPair = matchPair.substring(0, matchPair.indexOf("-")) + "%" + matchPair.substring(matchPair.indexOf("-"), matchPair.length()) + "%"; exterFAdata.append("\t\t\t<td class='" + className + "' width='"+width+"%'>"+ matchPair +"</td>\n"); } } exterFAdata.append("\t\t</tr>\n"); // 首先写下项目 exterFAdata.append("<tr onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' style='padding-left: 6'><a href='javascript:void(0)' id='" + folderId + "' name='allExter' class='link' " + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)' >" + "<span id='" + folderId + "_span'>-</span> " + curProject.getName() + "</a></td>\n"); //项目的外部匹配部份 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "folderTd"; if (QAConstant._External101.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ proFaResult.getExterMatch("101") +"</td>\n"); }else if (QAConstant._External100.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ proFaResult.getExterMatch("100") +"</td>\n"); }else if (!QAConstant._InternalRepeat.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ proFaResult.getExterMatch(matchPair) +"</td>\n"); } } //项目的内部匹配部份 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "folderTd"; if (interRepeat && QAConstant._InternalRepeat.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ proFaResult.getInterMatch("100-101") +"</td>\n"); }else if (interMatch && matchPair.indexOf("external") == -1) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ proFaResult.getInterMatch(matchPair) +"</td>\n"); } } //新字数,锁定字数,总字数 exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ proFaResult.getNewWords() +"</td>\n"); exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ proFaResult.getEqalWords(equivStr) +"</td>\n"); exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ proFaResult.getLockedWords() +"</td>\n"); exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ proFaResult.getTotalWords() +"</td>\n"); exterFAdata.append("</tr>"); allExterMatchSetInputData(curProject, exterFAdata, paddLeft, equivArray); exterFAdata.append("\t</table>\n"); output.write(exterFAdata.toString().getBytes("UTF-8")); // --------------文本段--------------------- output.write("<br/>\n".getBytes("UTF-8")); output.write(("\t\t\t<div class=\"legendStyle\"><b>" + Messages.getString("qa.fileAnalysis.WordsFA.paragraph") + "</b></div>").getBytes("UTF-8")); StringBuffer paraFAdata = new StringBuffer(); int paraTableColumnNum = 4 + 3; if (interRepeat && !interMatch) { paraTableColumnNum = 5 + 3; // 文件名列占两个单位的长度 }else if (interRepeat && interMatch) { paraTableColumnNum = 6 + 3; } float paraCloumnWidth = (float)100 / paraTableColumnNum; // 创建一个表 paraFAdata.append("\t<table class='tableStyle' cellpadding='0' cellspacing='1'> \n"); // 表头 paraFAdata.append("\t\t<tr>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='" + 2 * paraCloumnWidth + "%'>" + Messages.getString("qa.all.fa.fileName") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='" + paraCloumnWidth + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.newPara") + "</td>\n"); if (interMatch) { paraFAdata.append("\t\t\t<td class='headerTd' width='" + paraCloumnWidth + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.interMatchPara") + "</td>\n"); } paraFAdata.append("\t\t\t<td class='headerTd' width='" + paraCloumnWidth + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.exterMatchPara") + "</td>\n"); if (interRepeat) { paraFAdata.append("\t\t\t<td class='headerTd' width='" + paraCloumnWidth + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.interRepeatPara") + "</td>\n"); } paraFAdata.append("\t\t\t<td class='headerTd' width='" + paraCloumnWidth + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.exterRepeatPara") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='" + paraCloumnWidth + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.lockedPara") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='" + paraCloumnWidth + "%'>" + Messages.getString("qa.fileAnalysis.WordsFA.paraSum") + "</td>\n"); paraFAdata.append("\t\t</tr>\n"); // 首先写下项目 paddLeft = 6; paraFAdata.append("<tr onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' style='padding-left: 6'><a href='javascript:void(0)' id='" + folderId + "' name='paras' class='link' " + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)' ><span id='" + folderId + "_span'>-</span> " + curProject.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNewPara() + "</td>\n" + (interMatch ? "<td class='folderTd' align='right'>" + proFaResult.getInterMatchPara() + "</td>\n" : "") + "<td class='folderTd' align='right'>" + proFaResult.getExterMatchPara() + "</td>\n" + (interRepeat ? "<td class='folderTd' align='right'>" + proFaResult.getInterRepeatPara() + "</td>\n" : "") + "<td class='folderTd' align='right'>" + proFaResult.getExterRepeatPara() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getLockedPara() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTotalPara() + "</td>\n" + "</tr>"); paraSetInputData(curProject, paraFAdata, paddLeft); paraFAdata.append("\t</table>\n"); output.write(paraFAdata.toString().getBytes("UTF-8")); // output.write("\t\t</fieldset><br/>\n".getBytes("UTF-8")); /* String htmlPathDiv = "<div style='width:100%;font-size:14;color:blue;'>" + Messages.getString("qa.all.fa.fileLocation") + curProject.getFullPath().append("Report").append(htmlName).toOSString() + "</div>"; output.write(htmlPathDiv.getBytes("UTF-8"));*/ output.write("\t</body>\n".getBytes("UTF-8")); output.write("</html>".getBytes("UTF-8")); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.WordsFA.log6"), e); } catch (UnsupportedEncodingException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.WordsFA.log7"), e); } catch (IOException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.WordsFA.log8"), e); } return htmlPath; } /** * 将文件下所有的子文件(直接或间接子文件)的值加到文件夹中 */ public void setDataToFolder(IProject curProject) { // 先存放项目相关的信息,所有的文件都存放在该项目中的,因此直接遍历所有的文件 WordsFAResult proFaResult = new WordsFAResult(); for (int i = 0; i < model.getAnalysisIFileList().size(); i++) { IFile ifile = model.getAnalysisIFileList().get(i); WordsFAResult faResult = WordsFAResultMap.get(ifile.getLocation().toOSString()); proFaResult.setNewPara(faResult.getNewPara()); proFaResult.setInterRepeatPara(faResult.getInterRepeatPara()); proFaResult.setInterMatchPara(faResult.getInterMatchPara()); proFaResult.setExterRepeatPara(faResult.getExterRepeatPara()); proFaResult.setExterMatchPara(faResult.getExterMatchPara()); proFaResult.setLockedPara(faResult.getLockedPara()); proFaResult.setNewWords(faResult.getNewWords()); proFaResult.setInterMatchWords(faResult.getInterMatchWords()); proFaResult.setExterMatchWords(faResult.getExterMatchWords()); proFaResult.setLockedWords(faResult.getLockedWords()); proFaResult.setAllExterMatchWords(faResult.getAllExterMatchWords()); proFaResult.setAllInterMatchWords(faResult.getAllInterMatchWords()); } WordsFAResultMap.put(curProject.getLocation().toOSString(), proFaResult); // 先遍历所有的文件夹 for (int index = 0; index < allFolderList.size(); index++) { IContainer container = allFolderList.get(index); WordsFAResult folderFaResult = new WordsFAResult(); // 循环所有的已经分析完的文件 for (int i = 0; i < model.getAnalysisIFileList().size(); i++) { IFile ifile = model.getAnalysisIFileList().get(i); IContainer iFileParent = ifile.getParent(); while (iFileParent != null) { if (iFileParent.equals(container)) { WordsFAResult faResult = WordsFAResultMap.get(ifile.getLocation().toOSString()); folderFaResult.setNewPara(faResult.getNewPara()); folderFaResult.setInterRepeatPara(faResult.getInterRepeatPara()); folderFaResult.setInterMatchPara(faResult.getInterMatchPara()); folderFaResult.setExterRepeatPara(faResult.getExterRepeatPara()); folderFaResult.setExterMatchPara(faResult.getExterMatchPara()); folderFaResult.setLockedPara(faResult.getLockedPara()); folderFaResult.setNewWords(faResult.getNewWords()); folderFaResult.setInterMatchWords(faResult.getInterMatchWords()); folderFaResult.setExterMatchWords(faResult.getExterMatchWords()); folderFaResult.setLockedWords(faResult.getLockedWords()); //所有外部匹配的值 folderFaResult.setAllExterMatchWords(faResult.getAllExterMatchWords()); //所有内部匹配的值 folderFaResult.setAllInterMatchWords(faResult.getAllInterMatchWords()); break; } else { iFileParent = iFileParent.getParent(); } } } WordsFAResultMap.put(container.getLocation().toOSString(), folderFaResult); } } /** * 创建第一张表的数据,新字数,内部匹配,外部匹配,锁定字数的统计 * @param exterFAdata */ public void allExterMatchSetInputData(IContainer curContainer, StringBuffer exterFAdata, int paddLeft, String[] equivArray){ paddLeft += 10; int length = equivArray.length; // 先判断该容器中是否有直接子文件为本次分析文件 if (hasFAIFiles(curContainer)) { // 每个文件的具体数据 for (int fIndex = 0; fIndex < model.getAnalysisIFileList().size(); fIndex++) { IFile curIFile = model.getAnalysisIFileList().get(fIndex); if (curIFile.getParent().equals(curContainer)) { WordsFAResult faResult = WordsFAResultMap.get(curIFile.getLocation().toOSString()); exterFAdata.append("\t\t<tr id='" + curContainer.getFullPath().toOSString() + "' name='allExter' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n"); exterFAdata.append("\t\t\t<td class='fileTd' style='padding-left: " + paddLeft + "'>" + curIFile.getName() + "</td>\n");// 文件名 //创建外部匹配部份 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "fileTd"; if (QAConstant._External101.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getExterMatch("101") +"</td>\n"); }else if (QAConstant._External100.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getExterMatch("100") +"</td>\n"); }else if (!QAConstant._InternalRepeat.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getExterMatch(matchPair) +"</td>\n"); } } //创建内部匹配部份 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "fileTd"; if (interRepeat && QAConstant._InternalRepeat.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getInterMatch("100-101") +"</td>\n"); }else if (interMatch && matchPair.indexOf("external") == -1) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getInterMatch(matchPair) +"</td>\n"); } } //创建新字数,锁定字数,总字数三列 exterFAdata.append("\t\t\t<td class='fileTd' align='right'>"+ faResult.getNewWords() +"</td>\n"); exterFAdata.append("\t\t\t<td class='fileTd' align='right'>"+ faResult.getEqalWords(equivStr) +"</td>\n"); exterFAdata.append("\t\t\t<td class='fileTd' align='right'>"+ faResult.getLockedWords() +"</td>\n"); exterFAdata.append("\t\t\t<td class='fileTd' align='right'>"+ faResult.getTotalWords() +"</td>\n"); exterFAdata.append("\t\t</tr>\n"); } } } // 遍历所有含有分析文件的容器,找出当前容器的子容器, for (int index = 0; index < allFolderList.size(); index++) { IContainer childContainer = allFolderList.get(index); if (childContainer.getParent().equals(curContainer)) { WordsFAResult faResult = WordsFAResultMap.get(childContainer.getLocation().toOSString()); String folderId = childContainer.getFullPath().toOSString(); exterFAdata.append("<tr id='" + curContainer.getFullPath().toOSString() + "' name='allExter' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' ><a href='javascript:void(0)' id='" + folderId + "' name='allExter' class='link' style='padding-left: " + paddLeft + "'" + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)'>" + "<span id='" + folderId + "_span'>-</span> " + childContainer.getName() + "</a></td>\n" ); //创建外部匹配部份 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "folderTd"; if (QAConstant._External101.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getExterMatch("101") +"</td>\n"); }else if (QAConstant._External100.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getExterMatch("100") +"</td>\n"); // UNDO 这里的这个判断是否正确? }else if (!QAConstant._InternalRepeat.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getExterMatch(matchPair) +"</td>\n"); } } //创建内部匹配部 for (int i = 0; i < length; i++) { String matchPair = equivArray[i].substring(0, equivArray[i].indexOf(":") ); String className = "folderTd"; if (interRepeat && QAConstant._InternalRepeat.equals(matchPair)) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getInterMatch("100-101") +"</td>\n"); }else if (interMatch && matchPair.indexOf("external") == -1) { exterFAdata.append("\t\t\t<td class='" + className + "' align='right'>"+ faResult.getInterMatch(matchPair) +"</td>\n"); } } //创建新字数,锁定字数,新字数三列 exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ faResult.getNewWords() +"</td>\n"); exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ faResult.getEqalWords(equivStr) +"</td>\n"); exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ faResult.getLockedWords() +"</td>\n"); exterFAdata.append("\t\t\t<td class='folderTd' align='right'>"+ faResult.getTotalWords() +"</td>\n"); exterFAdata.append("</tr>\n"); allExterMatchSetInputData(childContainer, exterFAdata, paddLeft , equivArray); } } } /** * 创建第二张表的数据,关于文本段的统计 * @param curContainer * @param paraFAdata * @param paddLeft ; */ public void paraSetInputData(IContainer curContainer, StringBuffer paraFAdata, int paddLeft) { paddLeft += 10; // 先判断该容器中是否有直接子文件为本次分析文件 if (hasFAIFiles(curContainer)) { // 每个文件的具体数据 for (int fIndex = 0; fIndex < model.getAnalysisIFileList().size(); fIndex++) { IFile curIFile = model.getAnalysisIFileList().get(fIndex); if (curIFile.getParent().equals(curContainer)) { WordsFAResult faResult = WordsFAResultMap.get(curIFile.getLocation().toOSString()); paraFAdata.append("\t\t<tr id='" + curContainer.getFullPath().toOSString() + "' name='paras' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n"); paraFAdata.append("\t\t\t<td class='fileTd' style='padding-left: " + paddLeft + "'>" + curIFile.getName() + "</td>\n");// 文件名 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNewPara() + "</td>\n"); // 新文本段 if (interMatch) { paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getInterMatchPara() + "</td>\n"); // 内部匹配文本段 } paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getExterMatchPara() + "</td>\n"); // 外部匹配文本段 if (interRepeat) { paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getInterRepeatPara() + "</td>\n"); // 内部重复文本段 } paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getExterRepeatPara() + "</td>\n"); // 外部重复文本段 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getLockedPara() + "</td>\n"); // 锁定文本段 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTotalPara() + "</td>\n"); // 总段数 paraFAdata.append("\t\t</tr>\n"); } } } // 遍历所有含有分析文件的容器,找出当前容器的子容器, for (int index = 0; index < allFolderList.size(); index++) { IContainer childContainer = allFolderList.get(index); if (childContainer.getParent().equals(curContainer)) { WordsFAResult faResult = WordsFAResultMap.get(childContainer.getLocation().toOSString()); String folderId = childContainer.getFullPath().toOSString(); paraFAdata.append("<tr id='" + curContainer.getFullPath().toOSString() + "' name='paras' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' ><a href='javascript:void(0)' id='" + folderId + "' name='paras' class='link' style='padding-left: " + paddLeft + "'" + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)'>" + "<span id='" + folderId + "_span'>-</span> " + childContainer.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + faResult.getNewPara() + "</td>\n" + "<td class='folderTd' align='right'>" + (interMatch ? faResult.getInterMatchPara() + "</td>\n" + "<td class='folderTd' align='right'>" : "") + faResult.getExterMatchPara() + "</td>\n" + "<td class='folderTd' align='right'>" + (interRepeat ? faResult.getInterRepeatPara() + "</td>\n" + "<td class='folderTd' align='right'>" : "") + faResult.getExterRepeatPara() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getLockedPara() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTotalPara() + "</td>\n" + "</tr>\n"); paraSetInputData(childContainer, paraFAdata, paddLeft); } } } public static void main(String[] args) { String text = "this is a test string for test count time."; long time1 = System.currentTimeMillis(); int count = 0; for (int i = 0; i < 100000; i++) { count += CountWord.wordCount(text, "en-us"); } System.out.println("时间为 = " + (System.currentTimeMillis() - time1)); System.out.println("字数为 = " + count); } }
53,152
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
EditProgressFA.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/fileAnalysis/EditProgressFA.java
package net.heartsome.cat.ts.ui.qa.fileAnalysis; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.core.qa.FAModel; import net.heartsome.cat.ts.core.qa.FileAnalysis; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.model.EditProgressFAResult; import net.heartsome.cat.ts.ui.qa.resource.Messages; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 编辑进度分析 * @author robert 2011-12-14 */ public class EditProgressFA extends FileAnalysis { private FAModel model; /** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格 */ private static int workInterval = 4; /** 翻译进度分析结果,key为文件的绝对路径,值为已翻译文本段等值的pojo类 */ private Map<String, EditProgressFAResult> editProgFAResultMap; /** 所有包括分析文件的容器 */ private List<IContainer> allFolderList; public final static Logger logger = LoggerFactory.getLogger(EditProgressFA.class.getName()); @Override public int beginAnalysis(FAModel model, IProgressMonitor monitor, QAXmlHandler handler) { this.model = model; super.setModel(model); editProgFAResultMap = new HashMap<String, EditProgressFAResult>(); if (monitor == null) { monitor = new NullProgressMonitor(); } // 要分析的文件的所有 int allTUSize = model.getAllTuSize(); int traversalTuIndex = 0; int totalWork = allTUSize % workInterval == 0 ? (allTUSize / workInterval) : (allTUSize / workInterval) + 1; monitor.beginTask("", totalWork); for (int index = 0; index < model.getAnalysisIFileList().size(); index++) { IFile iFile = model.getAnalysisIFileList().get(index); monitor.setTaskName(MessageFormat.format(Messages.getString("qa.fileAnalysis.EditProgressFA.tip1"), iFile .getFullPath().toOSString())); String iFilePath = iFile.getLocation().toOSString(); // 获取单个文件的翻译进度的数据 Map<String, Integer> editProgMap = handler.getEditProgressData(iFilePath, monitor, workInterval, traversalTuIndex); // 如果获取的结果为null,则表示用户退出程序 if (editProgMap == null) { return QAConstant.QA_ZERO; } traversalTuIndex += handler.getTuSizeMap().get(iFilePath); int notApprovedParas = editProgMap.get("notApprovedParas"); int approvedParas = editProgMap.get("approvedParas"); int lockedParas = editProgMap.get("lockedParas"); int notApprovedWords = editProgMap.get("notApprovedWords"); int approvedWords = editProgMap.get("approvedWords"); int lockedWords = editProgMap.get("lockedWords"); EditProgressFAResult editResult = new EditProgressFAResult( notApprovedParas, approvedParas, lockedParas, notApprovedWords, approvedWords, lockedWords); editProgFAResultMap.put(iFilePath, editResult); } if (!handler.monitorWork(monitor, traversalTuIndex, workInterval, true)) { return QAConstant.QA_ZERO; } // 开始填充数据 printTransProgFAReslut(); return QAConstant.QA_ZERO; } public void printTransProgFAReslut() { String htmlPath = createFAResultHtml(); try { model.getAnalysisIFileList().get(0).getProject().getFolder("Intermediate").getFolder("Report").refreshLocal(IResource.DEPTH_ONE, null); } catch (CoreException e1) { e1.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.EditProgressFA.log1"), e1); } final FileEditorInput input = new FileEditorInput(ResourceUtils.fileToIFile(htmlPath)); Display.getDefault().asyncExec(new Runnable() { public void run() { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(input, QAConstant.FA_HtmlBrowserEditor, true); } catch (PartInitException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.EditProgressFA.log2"), e); } } }); } public String createFAResultHtml() { allFolderList = new LinkedList<IContainer>(); Date createDate = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String createTime = formatter.format(createDate); formatter = new SimpleDateFormat("yyyyMMdd-HHmmss"); String htmlNameTime = formatter.format(createDate); IProject curProject = model.getAnalysisIFileList().get(0).getProject(); String htmlName = "EDLog" + htmlNameTime + ".html"; String htmlPath = curProject.getLocation().append("Intermediate").append("Report").append(htmlName).toOSString(); File htmlFile = new File(htmlPath); if (!htmlFile.getParentFile().exists()) { htmlFile.getParentFile().mkdirs(); } FileOutputStream output; try { output = new FileOutputStream(htmlPath); output.write(QAConstant.FA_HtmlDoctype.getBytes("UTF-8")); output.write("<html>\n".getBytes("UTF-8")); String headerNode = QAConstant.FA_htmlHeader; headerNode = headerNode.replace("###Title###", Messages.getString("qa.fileAnalysis.EditProgressFA.tip2")); output.write(headerNode.getBytes("UTF-8")); output.write("\t<body>\n".getBytes("UTF-8")); output.write(("<p class=\"title\">" + Messages.getString("qa.fileAnalysis.EditProgressFA.name1") + "</p>") .getBytes("UTF-8")); // ----------------<<<<<<start-- 下面是相关信息提示部份--------------------- output.write("\t<div>\n".getBytes("UTF-8")); output.write("\t\t<table class=\"infoTableStyle\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n".getBytes("UTF-8")); // 分析文件总数 String title = Messages.getString("qa.fa.info.fileSum"); String content = "" + model.getSubFileNum(); String infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", content); output.write(infoStr.getBytes("UTF-8")); // 分析失败文件 title = Messages.getString("qa.fa.info.errorFiles"); StringBuffer errorFileSB = new StringBuffer(); errorFileSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); errorFileSB.append(model.getErrorIFileList().size()); errorFileSB.append("</div>"); for(IFile iFile : model.getErrorIFileList()){ errorFileSB.append("\t\t\t<div style=\"margin-bottom: 2px;\">"); errorFileSB.append(iFile.getFullPath().toOSString()); errorFileSB.append("</div>"); } infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", errorFileSB.toString()); output.write(infoStr.getBytes("UTF-8")); // 报告生成时间 title = Messages.getString("qa.fa.info.createTime"); infoStr = QAConstant.FA_Report_Info.replace("###Title###", title).replace("###Content###", createTime); output.write(infoStr.getBytes("UTF-8")); output.write("</table></div><br>\n".getBytes("UTF-8")); // ---------------->>>>>>end-- 报表信息提示部分结束--------------------- // --------------字数--------------------- output.write(("\t\t<div class=\"legendStyle\"><b>" + Messages.getString("qa.fileAnalysis.EditProgressFA.words") + "</b></div>").getBytes("UTF-8")); StringBuffer wordsFAdata = new StringBuffer(); getAllFolder(curProject, allFolderList); setDataToFolder(curProject); // 创建一个表 wordsFAdata.append("\t<table class='tableStyle' cellpadding='0' cellspacing='1'> \n"); // 表头 wordsFAdata.append("\t\t<tr>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='22%'>" + Messages.getString("qa.all.fa.fileName") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.nonApprove") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approved") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.lockWordsNum") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.wordsSum") + "</td>\n"); wordsFAdata.append("\t\t</tr>\n"); wordsFAdata.append("\t\t<tr>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveWords") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveProp") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveWords") + "</td>\n"); wordsFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveProp") + "</td>\n"); wordsFAdata.append("\t\t</tr>\n"); // 首先写下项目 EditProgressFAResult proFaResult = editProgFAResultMap.get(curProject.getLocation().toOSString()); int paddLeft = 6; String folderId = curProject.getFullPath().toOSString(); wordsFAdata.append("<tr onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' style='padding-left: 6'>\n" + "<a href='javascript:void(0)' id='" + folderId + "' name='words' class='link' " + "title='"+Messages.getString("qa.all.fa.clickToShrink")+"' onclick='clickFolder(id, name)' >" + "<span id='" + folderId + "_span'>-</span> " + curProject.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotApprovedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotApprovedWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getApprovedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getApprovedWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getLockedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTotalWords() + "</td>\n" + "</tr>\n"); wordsSetInputData(curProject, wordsFAdata, paddLeft); wordsFAdata.append("\t</table>\n"); output.write(wordsFAdata.toString().getBytes("UTF-8")); output.write("<br/>\n".getBytes("UTF-8")); // --------------文本段--------------------- output.write(("\t\t<div class=\"legendStyle\"><b>" + Messages.getString("qa.fileAnalysis.EditProgressFA.paragraph") +"</b></div>").getBytes("UTF-8")); StringBuffer paraFAdata = new StringBuffer(); // 创建一个表 paraFAdata.append("\t<table class='tableStyle' cellpadding='0' cellspacing='1'> \n"); // 表头 paraFAdata.append("\t\t<tr>\n"); paraFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='22%'>" + Messages.getString("qa.all.fa.fileName") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.nonApprove") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' colSpan='2' width='26%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approved") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.lockParasNum") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' rowSpan='2' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.paraSum") + "</td>\n"); paraFAdata.append("\t\t</tr>\n"); paraFAdata.append("\t\t<tr>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveParaNum") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveProp") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveParaNum") + "</td>\n"); paraFAdata.append("\t\t\t<td class='headerTd' width='13%'>" + Messages.getString("qa.fileAnalysis.EditProgressFA.approveProp") + "</td>\n"); paraFAdata.append("\t\t</tr>\n"); // 首先写下项目 paddLeft = 6; paraFAdata.append("<tr onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' style='padding-left: 6'>\n" + "<a href='javascript:void(0)' id='" + folderId + "' name='paras' class='link' title='"+Messages.getString("qa.all.fa.clickToShrink")+"' " + " onclick='clickFolder(id, name)'><span id='" + folderId + "_span'>-</span> " + curProject.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotApprovedParas() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getNotApprovedParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getApprovedParas() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getApprovedParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getLockedParas() + "</td>\n" + "<td class='folderTd' align='right'>" + proFaResult.getTotalParas() + "</td>\n" + "</tr>"); paraSetInputData(curProject, paraFAdata, paddLeft); paraFAdata.append("\t</table>\n"); output.write(paraFAdata.toString().getBytes("UTF-8")); /*String htmlPathDiv = "<div style='width:100%;font-size:14;color:blue;'>"+Messages.getString("qa.all.fa.fileLocation") + curProject.getFullPath().append("Report").append(htmlName).toOSString() + "</div>"; output.write(htmlPathDiv.getBytes("UTF-8"));*/ // -----------文本段结束-------------- output.write("\t</body>\n".getBytes("UTF-8")); output.write("</html>".getBytes("UTF-8")); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.EditProgressFA.log3"), e); } catch (UnsupportedEncodingException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.EditProgressFA.log4"), e); } catch (IOException e) { e.printStackTrace(); logger.error(Messages.getString("qa.fileAnalysis.EditProgressFA.log5"), e); } return htmlPath; } /** * 将文件下所有的子文件(直接或间接子文件)的值加到文件夹中 */ public void setDataToFolder(IProject curProject) { // 先存放项目相关的信息,所有的文件都存放在该项目中的,因此直接遍历所有的文件 EditProgressFAResult proFaResult = new EditProgressFAResult(); for (int i = 0; i < model.getAnalysisIFileList().size(); i++) { IFile ifile = model.getAnalysisIFileList().get(i); EditProgressFAResult faResult = editProgFAResultMap.get(ifile.getLocation().toOSString()); proFaResult.setNotApprovedParas(faResult.getNotApprovedParas()); proFaResult.setApprovedParas(faResult.getApprovedParas()); proFaResult.setLockedParas(faResult.getLockedParas()); proFaResult.setNotApprovedWords(faResult.getNotApprovedWords()); proFaResult.setApprovedWords(faResult.getApprovedWords()); proFaResult.setLockedWords(faResult.getLockedWords()); } editProgFAResultMap.put(curProject.getLocation().toOSString(), proFaResult); // 先遍历所有的文件夹 for (int index = 0; index < allFolderList.size(); index++) { IContainer container = allFolderList.get(index); EditProgressFAResult folderFaResult = new EditProgressFAResult(); // 循环所有的已经分析完的文件 for (int i = 0; i < model.getAnalysisIFileList().size(); i++) { IFile ifile = model.getAnalysisIFileList().get(i); IContainer iFileParent = ifile.getParent(); while (iFileParent != null) { if (iFileParent.equals(container)) { EditProgressFAResult faResult = editProgFAResultMap.get(ifile.getLocation().toOSString()); folderFaResult.setNotApprovedParas(faResult.getNotApprovedParas()); folderFaResult.setApprovedParas(faResult.getApprovedParas()); folderFaResult.setLockedParas(faResult.getLockedParas()); folderFaResult.setNotApprovedWords(faResult.getNotApprovedWords()); folderFaResult.setApprovedWords(faResult.getApprovedWords()); folderFaResult.setLockedWords(faResult.getLockedWords()); break; } else { iFileParent = iFileParent.getParent(); } } } editProgFAResultMap.put(container.getLocation().toOSString(), folderFaResult); } } /** * 向字数分析的字数展示模块填充数据 * @param curContainer * @param wordsFAdata */ public void wordsSetInputData(IContainer curContainer, StringBuffer wordsFAdata, int paddLeft) { paddLeft += 10; // 先判断该容器中是否有直接子文件为本次分析文件 if (hasFAIFiles(curContainer)) { // 每个文件的具体数据 for (int fIndex = 0; fIndex < model.getAnalysisIFileList().size(); fIndex++) { IFile curIFile = model.getAnalysisIFileList().get(fIndex); if (curIFile.getParent().equals(curContainer)) { EditProgressFAResult faResult = editProgFAResultMap.get(curIFile.getLocation().toOSString()); wordsFAdata.append("\t\t<tr id='" + curContainer.getFullPath().toOSString() + "' name='words' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n"); wordsFAdata.append("\t\t\t<td class='fileTd' style='padding-left: " + paddLeft + "'>" + curIFile.getName() + "</td>\n");// 文件名 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotApprovedWords() + "</td>\n"); // 未批准字数 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotApprovedWordsRatio() + "</td>\n"); // 未批准字数比例 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getApprovedWords() + "</td>\n"); // 已批准字数 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getApprovedWordsRatio() + "</td>\n"); // 已批准字数比例 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getLockedWords() + "</td>\n"); // 锁定字数 wordsFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTotalWords() + "</td>\n"); // 总字数 wordsFAdata.append("\t\t</tr>\n"); } } } // 遍历所有含有分析文件的容器,找出当前容器的子容器, for (int index = 0; index < allFolderList.size(); index++) { IContainer childContainer = allFolderList.get(index); if (childContainer.getParent().equals(curContainer)) { EditProgressFAResult faResult = editProgFAResultMap.get(childContainer.getLocation().toOSString()); String folderId = childContainer.getFullPath().toOSString(); wordsFAdata.append("<tr id='" + curContainer.getFullPath().toOSString() + "' name='words' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' ><a href='javascript:void(0)' id='" + folderId + "' name='words' class='link' style='padding-left: " + paddLeft + "'" + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)'>" + "<span id='" + folderId + "_span'>-</span> " + childContainer.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotApprovedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotApprovedWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getApprovedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getApprovedWordsRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getLockedWords() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getTotalWords() + "</td>\n" + "</tr>\n"); wordsSetInputData(childContainer, wordsFAdata, paddLeft); } } } public void paraSetInputData(IContainer curContainer, StringBuffer paraFAdata, int paddLeft) { paddLeft += 10; // 先判断该容器中是否有直接子文件为本次分析文件 if (hasFAIFiles(curContainer)) { // 每个文件的具体数据 for (int fIndex = 0; fIndex < model.getAnalysisIFileList().size(); fIndex++) { IFile curIFile = model.getAnalysisIFileList().get(fIndex); if (curIFile.getParent().equals(curContainer)) { EditProgressFAResult faResult = editProgFAResultMap.get(curIFile.getLocation().toOSString()); paraFAdata.append("\t\t<tr id='" + curContainer.getFullPath().toOSString() + "' name='paras' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n"); paraFAdata.append("\t\t\t<td class='fileTd' style='padding-left: " + paddLeft + "'>" + curIFile.getName() + "</td>\n");// 文件名 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotApprovedParas() + "</td>\n"); // 未批准文本段个数 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getNotApprovedParasRatio() + "</td>\n"); // 未批准文本段比例 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getApprovedParas() + "</td>\n"); // 已批准文本段个数 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getApprovedParasRatio() + "</td>\n"); // 已批准文本段比例 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getLockedParas() + "</td>\n"); // 锁定文本段 paraFAdata.append("\t\t\t<td class='fileTd' align='right'>" + faResult.getTotalParas() + "</td>\n"); // 总段数 paraFAdata.append("\t\t</tr>\n"); } } } // 遍历所有含有分析文件的容器,找出当前容器的子容器, for (int index = 0; index < allFolderList.size(); index++) { IContainer childContainer = allFolderList.get(index); if (childContainer.getParent().equals(curContainer)) { EditProgressFAResult faResult = editProgFAResultMap.get(childContainer.getLocation().toOSString()); String folderId = childContainer.getFullPath().toOSString(); paraFAdata.append("<tr id='" + curContainer.getFullPath().toOSString() + "' name='paras' " + "onmouseover= \"this.bgColor= '#F1F1FC'\" onmouseout= \"this.bgColor='#FFFFFF'\" bgcolor='#FFFFFF'>\n" + "<td class='folderTd' ><a href='javascript:void(0)' id='" + folderId + "' name='paras' class='link' style='padding-left: " + paddLeft + "'" + "title='" + Messages.getString("qa.all.fa.clickToShrink") + "' onclick='clickFolder(id, name)'>" + "<span id='" + folderId + "_span'>-</span> " + childContainer.getName() + "</a></td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotApprovedParas() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getNotApprovedParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getApprovedParas() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getApprovedParasRatio() + "</td>\n" + "<td class='folderTd' align='right'>" + faResult.getLockedParas() + "</td>\n" + "<td class='folderTd' align='right'>"+ faResult.getTotalParas() + "</td>\n" + "</tr>\n"); paraSetInputData(childContainer, paraFAdata, paddLeft); } } } }
24,443
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
NumberOrTagConsisQAHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/handlers/NumberOrTagConsisQAHandler.java
package net.heartsome.cat.ts.ui.qa.handlers; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.common.resources.ResourceUtils; 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.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QATUDataBean; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.NumberConsistenceQA; import net.heartsome.cat.ts.ui.qa.TagConsistenceQA; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.qa.views.QAResultViewPart; 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 net.heartsome.cat.ts.util.ProgressIndicatorManager; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.part.FileEditorInput; /** * 字数分析与标记一致性检查的触发类 * @author robert 2012-06-04 */ public class NumberOrTagConsisQAHandler extends AbstractHandler { /** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格 */ private int workInterval = 1; private QAXmlHandler xmlHandler; private String _INFO = Messages.getString("qa.all.dialog.info"); private String _ERROR = Messages.getString("qa.all.dialog.error"); @SuppressWarnings("unused") private Shell shell; /** 连接符号,用于连接源语言和目标语言的种类,例如“zh-CN -&gt; en” ,这个要与nattable界面上的过滤条件保持一致 */ private static final String Hyphen = " -> "; public Object execute(ExecutionEvent event) throws ExecutionException { boolean isMultiFile = false; IFile multiTempIFile = null; IEditorPart editorPart = HandlerUtil.getActiveEditor(event); // 改为布局 if (editorPart != null && editorPart instanceof XLIFFEditorImplWithNatTable) { String qaItem = event.getParameter("qaItemId"); XLIFFEditorImplWithNatTable nattable = (XLIFFEditorImplWithNatTable) editorPart; ArrayList<IFile> selectIFiles = new ArrayList<IFile>(); FileEditorInput input = (FileEditorInput) nattable.getEditorInput(); // 首先判断是否是合并打开的文件 if (nattable.isMultiFile()) { isMultiFile = true; } if (isMultiFile) { multiTempIFile = input.getFile(); List<String> multiFilesList = new XLFHandler().getMultiFiles(multiTempIFile); for (String filePath : multiFilesList) { selectIFiles.add(ResourceUtils.fileToIFile(filePath)); } } else { selectIFiles.add(input.getFile()); } QAModel model = new QAModel(); IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); shell = window.getShell(); // 先调用方法,查看品质检查结果视图是否处于显示状态,如果是显示的,就删除数据 IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IViewPart view = workbenchPage.findView(QAResultViewPart.ID); if (view != null) { // 运行时,将结果视图中列表的数据清除 ((QAResultViewPart) view).clearTableData(); } QAResult qaResult = new QAResult(); // 存储品质检查的检查项 // model.setBatchQAItemIdList(getBatchQAItems()); // 存储品质检查的检查时不包括的文本段 model.setNotInclude(getNotIncludePara()); // 给品质检查结果视图发出通告,本次检查对象为合并打开文件 qaResult.firePropertyChange(isMultiFile, new MultiFilesOper(selectIFiles.get(0).getProject(), selectIFiles, multiTempIFile)); if (isMultiFile) { model.setMuliFiles(true); model.setMultiOper(new MultiFilesOper(selectIFiles.get(0).getProject(), selectIFiles,multiTempIFile)); } else { model.setMuliFiles(false); } boolean isNumberQA = false; if (QAConstant.QA_NUMBER.equals(qaItem)) { isNumberQA = true; } else if (QAConstant.QA_TAG.equals(qaItem)) { isNumberQA = false; } List<String> fileList = new ArrayList<String>(); for(IFile iFIle : selectIFiles){ fileList.add(iFIle.getLocation().toOSString()); } qaResult.setFilePathList(fileList); HsMultiActiveCellEditor.commit(true); beginQA(selectIFiles, model, isNumberQA, qaResult); } return null; } private void beginQA(final ArrayList<IFile> selectIFiles, final QAModel model, final boolean isNumberQA, final QAResult qaResult) { final String titile = isNumberQA ? Messages.getString("qa.NumberOrTagConsisQAHandler.jobTitle1") : Messages .getString("qa.NumberOrTagConsisQAHandler.jobTitle2"); Job job = new Job(titile) { @Override protected IStatus run(IProgressMonitor monitor) { // 解析一格,其余九格 monitor.beginTask(titile, 10 * selectIFiles.size()); xmlHandler = new QAXmlHandler(); // 首先解析文件,如果为false,则退出 if (!openFile(selectIFiles, monitor)) { return Status.OK_STATUS; } int allTUSize = 0; for (IFile iFile : selectIFiles) { allTUSize += xmlHandler.getTuSizeMap().get(iFile.getLocation().toOSString()); } initWorkInterval(allTUSize); // 开始进行数据处理 IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); subMonitor.beginTask(titile + "...", allTUSize % workInterval == 0 ? (allTUSize / workInterval) : (allTUSize / workInterval) + 1); Map<String, ArrayList<String>> languageList = xmlHandler.getLanguages(); int lineNumber = 0; int traversalTuIndex = 0; IFile iFile; for (Entry<String, ArrayList<String>> langEntry : languageList.entrySet()) { String srcLang = langEntry.getKey(); for (String tgtLang : langEntry.getValue()) { List<String> rowIdsList = xmlHandler.getAllRowIdsByLanguages(srcLang.toUpperCase(), tgtLang.toUpperCase()); model.setRowIdsList(rowIdsList); // 开始针对每一个文本段进行检查 for (String rowId : rowIdsList) { traversalTuIndex++; lineNumber = rowIdsList.indexOf(rowId) + 1; // 行号 String filePath = RowIdUtil.getFileNameByRowId(rowId); iFile = ResourceUtils.fileToIFile(filePath); String langPair = srcLang + Hyphen + tgtLang; QATUDataBean tuDataBean = xmlHandler.getFilteredTUText(filePath, RowIdUtil.parseRowIdToXPath(rowId), model.getNotInclude()); if (tuDataBean == null) { if (!xmlHandler.monitorWork(subMonitor, traversalTuIndex, workInterval, false)) { return Status.CANCEL_STATUS; } continue; } if (!tuDataBean.isPassFilter()) { if (!xmlHandler.monitorWork(subMonitor, traversalTuIndex, workInterval, false)) { return Status.CANCEL_STATUS; } continue; } else if (tuDataBean.getTgtContent() == null || "".equals(tuDataBean.getTgtContent())) { // 正常情况下应有四个值 // 因为文本段完整性检查要判断译文是否为空的情况,所以,如果译文为空,只有文本段完整性要进行检查,其他检查项都跳过。 continue; } tuDataBean.setLineNumber(lineNumber + ""); tuDataBean.setFileName(iFile.getName()); tuDataBean.setSrcLang(srcLang); tuDataBean.setTgtLang(tgtLang); if (isNumberQA) { NumberConsistenceQA numberQA = new NumberConsistenceQA(); qaResult.setMultiOper(model.getMultiOper()); numberQA.setQaResult(qaResult); numberQA.startQA(model, subMonitor, iFile, xmlHandler, tuDataBean); } else { TagConsistenceQA tagQA = new TagConsistenceQA(); qaResult.setMultiOper(model.getMultiOper()); tagQA.setQaResult(qaResult); tagQA.startQA(model, subMonitor, iFile, xmlHandler, tuDataBean); } qaResult.sendDataToViewer(null); if (!xmlHandler.monitorWork(subMonitor, traversalTuIndex, workInterval, false)) { return Status.CANCEL_STATUS; } } } if (!xmlHandler.monitorWork(subMonitor, traversalTuIndex, workInterval, false)) { return Status.CANCEL_STATUS; } } qaResult.informQAEndFlag(); subMonitor.done(); monitor.done(); return Status.OK_STATUS; } }; // 当程序退出时,检测当前 job 是否正常关闭 CommonFunction.jobCantCancelTip(job); job.addJobChangeListener(new JobChangeAdapter(){ @Override public void running(IJobChangeEvent event) { ProgressIndicatorManager.displayProgressIndicator(); super.running(event); } @Override public void done(IJobChangeEvent event) { ProgressIndicatorManager.hideProgressIndicator(); super.done(event); } }); job.setUser(true); job.schedule(); } /** * 解析文件 * @param selectIFiles */ private boolean openFile(ArrayList<IFile> selectIFiles, IProgressMonitor monitor) { for (final IFile iFile : selectIFiles) { IProgressMonitor openMonitor = new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); Map<String, Object> newResultMap = xmlHandler.openFile(iFile.getLocation().toOSString(), openMonitor); // 针对退出解析 if (newResultMap != null && QAConstant.RETURNVALUE_RESULT_RETURN.equals(newResultMap.get(QAConstant.RETURNVALUE_RESULT))) { return false; } if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap .get(QAConstant.RETURNVALUE_RESULT)) { return false; } } return true; } /** * 获取首选项中品质检查的不包括的文本段 * @return */ public Map<String, Boolean> getNotIncludePara() { IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); Map<String, Boolean> notInclude = new HashMap<String, Boolean>(); // 不包括上下文匹配 notInclude.put(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE)); // 不包括完成匹配 notInclude.put(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE)); // 不包括已锁文本段 notInclude.put(QAConstant.QA_PREF_LOCKED_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_LOCKED_NOTINCLUDE)); return notInclude; } /** * 初始化进度条前进前隔值,使之总值不大于五百。 */ private int initWorkInterval(int allTUSize) { if (allTUSize > 500) { workInterval = allTUSize / 500; } return allTUSize; } public static void main(String[] args) { System.out.println(System.getProperty("user.name")); } }
11,858
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FileAnalysisHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/handlers/FileAnalysisHandler.java
package net.heartsome.cat.ts.ui.qa.handlers; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import net.heartsome.cat.common.file.XLFValidator; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.core.qa.FAModel; import net.heartsome.cat.ts.core.qa.FileAnalysis; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.dialogs.FileAnalysisDialog; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import net.heartsome.cat.ts.util.ProgressIndicatorManager; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 文件分析子菜单下的字数分析的handler。 * @author robert 2011-12-07 */ public class FileAnalysisHandler extends AbstractHandler { private FAModel model; private Shell shell; /** 解析出错时是否继续执行,0为继续,1为出错时继续执行,2为出错时退出执行 */ private int continuResponse; /** 文件分析项(字数分析,翻译进度分析,编辑进度分析) */ private String faItemId; /** 文件分析项的名称 */ private String title; private int allTUSize; /** 针对选择当前 nattable 编辑器是否合并打开 */ private boolean isMultiFile; public final static Logger logger = LoggerFactory.getLogger(FileAnalysisHandler.class.getName()); public Object execute(ExecutionEvent event) throws ExecutionException { model = new FAModel(); faItemId = event.getParameter("faItemId"); allTUSize = 0; IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); shell = window.getShell(); IFile multiTempIFile = null; IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .findView("net.heartsome.cat.common.ui.navigator.view"); ArrayList<IFile> selectIFiles = new ArrayList<IFile>(); if (HandlerUtil.getActivePart(event) instanceof IViewPart) { ISelection currentSelection = (StructuredSelection) viewPart.getSite().getSelectionProvider() .getSelection(); if (currentSelection != null && !currentSelection.isEmpty() && currentSelection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) currentSelection; @SuppressWarnings("unchecked") Iterator<Object> selectIt = structuredSelection.iterator(); while (selectIt.hasNext()) { Object object = selectIt.next(); if (object instanceof IFile) { IFile selectFile = (IFile) object; String fileExtension = selectFile.getFileExtension(); // 如果后缀名不是xlf,那么就进行提示 if (fileExtension == null || !CommonFunction.validXlfExtension(fileExtension)) { boolean isSure = MessageDialog.openConfirm(shell, Messages .getString("qa.all.dialog.warning"), MessageFormat.format( Messages.getString("qa.all.tip.notXliff"), new Object[] { selectFile.getFullPath() })); if (!isSure) { return null; } } selectIFiles.add(selectFile); } else if (object instanceof IContainer) { IContainer selectContainer = (IContainer) object; try { ResourceUtils.getXliffs(selectContainer, selectIFiles); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.handlers.FileAnalysisHandler.log1"), e); } } } } } else if (HandlerUtil.getActivePart(event) instanceof IEditorPart) { // 如果左边未选择品质检查的类型,那么,获取nattable中打开的文件 IEditorPart activeEditor = HandlerUtil.getActiveEditor(event); String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; if (activeEditor != null && !activeEditor.getSite().getId().equals(XLIFF_EDITOR_ID)) { MessageDialog.openWarning(shell, Messages.getString("qa.all.dialog.warning"), Messages.getString("qa.handlers.BatchQAHandler.tip2")); return null; } XLIFFEditorImplWithNatTable nattable = (XLIFFEditorImplWithNatTable) activeEditor; isMultiFile = nattable.isMultiFile(); multiTempIFile = ((FileEditorInput) nattable.getEditorInput()).getFile(); if (isMultiFile) { List<String> multiFilesList = new XLFHandler().getMultiFiles(multiTempIFile); for (String multiFileStr : multiFilesList) { selectIFiles.add(ResourceUtils.fileToIFile(multiFileStr)); } } else { selectIFiles.add(multiTempIFile); } } else { MessageDialog.openWarning(shell, Messages.getString("qa.all.dialog.warning"), Messages.getString("qa.handlers.FileAnalysisHandler.tip3")); return null; } CommonFunction.removeRepeateSelect(selectIFiles); if (selectIFiles.size() <= 0) { MessageDialog.openWarning(shell, Messages.getString("qa.all.dialog.warning"), Messages.getString("qa.handlers.FileAnalysisHandler.tip1")); return null; } List<IFile> lstFiles = new ArrayList<IFile>(); XLFValidator.resetFlag(); for (IFile iFile : selectIFiles) { if (!XLFValidator.validateXliffFile(iFile)) { lstFiles.add(iFile); } } XLFValidator.resetFlag(); selectIFiles.removeAll(lstFiles); if (selectIFiles.size() == 0) { return null; } // 判断要分析的文件是否是属于同一个项目中的. IProject project = selectIFiles.get(0).getProject(); if (selectIFiles.size() >= 2) { for (int i = 1; i < selectIFiles.size(); i++) { if (selectIFiles.get(i).getProject() != project) { MessageDialog.openWarning(shell, Messages.getString("qa.all.dialog.warning"), Messages.getString("qa.handlers.FileAnalysisHandler.tip2")); return null; } } } model.setAnalysisIFileList(selectIFiles); model.setShell(shell); model.setMultiFile(isMultiFile); if (isMultiFile) { model.setMultiTempIFile(multiTempIFile); } // 文件分析框的框名 title = model.getAnalysisItemMap().get(faItemId).get(QAConstant.FA_ITEM_NAME); FileAnalysisDialog dialog = new FileAnalysisDialog(shell, model, title, faItemId); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { analysisFile(title); } return null; } /** * 准备分析文件 */ public void analysisFile(String title) { final QAXmlHandler handler = new QAXmlHandler(); Job job = new Job(title) { @Override protected IStatus run(IProgressMonitor monitor) { // 要分析的文件的个数 int fileNum = model.getAnalysisIFileList().size(); model.setSubFileNum(fileNum); // 定义的进度条总共四格,其中,解析文件一格,分析文件三格 monitor.beginTask("", fileNum * 4); // 解析文件,如果解析不成功,退出程序, 解析要分析的文件,用掉fileNum*1个格子 if (!openXliff(handler, monitor)) { monitor.done(); return Status.CANCEL_STATUS; } if (model.getAnalysisIFileList().size() == 0) { MessageDialog.openInformation(shell, Messages.getString("qa.all.dialog.info"), Messages.getString("qa.handlers.FileAnalysisHandler.tip4")); return Status.CANCEL_STATUS; } // 填充要分析文件的所有trans-unit节点个数的总和 model.setAllTuSize(allTUSize); FileAnalysis fileAnalysis = getClassInstance(faItemId); // 分析文件用去fileNum*3个格子 IProgressMonitor subMonitor = new SubProgressMonitor(monitor, fileNum * 3, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); int analysisResult = fileAnalysis.beginAnalysis(model, subMonitor, handler); if (analysisResult == -1 || analysisResult == QAConstant.QA_ZERO) { return Status.CANCEL_STATUS; } subMonitor.done(); monitor.done(); return Status.OK_STATUS; } }; // 当程序退出时,检测当前 job 是否正常关闭 CommonFunction.jobCantCancelTip(job); job.addJobChangeListener(new JobChangeAdapter(){ @Override public void running(IJobChangeEvent event) { ProgressIndicatorManager.displayProgressIndicator(); super.running(event); } @Override public void done(IJobChangeEvent event) { ProgressIndicatorManager.hideProgressIndicator(); super.done(event); } }); job.setUser(true); job.schedule(); } /** * 解析所有的xliff文件 * @param handler * @param monitor * @return */ public boolean openXliff(QAXmlHandler handler, IProgressMonitor monitor) { for (int fileIndex = 0; fileIndex < model.getAnalysisIFileList().size(); fileIndex++) { IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); final IFile iFile = model.getAnalysisIFileList().get(fileIndex); subMonitor.setTaskName(MessageFormat.format(Messages.getString("qa.handlers.FileAnalysisHandler.tip5"), new Object[] { title, iFile.getFullPath().toString() })); continuResponse = QAConstant.QA_ZERO; try { Map<String, Object> newResultMap = handler.openFile(iFile.getLocation().toOSString(), subMonitor); // 针对退出解析 if (newResultMap != null && QAConstant.RETURNVALUE_RESULT_RETURN.equals(newResultMap.get(QAConstant.RETURNVALUE_RESULT))) { return false; } if (newResultMap == null || QAConstant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap .get(QAConstant.RETURNVALUE_RESULT)) { model.getErrorIFileList().add(iFile); // 针对文件解析出错 Display.getDefault().syncExec(new Runnable() { public void run() { boolean response = MessageDialog.openConfirm(shell, Messages .getString("qa.all.dialog.error"), MessageFormat.format(Messages .getString("qa.all.tip.openXliffError"), new Object[] { iFile.getFullPath() .toOSString() })); if (response) { continuResponse = QAConstant.QA_FIRST; } else { continuResponse = QAConstant.QA_TWO; } } }); } if (continuResponse == QAConstant.QA_FIRST) { model.getAnalysisIFileList().remove(fileIndex); fileIndex--; continue; } else if (continuResponse == QAConstant.QA_TWO) { return false; } allTUSize += handler.getTuSizeMap().get(iFile.getLocation().toOSString()); } catch (Exception e) { MessageDialog.openError(shell, Messages.getString("qa.all.dialog.info"), Messages.getString("qa.all.log.openXmlError") + e); logger.error(Messages.getString("qa.all.log.openXmlError"), e); return false; } } return true; } /** * 获取某个检查项实现类的实例 * @param faItemId * 文件分析项,即字数分析,翻译进度分析,编辑进度分析 * @return */ public FileAnalysis getClassInstance(String faItemId) { try { Map<String, String> valueMap = model.getAnalysisItemMap().get(faItemId); Object obj = null; try { obj = Class.forName(valueMap.get(QAConstant.FA_ITEM_CLASSNAME)).newInstance(); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.handlers.FileAnalysisHandler.log2"), e); } if (FileAnalysis.class.isInstance(obj)) { return (FileAnalysis) obj; } } catch (Exception e) { MessageDialog.openError(shell, Messages.getString("qa.all.dialog.info"), Messages.getString("qa.handlers.FileAnalysisHandler.tip6") + e); logger.error(Messages.getString("qa.handlers.FileAnalysisHandler.tip6"), e); } return null; } }
12,826
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
BatchQAHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/handlers/BatchQAHandler.java
package net.heartsome.cat.ts.ui.qa.handlers; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.heartsome.cat.common.file.XLFValidator; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.QualityAssurance; import net.heartsome.cat.ts.ui.qa.dialogs.BatchQADialog; import net.heartsome.cat.ts.ui.qa.model.QAModel; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.qa.views.QAResultViewPart; 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.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.part.FileEditorInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 批量检查的handler * @author robert 2011-11-09 */ public class BatchQAHandler extends AbstractHandler { private QualityAssurance quality; private IPreferenceStore preferenceStore; private QAModel model; /** 针对选择当前 nattable 编辑器是否合并打开 */ private boolean isMultiFile; public final static Logger logger = LoggerFactory.getLogger(BatchQAHandler.class.getName()); @SuppressWarnings("unchecked") public Object execute(ExecutionEvent event) throws ExecutionException { isMultiFile = false; preferenceStore = Activator.getDefault().getPreferenceStore(); // UNDO 如果焦点在其他视图上时,获取的文件错误。 IFile multiTempIFile = null; IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); final Shell shell = window.getShell(); // ISelection currentSelection = HandlerUtil.getCurrentSelection(event); IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .findView("net.heartsome.cat.common.ui.navigator.view"); ArrayList<IFile> selectIFiles = new ArrayList<IFile>(); if (HandlerUtil.getActivePart(event) instanceof IViewPart) { ISelection currentSelection = (StructuredSelection) viewPart.getSite().getSelectionProvider().getSelection(); if (currentSelection != null && !currentSelection.isEmpty() && currentSelection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) currentSelection; Iterator<Object> selectIt = structuredSelection.iterator(); while (selectIt.hasNext()) { Object object = selectIt.next(); if (object instanceof IFile) { IFile selectFile = (IFile) object; String fileExtension = selectFile.getFileExtension(); // 如果后缀名不是xlf,那么就进行提示 if (fileExtension == null || !CommonFunction.validXlfExtension(fileExtension)) { boolean isSure = MessageDialog.openConfirm(shell, Messages.getString("qa.all.dialog.warning"), MessageFormat.format(Messages.getString("qa.all.tip.notXliff"), new Object[] { selectFile.getFullPath() })); if (!isSure) { return null; } continue; } selectIFiles.add(selectFile); } else if (object instanceof IProject ) { IProject selectProject = (IProject) object; try { ResourceUtils.getXliffs(selectProject, selectIFiles); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.handlers.BatchQAHandler.log1"), e); } } else if (object instanceof IContainer) { IContainer selectContainer = (IContainer) object; try { ResourceUtils.getXliffs(selectContainer, selectIFiles); } catch (Exception e) { logger.error(Messages.getString("qa.handlers.BatchQAHandler.log1"), e); e.printStackTrace(); } } } } }else { //如果左边未选择品质检查的类型,那么,获取nattable中打开的文件 IEditorPart activeEditor = HandlerUtil.getActiveEditor(event); String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; if (activeEditor != null && !activeEditor.getSite().getId().equals(XLIFF_EDITOR_ID)) { MessageDialog.openWarning(shell, Messages.getString("qa.all.dialog.warning"), Messages.getString("qa.handlers.BatchQAHandler.tip2")); return null; } XLIFFEditorImplWithNatTable nattable = (XLIFFEditorImplWithNatTable) activeEditor; isMultiFile = nattable.isMultiFile(); multiTempIFile = ((FileEditorInput) nattable.getEditorInput()).getFile(); if (isMultiFile) { List<String> multiFilesList = new XLFHandler().getMultiFiles(multiTempIFile); for (String multiFileStr : multiFilesList) { selectIFiles.add(ResourceUtils.fileToIFile(multiFileStr)); } }else { selectIFiles.add(multiTempIFile); } } CommonFunction.removeRepeateSelect(selectIFiles); if (selectIFiles.size() == 0) { MessageDialog.openWarning(shell, Messages.getString("qa.all.dialog.warning"), Messages.getString("qa.handlers.BatchQAHandler.tip1")); return null; } List<IFile> lstFiles = new ArrayList<IFile>(); XLFValidator.resetFlag(); for (IFile iFile : selectIFiles) { if (!XLFValidator.validateXliffFile(iFile)) { lstFiles.add(iFile); } } XLFValidator.resetFlag(); selectIFiles.removeAll(lstFiles); if (selectIFiles.size() == 0) { return null; } model = new QAModel(); model.setQaXlfList(selectIFiles); quality = new QualityAssurance(model); BatchQADialog dialog = new BatchQADialog(shell, model, isMultiFile); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { // 先调用方法,查看品质检查结果视图是否处于显示状态,如果显示了的。删除数据 IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IViewPart view = workbenchPage.findView(QAResultViewPart.ID); if (view != null) { // 运行时,将结果视图中列表的数据清除 ((QAResultViewPart) view).clearTableData(); } QAResult qaResult = new QAResult(); // 存储品质检查的检查项 model.setBatchQAItemIdList(getBatchQAItems()); // 存储品质检查的检查时不包括的文本段 model.setNotInclude(getNotIncludePara()); //给品质检查结果视图发出通告,本次检查对象为合并打开文件 // qaResult.firePropertyChange(isMultiFile, new MultiFilesOper(selectIFiles.get(0).getProject(), selectIFiles, multiTempIFile)); // 将当前所处理的文件传至 qaResult List<String> fileList = new ArrayList<String>(); for(IFile iFIle : model.getQaXlfList()){ fileList.add(iFIle.getLocation().toOSString()); } qaResult.setFilePathList(fileList); HsMultiActiveCellEditor.commit(true); if (isMultiFile) { model.setMuliFiles(true); model.setMultiOper(new MultiFilesOper(selectIFiles.get(0).getProject(), selectIFiles, multiTempIFile)); qaResult.setMultiOper(model.getMultiOper()); quality.beginMultiFileQA(qaResult); }else { model.setMuliFiles(false); qaResult.setMultiOper(model.getMultiOper()); quality.beginQA(qaResult); } } return null; } /** * 从首选项中获取批量检查中要检查的项 * @return */ public LinkedList<String> getBatchQAItems() { LinkedList<String> itemsList = new LinkedList<String>(); String itemsValue = preferenceStore.getString(QAConstant.QA_PREF_BATCH_QAITEMS); List<String> itemsValList = new ArrayList<String>(); String[] itemsValArray = itemsValue.split(","); for (int index = 0; index < itemsValArray.length; index++) { itemsValList.add(itemsValArray[index]); } //获取所有的品质检查项的标识符 model.getQaItemId_Name_Class().keySet(); Iterator<String> qaIt = model.getQaItemId_Name_Class().keySet().iterator(); while (qaIt.hasNext()) { String qaItermId = qaIt.next(); if (itemsValList.indexOf(qaItermId) >= 0) { itemsList.add(qaItermId); } } return itemsList; } /** * 获取首选项中品质检查的不包括的文本段 * @return */ public Map<String, Boolean> getNotIncludePara() { Map<String, Boolean> notInclude = new HashMap<String, Boolean>(); // 不包括上下文匹配 notInclude.put(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_CONTEXT_NOTINCLUDE)); // 不包括完成匹配 notInclude.put(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_FULLMATCH_NOTINCLUDE)); // 不包括已锁文本段 notInclude.put(QAConstant.QA_PREF_LOCKED_NOTINCLUDE, preferenceStore.getBoolean(QAConstant.QA_PREF_LOCKED_NOTINCLUDE)); return notInclude; } }
9,856
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
AspellChecker.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/spell/AspellChecker.java
package net.heartsome.cat.ts.ui.qa.spell; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import net.heartsome.cat.ts.core.bean.SingleWord; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.qa.spell.inter.HSSpellChecker; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Aspell拼写检查品 * @author robert 2012-02-07 * @version * @since JDK1.6 */ public class AspellChecker implements HSSpellChecker { private Shell shell; /** aspell 运行路径 */ private String command; private BufferedReader spellReader; private BufferedWriter spellWriter; private String response; private Process spellProcess; private List<SingleWord> errorWords = new LinkedList<SingleWord>(); static String spellCheckLinePrefix = "^"; Runtime runtime; private static IWorkspaceRoot root; private AspellConfig aspellConfig; private boolean isError = false; /** aspell 运行靠的是输入命令,因此这里面保存的是命令行代码,key 为 lang */ private Map<String, String> commandLineMap; private List<Integer> tagPositionList; private List<SingleWord> wordList; public final static Logger logger = LoggerFactory.getLogger(AspellChecker.class.getName()); // UNDO 今天发现 aspell 拼写检查器配置失败时,程序的提示框有问题,是线程异常的问题,应该改正。 --robert 2012-07-23 public AspellChecker () { runtime = Runtime.getRuntime(); root = ResourcesPlugin.getWorkspace().getRoot(); String aspellConfigFile = root.getLocation().append(QAConstant.QA_SPELL_ASPELLCONFIGFILE).toOSString(); if (!new File(aspellConfigFile).exists()) { logger.error(Messages.getString("qa.spellCheck.AspellChecker.log1")); }else { aspellConfig = new AspellConfig( aspellConfigFile); commandLineMap = new HashMap<String, String>(); command = aspellConfig.getCommand(); //如果路径与语言都没有配置,那么,Aspell都不可用,为空 // if (("".equals(command) || "".equals(defaultDictionary) || defaultDictionary == null) && !isSpellNull) { // isSpellNull = true; // logger.error(Messages.getString(MessageFormat.format( // Messages.getString("qa.spellCheck.AspellChecker.log2"), target_lan))); // } //如果路径与语言都没有配置,那么,Aspell都不可用,为空 if ("".equals(command)) { logger.error(Messages.getString(Messages.getString("qa.spellCheck.AspellChecker.log2"))); } } } public List<SingleWord> getErrorWords(String pureText, List<SingleWord> wordList, String language) { this.wordList = wordList; errorWords.clear(); if (!commandLineMap.containsKey(language)) { createCommandLine(language); } String commandLine = commandLineMap.get(language); // commandLine = /usr/bin/aspell --encoding=utf-8 -a --lang=en-US --master=en_US // /usr/bin/aspell --encoding=utf-8 -a --lang=en-US --master=en_US // System.out.println("commandLine = " + commandLine); processTarget_1(commandLine, pureText.replace('\n', '\u0007')); return errorWords; } /** * 创建 运行命令行代码 * @param language */ private void createCommandLine(String language){ String dictionary = aspellConfig.getDictionaryForLang(language); // language = TextUtil.normLanguage(language); String commandLine = command + " -a --lang=" + language; if (!dictionary.equals("")) { commandLine = commandLine + " --master=" + dictionary; } commandLineMap.put(language, commandLine); } /** * 这是之前的方法,现在不于调用 */ private void processTarget(String commandLine, String target) { try { spellProcess = runtime.exec(commandLine); spellReader = new BufferedReader(new InputStreamReader(spellProcess.getInputStream())); spellWriter = new BufferedWriter(new OutputStreamWriter(spellProcess.getOutputStream())); // 跳过aspell的版本号 spellReader.readLine(); // spellProcess.waitFor(); target = target.replace('\n', '\u0007'); spellWriter.write(spellCheckLinePrefix + target); spellWriter.newLine(); spellWriter.flush(); response = spellReader.readLine(); } catch (Exception e) { isError = true; Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), Messages.getString("qa.spellCheck.AspellChecker.tip1")); } }); logger.error(Messages.getString("qa.spellCheck.AspellChecker.tip1"), e); return; } checkStatus(); try { spellReader.close(); spellWriter.close(); spellProcess.destroy(); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.spellCheck.all.log1"), e); } } private void processTarget_1(final String commandLine, final String target) { try { spellProcess = runtime.exec(commandLine); spellReader = new BufferedReader(new InputStreamReader( spellProcess.getInputStream())); spellWriter = new BufferedWriter(new OutputStreamWriter( spellProcess.getOutputStream())); new Thread() { public void run() { spellReader = new BufferedReader(new InputStreamReader( spellProcess.getInputStream())); spellWriter = new BufferedWriter(new OutputStreamWriter( spellProcess.getOutputStream())); try { // 跳过aspell的版本号 spellReader.readLine(); spellWriter.write(spellCheckLinePrefix + target); spellWriter.newLine(); spellWriter.flush(); response = spellReader.readLine(); checkStatus(); } catch (IOException e) { e.printStackTrace(); isError = true; Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), Messages.getString("qa.spellCheck.AspellChecker.tip1")); } }); logger.error(Messages.getString("qa.spellCheck.AspellChecker.tip1"), e); return; } finally { try { spellReader.close(); spellWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); new Thread() { public void run() { BufferedReader errorReader = new BufferedReader( new InputStreamReader(spellProcess.getErrorStream()), 4096); try { String line2 = null; while (spellProcess != null && errorReader != null && (line2 = errorReader.readLine()) != null) { if (line2 != null) { // System.out.println("line2 =" + line2); } } } catch (IOException e) { e.printStackTrace(); } finally { try { errorReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); int status = spellProcess.waitFor(); if (status != 0) { isError = true; Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), Messages.getString("qa.spellCheck.AspellChecker.tip1")); } }); logger.error(Messages.getString("qa.spellCheck.AspellChecker.tip1")); } spellProcess.destroy(); try { spellReader.close(); spellWriter.close(); spellProcess.getErrorStream().close(); spellProcess.getInputStream().close(); spellProcess.getOutputStream().close(); } catch (Exception ee) { logger.error("Aspell check error", ee); } } catch (Exception e) { try { if ((spellReader != null)) { spellReader.close(); } if ((spellWriter != null)) { spellWriter.close(); } if (spellProcess != null) { spellProcess.getErrorStream().close(); spellProcess.getInputStream().close(); spellProcess.getOutputStream().close(); } } catch (Exception ee) { logger.error("Aspell check error", ee); } } } /** * aspell 词典是否发生错误,如果错误,将不再进行拼写检查 * @return */ public boolean isError() { return isError; } private void checkStatus() { try { while (response != null && !response.equals("")) { if (isError) { return; } if (response.equals("*")) { // 当前单词是存在于词典中的 spellWriter.write(spellCheckLinePrefix); spellWriter.newLine(); spellWriter.flush(); response = spellReader.readLine(); } else { if (response.startsWith("&") || response.startsWith("#")) { parseSuggestions(response); response = spellReader.readLine(); } } } if (response == null || response.equals("")) { return; } } catch (IOException e) { MessageBox box = new MessageBox(shell, SWT.ICON_ERROR); box.setMessage(e.getMessage()); box.open(); logger.error(Messages.getString("qa.spellCheck.all.log2"), e); } } /** * 分解查询结果,将错误单词添加到结果集中 * 查询结果如:& yayay 62 1: Maya, ayah, ya, Yalu, Yuan, yaws, yuan, yaw, 第二个值为错误单词,第三个值为建议单词个数,第四个值为该单词起始下标(从1开始的) * @param line ; */ private void parseSuggestions(String line) { StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { st.nextToken(); st.nextToken(); st.nextToken(); int start = -1; if (st.hasMoreTokens()) { // 备注,aspell 的查询结果,每个单词的起始坐标是从 1 开始的 start = Integer.parseInt(st.nextToken().replace(":", "")) - 1; }else { return; } int startAdd = 0; if (tagPositionList != null) { // 将标记放回去,使每个非译片段回复之前未去标记的状态 for(Integer tagIndex : tagPositionList){ if (start > tagIndex) { startAdd ++; } } start = start + startAdd; } boolean exsit = false; for(SingleWord word : wordList){ if (word.getStart() == start) { errorWords.add(word); exsit = true; break; } } if (!exsit) { logger.error("Aspell check error."); } } } public boolean langIsLoad(String language) { return false; } public boolean checkLangAvailable(String language) { if (aspellConfig == null || aspellConfig.getDictionaryList() == null) { return false; } return aspellConfig.getDictionaryList().containsKey(language); } public void setTagPosition(List<Integer> tagPositionList) { this.tagPositionList = tagPositionList; } }
11,123
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
RealTimeSpellCheck.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/spell/RealTimeSpellCheck.java
package net.heartsome.cat.ts.ui.qa.spell; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import java.util.regex.Matcher; import net.heartsome.cat.common.core.Constant; import net.heartsome.cat.common.innertag.factory.PlaceHolderEditModeBuilder; import net.heartsome.cat.ts.core.bean.SingleWord; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.nonTransElement.NonTransElementOperate; import net.heartsome.cat.ts.ui.qa.spell.inter.HSSpellChecker; import net.heartsome.cat.ts.ui.xliffeditor.nattable.qa.IRealTimeSpellCheck; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.PlatformUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 实时拼写检查实现类,之前考虑将些类做成单例模式,但后来将 RealTimeSpellCheckTrigger 做成了单例模式,故这个类不需要再这样做了。 * @author robert 2013-01-21 */ public class RealTimeSpellCheck implements IRealTimeSpellCheck, IPropertyChangeListener{ /** 拼写检查器类型 */ private boolean isHunspell = false; private HSSpellChecker spelling = null; private NonTransElementOperate nontransOper; private IPreferenceStore preferenceStore; private boolean isRealTimeSpell = false; private static StringTokenizer stringToken; /** 是否忽略非译元素 */ private boolean ignoreNontrans; /** 是否忽略单词首字母为数字 */ private boolean ignoreDigitalFirst; /** 是否忽略单词首字母为大写 */ private boolean ignoreUpperCaseFirst; /** 忽略全大写单词 */ private boolean ignoreAllUpperCase; private static final Logger LOGGER = LoggerFactory.getLogger(RealTimeSpellCheck.class.getName()); public RealTimeSpellCheck(){ preferenceStore = Activator.getDefault().getPreferenceStore(); preferenceStore.addPropertyChangeListener(this); loadParams(); } private void loadParams(){ isHunspell = preferenceStore.getBoolean(QAConstant.QA_PREF_isHunspell); isRealTimeSpell = preferenceStore.getBoolean(QAConstant.QA_PREF_realTimeSpell); ignoreNontrans = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreNontrans); ignoreDigitalFirst = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreDigitalFirst); ignoreUpperCaseFirst = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreUpperCaseFirst); ignoreAllUpperCase = preferenceStore.getBoolean(QAConstant.QA_PREF_ignoreAllUpperCase); if (isHunspell) { if (ignoreNontrans) { nontransOper = new NonTransElementOperate(); nontransOper.openNonTransDB(); } spelling = new Hunspell(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()); }else { spelling = new AspellChecker(); } } // interface public boolean checkLangAvailable(String language){ // 首选项是否开启实时拼写检查 if (!isRealTimeSpell) { return false; } return spelling.checkLangAvailable(language); } // interface public List<SingleWord> getErrorWords(String tgtText, String language) { if (isHunspell) { LinkedList<SingleWord> wordList = new LinkedList<SingleWord>(); getSingleWords(tgtText, wordList); return spelling.getErrorWords(null, wordList, language); }else { List<Integer> tagPositionList = getTagPosition(tgtText); String pureText = PlaceHolderEditModeBuilder.PATTERN.matcher(tgtText).replaceAll(""); LinkedList<SingleWord> wordList = new LinkedList<SingleWord>(); getSingleWords(tgtText, wordList); spelling.setTagPosition(tagPositionList); return spelling.getErrorWords(pureText, wordList, language); } } public void propertyChange(PropertyChangeEvent event) { loadParams(); } /** * 获取单个单词,这里面主要是根据不同的选项。得到要进行拼写检查的单词 */ private void getSingleWords(String tgtText, List<SingleWord> tgtWordList) { stringToken = new StringTokenizer(tgtText, Constant.SEPARATORS, false); List<Integer[]> ignoreParaList = null; // 如果要处理忽略非译元素,那么执行如下操作 (备注:所有的忽略项。只是针对 hunspell) if (isHunspell && ignoreNontrans) { List<Integer> tagPositionList = getTagPosition(tgtText); String pureText = PlaceHolderEditModeBuilder.PATTERN.matcher(tgtText).replaceAll(""); ignoreParaList = nontransOper.getIgnorePara(pureText, tagPositionList); } int start = 0; int length = 0; int end = 0; while(stringToken.hasMoreTokens()){ String word = stringToken.nextToken(); String pureWord = PlaceHolderEditModeBuilder.PATTERN.matcher(word).replaceAll(""); start = tgtText.indexOf(word, start); length = word.length(); end = start + length; // 经过一系列的判断,从而删除一些不符合标准的单词。将剩下的单词传入拼写检查器中进行检查 if (isHunspell) { // 是否忽略非译元素 if (ignoreNontrans) { boolean needIgnore = false; for(Integer[] ignoreIndexs : ignoreParaList){ if (start >= ignoreIndexs[0] && end <= ignoreIndexs[1] ) { needIgnore = true; break; } } if (needIgnore) { start = start + word.length(); continue; } } // 是否忽略首字母为数字 if (ignoreDigitalFirst && checkDigitalFirst(pureWord)) { start = start + word.length(); continue; } // 是否忽略首字母为大写 if (ignoreUpperCaseFirst && checkUpperCaseFirst(pureWord)) { start = start + word.length(); continue; } //是否忽略全大写单词 if (ignoreAllUpperCase && checkAllUpperCase(pureWord)) { start = start + word.length(); continue; } } tgtWordList.add(new SingleWord(word, pureWord, start, length)); start = start + word.length(); } } /** * 检查单词是否首字母大写 * @return */ private boolean checkDigitalFirst(String pureWord){ return Character.isDigit(pureWord.charAt(0)); } /** * 检查单词是否首字母为数字 * @return */ private boolean checkUpperCaseFirst(String pureWord){ for (int i = 0; i < pureWord.length(); i++) { if (Character.isDigit(pureWord.charAt(i))) { continue; }else { return Character.isUpperCase(pureWord.charAt(i)); } } return true; } /** * 检查单词是否首字母为数字 * @return */ private boolean checkAllUpperCase(String pureWord){ return pureWord.equals(pureWord.toUpperCase()); } /** * 获取每个标记占位符的位置 * @param text */ private List<Integer> getTagPosition(String text){ List<Integer> tagPostionList = new LinkedList<Integer>(); Matcher matcher = PlaceHolderEditModeBuilder.PATTERN.matcher(text); while(matcher.find()){ tagPostionList.add(matcher.start()); } return tagPostionList; } public static void main(String[] args) { String pureWord = "@1RObert"; if (Character.isDigit(pureWord.charAt(0))) { System.out.println("是的"); }else { System.out.println("不是的"); } } }
7,143
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Hunspell.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/spell/Hunspell.java
package net.heartsome.cat.ts.ui.qa.spell; import java.io.File; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.ts.core.bean.SingleWord; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.core.qa.QAXmlHandler; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.qa.spell.inter.HSSpellChecker; import net.heartsome.cat.ts.ui.qa.spell.inter.HunspellLibrary; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; /** * Hunspell 管理类 * @author robert 2013-01-10 */ public class Hunspell implements HSSpellChecker{ /** 单例模式, Hunspell 实例 */ private static Hunspell instance = null; /** 由 JNA 创建的 Library 实例,由这个实例加载相关函数,进行词典查询 */ private HunspellLibrary hunspellLibrary = null; private QAXmlHandler xmlHandler; /** hunspell 支持的语言,若一种语言不满足此项,则退出 */ private Map<String, String> availableLangMap = new HashMap<String, String>(); /** 保存当前已经加载的语言词典 */ private HashMap<String, Dictionary> dictionariesMap = new HashMap<String, Dictionary>(); /** hunspell 运行库文件 */ private String libFile; /** hunspell 拼写检查器是否运行错误的标识符 */ private boolean isError = false; private Shell shell; private final static Logger logger = LoggerFactory.getLogger(Hunspell.class.getName()); private IWorkspaceRoot root; /** * 管理 hunspell 运行库,以及词典 * @return * @throws UnsatisfiedLinkError * @throws UnsupportedOperationException */ public static synchronized void synchronizeInit(Shell shell) throws UnsatisfiedLinkError, UnsupportedOperationException { if (instance == null) { instance = new Hunspell(shell); } } public static Hunspell getInstance(Shell shell){ if (instance == null) { synchronizeInit(shell); } return instance; } protected void tryLoad(String libFile) throws UnsupportedOperationException { hunspellLibrary = (HunspellLibrary)Native.loadLibrary(libFile, HunspellLibrary.class); } /** * hunspell 运行实例 */ public Hunspell(Shell _shell){ this.shell = _shell; try { root = ResourcesPlugin.getWorkspace().getRoot(); // 先求出所有所支持的语言 xmlHandler = new QAXmlHandler(); // Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID); // String configXml = FileLocator.toFileURL(bundle.getEntry(QAConstant.QA_SPELL_hunspellConfigFile)).getPath(); // String configXml = root.getLocation().append(QAConstant.QA_SPELL_hunspellConfigFile).toOSString() ; String configXml = Platform.getConfigurationLocation().getURL().getPath() + QAConstant.QA_SPELL_hunspellConfigFile; // if (!new File(configXml).exists() || new File(configXml).isDirectory()) { // copyHunspellData(); // } if (!new File(configXml).exists() || new File(configXml).isDirectory()) { isError = true; Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), Messages.getString("qa.spell.hunspell.notFindHunpsellConfigTip")); } }); return; } availableLangMap = xmlHandler.getHunspellAvailableLang(configXml); if (availableLangMap == null) { Display.getDefault().syncExec(new Runnable() { public void run() { MessageDialog.openError(shell, Messages.getString("qa.all.dialog.error"), Messages.getString("qa.spell.hunspell.hunspellConfigErrorTip")); } }); isError = true; return; } // libFile = FileLocator.toFileURL(bundle.getEntry(QAConstant.QA_SPELL_hunspellLibraryFolder)).getFile(); // libFile = new File(libFile).getAbsolutePath() + System.getProperty("file.separator") + libName(); // libFile = "C:\\Documents and Settings\\Administrator\\桌面\\h\\lib\\" + libName(); // libFile = root.getLocation().append(".metadata/h/native-library").append(libName()).toOSString(); // libFile = new File(Platform.getConfigurationLocation().getURL().getPath() + "h/native-library" + System.getProperty("file.separator") + libName()).getAbsolutePath(); libFile = root.getLocation().append(QAConstant.QA_SPELL_hunspellLibraryFolder).append(libName()).toOSString() ; if (!new File(libFile).exists() || new File(libFile).isDirectory()) { copyHunspellLibFile(); } if (!new File(libFile).exists()) { MessageFormat.format(Messages.getString("qa.spell.hunspell.notFindHunspellLibTip"), new Object[]{libFile}); isError = true; return; } // 加载运行库 hunspellLibrary = (HunspellLibrary)Native.loadLibrary(libFile, HunspellLibrary.class); } catch (Exception e) { isError = true; e.printStackTrace(); } } public String getLibFile() { return libFile; } /** * 获取各个版本下的 hunspell 软件的函数库 */ public static String libName() throws UnsupportedOperationException { String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("windows")) { return libNameBare()+".dll"; } else if (os.startsWith("mac os x")) { return libNameBare()+".jnilib"; } else { return "lib"+libNameBare()+".so"; } } public static String libNameBare() throws UnsupportedOperationException { String os = System.getProperty("os.name").toLowerCase(); String arch = System.getProperty("os.arch").toLowerCase(); boolean x86 = arch.equals("x86") || arch.equals("i386") || arch.equals("i686"); boolean amd64= arch.equals("x86_64") || arch.equals("amd64") || arch.equals("ia64n"); if (os.startsWith("windows")) { if (x86) { return "hunspell-win-x86-32"; } if (amd64) { return "hunspell-win-x86-64"; } } else if (os.startsWith("mac os x")) { if (x86) { return "hunspell-darwin-x86-32"; } if (amd64) { return "hunspell-darwin-x86-64"; } if (arch.equals("ppc")) { return "hunspell-darwin-ppc-32"; } } else if (os.startsWith("linux")) { if (x86) { return "hunspell-linux-x86-32"; } if (amd64) { return "hunspell-linux-x86-64"; } } throw new UnsupportedOperationException("Unknown OS/arch: "+os+"/"+arch); } /** * 获取某种语言的字典实例 */ public Dictionary getDictionary(String language) throws FileNotFoundException, UnsupportedEncodingException { // 如果语言发生改变,重新加载该语言的词典 if (dictionariesMap.containsKey(language)) { return dictionariesMap.get(language); } else { Dictionary dictionary = new Dictionary(language); dictionariesMap.put(language, dictionary); return dictionary; } } /** * 将词典的语言从内存中移除 */ public void destroyDictionary(String baseFileName) { if (dictionariesMap.containsKey(baseFileName)) { dictionariesMap.remove(baseFileName); } } /** * 某种语言的词典实例(单例模式) */ public class Dictionary { /** hunspell 函数库的指针 */ private Pointer hunspellDictPoint = null; /** hunspell 所用的编码 */ private String encoding; /** 某种语言的词典实例 */ public Dictionary(String language){ try { String dictionaryName = availableLangMap.get(language); // Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID); // String dictionaryFolder = FileLocator.toFileURL(bundle.getEntry(QAConstant.QA_SPELL_hunspellDictionaryFolder)).getPath(); // String dictionaryFolder = "C:\\Documents and Settings\\Administrator\\桌面\\h\\hunspellDictionaries"; // String dictionaryFolder = root.getLocation().append(".metadata/h/hunspellDictionaries").toOSString(); // String dictionaryFolder = new File(Platform.getConfigurationLocation().getURL().getPath() + "h/hunspellDictionaries").getAbsolutePath(); String dictionaryFolder = root.getLocation().append(QAConstant.QA_SPELL_hunspellDictionaryFolder).toOSString() ; if (!new File(dictionaryFolder).exists() || !new File(dictionaryFolder).isDirectory()) { copyHunspellDictionaries(dictionaryName, language); } String dicPath = dictionaryFolder + System.getProperty("file.separator") + dictionaryName + ".dic"; String affPath = dictionaryFolder + System.getProperty("file.separator") + dictionaryName + ".aff"; File dic = new File(dicPath); File aff = new File(affPath); if (!dic.exists() || !aff.exists() || !dic.canRead() || !aff.canRead()) { copyHunspellDictionaries(dictionaryName, language); } if (!dic.exists() || !aff.exists()) { throw new FileNotFoundException(MessageFormat.format(Messages.getString("qa.spell.hunspell.notFindDictionaryTip"), new Object[]{language})); } if (!dic.canRead() || !aff.canRead()) { throw new FileNotFoundException(MessageFormat.format(Messages.getString("qa.spell.hunspell.dicReadErrorTip"), new Object[]{language})); } hunspellDictPoint = hunspellLibrary.Hunspell_create(aff.getAbsolutePath(), dic.getAbsolutePath()); encoding = hunspellLibrary.Hunspell_get_dic_encoding(hunspellDictPoint); } catch (Exception e) { e.printStackTrace(); } } /** * 当程序结束时,销毁词典,释放资源 */ public void destroy() { if (hunspellLibrary != null && hunspellDictPoint != null) { hunspellLibrary.Hunspell_destroy(hunspellDictPoint); hunspellDictPoint = null; } } /** * 查询一个单词是否拼写错误,若拼写规范,则返回 true */ public boolean misspelled(String word) { try { return hunspellLibrary.Hunspell_spell(hunspellDictPoint, stringToBytes(word)) == 0; } catch (UnsupportedEncodingException e) { return true; } } /** * 在词典的编码中,将一个 java 字符串转换成一个 0 节字的数组,这如 hunspell 功能所预期的一样 */ protected byte[] stringToBytes(String str) throws UnsupportedEncodingException { return (str + "\u0000").getBytes(encoding); // return (new String((str + "\u0000").getBytes(), "GB2312")).getBytes(encoding); // return (str + (new String("\u0000".getBytes(), "utf8"))).getBytes(encoding); // return ((new String((str + "\u0000").getBytes(), encoding))).getBytes(encoding); //ISO8859-1 // return ((new String(str.getBytes(), "utf-8")) + new String("\u0000".getBytes(), "utf-8")).getBytes(encoding); // return ((new String(str.getBytes(), encoding)) + new String("\u0000".getBytes(), encoding)).getBytes(encoding); // return ((new String(str.getBytes(), "GBK")) + new String("\u0000".getBytes(), "GBK")).getBytes(encoding); // logger.info(str); // String word = new String((str + "\u0000").getBytes("UTF-8"), encoding); // logger.info(word); // word = new String((str + "\u0000").getBytes("GB2312"), encoding); // logger.info(word); // word = new String((str + "\u0000").getBytes("iso-8859-1"), encoding); // logger.info(word); // word = new String((str + "\u0000").getBytes("GBK"), encoding); // logger.info(word); // word = new String((str + "\u0000").getBytes(encoding), encoding); // logger.info(word); // logger.info("--------------------------"); // // //// return (new String((str + "\u0000").getBytes("UTF-8"), encoding)).getBytes(encoding); //// return str.getBytes("iso-8859-1"); //// return (new String((str + "\u0000").getBytes(encoding), "UTF-8")).getBytes("UTF-8"); // String word1 = str + "\u0000"; // return word1.getBytes(encoding); // 不加括号 } /** * 返回一个单词的正确拼写建议 */ public List<String> suggest(String word) { try { int suggestionsCount = 0; PointerByReference suggestions = new PointerByReference(); suggestionsCount = hunspellLibrary.Hunspell_suggest( hunspellDictPoint, suggestions, stringToBytes(word)); return pointerToCStringsToList(suggestions, suggestionsCount); } catch (UnsupportedEncodingException ex) { return Collections.emptyList(); } } private List<String> pointerToCStringsToList(PointerByReference slst, int n) { if ( n == 0 ) { return Collections.emptyList(); } List<String> strings = new ArrayList<String>(n); try { // Get each of the suggestions out of the pointer array. Pointer[] pointerArray = slst.getValue().getPointerArray(0, n); for (int i=0; i<n; i++) { // 工作编码为 8bit 或者 utf-8 long len = pointerArray[i].indexOf(0, (byte)0); if (len != -1) { if (len > Integer.MAX_VALUE) { throw new RuntimeException("String improperly terminated: " + len); } byte[] data = pointerArray[i].getByteArray(0, (int)len); strings.add(new String(data, encoding)); } } } catch (UnsupportedEncodingException e) { // Shouldn't happen... } finally { hunspellLibrary.Hunspell_free_list(hunspellDictPoint, slst, n); } return strings; } } public void setTarget(String t) { } public List<SingleWord> getErrorWords(String tgtText, List<SingleWord> wordList, String language) { List<SingleWord> errorWords = new LinkedList<SingleWord>(); try { Dictionary dictionary = getDictionary(language); for (SingleWord wordBean : wordList) { // if (SEPARATORS.indexOf(token) != -1) { // continue; // } String pureWord = wordBean.getPureWord(); // 以数字开头 if (pureWord.matches("[\\d]*")) { continue; } if (pureWord.length() == 1 && pureWord.charAt(0) >= '\uE000' && pureWord.charAt(0) <= '\uF8FF') { continue; } if (pureWord.trim().equals("") || pureWord.trim().equals("–")) { continue; } if (dictionary.misspelled(pureWord)) { errorWords.add(wordBean); } } } catch (Exception e) { e.printStackTrace(); } return errorWords; } public boolean isError() { return isError; } public boolean langIsLoad(String language) { return dictionariesMap.containsKey(language); } public boolean checkLangAvailable(String language) { return availableLangMap.containsKey(language); } /** * 将 hunspell 的词典从 configurationa 中拷到 工作空间下 的 .metadata/hunspell/hunspellDictionaries 下面 */ private void copyHunspellDictionaries(String dictionaryName, String language) throws Exception{ String tgtDicFolderPath = ResourcesPlugin.getWorkspace().getRoot() .getLocation().append(QAConstant.QA_SPELL_hunspellDictionaryFolder).toOSString(); File dicFolder = new File(tgtDicFolderPath); if (!dicFolder.exists() || dicFolder.isFile()) { dicFolder.mkdirs(); } String srcDicFolderPath = Platform.getConfigurationLocation().getURL().getPath() + "net.heartsome.cat.ts.ui" + System.getProperty("file.separator") + "hunspell" + System.getProperty("file.separator") + "hunspellDictionaries"; String srcDicPath = srcDicFolderPath + System.getProperty("file.separator") + dictionaryName + ".dic"; String srcAffPath = srcDicFolderPath + System.getProperty("file.separator") + dictionaryName + ".aff"; if (!new File(srcDicPath).exists() || !new File(srcAffPath).exists() || !new File(srcDicPath).canRead() || !new File(srcAffPath).canRead()) { throw new FileNotFoundException(MessageFormat.format(Messages.getString("qa.spell.hunspell.notFindDictionaryTip"), new Object[]{language})); } try { String tgtDicPath = tgtDicFolderPath + System.getProperty("file.separator") + dictionaryName + ".dic"; String tgtAffPath = tgtDicFolderPath + System.getProperty("file.separator") + dictionaryName + ".aff"; ResourceUtils.copyDirectory(new File(srcDicPath), new File(tgtDicPath)); ResourceUtils.copyDirectory(new File(srcAffPath), new File(tgtAffPath)); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.spell.hunspell.LOG.copyError"), e); } } /** * 将 hunspell 的运行库拷贝到工作空间的 .metadata/hunspell/native-library 下 */ private void copyHunspellLibFile(){ String hunspellPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(QAConstant.QA_SPELL_hunspellFolder).toOSString(); File hunspellFolder = new File(hunspellPath); if (!hunspellFolder.exists() || hunspellFolder.isFile()) { hunspellFolder.mkdirs(); } String srcLocation = Platform.getConfigurationLocation().getURL().getPath() + "net.heartsome.cat.ts.ui" + System.getProperty("file.separator") + "hunspell" + System.getProperty("file.separator") + "native-library"; try { String libFolderPath = root.getLocation().append(QAConstant.QA_SPELL_hunspellLibraryFolder).toOSString(); ResourceUtils.copyDirectory(new File(srcLocation), new File(libFolderPath)); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.spell.hunspell.LOG.copyError"), e); } } public void setTagPosition(List<Integer> tagPositionList) { // do nothing, 该方法只用于 aspell } public static void main(String[] args) { try { System.out.println(("this" + "\u0000").getBytes("utf-8")); } catch (Exception e) { e.printStackTrace(); } // return (str + "\u0000").getBytes(encoding); } }
18,075
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z