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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ColumnSearchStrategy.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/search/strategy/ColumnSearchStrategy.java | package net.sourceforge.nattable.search.strategy;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.nattable.config.IConfigRegistry;
import net.sourceforge.nattable.coordinate.PositionCoordinate;
import net.sourceforge.nattable.layer.ILayer;
import net.sourceforge.nattable.search.ISearchDirection;
public class ColumnSearchStrategy extends AbstractSearchStrategy {
private int[] columnPositions;
private int startingRowPosition;
private final String searchDirection;
private final IConfigRegistry configRegistry;
public ColumnSearchStrategy(int[] columnPositions, IConfigRegistry configRegistry) {
this(columnPositions, 0, configRegistry, ISearchDirection.SEARCH_FORWARD);
}
public ColumnSearchStrategy(int[] columnPositions, int startingRowPosition, IConfigRegistry configRegistry, String searchDirection) {
this.columnPositions = columnPositions;
this.startingRowPosition = startingRowPosition;
this.configRegistry = configRegistry;
this.searchDirection = searchDirection;
}
public PositionCoordinate executeSearch(Object valueToMatch) {
return CellDisplayValueSearchUtil.findCell(getContextLayer(), configRegistry, getColumnCellsToSearch(getContextLayer()), valueToMatch, getComparator(), isCaseSensitive());
}
public void setStartingRowPosition(int startingRowPosition) {
this.startingRowPosition = startingRowPosition;
}
public void setColumnPositions(int[] columnPositions) {
this.columnPositions = columnPositions;
}
protected PositionCoordinate[] getColumnCellsToSearch(ILayer contextLayer) {
List<PositionCoordinate> cellsToSearch = new ArrayList<PositionCoordinate>();
int rowPosition = startingRowPosition;
// See how many rows we can add, depends on where the search is starting from
final int rowCount = contextLayer.getRowCount();
int height = rowCount;
if (searchDirection.equals(ISearchDirection.SEARCH_FORWARD)) {
height = height - startingRowPosition;
} else {
height = startingRowPosition;
}
for (int columnIndex = 0; columnIndex < columnPositions.length; columnIndex++) {
final int startingColumnPosition = columnPositions[columnIndex];
if (searchDirection.equals(ISearchDirection.SEARCH_BACKWARDS)) {
cellsToSearch.addAll(CellDisplayValueSearchUtil.getDescendingCellCoordinates(getContextLayer(), startingColumnPosition, rowPosition, 1, height));
rowPosition = rowCount - 1;
} else {
cellsToSearch.addAll(CellDisplayValueSearchUtil.getCellCoordinates(getContextLayer(), startingColumnPosition, rowPosition, 1, height));
rowPosition = 0;
}
height = rowCount;
// After first column is set, start the next column from the top
}
return cellsToSearch.toArray(new PositionCoordinate[0]);
}
} | 2,805 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
GridSearchStrategy.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/search/strategy/GridSearchStrategy.java | package net.sourceforge.nattable.search.strategy;
import net.sourceforge.nattable.config.IConfigRegistry;
import net.sourceforge.nattable.coordinate.PositionCoordinate;
import net.sourceforge.nattable.layer.ILayer;
import net.sourceforge.nattable.search.ISearchDirection;
import net.sourceforge.nattable.selection.SelectionLayer;
public class GridSearchStrategy extends AbstractSearchStrategy {
private final IConfigRegistry configRegistry;
public GridSearchStrategy(IConfigRegistry configRegistry, boolean wrapSearch) {
this(configRegistry, wrapSearch, ISearchDirection.SEARCH_FORWARD);
}
public GridSearchStrategy(IConfigRegistry configRegistry, boolean wrapSearch, String searchDirection) {
this.configRegistry = configRegistry;
this.wrapSearch = wrapSearch;
this.searchDirection = searchDirection;
}
public PositionCoordinate executeSearch(Object valueToMatch) {
ILayer contextLayer = getContextLayer();
if (! (contextLayer instanceof SelectionLayer)) {
throw new RuntimeException("For the GridSearchStrategy to work it needs the selectionLayer to be passed as the contextLayer.");
}
SelectionLayer selectionLayer = (SelectionLayer) contextLayer;
PositionCoordinate selectionAnchor = selectionLayer .getSelectionAnchor();
boolean hadSelectionAnchor = true;
if (selectionAnchor.columnPosition < 0 || selectionAnchor.rowPosition < 0) {
selectionAnchor.columnPosition = 0;
selectionAnchor.rowPosition = 0;
hadSelectionAnchor = false;
}
int anchorColumnPosition = selectionAnchor.columnPosition;
int startingRowPosition;
int[] columnsToSearch = null;
final int columnCount = selectionLayer.getColumnCount();
if (searchDirection.equals(ISearchDirection.SEARCH_FORWARD)) {
int rowPosition = hadSelectionAnchor ? selectionAnchor.rowPosition + 1 : selectionAnchor.rowPosition;
if (rowPosition > (contextLayer.getRowCount() - 1)) {
rowPosition = wrapSearch ? 0 : contextLayer.getRowCount() - 1;
}
int rowCount = selectionLayer.getRowCount();
startingRowPosition = rowPosition < rowCount ? rowPosition : 0;
if (selectionAnchor.rowPosition + 1 >= rowCount && anchorColumnPosition + 1 >= columnCount && hadSelectionAnchor) {
if (wrapSearch) {
anchorColumnPosition = 0;
} else {
return null;
}
} else if (selectionAnchor.rowPosition == rowCount - 1 && anchorColumnPosition < columnCount - 1) {
anchorColumnPosition++;
}
columnsToSearch = getColumnsToSearchArray(columnCount, anchorColumnPosition);
} else {
int rowPosition = selectionAnchor.rowPosition - 1;
if (rowPosition < 0) {
rowPosition = wrapSearch ? contextLayer.getRowCount() - 1 : 0;
}
startingRowPosition = rowPosition > 0 ? rowPosition : 0;
if (selectionAnchor.rowPosition - 1 < 0 && anchorColumnPosition - 1 < 0 && hadSelectionAnchor) {
if (wrapSearch) {
anchorColumnPosition = columnCount - 1;
} else {
return null;
}
} else if (selectionAnchor.rowPosition == 0 && anchorColumnPosition > 0) {
anchorColumnPosition--;
}
columnsToSearch = getDescendingColumnsToSearchArray(anchorColumnPosition);
}
PositionCoordinate executeSearch = searchGrid(valueToMatch, contextLayer, selectionLayer, anchorColumnPosition,
startingRowPosition, columnsToSearch);
return executeSearch;
}
private PositionCoordinate searchGrid(Object valueToMatch, ILayer contextLayer, SelectionLayer selectionLayer,
final int anchorColumnPosition, int startingRowPosition, int[] columnsToSearch) {
// Search for value across columns
ColumnSearchStrategy columnSearcher = new ColumnSearchStrategy(columnsToSearch, startingRowPosition, configRegistry, searchDirection);
columnSearcher.setCaseSensitive(caseSensitive);
columnSearcher.setWrapSearch(wrapSearch);
columnSearcher.setContextLayer(contextLayer);
columnSearcher.setComparator(getComparator());
PositionCoordinate executeSearch = columnSearcher.executeSearch(valueToMatch);
if (executeSearch == null && wrapSearch) {
if (searchDirection.equals(ISearchDirection.SEARCH_FORWARD)) {
columnSearcher.setColumnPositions(getColumnsToSearchArray(anchorColumnPosition + 1, 0));
} else {
columnSearcher.setColumnPositions(getDescendingColumnsToSearchArray(anchorColumnPosition));
}
columnSearcher.setStartingRowPosition(0);
executeSearch = columnSearcher.executeSearch(valueToMatch);
}
return executeSearch;
}
protected int[] getColumnsToSearchArray(int columnCount, int startingColumnPosition) {
final int numberOfColumnsToSearch = (columnCount - startingColumnPosition);
final int[] columnPositions = new int[numberOfColumnsToSearch];
for (int columnPosition = 0; columnPosition < numberOfColumnsToSearch; columnPosition++) {
columnPositions[columnPosition] = startingColumnPosition + columnPosition;
}
return columnPositions;
}
protected int[] getDescendingColumnsToSearchArray(int startingColumnPosition) {
final int[] columnPositions = new int[startingColumnPosition + 1];
for (int columnPosition = 0; startingColumnPosition >= 0; columnPosition++) {
columnPositions[columnPosition] = startingColumnPosition-- ;
}
return columnPositions;
}
}
| 5,322 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CellDisplayValueSearchUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/search/strategy/CellDisplayValueSearchUtil.java | package net.sourceforge.nattable.search.strategy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import net.sourceforge.nattable.config.CellConfigAttributes;
import net.sourceforge.nattable.config.IConfigRegistry;
import net.sourceforge.nattable.coordinate.PositionCoordinate;
import net.sourceforge.nattable.data.convert.IDisplayConverter;
import net.sourceforge.nattable.layer.ILayer;
import net.sourceforge.nattable.style.DisplayMode;
public class CellDisplayValueSearchUtil {
static List<PositionCoordinate> getCellCoordinates(ILayer contextLayer, int startingColumnPosition, int startingRowPosition, int width, int height) {
List<PositionCoordinate> coordinates = new ArrayList<PositionCoordinate>();
for (int columnPosition = 0; columnPosition < width; columnPosition++) {
for (int rowPosition = 0; rowPosition < height; rowPosition++) {
PositionCoordinate coordinate = new PositionCoordinate(contextLayer, startingColumnPosition, startingRowPosition++);
coordinates.add(coordinate);
}
startingColumnPosition++;
}
return coordinates;
}
static List<PositionCoordinate> getDescendingCellCoordinates(ILayer contextLayer, int startingColumnPosition, int startingRowPosition, int width, int height) {
List<PositionCoordinate> coordinates = new ArrayList<PositionCoordinate>();
for (int columnPosition = width; columnPosition >= 0 && startingColumnPosition >= 0; columnPosition--) {
for (int rowPosition = height; rowPosition >= 0 && startingRowPosition >= 0; rowPosition--) {
PositionCoordinate coordinate = new PositionCoordinate(contextLayer, startingColumnPosition, startingRowPosition--);
coordinates.add(coordinate);
}
startingColumnPosition--;
}
return coordinates;
}
@SuppressWarnings("unchecked")
static PositionCoordinate findCell(final ILayer layer, final IConfigRegistry configRegistry, final PositionCoordinate[] cellsToSearch, final Object valueToMatch, final Comparator comparator, final boolean caseSensitive) {
final List<PositionCoordinate> cellCoordinates = Arrays.asList(cellsToSearch);
// Find cell
PositionCoordinate targetCoordinate = null;
String stringValue = caseSensitive ? valueToMatch.toString() : valueToMatch.toString().toLowerCase();
for (int cellIndex = 0; cellIndex < cellCoordinates.size(); cellIndex++) {
final PositionCoordinate cellCoordinate = cellCoordinates.get(cellIndex);
final int columnPosition = cellCoordinate.columnPosition;
final int rowPosition = cellCoordinate.rowPosition;
// Convert cell's data
final IDisplayConverter displayConverter = configRegistry.getConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, DisplayMode.NORMAL, layer.getConfigLabelsByPosition(columnPosition, rowPosition).getLabels());
final Object dataValue = displayConverter.canonicalToDisplayValue(layer.getDataValueByPosition(columnPosition, rowPosition));
// Compare with valueToMatch
if (dataValue instanceof Comparable<?>) {
String dataValueString = caseSensitive ? dataValue.toString() : dataValue.toString().toLowerCase();
if (comparator.compare(stringValue, dataValueString) == 0 || dataValueString.contains(stringValue)) {
targetCoordinate = cellCoordinate;
break;
}
}
}
return targetCoordinate;
}
}
| 3,412 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractSearchStrategy.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/search/strategy/AbstractSearchStrategy.java | package net.sourceforge.nattable.search.strategy;
import java.util.Comparator;
import net.sourceforge.nattable.layer.ILayer;
public abstract class AbstractSearchStrategy implements ISearchStrategy {
private ILayer contextLayer;
protected String searchDirection;
protected boolean wrapSearch = false;
protected boolean caseSensitive = false;
protected Comparator<?> comparator;
public void setContextLayer(ILayer contextLayer) {
this.contextLayer = contextLayer;
}
public ILayer getContextLayer() {
return contextLayer;
}
public void setSearchDirection(String searchDirection) {
this.searchDirection = searchDirection;
}
public String getSearchDirection() {
return searchDirection;
}
public void setWrapSearch(boolean wrapSearch) {
this.wrapSearch = wrapSearch;
}
public boolean isWrapSearch() {
return wrapSearch;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public Comparator<?> getComparator() {
return comparator;
}
public void setComparator(Comparator<?> comparator) {
this.comparator = comparator;
}
}
| 1,236 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SelectionSearchStrategy.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/search/strategy/SelectionSearchStrategy.java | package net.sourceforge.nattable.search.strategy;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.sourceforge.nattable.config.IConfigRegistry;
import net.sourceforge.nattable.coordinate.PositionCoordinate;
import net.sourceforge.nattable.layer.ILayer;
import net.sourceforge.nattable.search.ISearchDirection;
import net.sourceforge.nattable.selection.SelectionLayer;
public class SelectionSearchStrategy extends AbstractSearchStrategy {
private final IConfigRegistry configRegistry;
private final String searchDirection;
public SelectionSearchStrategy(IConfigRegistry configRegistry) {
this(configRegistry, ISearchDirection.SEARCH_FORWARD);
}
public SelectionSearchStrategy(IConfigRegistry configRegistry, String searchDirection) {
this.configRegistry = configRegistry;
this.searchDirection = searchDirection;
}
public PositionCoordinate executeSearch(Object valueToMatch) {
ILayer contextLayer = getContextLayer();
if (! (contextLayer instanceof SelectionLayer)) {
throw new RuntimeException("For the GridSearchStrategy to work it needs the selectionLayer to be passed as the contextLayer.");
}
SelectionLayer selectionLayer = (SelectionLayer)contextLayer;
PositionCoordinate coordinate = CellDisplayValueSearchUtil.findCell(selectionLayer, configRegistry, getSelectedCells(selectionLayer), valueToMatch, getComparator(), isCaseSensitive());
return coordinate;
}
protected PositionCoordinate[] getSelectedCells(SelectionLayer selectionLayer) {
PositionCoordinate[] selectedCells = null;
if (searchDirection.equals(ISearchDirection.SEARCH_BACKWARDS)) {
List<PositionCoordinate> coordinates = Arrays.asList(selectionLayer.getSelectedCells());
Collections.reverse(coordinates);
selectedCells = coordinates.toArray(new PositionCoordinate[0]);
} else {
selectedCells = selectionLayer.getSelectedCells();
}
return selectedCells;
}
} | 1,980 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SearchEvent.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/search/event/SearchEvent.java | package net.sourceforge.nattable.search.event;
import net.sourceforge.nattable.coordinate.PositionCoordinate;
import net.sourceforge.nattable.layer.event.AbstractContextFreeEvent;
public class SearchEvent extends AbstractContextFreeEvent {
private final PositionCoordinate cellCoordinate;
public SearchEvent(PositionCoordinate cellCoordinate) {
this.cellCoordinate = cellCoordinate;
}
public PositionCoordinate getCellCoordinate() {
return cellCoordinate;
}
public SearchEvent cloneEvent() {
return new SearchEvent(cellCoordinate);
}
}
| 582 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ITickUpdateHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/tickupdate/ITickUpdateHandler.java | package net.sourceforge.nattable.tickupdate;
public interface ITickUpdateHandler {
public boolean isApplicableFor(Object value);
/**
* @param currentValue of the cell
* @return new value after INcrementing
*/
public Object getIncrementedValue(Object currentValue);
/**
* @param currentValue of the cell
* @return new value after DEcrementing
*/
public Object getDecrementedValue(Object currentValue);
// Default implementation
ITickUpdateHandler UPDATE_VALUE_BY_ONE = new ITickUpdateHandler() {
public boolean isApplicableFor(Object value) {
return value instanceof Number;
}
public Object getDecrementedValue(Object currentValue) {
Number oldValue = (Number) currentValue;
return Float.valueOf(oldValue.floatValue() - 1);
}
public Object getIncrementedValue(Object currentValue) {
Number oldValue = (Number) currentValue;
return Float.valueOf(oldValue.floatValue() + 1);
}
};
}
| 983 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TickUpdateConfigAttributes.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/tickupdate/TickUpdateConfigAttributes.java | package net.sourceforge.nattable.tickupdate;
import net.sourceforge.nattable.style.ConfigAttribute;
public class TickUpdateConfigAttributes {
public static final ConfigAttribute<ITickUpdateHandler> UPDATE_HANDLER = new ConfigAttribute<ITickUpdateHandler>();
}
| 272 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TickUpdateAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/tickupdate/action/TickUpdateAction.java | package net.sourceforge.nattable.tickupdate.action;
import net.sourceforge.nattable.NatTable;
import net.sourceforge.nattable.tickupdate.command.TickUpdateCommand;
import net.sourceforge.nattable.ui.action.IKeyAction;
import org.eclipse.swt.events.KeyEvent;
public class TickUpdateAction implements IKeyAction {
private final boolean increment;
public TickUpdateAction(boolean increment) {
this.increment = increment;
}
public void run(NatTable natTable, KeyEvent event) {
natTable.doCommand(new TickUpdateCommand(natTable.getConfigRegistry(), increment));
}
}
| 598 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DefaultTickUpdateConfiguration.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/tickupdate/config/DefaultTickUpdateConfiguration.java | package net.sourceforge.nattable.tickupdate.config;
import org.eclipse.swt.SWT;
import net.sourceforge.nattable.config.AbstractLayerConfiguration;
import net.sourceforge.nattable.config.IConfigRegistry;
import net.sourceforge.nattable.selection.SelectionLayer;
import net.sourceforge.nattable.tickupdate.ITickUpdateHandler;
import net.sourceforge.nattable.tickupdate.TickUpdateConfigAttributes;
import net.sourceforge.nattable.tickupdate.action.TickUpdateAction;
import net.sourceforge.nattable.tickupdate.command.TickUpdateCommandHandler;
import net.sourceforge.nattable.ui.binding.UiBindingRegistry;
import net.sourceforge.nattable.ui.matcher.KeyEventMatcher;
public class DefaultTickUpdateConfiguration extends AbstractLayerConfiguration<SelectionLayer> {
@Override
public void configureRegistry(IConfigRegistry configRegistry) {
configRegistry.registerConfigAttribute(TickUpdateConfigAttributes.UPDATE_HANDLER, ITickUpdateHandler.UPDATE_VALUE_BY_ONE);
}
@Override
public void configureTypedLayer(SelectionLayer selectionLayer) {
selectionLayer.registerCommandHandler(new TickUpdateCommandHandler(selectionLayer));
}
@Override
public void configureUiBindings(UiBindingRegistry uiBindingRegistry) {
uiBindingRegistry.registerKeyBinding(
new KeyEventMatcher(SWT.NONE, SWT.KEYPAD_ADD),
new TickUpdateAction(true));
uiBindingRegistry.registerKeyBinding(
new KeyEventMatcher(SWT.NONE, SWT.KEYPAD_SUBTRACT),
new TickUpdateAction(false));
}
}
| 1,523 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TickUpdateCommandHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/tickupdate/command/TickUpdateCommandHandler.java | package net.sourceforge.nattable.tickupdate.command;
import net.sourceforge.nattable.command.AbstractLayerCommandHandler;
import net.sourceforge.nattable.config.IConfigRegistry;
import net.sourceforge.nattable.config.IEditableRule;
import net.sourceforge.nattable.coordinate.PositionCoordinate;
import net.sourceforge.nattable.edit.EditConfigAttributes;
import net.sourceforge.nattable.edit.command.EditUtils;
import net.sourceforge.nattable.edit.command.UpdateDataCommand;
import net.sourceforge.nattable.edit.editor.ICellEditor;
import net.sourceforge.nattable.layer.cell.LayerCell;
import net.sourceforge.nattable.selection.SelectionLayer;
import net.sourceforge.nattable.style.DisplayMode;
import net.sourceforge.nattable.tickupdate.ITickUpdateHandler;
import net.sourceforge.nattable.tickupdate.TickUpdateConfigAttributes;
public class TickUpdateCommandHandler extends AbstractLayerCommandHandler<TickUpdateCommand> {
private SelectionLayer selectionLayer;
public TickUpdateCommandHandler(SelectionLayer selectionLayer) {
this.selectionLayer = selectionLayer;
}
public boolean doCommand(TickUpdateCommand command) {
PositionCoordinate[] selectedPositions = selectionLayer.getSelectedCells();
IConfigRegistry configRegistry = command.getConfigRegistry();
// Tick update for multiple cells in selection
if (selectedPositions.length > 1) {
ICellEditor lastSelectedCellEditor = EditUtils.lastSelectedCellEditor(selectionLayer, configRegistry);
// Can all cells be updated ?
if (EditUtils.isEditorSame(selectionLayer, configRegistry, lastSelectedCellEditor)
&& EditUtils.allCellsEditable(selectionLayer, configRegistry)){
for (PositionCoordinate position : selectedPositions) {
updateSingleCell(command, position);
}
}
} else {
// Tick update for single selected cell
updateSingleCell(command, selectionLayer.getLastSelectedCellPosition());
}
return true;
}
private void updateSingleCell(TickUpdateCommand command, PositionCoordinate selectedPosition) {
LayerCell cell = selectionLayer.getCellByPosition(selectedPosition.columnPosition, selectedPosition.rowPosition);
IEditableRule editableRule = command.getConfigRegistry().getConfigAttribute(
EditConfigAttributes.CELL_EDITABLE_RULE,
DisplayMode.EDIT,
cell.getConfigLabels().getLabels());
if(editableRule.isEditable(selectedPosition.columnPosition, selectedPosition.rowPosition)){
selectionLayer.doCommand(new UpdateDataCommand(
selectionLayer,
selectedPosition.columnPosition,
selectedPosition.rowPosition,
getNewCellValue(command, cell)));
}
}
private Object getNewCellValue(TickUpdateCommand command, LayerCell cell) {
ITickUpdateHandler tickUpdateHandler = command.getConfigRegistry().getConfigAttribute(
TickUpdateConfigAttributes.UPDATE_HANDLER,
DisplayMode.EDIT,
cell.getConfigLabels().getLabels());
Object dataValue = cell.getDataValue();
if (tickUpdateHandler != null && tickUpdateHandler.isApplicableFor(dataValue)) {
if (command.isIncrement()) {
return tickUpdateHandler.getIncrementedValue(dataValue);
} else {
return tickUpdateHandler.getDecrementedValue(dataValue);
}
} else {
return dataValue;
}
}
public Class<TickUpdateCommand> getCommandClass() {
return TickUpdateCommand.class;
}
}
| 3,427 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TickUpdateCommand.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/tickupdate/command/TickUpdateCommand.java | package net.sourceforge.nattable.tickupdate.command;
import net.sourceforge.nattable.command.ILayerCommand;
import net.sourceforge.nattable.config.IConfigRegistry;
import net.sourceforge.nattable.layer.ILayer;
public class TickUpdateCommand implements ILayerCommand {
private final IConfigRegistry configRegistry;
private final boolean increment;
public TickUpdateCommand(IConfigRegistry configRegistry, boolean increment) {
this.configRegistry = configRegistry;
this.increment = increment;
}
protected TickUpdateCommand(TickUpdateCommand command) {
this.configRegistry = command.configRegistry;
this.increment = command.increment;
}
public TickUpdateCommand cloneCommand() {
return new TickUpdateCommand(this);
}
public boolean convertToTargetLayer(ILayer targetLayer) {
// No op.
return true;
}
public IConfigRegistry getConfigRegistry() {
return configRegistry;
}
public boolean isIncrement() {
return increment;
}
}
| 1,002 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DisplayColumnRenameDialogCommandHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/columnRename/DisplayColumnRenameDialogCommandHandler.java | package net.sourceforge.nattable.columnRename;
import net.sourceforge.nattable.command.AbstractLayerCommandHandler;
import net.sourceforge.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.swt.widgets.Shell;
public class DisplayColumnRenameDialogCommandHandler extends
AbstractLayerCommandHandler<DisplayColumnRenameDialogCommand> {
private final ColumnHeaderLayer columnHeaderLayer;
public DisplayColumnRenameDialogCommandHandler(ColumnHeaderLayer columnHeaderLayer) {
this.columnHeaderLayer = columnHeaderLayer;
}
@Override
protected boolean doCommand(DisplayColumnRenameDialogCommand command) {
int columnPosition = command.getColumnPosition();
String originalLabel = columnHeaderLayer.getOriginalColumnLabel(columnPosition);
String renamedLabel = columnHeaderLayer.getRenamedColumnLabel(columnPosition);
ColumnRenameDialog dialog = new ColumnRenameDialog(new Shell(), originalLabel, renamedLabel);
dialog.open();
if (dialog.isCancelPressed()) {
return true;
}
return columnHeaderLayer.renameColumnPosition(columnPosition, dialog.getNewColumnLabel());
}
public Class<DisplayColumnRenameDialogCommand> getCommandClass() {
return DisplayColumnRenameDialogCommand.class;
}
}
| 1,264 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RenameColumnHeaderCommandHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/columnRename/RenameColumnHeaderCommandHandler.java | package net.sourceforge.nattable.columnRename;
import net.sourceforge.nattable.command.AbstractLayerCommandHandler;
import net.sourceforge.nattable.grid.layer.ColumnHeaderLayer;
/**
* Handles renaming of columns.<br/>
* Registered with the {@link ColumnHeaderLayer}.
*/
public class RenameColumnHeaderCommandHandler
extends AbstractLayerCommandHandler<RenameColumnHeaderCommand> {
ColumnHeaderLayer columnHeaderLayer;
public RenameColumnHeaderCommandHandler(ColumnHeaderLayer columnHeaderLayer) {
this.columnHeaderLayer = columnHeaderLayer;
}
@Override
protected boolean doCommand(RenameColumnHeaderCommand command) {
return columnHeaderLayer.renameColumnPosition(command.getColumnPosition(), command.getCustomColumnName());
}
public Class<RenameColumnHeaderCommand> getCommandClass() {
return RenameColumnHeaderCommand.class;
}
}
| 887 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RenameColumnHeaderCommand.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/columnRename/RenameColumnHeaderCommand.java | package net.sourceforge.nattable.columnRename;
import net.sourceforge.nattable.command.AbstractColumnCommand;
import net.sourceforge.nattable.command.ILayerCommand;
import net.sourceforge.nattable.layer.ILayer;
/**
* Command fired to rename a column header
*
* @see RenameColumnHeaderCommandHandler
*/
public class RenameColumnHeaderCommand extends AbstractColumnCommand {
private final String customColumnName;
public RenameColumnHeaderCommand(ILayer layer, int columnPosition, String customColumnName) {
super(layer, columnPosition);
this.customColumnName = customColumnName;
}
public ILayerCommand cloneCommand() {
return new RenameColumnHeaderCommand(getLayer(), getColumnPosition(), customColumnName);
}
public String getCustomColumnName() {
return customColumnName;
}
}
| 831 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ColumnRenameDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/columnRename/ColumnRenameDialog.java | package net.sourceforge.nattable.columnRename;
import net.sourceforge.nattable.style.editor.AbstractStyleEditorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
public class ColumnRenameDialog extends AbstractStyleEditorDialog {
private ColumnLabelPanel columnLabelPanel;
private final String columnLabel;
private String renamedColumnLabel;
public ColumnRenameDialog(Shell parent, String columnLabel, String renamedColumnLabel) {
super(parent);
this.columnLabel = columnLabel;
this.renamedColumnLabel = renamedColumnLabel;
}
@Override
protected void initComponents(final Shell shell) {
GridLayout shellLayout = new GridLayout();
shell.setLayout(shellLayout);
shell.setText("Rename column");
// Closing the window is the same as canceling the form
shell.addShellListener(new ShellAdapter() {
@Override
public void shellClosed(ShellEvent e) {
doFormCancel(shell);
}
});
// Tabs panel
Composite panel = new Composite(shell, SWT.NONE);
panel.setLayout(new GridLayout());
GridData fillGridData = new GridData();
fillGridData.grabExcessHorizontalSpace = true;
fillGridData.horizontalAlignment = GridData.FILL;
panel.setLayoutData(fillGridData);
columnLabelPanel = new ColumnLabelPanel(panel, columnLabel, renamedColumnLabel);
try {
columnLabelPanel.edit(renamedColumnLabel);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
@Override
protected void doFormOK(Shell shell) {
renamedColumnLabel = columnLabelPanel.getNewValue();
shell.dispose();
}
@Override
protected void doFormClear(Shell shell) {
renamedColumnLabel = null;
shell.dispose();
}
public String getNewColumnLabel() {
return renamedColumnLabel;
}
}
| 2,015 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RenameColumnHelper.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/columnRename/RenameColumnHelper.java | package net.sourceforge.nattable.columnRename;
import static org.apache.commons.lang.StringUtils.isEmpty;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import net.sourceforge.nattable.grid.layer.ColumnHeaderLayer;
import net.sourceforge.nattable.persistence.IPersistable;
import net.sourceforge.nattable.util.PersistenceUtils;
public class RenameColumnHelper implements IPersistable {
public static final String PERSISTENCE_KEY_RENAMED_COLUMN_HEADERS = ".renamedColumnHeaders";
private final ColumnHeaderLayer columnHeaderLayer;
/** Tracks the renamed labels provided by the users */
private Map<Integer, String> renamedColumnsLabelsByIndex = new TreeMap<Integer, String>();
public RenameColumnHelper(ColumnHeaderLayer columnHeaderLayer) {
this.columnHeaderLayer = columnHeaderLayer;
}
/**
* Rename the column at the given position.<br/>
* Note: This does not change the underlying column name.
*
* @return
*/
public boolean renameColumnPosition(int columnPosition, String customColumnName) {
int index = columnHeaderLayer.getColumnIndexByPosition(columnPosition);
if (index >= 0) {
if (customColumnName == null) {
renamedColumnsLabelsByIndex.remove(index);
} else {
renamedColumnsLabelsByIndex.put(index, customColumnName);
}
return true;
}
return false;
}
/**
* @return the custom label for this column as specified by the user
* Null if the columns is not renamed
*/
public String getRenamedColumnLabel(int columnIndex) {
return renamedColumnsLabelsByIndex.get(columnIndex);
}
/**
* @return TRUE if the column has been renamed
*/
public boolean isColumnRenamed(int columnIndex) {
return renamedColumnsLabelsByIndex.get(columnIndex) != null;
}
public boolean isAnyColumnRenamed() {
return renamedColumnsLabelsByIndex.size() > 0;
}
public void loadState(String prefix, Properties properties) {
Object property = properties.get(prefix + PERSISTENCE_KEY_RENAMED_COLUMN_HEADERS);
try {
renamedColumnsLabelsByIndex = PersistenceUtils.parseString(property);
} catch (Exception e) {
System.err.println("Error while restoring renamed column headers: " + e.getMessage());
System.err.println("Skipping restore.");
renamedColumnsLabelsByIndex.clear();
}
}
public void saveState(String prefix, Properties properties) {
String string = PersistenceUtils.mapAsString(renamedColumnsLabelsByIndex);
if (!isEmpty(string)) {
properties.put(prefix + PERSISTENCE_KEY_RENAMED_COLUMN_HEADERS, string);
}
}
}
| 2,622 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ColumnLabelPanel.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/columnRename/ColumnLabelPanel.java | package net.sourceforge.nattable.columnRename;
import net.sourceforge.nattable.style.editor.AbstractEditorPanel;
import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class ColumnLabelPanel extends AbstractEditorPanel<String> {
private Text textField;
private final String columnLabel;
private final String newColumnLabel;
public ColumnLabelPanel(Composite parent, String columnLabel, String newColumnLabel) {
super(parent, SWT.NONE);
this.columnLabel = columnLabel;
this.newColumnLabel = newColumnLabel;
init();
}
private void init() {
GridLayout gridLayout = new GridLayout(2, false);
setLayout(gridLayout);
// Original label
Label label = new Label(this, SWT.NONE);
label.setText("Original");
Label originalLabel = new Label(this, SWT.NONE);
originalLabel.setText(columnLabel);
// Text field for new label
Label renameLabel = new Label(this, SWT.NONE);
renameLabel.setText("Rename");
textField = new Text(this, SWT.BORDER);
GridData gridData = new GridData(200, 15);
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
textField.setLayoutData(gridData);
if (StringUtils.isNotEmpty(newColumnLabel)) {
textField.setText(newColumnLabel);
}
}
@Override
public void edit(String newColumnHeaderLabel) throws Exception {
if (StringUtils.isNotEmpty(newColumnHeaderLabel)) {
textField.setText(newColumnHeaderLabel);
}
}
@Override
public String getEditorName() {
return "Column label";
}
@Override
public String getNewValue() {
if (textField.isEnabled() && StringUtils.isNotEmpty(textField.getText())) {
return textField.getText();
}
return null;
}
}
| 1,969 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DisplayColumnRenameDialogCommand.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/net.sourceforge.nattable.core/src/net/sourceforge/nattable/columnRename/DisplayColumnRenameDialogCommand.java | package net.sourceforge.nattable.columnRename;
import net.sourceforge.nattable.command.AbstractColumnCommand;
import net.sourceforge.nattable.command.ILayerCommand;
import net.sourceforge.nattable.layer.ILayer;
/**
* Fire this command to pop-up the rename column dialog.
*/
public class DisplayColumnRenameDialogCommand extends AbstractColumnCommand {
/**
* @param columnPosition of the column to be renamed
*/
public DisplayColumnRenameDialogCommand(ILayer layer, int columnPosition) {
super(layer, columnPosition);
}
public ILayerCommand cloneCommand() {
return new DisplayColumnRenameDialogCommand(getLayer(), getColumnPosition());
}
}
| 683 | 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.websearch/src/net/heartsome/cat/ts/websearch/Activator.java | package net.heartsome.cat.ts.websearch;
import java.io.IOException;
import org.eclipse.core.runtime.FileLocator;
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.websearch"; //$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);
}
/**
*
* 得到工程的绝对路径
* @return ;
*/
public static String getPath(){
try {
return FileLocator.resolve(Activator.getDefault().getBundle().getEntry("/")).getFile();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| 1,814 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WebSearchPreferencStore.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/config/WebSearchPreferencStore.java | /**
* WebSearchPreferencStore.java
*
* Version information :
*
* Date:2013-9-22
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.config;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.websearch.Activator;
import net.heartsome.cat.ts.websearch.bean.SearchEntry;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* 配置信息的保存类
* @author yule
* @version
* @since JDK1.6
*/
public class WebSearchPreferencStore {
public final static Logger logger = LoggerFactory.getLogger(WebSearchPreferencStore.class);
public static String preFix_path = Activator.getPath();
// private String customConfigPath = preFix_path + "configure/WebSearchConfig.xml";
private String customConfigPath = null;
// private String defaultConfigPath = preFix_path + "configure/WebSearchDefaultConfig.xml";
private String defaultConfigPath = null;
private VTDUtils customVu;
private VTDUtils defaultVu;
private static WebSearchPreferencStore ins = null;
private PropertyChangeSupport support = new PropertyChangeSupport(this);
private WebSearchPreferencStore() {
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
try {
customConfigPath = FileLocator.toFileURL(bundle.getEntry("configure/WebSearchConfig.xml")).getPath();
defaultConfigPath = FileLocator.toFileURL(bundle.getEntry("configure/WebSearchDefaultConfig.xml")).getPath();
} catch (Exception e) {
logger.error("", e);
}
customVu = new VTDUtils();
defaultVu = new VTDUtils();
try {
customVu.parseFile(customConfigPath, false);
defaultVu.parseFile(defaultConfigPath, false);
} catch (ParseException e) {
logger.error("path:" + customVu + "|" + defaultVu, e);
e.printStackTrace();
} catch (IOException e) {
logger.error("path:" + customVu + "|" + defaultVu, e);
e.printStackTrace();
}
}
public static WebSearchPreferencStore getIns() {
if (null == ins) {
ins = new WebSearchPreferencStore();
}
return ins;
}
/**
* @param vu
* @param isDefault
* getCustomContent===false:返回所有内容 getCustomContent===true :返回非默认的内容
* @return ;
*/
private List<SearchEntry> getConfig(VTDUtils vu, boolean getCustomContent) {
VTDNav vn = vu.getVTDNav();
AutoPilot mainAp = new AutoPilot(vn);
AutoPilot uesedAp = new AutoPilot(vn);
AutoPilot nameAp = new AutoPilot(vn);
AutoPilot urlAp = new AutoPilot(vn);
List<SearchEntry> cache = new ArrayList<SearchEntry>();
try {
mainAp.selectXPath("/WebSearchInfo/Providers/ProviderInfo");
uesedAp.selectXPath("./Used");
nameAp.selectXPath("./Name");
urlAp.selectXPath("./Url");
SearchEntry temp = null;
while (mainAp.evalXPath() != -1) {
int attrVal = vn.getAttrVal("isDefault");
if (getCustomContent) {
if (-1 != attrVal) {
continue;
}
}
temp = new SearchEntry();
if (-1 != attrVal) {
temp.setDefault(true);
}
int idIndex = vn.getAttrVal("id");
if (-1 != idIndex) {
temp.setId(vn.toString(idIndex));
}
vn.push();
uesedAp.resetXPath();
if (uesedAp.evalXPath() != -1) {
int textIndex = vn.getText();
if (-1 != textIndex && null != temp) {
temp.setChecked("true".equalsIgnoreCase(vn.toString(textIndex)) ? true : false);
}
} else {
temp = null;
}
vn.pop();
vn.push();
nameAp.resetXPath();
if (nameAp.evalXPath() != -1) {
int textIndex = vn.getText();
if (-1 != textIndex && null != temp) {
temp.setSearchName(TextUtil.resetSpecialString(vn.toString(textIndex)));
}
} else {
temp = null;
}
vn.pop();
vn.push();
urlAp.resetXPath();
if (urlAp.evalXPath() != -1) {
int textIndex = vn.getText();
if (-1 != textIndex && null != temp) {
temp.setSearchUrl((TextUtil.resetSpecialString(vn.toString(textIndex))));
}
} else {
temp = null;
}
vn.pop();
if (null != temp) {
cache.add(temp);
}
}
} catch (XPathEvalException e) {
e.printStackTrace();
logger.error("", e);
} catch (NavException e) {
e.printStackTrace();
logger.error("", e);
} catch (XPathParseException e) {
e.printStackTrace();
logger.error("", e);
}
return cache;
}
/**
* 获取所有自定义的配置信息
* @return ;
*/
public List<SearchEntry> getSearchConfig() {
List<SearchEntry> config = getConfig(customVu, false);
return config;
}
/**
* 获取自定义的配置信息中,已经勾选显示在视图页面中的选项
* @return ;
*/
public List<SearchEntry> getUseredConfig() {
List<SearchEntry> config = getConfig(customVu, false);
return getUseredConfig(config);
}
private List<SearchEntry> getUseredConfig(List<SearchEntry> searchEntrys) {
List<SearchEntry> list = new ArrayList<SearchEntry>();
if (null == searchEntrys) {
return list;
}
for (SearchEntry s : searchEntrys) {
if (s.isChecked()) {
list.add(s);
}
}
return list;
}
/**
* 获取默认的配置信息,包括自定义配置文件和默认配置文件两个文件中的信息
* @return ;
*/
public List<SearchEntry> getDefaluSearchConfig() {
List<SearchEntry> config = getConfig(customVu, true);
for (SearchEntry temp : config) {
temp.setChecked(false);
}
List<SearchEntry> defaultconfig = getConfig(defaultVu, false);
defaultconfig.addAll(config);
return defaultconfig;
}
/**
* 保存设置值
* @param searchEntry
* ;
*/
public void storeConfig(List<SearchEntry> searchEntry) {
FileOutputStream out = null;
boolean hasError = false;
try {
out = new FileOutputStream(customConfigPath);
writeContent(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
writeContent(out,
"<WebSearchInfo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instancexmlns:xsd=http://www.w3.org/2001/XMLSchema\">\r\n");
writeContent(out, " <Providers>\r\n");
if (null != searchEntry) {
for (SearchEntry s : searchEntry) {
writeContent(out, convert2Xml(s));
}
}
writeContent(out, " </Providers>\r\n </WebSearchInfo>");
out.flush();
support.firePropertyChange("URL", null, getUseredConfig(searchEntry));
} catch (FileNotFoundException e) {
hasError = true;
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
hasError = true;
e.printStackTrace();
} catch (IOException e) {
hasError = true;
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
if (hasError) {
XMLModifier modifier;
try {
modifier = new XMLModifier(customVu.getVTDNav());
modifier.output(customConfigPath);
} catch (ModifyException e) {
e.printStackTrace();
logger.error("", e);
} catch (TranscodeException e) {
e.printStackTrace();
logger.error("", e);
} catch (IOException e) {
e.printStackTrace();
logger.error("", e);
}
} else {
try {
customVu.parseFile(customConfigPath, false);
} catch (ParseException e) {
e.printStackTrace();
logger.error("", e);
} catch (IOException e) {
e.printStackTrace();
logger.error("", e);
}
}
}
}
private void writeContent(OutputStream out, String str) throws UnsupportedEncodingException, IOException {
out.write(str.getBytes("utf-8"));
}
private String convert2Xml(SearchEntry searchEntry) {
StringBuilder sb = new StringBuilder();
String id = searchEntry.getId();
id = " id = \"" + id + "\" ";
boolean isDefault = searchEntry.isDefault();
String defaultAttr = "";
if (isDefault) {
defaultAttr = " isDefault=" + "\"" + true + "\" ";
}
sb.append(" <ProviderInfo " + id + defaultAttr + ">\r\n");
sb.append(" <Used >" + searchEntry.isChecked() + "</Used>\r\n");
sb.append(" <Name>" + TextUtil.cleanSpecialString(searchEntry.getSearchName()) + "</Name>\r\n");
sb.append(" <Url>" + TextUtil.cleanSpecialString(searchEntry.getSearchUrl()) + "</Url>\r\n");
sb.append(" </ProviderInfo>\r\n");
return sb.toString();
}
public void addProperChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void removeProperChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
/**
* 导入
* @param filePath
* @return ;
*/
public List<SearchEntry> importSearchConfig(String filePath) {
VTDUtils vuTemp = new VTDUtils();
try {
vuTemp.parseFile(filePath, false);
return getConfig(vuTemp, false);
} catch (ParseException e) {
e.printStackTrace();
logger.error("", e);
} catch (IOException e) {
e.printStackTrace();
logger.error("", e);
} catch (Exception e) {
e.printStackTrace();
logger.error("", e);
}
return null;
}
/**
* 导出
* @param targetFilePath
* @return ;
*/
public boolean exportSearchConfig(String targetFilePath) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(customConfigPath);
out = new FileOutputStream(targetFilePath);
byte[] b = new byte[1024];
int count = -1;
while ((count = in.read(b)) != -1) {
out.write(b, 0, count);
out.flush();
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error("", e);
return false;
} catch (IOException e) {
e.printStackTrace();
logger.error("", e);
return false;
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("", e);
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("", e);
}
}
}
}
}
| 11,543 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SearchEntry.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/bean/SearchEntry.java | /**
* SearchEntry.java
*
* Version information :
*
* Date:2013-9-22
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.bean;
/**
* 搜索设置的配置信息
* @author yule
* @version
* @since JDK1.6
*/
public class SearchEntry {
/**
* 关键字替换字符
*/
public final static String KEY_WORD = "\\[\\{\\}\\]";
/**
* 搜索名字
*/
private String searchName;
/**
* 搜索url配置
*/
private String searchUrl;
/**
* 搜索是否选中
*/
private boolean isChecked;
/**
* 搜索图标 ,没有使用.图片改为自动从网站获取
*/
private String imagePath;
/** @return the searchName */
private boolean isDefault;
private String id ;
/** @return the id */
public String getId() {
if(null == id){
id =""+System.currentTimeMillis();
}
return id;
}
/** @param id the id to set */
public void setId(String id) {
this.id = id;
}
/** @return the isDefault */
public boolean isDefault() {
return isDefault;
}
/** @param isDefault the isDefault to set */
public void setDefault(boolean isDefault) {
this.isDefault = isDefault;
}
public String getSearchName() {
return searchName;
}
/** @param searchName the searchName to set */
public void setSearchName(String searchName) {
this.searchName = searchName;
}
/** @return the searchUrl */
public String getSearchUrl() {
return searchUrl;
}
/** @param searchUrl the searchUrl to set */
public void setSearchUrl(String searchUrl) {
this.searchUrl = searchUrl;
}
/** @return the isChecked */
public boolean isChecked() {
return isChecked;
}
/** @param isChecked the isChecked to set */
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
/** @return the imagePath */
public String getImagePath() {
return imagePath;
}
/** @param imagePath the imagePath to set */
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
| 2,594 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WebSearchHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/handler/WebSearchHandler.java | /**
* WebSearchHandler.java
*
* Version information :
*
* Date:2013-9-18
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.handler;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import net.heartsome.cat.ts.websearch.ui.view.BrowserViewPart;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class WebSearchHandler extends AbstractHandler {
public final static Logger logger = LoggerFactory.getLogger(WebSearchHandler.class);
/** (non-Javadoc)
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = HandlerUtil.getActiveEditor(event);
String selectPureText ="";
if (editor instanceof IXliffEditor) {
IXliffEditor xliffEditor = (IXliffEditor) editor;
selectPureText= xliffEditor.getSelectPureText();
}
try {
IViewPart showView = getActivePage().showView(BrowserViewPart.ID);
if(showView instanceof BrowserViewPart){
BrowserViewPart browserViewPart = (BrowserViewPart) showView;
browserViewPart.setKeyWord(selectPureText,true);
}
} catch (PartInitException e) {
e.printStackTrace();
logger.error("", e);
}
// 暂时去掉VIEW弹出显示
// IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
// if (activePage instanceof WorkbenchPage) {
// WorkbenchPage workbenchPage = (WorkbenchPage) activePage;
// IViewReference findViewReference = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
// .findViewReference(BrowserViewPart.ID);
// workbenchPage.detachView(findViewReference);
// }
return null;
}
public static IWorkbenchPage getActivePage(){
return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
} | 2,898 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WebSearchPreferenceInitializer.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/ui/preference/WebSearchPreferenceInitializer.java | /**
* WebSearchPreferenceInitializer.java
*
* Version information :
*
* Date:2013-9-18
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.ui.preference;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class WebSearchPreferenceInitializer extends AbstractPreferenceInitializer {
/** (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
@Override
public void initializeDefaultPreferences() {
// TODO Auto-generated method stub
}
}
| 1,174 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WebSearchPreferencePage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/ui/preference/WebSearchPreferencePage.java | /**
* WebSearchPreferencePage.java
*
* Version information :
*
* Date:2013-9-18
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.ui.preference;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.ui.HsImageLabel;
import net.heartsome.cat.ts.websearch.Activator;
import net.heartsome.cat.ts.websearch.bean.SearchEntry;
import net.heartsome.cat.ts.websearch.config.WebSearchPreferencStore;
import net.heartsome.cat.ts.websearch.resource.Messages;
import net.heartsome.cat.ts.websearch.ui.dialog.AddSearchEntryDialog;
import net.heartsome.cat.ts.websearch.ui.dialog.AddSearchEntryDialog.OKHandler;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ICheckStateProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
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.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class WebSearchPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
public final static Logger logger = LoggerFactory.getLogger(WebSearchPreferencePage.class);
public static final String ID = "net.heartsome.cat.ts.websearch.ui.preference.WebSearchPreferencePage";
private static final String[] tittles = new String[] {
Messages.getString("Websearch.WebSearcPreferencePage.tableTilte1"),
Messages.getString("Websearch.WebSearcPreferencePage.tableTilte2"),
Messages.getString("Websearch.WebSearcPreferencePage.tableTilte3") };
private static final String APP_PROP = "APP_PROP";
private static final String NAME_PROP = "NAME_PROP";
private static final String URL_PROP = "URL_PROP";
private CheckboxTableViewer checkboxTableViewer;
private List<SearchEntry> cache;
private boolean isDirty = false;
/** @return the isDirty */
public boolean isDirty() {
return isDirty;
}
/**
* @param isDirty
* the isDirty to set
*/
public void setDirty(boolean isDirty) {
this.isDirty = isDirty;
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
@Override
public void init(IWorkbench workbench) {
// TODO Auto-generated method stub
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
@Override
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 group = new Group(tparent, SWT.NONE);
group.setText(Messages.getString("Websearch.WebSearcPreferencePage.urlSet"));
group.setLayout(new GridLayout(1, false));
group.setLayoutData(new GridData(GridData.FILL_BOTH));
// Composite composite = new Composite(group, SWT.NONE);
createTitleArea(group);
Composite urlArea = new Composite(group, SWT.NONE);
GridLayout urlArea_layout = new GridLayout(2, false);
urlArea.setLayout(urlArea_layout);
urlArea.setLayoutData(new GridData(GridData.FILL_BOTH));
createTableArea(urlArea);
createTableCmdArea(urlArea);
installListeners();
return group;
}
private Composite createTitleArea(Composite parent) {
HsImageLabel paraConsisLbl = new HsImageLabel(Messages.getString("Websearch.WebSearcPreferencePage.setInfo"),
Activator.getImageDescriptor("image/websearch32.png"));
paraConsisLbl.createControl(parent);
paraConsisLbl.computeSize();
return parent;
}
private Table table;
private Composite createTableArea(Composite parent) {
Composite tableArea = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout(1, false);
gridLayout.marginWidth = 0;
tableArea.setLayout(gridLayout);
GridData gridData = new GridData(GridData.FILL_BOTH);
tableArea.setLayoutData(gridData);
checkboxTableViewer = CheckboxTableViewer.newCheckList(tableArea, SWT.BORDER | SWT.FULL_SELECTION);
table = checkboxTableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(false);
TableLayout tableLayout = new TableLayout();
tableLayout.addColumnData(new ColumnPixelData(40));
tableLayout.addColumnData(new ColumnWeightData(50, 50, true));
tableLayout.addColumnData(new ColumnWeightData(70, 50, true));
table.setLayout(tableLayout);
GridData tableGridData = new GridData(GridData.FILL_BOTH);
table.setLayoutData(tableGridData);
WebSearchLableProvider webSearchLableProvider = new WebSearchLableProvider();
webSearchLableProvider.createColumns(checkboxTableViewer);
checkboxTableViewer.setContentProvider(new WebSearchContentProvider());
checkboxTableViewer.setLabelProvider(webSearchLableProvider);
checkboxTableViewer.setCheckStateProvider(new CheckProvider());
checkboxTableViewer.addCheckStateListener(new CheckListener());
// checkboxTableViewer.setCellEditors(new CellEditor[] { null, new TextCellEditor(table),
// new TextCellEditor(table) });
// checkboxTableViewer.setCellModifier(new NameModifier());
checkboxTableViewer.setColumnProperties(new String[] { APP_PROP, NAME_PROP, URL_PROP });
cache = WebSearchPreferencStore.getIns().getSearchConfig();
checkboxTableViewer.setInput((Object) cache);
return tableArea;
}
private Button addItemBtn;
private Button editItemBtn;
private Button deleteItemBtn;
private Button upItemBtn;
private Button downItemBtn;
private Button importItemsBtn;
private Button exportItemsBtn;
private Composite createTableCmdArea(Composite parent) {
Composite urlCmdArea = new Composite(parent, SWT.NONE);
GridLayout urlCmdArea_layout = new GridLayout(1, true);
urlCmdArea.setLayout(urlCmdArea_layout);
urlCmdArea.setLayoutData(new GridData(GridData.FILL_VERTICAL));
addItemBtn = new Button(urlCmdArea, SWT.NONE);
addItemBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
addItemBtn.setText(Messages.getString("Websearch.WebSearcPreferencePage.Add"));
editItemBtn = new Button(urlCmdArea, SWT.NONE);
editItemBtn.setText(Messages.getString("Websearch.WebSearcPreferencePage.edit"));
editItemBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
editItemBtn.setEnabled(false);
deleteItemBtn = new Button(urlCmdArea, SWT.NONE);
deleteItemBtn.setText(Messages.getString("Websearch.WebSearcPreferencePage.delete"));
deleteItemBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
deleteItemBtn.setEnabled(false);
upItemBtn = new Button(urlCmdArea, SWT.NONE);
upItemBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
upItemBtn.setText(Messages.getString("Websearch.WebSearcPreferencePage.upitem"));
upItemBtn.setEnabled(false);
downItemBtn = new Button(urlCmdArea, SWT.NONE);
downItemBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
downItemBtn.setText(Messages.getString("Websearch.WebSearcPreferencePage.downitem"));
downItemBtn.setEnabled(false);
importItemsBtn = new Button(urlCmdArea, SWT.NONE);
importItemsBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
importItemsBtn.setText(Messages.getString("Websearch.WebSearcPreferencePage.import"));
exportItemsBtn = new Button(urlCmdArea, SWT.NONE);
exportItemsBtn.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
exportItemsBtn.setText(Messages.getString("Websearch.WebSearcPreferencePage.export"));
return urlCmdArea;
}
private class NameModifier implements ICellModifier {
@Override
public void modify(Object element, String property, Object value) {
if (element instanceof Item) {
Item item = (Item) element;
SearchEntry data = (SearchEntry) item.getData();
if (NAME_PROP.equals(property)) {
if (!((String) value).equals(data.getSearchName())) {
data.setSearchName((String) value);
checkboxTableViewer.update(data, null);
setDirty(true);
}
} else if (URL_PROP.equals(property)) {
if (!((String) value).equals(data.getSearchUrl())) {
data.setSearchUrl((String) value);
checkboxTableViewer.update(data, null);
setDirty(true);
}
}
}
}
@Override
public Object getValue(Object element, String property) {
if (element instanceof SearchEntry) {
SearchEntry searchEntry = (SearchEntry) element;
if (NAME_PROP.equals(property)) {
return searchEntry.getSearchName();
} else if (URL_PROP.equals(property)) {
return searchEntry.getSearchUrl();
}
}
return "";
}
@Override
public boolean canModify(Object element, String property) {
if (NAME_PROP.equals(property) || URL_PROP.equals(property)) {
return true;
}
return false;
}
}
private class CheckListener implements ICheckStateListener {
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged(org.eclipse.jface.viewers.CheckStateChangedEvent)
*/
@Override
public void checkStateChanged(CheckStateChangedEvent event) {
Object element = event.getElement();
if (element instanceof SearchEntry) {
SearchEntry searchEntry = (SearchEntry) element;
if (searchEntry.isChecked() != event.getChecked()) {
searchEntry.setChecked(event.getChecked());
setDirty(true);
}
}
}
}
private class WebSearchLableProvider implements ITableLabelProvider {
private List<Image> cache = new ArrayList<Image>();
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
@Override
public void addListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
*/
@Override
public void dispose() {
// TODO Auto-generated method stub
for (Image e : cache) {
e.dispose();
}
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object, java.lang.String)
*/
@Override
public boolean isLabelProperty(Object element, String property) {
// TODO Auto-generated method stub
return false;
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
@Override
public void removeListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
@Override
public Image getColumnImage(Object element, int columnIndex) {
SearchEntry searchEntry = null;
if (element instanceof SearchEntry) {
searchEntry = (SearchEntry) element;
} else {
return null;
}
switch (columnIndex) {
case 1:
String imagePath = searchEntry.getImagePath();
if (null == imagePath) {
return null;
}
Image e = Activator.getImageDescriptor(imagePath).createImage();
cache.add(e);
return e;
default:
return null;
}
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object element, int columnIndex) {
SearchEntry searchEntry = null;
if (element instanceof SearchEntry) {
searchEntry = (SearchEntry) element;
} else {
return null;
}
switch (columnIndex) {
case 1:
return searchEntry.getSearchName();
case 2:
return searchEntry.getSearchUrl();
default:
return null;
}
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object)
*/
public void createColumns(TableViewer viewer) {
for (int i = 0; i < tittles.length; i++) {
TableColumn column = new TableViewerColumn(viewer, SWT.NONE).getColumn();
column.setText(tittles[i]);
column.setResizable(true);
}
}
}
private class WebSearchContentProvider implements IStructuredContentProvider {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object inputElement) {
if (inputElement instanceof List<?>) {
@SuppressWarnings("unchecked")
List<SearchEntry> list = (List<SearchEntry>) inputElement;
return list.toArray(new SearchEntry[list.size()]);
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
@Override
public void dispose() {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
* java.lang.Object, java.lang.Object)
*/
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
private class CheckProvider implements ICheckStateProvider {
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.ICheckStateProvider#isChecked(java.lang.Object)
*/
@Override
public boolean isChecked(Object element) {
if (element instanceof SearchEntry) {
SearchEntry searchEntry = (SearchEntry) element;
if (searchEntry.isChecked()) {
return true;
}
}
return false;
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.viewers.ICheckStateProvider#isGrayed(java.lang.Object)
*/
@Override
public boolean isGrayed(Object element) {
return false;
}
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#performOk()
*/
@Override
public boolean performOk() {
if (isDirty()) {
WebSearchPreferencStore.getIns().storeConfig(cache);
setDirty(false);
}
return super.performOk();
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
@Override
protected void performDefaults() {
cache = WebSearchPreferencStore.getIns().getDefaluSearchConfig();
refreshTable(cache);
WebSearchPreferencStore.getIns().storeConfig(cache);
setDirty(false);
super.performDefaults();
}
public void refreshTable(Object input) {
checkboxTableViewer.setInput(input);
checkboxTableViewer.refresh();
}
private void installListeners() {
checkboxTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
updateState();
}
});
upItemBtn.addSelectionListener(new SelectionAdapter() {
/**
* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
@Override
public void widgetSelected(SelectionEvent e) {
upSelectItem();
}
});
downItemBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
downSelectItem();
}
});
deleteItemBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
deleteSelectItem();
}
});
addItemBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
addItem();
}
});
editItemBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
editItem();
}
});
importItemsBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
importConfig();
}
});
exportItemsBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
exportConfig();
}
});
}
public SearchEntry getSelectTableItem() {
int selectionIndex = getSelectIndex();
if (-1 == selectionIndex) {
return null;
}
return (SearchEntry) table.getItem(selectionIndex).getData();
}
private int getSelectIndex() {
return table.getSelectionIndex();
}
public void upSelectItem() {
int selectIndex = getSelectIndex();
if (-1 == selectIndex || 0 == selectIndex) {
return;
}
SearchEntry currentSelect = cache.get(selectIndex);
SearchEntry lastData = cache.get(selectIndex - 1);
cache.set(selectIndex - 1, currentSelect);
cache.set(selectIndex, lastData);
checkboxTableViewer.refresh();
setDirty(true);
updateState();
}
public void downSelectItem() {
int selectIndex = getSelectIndex();
if (-1 == selectIndex || cache.size() - 1 == selectIndex) {
return;
}
SearchEntry currentSelect = cache.get(selectIndex);
SearchEntry lastData = cache.get(selectIndex + 1);
cache.set(selectIndex + 1, currentSelect);
cache.set(selectIndex, lastData);
checkboxTableViewer.refresh();
setDirty(true);
updateState();
}
public void deleteSelectItem() {
int selectIndex = getSelectIndex();
if (-1 == selectIndex) {
return;
}
SearchEntry searchEntry = cache.get(selectIndex);
boolean config = MessageDialog.openConfirm(
getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
MessageFormat.format(Messages.getString("Websearch.WebSearcPreferencePage.deleteConfig"),
searchEntry.getSearchName()));
if (config) {
cache.remove(selectIndex);
checkboxTableViewer.refresh();
setDirty(true);
updateState();
}
}
public void addItem() {
final SearchEntry entry = new SearchEntry();
AddSearchEntryDialog addDilog = new AddSearchEntryDialog(getShell(), entry, AddSearchEntryDialog.ADD);
addDilog.setHandler(new OKHandler(){
@Override
public boolean doOk() {
if (null == entry.getSearchName()) {
return false;
}
if (hasDisplayNameDulicate(cache, entry)) {
MessageDialog.openInformation(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.hasDuplicateName"));
return false;
}
if (hasDupliacateUrl(cache, entry)) {
MessageDialog.openInformation(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.hasDuplicateUrl"));
return false;
}
cache.add(entry);
setDirty(true);
checkboxTableViewer.refresh();
updateState();
return true;
}
});
addDilog.open();
}
private boolean hasDupliacateUrl(List<SearchEntry> cacheParam, SearchEntry entryParam) {
for (SearchEntry temp : cacheParam) {
if (temp == entryParam) {
continue;
}
if (temp.getSearchUrl().equals(entryParam.getSearchUrl())) {
return true;
}
}
return false;
}
private boolean hasDisplayNameDulicate(List<SearchEntry> cacheParam, SearchEntry entryParam) {
for (SearchEntry temp : cacheParam) {
if (temp == entryParam) {
continue;
}
if (temp.getSearchName().equals(entryParam.getSearchName())) {
return true;
}
}
return false;
}
public void editItem() {
final SearchEntry selectTableItem = getSelectTableItem();
if (null == selectTableItem) {
return;
}
final String oldName = selectTableItem.getSearchName();
final String oldUrl = selectTableItem.getSearchUrl();
final boolean isChecked = selectTableItem.isChecked();
AddSearchEntryDialog addDilog = new AddSearchEntryDialog(getShell(), selectTableItem, AddSearchEntryDialog.EDIT);
addDilog.setHandler(new OKHandler() {
@Override
public boolean doOk() {
if (oldName.equals(selectTableItem.getSearchName()) //
&& isChecked == selectTableItem.isChecked()//
&& oldUrl.equals(selectTableItem.getSearchUrl())) {
return false;
}
if (hasDisplayNameDulicate(cache, selectTableItem)) {
selectTableItem.setChecked(isChecked);
selectTableItem.setSearchName(oldName);
selectTableItem.setSearchUrl(oldUrl);
MessageDialog.openInformation(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.hasDuplicateName"));
return false;
}
if (hasDupliacateUrl(cache, selectTableItem)) {
selectTableItem.setChecked(isChecked);
selectTableItem.setSearchName(oldName);
selectTableItem.setSearchUrl(oldUrl);
MessageDialog.openInformation(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.hasDuplicateUrl"));
return false;
}
setDirty(true);
checkboxTableViewer.refresh();
updateState();
return true;
}
});
addDilog.open();
}
private void updateState() {
if (getSelectIndex() == -1) {
upItemBtn.setEnabled(false);
downItemBtn.setEnabled(false);
deleteItemBtn.setEnabled(false);
editItemBtn.setEnabled(false);
} else {
deleteItemBtn.setEnabled(true);
editItemBtn.setEnabled(true);
if (getSelectIndex() == 0) {
upItemBtn.setEnabled(false);
} else {
upItemBtn.setEnabled(true);
}
if (getSelectIndex() == cache.size() - 1) {
downItemBtn.setEnabled(false);
} else {
downItemBtn.setEnabled(true);
}
}
}
public void importConfig() {
boolean config = MessageDialog.openConfirm(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.importConfig"));
if (!config) {
return;
}
FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
dialog.setFilterExtensions(new String[] { "*.xml" });
dialog.open();
String filterPath = dialog.getFilterPath();
if (null == filterPath || filterPath.isEmpty()) {
return;
}
String fileName = dialog.getFileName();
if (fileName == null) {
return;
}
String filePath = filterPath + File.separator + fileName;
List<SearchEntry> importSearchConfig = WebSearchPreferencStore.getIns().importSearchConfig(filePath);
if (null == importSearchConfig || importSearchConfig.isEmpty()) {
MessageDialog.openError(getShell(), Messages.getString("Websearch.WebSearcPreferencePage.errorTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.importError"));
return;
} else {
cache = importSearchConfig;
refreshTable(cache);
setDirty(true);
}
}
public void exportConfig() {
FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
dialog.setFileName("Web_Config.xml");
dialog.open();
String filterPath = dialog.getFilterPath();
if (null == filterPath || filterPath.isEmpty()) {
return;
}
File file = new File(filterPath + File.separator + dialog.getFileName());
boolean config = true;
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
logger.error("", e);
}
} else {
config = MessageDialog.openConfirm(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.ConfirmInfo"));
}
if (config) {
boolean exportSearchConfig = WebSearchPreferencStore.getIns().exportSearchConfig(file.getAbsolutePath());
if (exportSearchConfig) {
MessageDialog.openInformation(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.exportFinish"));
} else {
MessageDialog.openInformation(getShell(),
Messages.getString("Websearch.WebSearcPreferencePage.tipTitle"),
Messages.getString("Websearch.WebSearcPreferencePage.failexport"));
}
}
}
}
| 26,238 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
BrowserViewPart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/ui/view/BrowserViewPart.java | /**
* BrowserViewPart.java
*
* Version information :
*
* Date:2013-9-16
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.ui.view;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import net.heartsome.cat.ts.ui.util.PreferenceUtil;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.HsMultiActiveCellEditor;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.StyledTextCellEditor;
import net.heartsome.cat.ts.websearch.bean.SearchEntry;
import net.heartsome.cat.ts.websearch.config.WebSearchPreferencStore;
import net.heartsome.cat.ts.websearch.resource.Messages;
import net.heartsome.cat.ts.websearch.ui.browser.BrowserTab;
import net.heartsome.cat.ts.websearch.ui.preference.WebSearchPreferencePage;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
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.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.UIJob;
/**
* @author Administrator
* @version
* @since JDK1.6
*/
public class BrowserViewPart extends ViewPart {
public static final String ID = "net.heartsome.cat.ts.websearch.ui.view.BrowserViewPart"; //$NON-NLS-1$
private List<SearchEntry> urls;
private BrowserTab[] browserTabs;
private Text keyWordForSearch;
private CTabFolder tabFolder;
private PropertyChangeListener urlChangelistener = new ProperChangeListener();
private ResfreshCurentTab refreshContentJob;
private Map<String, Image> titleIamgeCache = new HashMap<String, Image>(5);
private Font font;
/**
* Create contents of the view part.
* @param parent
*/
@Override
public void createPartControl(Composite parent) {
urls = WebSearchPreferencStore.getIns().getUseredConfig();
WebSearchPreferencStore.getIns().addProperChangeListener(urlChangelistener);
Composite container = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout(1, false);
gridLayout.verticalSpacing = 0;
container.setLayout(gridLayout);
Composite seachArea = new Composite(container, SWT.NONE);
createSearchArea(seachArea);
Composite separatorCmp = new Composite(container, SWT.NONE);
createSeparatorArea(separatorCmp);
Composite displayArea = new Composite(container, SWT.NONE);
createBrowserArea(displayArea);
refreshContentJob = new ResfreshCurentTab();
refreshContentJob.start();
}
private Composite createSearchArea(Composite parent) {
GridLayout gridLayout = new GridLayout(3, false);
parent.setLayout(gridLayout);
GridData gd_seachArea = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
parent.setLayoutData(gd_seachArea);
keyWordForSearch = new Text(parent, SWT.SEARCH);
GridData gd_keyWordForSearch = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
gd_keyWordForSearch.heightHint = 20;
keyWordForSearch.setLayoutData(gd_keyWordForSearch);
keyWordForSearch.setText("");
font = keyWordForSearch.getFont();
FontData fontData = font.getFontData()[0];
fontData.setStyle(fontData.getStyle());
fontData.setHeight(12);
font = new Font(Display.getDefault(), fontData);
keyWordForSearch.setFont(font);
keyWordForSearch.addKeyListener(new KeyListener() {
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.keyCode == SWT.CR || e.keyCode == SWT.LF) {
refreshKeyWordSearch(true);
}
}
});
Button searchBtn = new Button(parent, SWT.NONE);
searchBtn.setText(Messages.getString("Websearch.browserViewPart.searchBtnLbl"));
searchBtn.setLayoutData(new GridData(GridData.FILL_VERTICAL));
searchBtn.addSelectionListener(new SelectionAdapter() {
/**
* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
@Override
public void widgetSelected(SelectionEvent e) {
refreshKeyWordSearch(true);
}
});
Button settingBtn = new Button(parent, SWT.NONE);
settingBtn.setText(Messages.getString("Websearch.browserViewPart.settingBtnLbl"));
settingBtn.setLayoutData(new GridData(GridData.FILL_VERTICAL));
settingBtn.addSelectionListener(new SelectionAdapter() {
/**
* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
@Override
public void widgetSelected(SelectionEvent e) {
PreferenceUtil.openPreferenceDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow(), WebSearchPreferencePage.ID);
}
});
return parent;
}
private Composite createSeparatorArea(Composite parent) {
GridLayout gridLayout = new GridLayout(1, false);
parent.setLayout(gridLayout);
parent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label label = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return parent;
}
private Composite createBrowserArea(Composite parent) {
GridLayout gridLayout = new GridLayout(1, false);
parent.setLayout(gridLayout);
GridData gd_displayArea = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
parent.setLayoutData(gd_displayArea);
tabFolder = new CTabFolder(parent, SWT.TOP|SWT.MULTI|SWT.FLAT);
tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
UIJob job = new UIJob(Display.getDefault(),"refresh browser") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
refreshTabContent();
return Status.OK_STATUS;
}
/** (non-Javadoc)
* @see org.eclipse.core.runtime.jobs.Job#shouldRun()
*/
@Override
public boolean shouldRun() {
return !tabFolder.isDisposed();
}
};
job.schedule();
return parent;
}
public BrowserTab getCurrentTab() {
int selectionIndex = tabFolder.getSelectionIndex();
return browserTabs[selectionIndex];
}
public void refreshTabContent() {
if (browserTabs != null && browserTabs.length != 0) {
for (BrowserTab tab : browserTabs) {
tab.close();
}
}
browserTabs = new BrowserTab[urls.size()];
for (int i = 0; i < urls.size(); i++) {
SearchEntry searchEntry = urls.get(i);
browserTabs[i] = new BrowserTab(searchEntry);
CTabItem item = new CTabItem(tabFolder, SWT.NONE);
browserTabs[i].setItem(item);
item.setText(searchEntry.getSearchName().replaceAll("&", "&&"));
item.setControl(browserTabs[i].createTabFolderPage(tabFolder));
item.setData(browserTabs[i]);
Image image = getImage(searchEntry.getSearchUrl());
if (null != image) {
item.setImage(image);
}
browserTabs[i].searchKeyWord(keyWordForSearch.getText());
}
tabFolder.setSelection(0);
tabFolder.layout();
}
public void refreshKeyWordSearch(boolean refreshAll) {
if (browserTabs == null || browserTabs.length == 0) {
return;
}
if (!refreshAll) {
getCurrentTab().searchKeyWord(keyWordForSearch.getText());
} else {
for (BrowserTab tab : browserTabs) {
tab.searchKeyWord(keyWordForSearch.getText());
}
}
}
@Override
public void setFocus() {
// Set the focus
}
public void setKeyWord(String word, boolean refreshAll) {
if (null == this.keyWordForSearch) {
return;
}
this.keyWordForSearch.setText(word);
refreshKeyWordSearch(refreshAll);
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
@Override
public void dispose() {
if (browserTabs != null && browserTabs.length != 0) {
for (BrowserTab tab : browserTabs) {
tab.close();
}
}
disposeCacheImage();
if (null != font) {
font.dispose();
}
WebSearchPreferencStore.getIns().removeProperChangeListener(urlChangelistener);
if (null != refreshContentJob) {
refreshContentJob.setStop(true);
}
super.dispose();
}
public void disposeCacheImage() {
Collection<Image> values = titleIamgeCache.values();
for (Image image : values) {
if (null != image) {
image.dispose();
}
}
}
private class ProperChangeListener implements PropertyChangeListener {
/**
* (non-Javadoc)
* @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
*/
@SuppressWarnings("unchecked")
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("URL".equals(evt.getPropertyName())) {
BrowserViewPart.this.urls = (List<SearchEntry>) evt.getNewValue();
refreshTabContent();
}
}
}
class ResfreshCurentTab extends Thread {
private boolean isStop;
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
if (isStop()) {
shutDown();
return;
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (isStop()) {
return;
}
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
if(null == activeWorkbenchWindow){
return;
}
IViewPart findView=activeWorkbenchWindow.getActivePage()
.findView(ID);
if (null == findView) {
return;
}
if (!activeWorkbenchWindow.getActivePage()
.isPartVisible(findView)) {
return;
}
StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getFocusCellEditor();
if (null == cellEditor) {
return;
}
if (cellEditor.getMouseState()) {
return;
}
final String selectedPureText = cellEditor.getSelectedPureText();
if (null == selectedPureText || selectedPureText.trim().isEmpty()) {
return;
}
if (keyWordForSearch.getText().equals(selectedPureText)) {
return;
}
keyWordForSearch.setText(selectedPureText);
refreshKeyWordSearch(false);
}
});
}
}
/** @return the isStop */
public boolean isStop() {
return isStop;
}
/**
* @param isStop
* the isStop to set
*/
public void setStop(boolean isStop) {
this.isStop = isStop;
}
public void shutDown() {
this.interrupt();
}
}
private String getImageUrl(String url) {
String imageName = "favicon.ico";
String HTTP = "http://";
url = url.toLowerCase(Locale.ENGLISH);
String imageUrl = "";
if (url.startsWith(HTTP)) {
url = url.substring(HTTP.length());
}
int separator = url.indexOf("/");
if (-1 != separator) {
url = url.substring(0, separator);
}
url = url+"/";
imageUrl = HTTP + url + imageName;
return imageUrl;
}
public Image getTitleImage(String iamgeUrl) {
Image cacheImage = titleIamgeCache.get(iamgeUrl);
if (null != cacheImage) {
return cacheImage;
}
URL url = null;
try {
url = new URL(iamgeUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (null == url) {
return null;
}
Image image = null;
try {
ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(url);
ImageData imageData = imageDescriptor.getImageData();
ImageData scaledTo = imageData.scaledTo(16, 16);
image = ImageDescriptor.createFromImageData(scaledTo).createImage();
} catch (Exception e) {
// no need handle
return null;
}
if (null != image) {
titleIamgeCache.put(iamgeUrl, image);
}
return image;
}
public Image getImage(String WebConfigUrl) {
return getTitleImage(getImageUrl(WebConfigUrl));
}
}
| 13,495 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AddSearchEntryDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/ui/dialog/AddSearchEntryDialog.java | /**
* AddSearchEntryDialog.java
*
* Version information :
*
* Date:2013-9-24
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.ui.dialog;
import net.heartsome.cat.ts.websearch.bean.SearchEntry;
import net.heartsome.cat.ts.websearch.resource.Messages;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.util.Assert;
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.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.Shell;
import org.eclipse.swt.widgets.Text;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class AddSearchEntryDialog extends Dialog {
public static final int ADD = 0;
public static final int EDIT = 1;
private Text nameText;
private Text urlText;
private Button btnYesRadioButton;
private Button btnNoRadioButton;
private SearchEntry searEntry;
private int style = -1;
private OKHandler handler;
/**
* Create the dialog.
* @param parentShell
*/
public AddSearchEntryDialog(Shell parentShell, SearchEntry searEntry, int style) {
super(parentShell);
this.searEntry = searEntry;
this.style = style;
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("Websearch.AddSearchEntryDialog.title"));
setShellStyle(getShellStyle() & ~SWT.APPLICATION_MODAL);
}
/**
* 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));
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.heightHint = SWT.DEFAULT;
gridData.widthHint = 450;
container.setLayoutData(gridData);
Composite nameSetArea = new Composite(container, SWT.NONE);
GridLayout gridLayout = new GridLayout(2, false);
nameSetArea.setLayout(gridLayout);
nameSetArea.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label nameLable = new Label(nameSetArea, SWT.NONE);
GridData gd_nameLable = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_nameLable.widthHint = 38;
nameLable.setLayoutData(gd_nameLable);
nameLable.setText(Messages.getString("Websearch.AddSearchEntryDialog.NameLable"));
nameText = new Text(nameSetArea, SWT.BORDER);
nameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (style == EDIT) {
nameText.setText(searEntry.getSearchName());
}
nameText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
setOkState();
}
});
Composite urlSetArea = new Composite(container, SWT.NONE);
GridLayout gridLayout2 = new GridLayout(2, false);
urlSetArea.setLayout(gridLayout2);
urlSetArea.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label urlLable = new Label(urlSetArea, SWT.NONE);
GridData gd_urlLable = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_urlLable.widthHint = 38;
urlLable.setLayoutData(gd_urlLable);
urlLable.setText("URL");
urlText = new Text(urlSetArea, SWT.BORDER);
if (style == EDIT) {
urlText.setText(searEntry.getSearchUrl());
}
urlText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
urlText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
setOkState();
}
});
Composite setArea = new Composite(container, SWT.NONE);
setArea.setLayout(new GridLayout(1, true));
setArea.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Group group = new Group(setArea, SWT.NONE);
group.setLayout(new GridLayout(2, true));
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setText(Messages.getString("Websearch.AddSearchEntryDialog.GroupTitle"));
btnYesRadioButton = new Button(group, SWT.RADIO);
btnYesRadioButton.setText(Messages.getString("Websearch.AddSearchEntryDialog.GroupYes"));
btnYesRadioButton.setSelection(true);
btnYesRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnNoRadioButton = new Button(group, SWT.RADIO);
btnNoRadioButton.setText(Messages.getString("Websearch.AddSearchEntryDialog.GroupNo"));
btnNoRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (style == EDIT) {
btnYesRadioButton.setSelection(searEntry.isChecked());
btnNoRadioButton.setSelection(!searEntry.isChecked());
}
return container;
}
private Button okBtn;
/**
* Create contents of the button bar.
* @param parent
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
okBtn = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
okBtn.setEnabled(false);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
setOkState();
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@SuppressWarnings("deprecation")
@Override
protected void okPressed() {
if (validateValue()) {
this.searEntry.setSearchName(nameText.getText());
if (style == ADD) {
this.searEntry.setDefault(false);
}
this.searEntry.setSearchUrl(urlText.getText());
this.searEntry.setChecked(btnYesRadioButton.getSelection());
Assert.isNotNull(handler, "OKhandler can not be null");
if (!handler.doOk()) {
return;
}
}
super.okPressed();
}
public boolean validateValue() {
String nameValue = nameText.getText();
String urlValue = urlText.getText();
if (nameValue.trim().isEmpty() || urlValue.trim().isEmpty()) {
return false;
}
return true;
}
private void setOkState() {
if (validateValue()) {
okBtn.setEnabled(true);
} else {
okBtn.setEnabled(false);
}
}
public void setHandler(OKHandler handler) {
this.handler = handler;
}
public interface OKHandler {
boolean doOk();
}
}
| 7,050 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
BrowserTab.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/ui/browser/BrowserTab.java | /**
* BrowserTab.java
*
* Version information :
*
* Date:2013-9-16
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.ts.websearch.ui.browser;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import net.heartsome.cat.ts.websearch.bean.SearchEntry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author yule_chen
* @version
* @since JDK1.6
*/
public class BrowserTab {
public final static Logger logger = LoggerFactory.getLogger(BrowserTab.class);
private Browser browser;
private SearchEntry searchEntry;
private Composite tabFolderPage;
private CTabItem item;
private OpenWindowListener openLisenter;
/** @return the searchEntry */
public SearchEntry getSearchEntry() {
return searchEntry;
}
/** @return the item */
public CTabItem getItem() {
return item;
}
/**
* @param item
* the item to set
*/
public void setItem(CTabItem item) {
this.item = item;
}
/**
* @param searchEntry
* the searchEntry to set
*/
public void setSearchEntry(SearchEntry searchEntry) {
this.searchEntry = searchEntry;
}
public BrowserTab(SearchEntry searchEntry) {
this.searchEntry = searchEntry;
}
public Composite createTabFolderPage(CTabFolder tabFolder) {
tabFolderPage = new Composite(tabFolder, SWT.NONE);
tabFolderPage.setLayout(new FillLayout());
browser = new Browser(tabFolderPage, SWT.NONE);
hookOpenListner();
return tabFolderPage;
}
public void hookOpenListner() {
openLisenter = new OpenWindowListener() {
@Override
public void open(WindowEvent event) {
event.required=true;
BrowserComponent app = new BrowserComponent(false);
event.browser = app.getBrowser();
}
};
browser.addOpenWindowListener(openLisenter);
}
/**
* 清理资源 ;
*/
public void close() {
if (null != browser) {
if(!browser.isDisposed()){
if(null != openLisenter){
browser.removeOpenWindowListener(openLisenter);
}
}
browser.dispose();
}
if (tabFolderPage != null) {
tabFolderPage.dispose();
}
if (null != item) {
item.dispose();
}
}
public void searchKeyWord(String keyWord) {
String searchUrl = searchEntry.getSearchUrl();
searchUrl = searchUrl.replaceAll(SearchEntry.KEY_WORD, encodeUrl(keyWord));
browser.setUrl(searchUrl);
}
public String encodeUrl(String keyWord) {
if (null == keyWord) {
return "";
}
try {
return URLEncoder.encode(keyWord, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
logger.error("", e);
}
return "";
}
public Browser getBrowser() {
return browser;
}
}
| 3,632 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
BrowserComponent.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.websearch/src/net/heartsome/cat/ts/websearch/ui/browser/BrowserComponent.java | /*******************************************************************************
* Copyright (c) 2000, 2004 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.websearch.ui.browser;
import org.eclipse.swt.*;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import java.io.*;
import java.util.*;
public class BrowserComponent {
static ResourceBundle resourceBundle = ResourceBundle
.getBundle("net.heartsome.cat.ts.websearch.ui.browser.browser_component");
int index;
boolean busy;
Image images[];
Image icon = null;
boolean title = false;
Composite parent;
Text locationBar;
Browser browser;
ToolBar toolbar;
Canvas canvas;
ToolItem itemBack, itemForward;
Label status;
ProgressBar progressBar;
SWTError error = null;
static final String[] imageLocations = { "eclipse01.bmp", "eclipse02.bmp", "eclipse03.bmp", "eclipse04.bmp",
"eclipse05.bmp", "eclipse06.bmp", "eclipse07.bmp", "eclipse08.bmp", "eclipse09.bmp", "eclipse10.bmp",
"eclipse11.bmp", "eclipse12.bmp", };
static final String iconLocation = "document.gif";
public BrowserComponent(boolean top) {
Shell shell = new Shell(Display.getDefault());
this.icon = getTitleIcon();
if (icon != null)
shell.setImage(icon);
shell.setLayout(new FillLayout());
this.parent = shell;
setShellDecoration(icon, true);
shell.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
freeResources();
}
});
try {
this.browser = new Browser(parent, SWT.BORDER);
} catch (SWTError e) {
error = e;
/* Browser widget could not be instantiated */
parent.setLayout(new FillLayout());
Label label = new Label(parent, SWT.CENTER | SWT.WRAP);
label.setText(getResourceString("BrowserNotCreated"));
parent.layout(true);
return;
}
initResources();
// final Display display = parent.getDisplay();
browser.setData("org.eclipse.swt.examples.browserexample.BrowserApplication", this);
browser.addOpenWindowListener(new OpenWindowListener() {
public void open(WindowEvent event) {
BrowserComponent app = new BrowserComponent(false);
// app.setShellDecoration(icon, true);
event.browser = app.getBrowser();
}
});
if (top) {
browser.setUrl(getResourceString("Startup"));
show(false, null, null, true, true, true, true);
} else {
browser.addVisibilityWindowListener(new VisibilityWindowListener() {
public void hide(WindowEvent e) {
}
public void show(WindowEvent e) {
Browser browser = (Browser) e.widget;
BrowserComponent app = (BrowserComponent) browser
.getData("org.eclipse.swt.examples.browserexample.BrowserApplication");
app.show(true, e.location, e.size, e.addressBar, e.menuBar, e.statusBar, e.toolBar);
}
});
browser.addCloseWindowListener(new CloseWindowListener() {
public void close(WindowEvent event) {
Browser browser = (Browser) event.widget;
Shell shell = browser.getShell();
shell.close();
}
});
}
}
/**
* Disposes of all resources associated with a particular instance of the BrowserApplication.
*/
public void dispose() {
freeResources();
}
/**
* Gets a string from the resource bundle. We don't want to crash because of a missing String. Returns the key if
* not found.
*/
static String getResourceString(String key) {
try {
return resourceBundle.getString(key);
} catch (MissingResourceException e) {
return key;
} catch (NullPointerException e) {
return "!" + key + "!";
}
}
public SWTError getError() {
return error;
}
public Browser getBrowser() {
return browser;
}
public void setShellDecoration(Image icon, boolean title) {
this.icon = icon;
this.title = title;
}
void show(boolean owned, Point location, Point size, boolean addressBar, boolean menuBar, boolean statusBar,
boolean toolBar) {
final Shell shell = browser.getShell();
if (owned) {
if (location != null)
shell.setLocation(location);
if (size != null)
shell.setSize(shell.computeSize(size.x, size.y));
}
FormData data = null;
if (toolBar) {
toolbar = new ToolBar(parent, SWT.NONE);
data = new FormData();
data.top = new FormAttachment(0, 5);
toolbar.setLayoutData(data);
itemBack = new ToolItem(toolbar, SWT.PUSH);
itemBack.setText(getResourceString("Back"));
itemForward = new ToolItem(toolbar, SWT.PUSH);
itemForward.setText(getResourceString("Forward"));
final ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
itemStop.setText(getResourceString("Stop"));
final ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
itemRefresh.setText(getResourceString("Refresh"));
final ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
itemGo.setText(getResourceString("Go"));
itemBack.setEnabled(browser.isBackEnabled());
itemForward.setEnabled(browser.isForwardEnabled());
Listener listener = new Listener() {
public void handleEvent(Event event) {
ToolItem item = (ToolItem) event.widget;
if (item == itemBack)
browser.back();
else if (item == itemForward)
browser.forward();
else if (item == itemStop)
browser.stop();
else if (item == itemRefresh)
browser.refresh();
else if (item == itemGo)
browser.setUrl(locationBar.getText());
}
};
itemBack.addListener(SWT.Selection, listener);
itemForward.addListener(SWT.Selection, listener);
itemStop.addListener(SWT.Selection, listener);
itemRefresh.addListener(SWT.Selection, listener);
itemGo.addListener(SWT.Selection, listener);
canvas = new Canvas(parent, SWT.NO_BACKGROUND);
data = new FormData();
data.width = 24;
data.height = 24;
data.top = new FormAttachment(0, 5);
data.right = new FormAttachment(100, -5);
canvas.setLayoutData(data);
final Rectangle rect = images[0].getBounds();
canvas.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event e) {
Point pt = ((Canvas) e.widget).getSize();
e.gc.drawImage(images[index], 0, 0, rect.width, rect.height, 0, 0, pt.x, pt.y);
}
});
canvas.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(getResourceString("Startup"));
}
});
final Display display = parent.getDisplay();
display.asyncExec(new Runnable() {
public void run() {
if (canvas.isDisposed())
return;
if (busy) {
index++;
if (index == images.length)
index = 0;
canvas.redraw();
}
display.timerExec(150, this);
}
});
}
if (addressBar) {
locationBar = new Text(parent, SWT.BORDER);
data = new FormData();
if (toolbar != null) {
data.top = new FormAttachment(toolbar, 0, SWT.TOP);
data.left = new FormAttachment(toolbar, 5, SWT.RIGHT);
data.right = new FormAttachment(canvas, -5, SWT.DEFAULT);
} else {
data.top = new FormAttachment(0, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
}
locationBar.setLayoutData(data);
locationBar.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(locationBar.getText());
}
});
}
if (statusBar) {
status = new Label(parent, SWT.NONE);
progressBar = new ProgressBar(parent, SWT.NONE);
data = new FormData();
data.left = new FormAttachment(0, 5);
data.right = new FormAttachment(progressBar, 0, SWT.DEFAULT);
data.bottom = new FormAttachment(100, -5);
status.setLayoutData(data);
data = new FormData();
data.right = new FormAttachment(100, -5);
data.bottom = new FormAttachment(100, -5);
progressBar.setLayoutData(data);
browser.addStatusTextListener(new StatusTextListener() {
public void changed(StatusTextEvent event) {
status.setText(event.text);
}
});
}
parent.setLayout(new FormLayout());
Control aboveBrowser = toolBar ? (Control) canvas : (addressBar ? (Control) locationBar : null);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.top = aboveBrowser != null ? new FormAttachment(aboveBrowser, 5, SWT.DEFAULT) : new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
data.bottom = status != null ? new FormAttachment(status, -5, SWT.DEFAULT) : new FormAttachment(100, 0);
browser.setLayoutData(data);
if (statusBar || toolBar) {
browser.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
if (event.total == 0)
return;
int ratio = event.current * 100 / event.total;
if (progressBar != null)
progressBar.setSelection(ratio);
busy = event.current != event.total;
if (!busy) {
index = 0;
if (canvas != null)
canvas.redraw();
}
}
public void completed(ProgressEvent event) {
if (progressBar != null)
progressBar.setSelection(0);
busy = false;
index = 0;
if (canvas != null) {
itemBack.setEnabled(browser.isBackEnabled());
itemForward.setEnabled(browser.isForwardEnabled());
canvas.redraw();
}
}
});
}
if (addressBar || statusBar || toolBar) {
browser.addLocationListener(new LocationListener() {
public void changed(LocationEvent event) {
busy = true;
if (event.top && locationBar != null)
locationBar.setText(event.location);
}
public void changing(LocationEvent event) {
}
});
}
if (title) {
browser.addTitleListener(new TitleListener() {
public void changed(TitleEvent event) {
shell.setText(event.title + " - " + getResourceString("window.title"));
}
});
}
parent.layout(true);
if (owned)
shell.open();
}
/**
* Grabs input focus
*/
public void focus() {
if (locationBar != null)
locationBar.setFocus();
else if (browser != null)
browser.setFocus();
else
parent.setFocus();
}
/**
* Frees the resources
*/
void freeResources() {
if (images != null) {
for (int i = 0; i < images.length; ++i) {
final Image image = images[i];
if (image != null)
image.dispose();
}
images = null;
}
if (null != icon && !icon.isDisposed()) {
icon.dispose();
}
}
/**
* Loads the resources
*/
void initResources() {
final Class clazz = this.getClass();
if (resourceBundle != null) {
try {
if (images == null) {
images = new Image[imageLocations.length];
for (int i = 0; i < imageLocations.length; ++i) {
InputStream sourceStream = clazz.getResourceAsStream(imageLocations[i]);
ImageData source = new ImageData(sourceStream);
ImageData mask = source.getTransparencyMask();
images[i] = new Image(null, source, mask);
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
} catch (Throwable t) {
}
}
String error = (resourceBundle != null) ? getResourceString("error.CouldNotLoadResources")
: "Unable to load resources";
freeResources();
throw new RuntimeException(error);
}
private Image getTitleIcon() {
InputStream stream = BrowserComponent.class.getResourceAsStream(iconLocation);
Image icon = new Image(Display.getDefault(), stream);
return icon;
}
}
| 12,213 | 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.websearch/src/net/heartsome/cat/ts/websearch/resource/Messages.java | package net.heartsome.cat.ts.websearch.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.websearch.resource.Messages";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 561 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IExecutePretranslation.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/extenstion/IExecutePretranslation.java | /**
* IExecutePretranslation.java
*
* Version information :
*
* Date:2012-6-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.convert.extenstion;
import java.util.List;
import org.eclipse.core.resources.IFile;
/**
* 转换器中调用预翻译扩展
* @author jason
* @version
* @since JDK1.6
*/
public interface IExecutePretranslation {
void executePreTranslation(List<IFile> files);
}
| 929 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImplementationLoader.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/ImplementationLoader.java | package net.heartsome.cat.convert.ui;
import java.text.MessageFormat;
import net.heartsome.cat.convert.ui.resource.Messages;
/**
* 加载具体的 factory facade 实现
* @author cheney
* @since JDK1.6
*/
public final class ImplementationLoader {
/**
*
*/
private ImplementationLoader() {
// 防止创建实例
}
/**
* 加载特定实现类的实例
* @param type
* 特定实现类的接口类型
* @return ;
*/
public static Object newInstance(final Class type) {
String name = type.getName();
Object result = null;
try {
result = type.getClassLoader().loadClass(name + "Impl").newInstance();
} catch (Throwable throwable) {
String txt = Messages.getString("ui.ImplementationLoader.msg");
String msg = MessageFormat.format(txt, new Object[] { name });
throw new RuntimeException(msg, throwable);
}
return result;
}
}
| 885 | 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.converter.ui/src/net/heartsome/cat/convert/ui/Activator.java | package net.heartsome.cat.convert.ui;
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 {
/**
* 在执行文件转换时,是否打印转换配置信息的控制开关
*/
public static final String CONVERSION_DEBUG_ON = "net.heartsome.cat.converter.ui/debug/conversion";
/**
* The plug-in ID
*/
public static final String PLUGIN_ID = "net.heartsome.cat.converter.ui";
// The shared instance
private static Activator plugin;
// bundle context
private static BundleContext context;
/**
* 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);
Activator.context = 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;
Activator.context = 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);
}
/**
* 获得插件的 bundle context
* @return 插件的 bundle context;
*/
public static BundleContext getContext() {
return context;
}
}
| 1,835 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionWizardDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ConversionWizardDialog.java | package net.heartsome.cat.convert.ui.wizard;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.convert.ui.Activator;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.swt.widgets.Shell;
/**
* 继承 WizardDialog,并覆盖 getDialogBoundsSettings 方法,以记住此向导对话框上一次打开时的大小
* @author cheney
* @since JDK1.6
*/
public class ConversionWizardDialog extends TSWizardDialog {
/**
* 正向转换向导对话框构造函数
* @param parentShell
* @param newWizard
*/
public ConversionWizardDialog(Shell parentShell, IWizard newWizard) {
super(parentShell, newWizard);
}
@Override
protected IDialogSettings getDialogBoundsSettings() {
return Activator.getDefault().getDialogSettings();
}
}
| 841 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionWizardPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ConversionWizardPage.java | package net.heartsome.cat.convert.ui.wizard;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.common.ui.dialog.FileFolderSelectionDialog;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.dialog.FileDialogFactoryFacade;
import net.heartsome.cat.convert.ui.dialog.IConversionItemDialog;
import net.heartsome.cat.convert.ui.model.ConversionConfigBean;
import net.heartsome.cat.convert.ui.model.ConverterContext;
import net.heartsome.cat.convert.ui.model.ConverterUtil;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.utils.ConversionResource;
import net.heartsome.cat.convert.ui.utils.EncodingResolver;
import net.heartsome.cat.convert.ui.utils.FileFormatUtils;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.ConverterBean;
import net.heartsome.cat.ts.ui.composite.LanguageLabelProvider;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.property.value.IValueProperty;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.internal.filesystem.local.LocalFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ViewerSupport;
import org.eclipse.jface.databinding.wizard.WizardPageSupport;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 项目正向转换选项配置页
* @author weachy
* @since JDK1.5
*/
@SuppressWarnings("restriction")
public class ConversionWizardPage extends WizardPage {
private static final Logger LOGGER = LoggerFactory.getLogger(ConversionWizardPage.class);
public static final String REPLACE_TARGET = "net.heartsome.cat.convert.ui.wizard.ConversionWizardPage.btnReplaceTarget";
public static final String OPEN_PRE_TRANS = "net.heartsome.cat.convert.ui.wizard.ConversionWizardPage.btnOpenPreTrans";
/** 支持的类型 */
private final List<ConverterBean> supportTypes = FileFormatUtils.getSupportTypes();
private List<ConverterViewModel> converterViewModels;
private boolean isOpenPreTrans = false;
private boolean isReplaceTarget = false;
/** 支持的格式列表 */
private Combo formatCombo;
/** 源文件编码列表 */
private Combo srcEncCombo;
/** 目标语言列表 */
private TableViewer tgtLangViewer;
/** 文件列表 */
private Table filesTable;
private TableColumn lineNumColumn;
private TableColumn sourceColumn;
private TableColumn formatColumn;
private TableColumn srcEncColumn;
/** 分段选项 */
private Text srxFile;
private ArrayList<ConversionConfigBean> conversionConfigBeans;
private TableViewer tableViewer;
private IProject currentProject;
private String srcLang;
private List<Language> targetlanguage;
/**
* 正向项目转换配置信息页的构造函数
* @param pageName
*/
protected ConversionWizardPage(String pageName, List<ConverterViewModel> converterViewModels,
ArrayList<ConversionConfigBean> conversionConfigBeans, IProject currentProject) {
super(pageName);
this.converterViewModels = converterViewModels;
this.conversionConfigBeans = conversionConfigBeans;
this.currentProject = currentProject;
setTitle(Messages.getString("wizard.ConversionWizardPage.title")); //$NON-NLS-1$
setDescription(Messages.getString("wizard.ConversionWizardPage.description")); //$NON-NLS-1$
setImageDescriptor(Activator.getImageDescriptor("images/dialog/source-toxliff-logo.png"));
ConversionConfigBean b = conversionConfigBeans.get(0);
srcLang = b.getSrcLang();
targetlanguage = b.getTgtLangList();
}
public void createControl(Composite parent) {
Composite contents = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
contents.setLayout(layout);
contents.setLayoutData(new GridData(GridData.FILL_BOTH));
createFilesGroup(contents); // 文件列表区域
createPropertiesGroup(contents);// 源文件属性区域组
createConversionOptionsGroup(contents); // 转换选项组
createSegmentationGroup(contents); // 分段规则选择区域组
bindValue(); // 数据绑定
loadFiles(); // 加载文件列表
filesTable.select(0); // 默认选中第一行数据
filesTable.notifyListeners(SWT.Selection, null);
Dialog.applyDialogFont(parent);
setControl(contents);
srxFile.setText(ConverterContext.defaultSrx);
validate();
}
private void createPropertiesGroup(Composite contents) {
Group langComposite = new Group(contents, SWT.NONE);
langComposite.setText(Messages.getString("wizard.ConversionWizardPage.langComposite")); //$NON-NLS-1$
langComposite.setLayout(new GridLayout(2, false));
langComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label formatLabel = new Label(langComposite, SWT.NONE);
formatLabel.setText(Messages.getString("wizard.ConversionWizardPage.formatLabel")); //$NON-NLS-1$
formatCombo = new Combo(langComposite, SWT.READ_ONLY | SWT.DROP_DOWN);
formatCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
formatCombo.addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("unchecked")
public void widgetSelected(SelectionEvent arg0) {
ISelection selection = tableViewer.getSelection();
if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Iterator<ConversionConfigBean> iter = structuredSelection.iterator();
while (iter.hasNext()) {
ConversionConfigBean bean = iter.next();
bean.setFileType(formatCombo.getText());
}
String format = getSelectedFormat(formatCombo.getText()); // 得到选中的文件类型
int[] indices = filesTable.getSelectionIndices();
for (int index : indices) {
converterViewModels.get(index).setSelectedType(format);
String sourcePath = converterViewModels.get(index).getConversionItem().getLocation()
.toOSString();
String sourceLocalPath = ConverterUtil.toLocalPath(sourcePath);
String srcEncValue = EncodingResolver.getEncoding(sourceLocalPath, formatCombo.getText());
if (srcEncValue != null) {
conversionConfigBeans.get(index).setSrcEncoding(srcEncValue);
}
}
validate();
}
}
});
Label srcEncLabel = new Label(langComposite, SWT.NONE);
srcEncLabel.setText(Messages.getString("wizard.ConversionWizardPage.srcEncLabel")); //$NON-NLS-1$
srcEncCombo = new Combo(langComposite, SWT.DROP_DOWN | SWT.READ_ONLY);
srcEncCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
srcEncCombo.addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("unchecked")
public void widgetSelected(SelectionEvent arg0) {
ISelection selection = tableViewer.getSelection();
if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Iterator<ConversionConfigBean> iter = structuredSelection.iterator();
while (iter.hasNext()) {
ConversionConfigBean bean = iter.next();
bean.setSrcEncoding(srcEncCombo.getText());
}
validate();
}
}
});
}
/**
* 转换选项组
* @param contents
* ;
*/
private void createConversionOptionsGroup(Composite contents) {
Group options = new Group(contents, SWT.NONE);
options.setText(Messages.getString("wizard.ConversionWizardPage.options")); //$NON-NLS-1$
options.setLayout(new GridLayout(1, false));
options.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
/* 如果已经存在,是否要替换 */
final Button btnReplaceTarget = new Button(options, SWT.CHECK);
btnReplaceTarget.setText(Messages.getString("wizard.ConversionWizardPage.btnReplaceTarget")); //$NON-NLS-1$
btnReplaceTarget.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnReplaceTarget.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
isReplaceTarget = btnReplaceTarget.getSelection();
for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) {
conversionConfigBean.setReplaceTarget(btnReplaceTarget.getSelection());
}
validate();
}
});
final Button btnOpenPreTrans = new Button(options, SWT.CHECK);
btnOpenPreTrans.setText(Messages.getString("wizard.ConversionWizardPage.btnOpenPreTrans"));
btnOpenPreTrans.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnOpenPreTrans.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
isOpenPreTrans = btnOpenPreTrans.getSelection();
}
});
Composite composite = new Composite(options, SWT.NONE);
GridLayout gd = new GridLayout(1, false);
gd.marginWidth = 0;
gd.marginHeight = 0;
composite.setLayout(gd);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
Label tgtLangLbl = new Label(composite, SWT.NONE);
tgtLangLbl.setText(Messages.getString("wizard.ConversionWizardPage.tgtLangLbl"));
tgtLangViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
Table tgtLangTable = tgtLangViewer.getTable();
GridData gdTgtLangTable = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
gdTgtLangTable.heightHint = 80;
tgtLangTable.setLayoutData(gdTgtLangTable);
tgtLangViewer.setLabelProvider(new LanguageLabelProvider());
tgtLangViewer.setContentProvider(new ArrayContentProvider());
tgtLangViewer.setInput(conversionConfigBeans.get(0).getTgtLangList());
tgtLangViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
@SuppressWarnings("unchecked")
List<Language> selectedList = sel.toList();
for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) {
conversionConfigBean.setHasSelTgtLangList(selectedList);
}
validate();
}
});
tgtLangViewer.getTable().select(0);
IDialogSettings dialogSettings = Activator.getDefault().getDialogSettings();
btnReplaceTarget.setSelection(dialogSettings.getBoolean(REPLACE_TARGET));
btnOpenPreTrans.setSelection(dialogSettings.getBoolean(OPEN_PRE_TRANS));
this.isOpenPreTrans = btnOpenPreTrans.getSelection();
isReplaceTarget = btnReplaceTarget.getSelection();
for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) {
conversionConfigBean.setReplaceTarget(isReplaceTarget);
}
validate();
}
/**
* 创建分段规则选择组
* @param contents
* ;
*/
private void createSegmentationGroup(Composite contents) {
Group segmentation = new Group(contents, SWT.NONE);
segmentation.setText(Messages.getString("wizard.ConversionWizardPage.segmentation")); //$NON-NLS-1$
segmentation.setLayout(new GridLayout(3, false));
GridData data = new GridData(GridData.FILL_HORIZONTAL);
data.widthHint = 500;
segmentation.setLayoutData(data);
Label segLabel = new Label(segmentation, SWT.NONE);
segLabel.setText(Messages.getString("wizard.ConversionWizardPage.segLabel")); //$NON-NLS-1$
srxFile = new Text(segmentation, SWT.BORDER | SWT.READ_ONLY);
srxFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
srxFile.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) {
conversionConfigBean.setInitSegmenter(srxFile.getText());
}
validate();
}
});
final Button segBrowse = new Button(segmentation, SWT.PUSH);
segBrowse.setText(Messages.getString("wizard.ConversionWizardPage.segBrowse")); //$NON-NLS-1$
segBrowse.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
IConversionItemDialog conversionItemDialog = FileDialogFactoryFacade.createFileDialog(getShell(),
SWT.NONE);
int result = conversionItemDialog.open();
if (result == IDialogConstants.OK_ID) {
IConversionItem conversionItem = conversionItemDialog.getConversionItem();
srxFile.setText(conversionItem.getLocation().toOSString());
}
}
});
}
/**
* 得到选中的类型
* @param description
* 描述名字
* @return 类型名字;
*/
private String getSelectedFormat(String description) {
for (ConverterBean converterBean : supportTypes) {
if (description.equals(converterBean.getDescription())) {
return converterBean.getName();
}
}
return ""; //$NON-NLS-1$
}
private void validate() {
if (conversionConfigBeans.size() == 0) {
setPageComplete(false);
return;
}
ConversionConfigBean cb = conversionConfigBeans.get(0);
if (cb.getHasSelTgtLangList() == null || cb.getHasSelTgtLangList().size() == 0) {
setPageComplete(false);
setErrorMessage(Messages.getString("wizard.ConversionWizardPage.msg1"));
return;
}
IStatus result = Status.OK_STATUS;
int line = 1;
for (ConverterViewModel converterViewModel : converterViewModels) {
result = converterViewModel.validate();
if (!result.isOK()) {
break;
}
line++;
}
if (!result.isOK()) {
filesTable.setSelection(line - 1);
filesTable.notifyListeners(SWT.Selection, null);
setPageComplete(false);
setErrorMessage(MessageFormat.format(Messages.getString("wizard.ConversionWizardPage.msg2"), line)
+ result.getMessage());
} else {
setErrorMessage(null);
setPageComplete(true);
}
}
/**
* 创建文件列表区域
* @param contents
* ;
*/
private Composite createFilesGroup(Composite contents) {
Composite filesComposite = new Composite(contents, SWT.NONE);
GridLayout gd = new GridLayout(2, false);
gd.marginWidth = 0;
filesComposite.setLayout(gd);
filesComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
filesTable = new Table(filesComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI
| SWT.FULL_SELECTION);
GridData tableData = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
tableData.heightHint = 100;
filesTable.setLayoutData(tableData);
filesTable.setLinesVisible(true);
filesTable.setHeaderVisible(true);
filesTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
doSelectedEvent();
}
});
tableViewer = new TableViewer(filesTable);
lineNumColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
lineNumColumn.setText(Messages.getString("wizard.ConversionWizardPage.lineNumColumn"));
sourceColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
sourceColumn.setText(Messages.getString("wizard.ConversionWizardPage.sourceColumn"));
formatColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
formatColumn.setText(Messages.getString("wizard.ConversionWizardPage.formatColumn"));
srcEncColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
srcEncColumn.setText(Messages.getString("wizard.ConversionWizardPage.srcEncColumn"));
IValueProperty[] valueProperties = BeanProperties.values(ConversionConfigBean.class, new String[] { "index",
"source", "fileType", "srcEncoding" });
ViewerSupport.bind(tableViewer, new WritableList(conversionConfigBeans, ConversionConfigBean.class),
valueProperties);
filesComposite.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent arg0) {
int width = filesTable.getClientArea().width;
lineNumColumn.setWidth(width * 1 / 10);
sourceColumn.setWidth(width * 5 / 10);
formatColumn.setWidth(width * 3 / 10);
srcEncColumn.setWidth(width * 1 / 10);
}
});
Composite opComp = new Composite(filesComposite, SWT.NONE);
GridLayout opCompGl = new GridLayout();
opCompGl.marginWidth = 0;
opCompGl.marginLeft = 0;
opCompGl.marginTop = 0;
opCompGl.marginHeight = 0;
opComp.setLayout(opCompGl);
GridData gd_opComp = new GridData();
gd_opComp.verticalAlignment = SWT.TOP;
opComp.setLayoutData(gd_opComp);
Button addBt = new Button(opComp, SWT.NONE);
addBt.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
addBt.setText(Messages.getString("wizard.ConversionWizardPage.addbutton"));
addBt.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileFolderSelectionDialog dialog = new FileFolderSelectionDialog(getShell(), true, IResource.FILE) {
// 打开对话框时展开树形目录
public void create() {
super.create();
super.getTreeViewer().expandAll();
}
};
dialog.setMessage(Messages.getString("wizard.ConversionWizardPage.selectfiledialog.message"));
dialog.setTitle(Messages.getString("wizard.ConversionWizardPage.selectfiledialog.title"));
dialog.setDoubleClickSelects(true);
try {
dialog.setInput(EFS.getStore(ResourcesPlugin.getWorkspace().getRoot().getLocationURI()));
} catch (CoreException e1) {
LOGGER.error("", e1);
e1.printStackTrace();
}
dialog.addFilter(new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof LocalFile) {
LocalFile folder = (LocalFile) element;
if (folder.getName().equalsIgnoreCase(".hsConfig")
|| folder.getName().equalsIgnoreCase(".metadata")) {
return false;
}
String projectPath = currentProject.getLocation().toOSString();
if (projectPath.equals(folder.toString())) {
return true;
}
String xliffFolderPath = folder.toString();
String path1 = projectPath + File.separator + Constant.FOLDER_SRC;
if (xliffFolderPath.startsWith(path1)) {
for (ConversionConfigBean bean : conversionConfigBeans) {
if (xliffFolderPath.indexOf(bean.getSource()) != -1) {
return false;
}
}
return true;
}
}
return false;
}
});
dialog.create();
dialog.open();
if (dialog.getResult() != null) {
Object[] selectFiles = dialog.getResult();
for (Object selectedFile : selectFiles) {
LocalFile folder = (LocalFile) selectedFile;
ConverterViewModel model = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_POSITIVE);
Object adapter = Platform.getAdapterManager().getAdapter(
ResourcesPlugin.getWorkspace().getRoot()
.getFileForLocation(Path.fromOSString(folder.toString())),
IConversionItem.class);
IConversionItem sourceItem = null;
if (adapter instanceof IConversionItem) {
sourceItem = (IConversionItem) adapter;
}
model.setConversionItem(sourceItem); // 记住所选择的文件
ConversionConfigBean bean = model.getConfigBean();
bean.setSource(ResourceUtils.toWorkspacePath(folder.toString())); // 初始化源文件路径
bean.setSrcLang(srcLang); // 初始化源语言
bean.setTgtLangList(targetlanguage);
if (targetlanguage != null && targetlanguage.size() > 0) {
List<Language> lang = new ArrayList<Language>();
lang.add(targetlanguage.get(0));
bean.setHasSelTgtLangList(lang);
}
bean.setReplaceTarget(isReplaceTarget);
bean.setInitSegmenter(srxFile.getText());
conversionConfigBeans.add(bean);
converterViewModels.add(model);
}
loadFiles();
validate();
tableViewer.refresh();
}
}
});
Button removeBt = new Button(opComp, SWT.NONE);
removeBt.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
removeBt.setText(Messages.getString("wizard.ConversionWizardPage.removebutton"));
removeBt.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (conversionConfigBeans.size() == 0) {
return;
}
ISelection sel = tableViewer.getSelection();
if (sel.isEmpty()) {
MessageDialog.openError(getShell(),
Messages.getString("wizard.ConversionWizardPage.removebutton.msg1.title"),
Messages.getString("wizard.ConversionWizardPage.removebutton.msg1"));
return;
}
if (sel instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) sel;
Object[] objs = ssel.toArray();
int index = conversionConfigBeans.indexOf(ssel.getFirstElement());
index -= ssel.size();
index = index < 0 ? 0 : index;
for (Object obj : objs) {
int i = conversionConfigBeans.indexOf(obj);
conversionConfigBeans.remove(i);
converterViewModels.remove(i);
}
loadFiles();
tableViewer.refresh();
if (!conversionConfigBeans.isEmpty()) {
tableViewer.getTable().select(index);
doSelectedEvent();
}
validate();
}
}
});
return filesComposite;
}
private void doSelectedEvent() {
TableItem[] selected = filesTable.getSelection();
if (selected.length == 0) {
return;
}
String strSrcFormat = ""; //$NON-NLS-1$
String strSrcEnc = ""; //$NON-NLS-1$
for (int i = 0; i < selected.length; i++) {
String curFormat = selected[i].getText(2);
String curSrcEnc = selected[i].getText(3);
if (i == 0) {
strSrcFormat = curFormat;
strSrcEnc = curSrcEnc;
} else {
if (!strSrcFormat.equals(curFormat)) {
strSrcFormat = ""; //$NON-NLS-1$
}
if (!strSrcEnc.equals(curSrcEnc)) {
strSrcEnc = ""; //$NON-NLS-1$
}
}
}
if (!"".equals(strSrcFormat)) { //$NON-NLS-1$
formatCombo.setText(strSrcFormat);
} else {
formatCombo.deselectAll();
}
if (!"".equals(strSrcEnc)) { //$NON-NLS-1$
srcEncCombo.setText(strSrcEnc);
} else {
srcEncCombo.deselectAll();
}
}
/**
* 对 UI 和 View Model 进行绑定 ;
*/
private void bindValue() {
DataBindingContext dbc = new DataBindingContext();
WizardPageSupport.create(this, dbc);
ConversionConfigBean configBean = conversionConfigBeans.get(0);
// bind the format
dbc.bindList(SWTObservables.observeItems(formatCombo), BeansObservables.observeList(configBean, "fileFormats")); //$NON-NLS-1$
// final IObservableValue format = BeansObservables.observeValue(selectedModel, "selectedType");
// dbc.bindValue(SWTObservables.observeSelection(formatCombo), format);
// bind the source encoding
dbc.bindList(SWTObservables.observeItems(srcEncCombo), BeansObservables.observeList(configBean, "pageEncoding")); //$NON-NLS-1$
}
/**
* 加载文件数据。
*/
private void loadFiles() {
for (int i = 0; i < conversionConfigBeans.size(); i++) {
ConversionConfigBean bean = conversionConfigBeans.get(i);
bean.setIndex((i + 1) + "");
String source = bean.getSource();
String sourceLocalPath = ConverterUtil.toLocalPath(source);
// 自动识别文件类型
String format = FileFormatUtils.detectFormat(sourceLocalPath);
if (format == null) {
format = ""; //$NON-NLS-1$
}
// 自动分析源文件编码
String srcEncValue = EncodingResolver.getEncoding(sourceLocalPath, format);
if (srcEncValue == null) {
srcEncValue = ""; //$NON-NLS-1$
}
bean.setEmbedSkl(FileFormatUtils.canEmbedSkl(format));
// XLIFF 文件路径
String xliff = ""; //$NON-NLS-1$
// 骨架文件路径
String skeleton = ""; //$NON-NLS-1$
//XLiff 文件夹
String xliffDir = "";
try {
ConversionResource resource = new ConversionResource(Converter.DIRECTION_POSITIVE, sourceLocalPath);
xliff = resource.getXliffPath();
skeleton = resource.getSkeletonPath();
xliffDir = resource.getXliffDir();
} catch (CoreException e) {
LOGGER.error("", e);
}
if (!"".equals(format)) { //$NON-NLS-1$
String name = getSelectedFormat(format);
if (name != null && !"".equals(name)) { //$NON-NLS-1$
converterViewModels.get(i).setSelectedType(name); // 添加类型
}
}
bean.setFileType(format);
bean.setSrcEncoding(srcEncValue);
bean.setXliffDir(xliffDir);
bean.setTarget(xliff);
bean.setSkeleton(ConverterUtil.toLocalPath(skeleton));
}
}
@Override
public void dispose() {
super.dispose();
if (filesTable != null) {
filesTable.dispose();
}
if (conversionConfigBeans != null) {
conversionConfigBeans.clear();
conversionConfigBeans = null;
}
System.gc();
}
public boolean isOpenPreTrans() {
return this.isOpenPreTrans;
}
public boolean isReplaceTarget() {
return isReplaceTarget;
}
}
| 26,820 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ReverseConversionWizardPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ReverseConversionWizardPage.java | package net.heartsome.cat.convert.ui.wizard;
import java.lang.reflect.InvocationTargetException;
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.core.Constant;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConversionConfigBean;
import net.heartsome.cat.convert.ui.model.ConverterUtil;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.utils.ConversionResource;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.ts.core.file.DocumentPropertiesKeys;
import net.heartsome.cat.ts.core.file.XLFHandler;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.property.value.IValueProperty;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ViewerSupport;
import org.eclipse.jface.databinding.wizard.WizardPageSupport;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.layout.LayoutConstants;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 项目逆向转换选项配置页
* @author weachy
* @since JDK1.5
*/
public class ReverseConversionWizardPage extends WizardPage {
private static final Logger LOGGER = LoggerFactory.getLogger(ReverseConversionWizardPage.class);
private List<ConverterViewModel> converterViewModels;
/** 源文件编码列表 */
private Combo tgtEncCombo;
/** 如果已经存在,是否要替换 */
private Button btnReplaceTarget;
/** 文件列表 */
private Table filesTable;
private TableColumn lineNumberColumn;
/** xliff 文件列 */
private TableColumn xliffColumn;
/** 目标编码列 */
private TableColumn tgtEncColumn;
/** 目标文件列 */
private TableColumn targetColumn;
private ArrayList<ConversionConfigBean> conversionConfigBeans;
private TableViewer tableViewer;
/**
* 正向项目转换配置信息页的构造函数
* @param pageName
*/
protected ReverseConversionWizardPage(String pageName) {
super(pageName);
setTitle(Messages.getString("wizard.ReverseConversionWizardPage.title"));
setImageDescriptor(Activator.getImageDescriptor("images/dialog/xliff-totarget-logo.png"));
}
/**
* 初始化本页面需要的数据 ;
*/
private void initData() {
ReverseConversionWizard wizard = (ReverseConversionWizard) getWizard();
converterViewModels = wizard.getConverterViewModels();
conversionConfigBeans = new ArrayList<ConversionConfigBean>();
for (ConverterViewModel converterViewModel : converterViewModels) {
IConversionItem conversionItem = converterViewModel.getConversionItem();
String xliff = ResourceUtils.toWorkspacePath(conversionItem.getLocation());
ConversionConfigBean bean = converterViewModel.getConfigBean();
bean.setSource(xliff);
conversionConfigBeans.add(bean);
}
}
public void createControl(Composite parent) {
initData(); // 先初始化本页面需要的数据
Composite contents = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
contents.setLayout(layout);
GridData gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
contents.setLayoutData(gridData);
createFilesGroup(contents); // 文件列表区域
createPropertiesGroup(contents); // 源文件属性区域组
createConversionOptionsGroup(contents); // 转换选项组
bindValue(); // 数据绑定
try {
loadFiles(); // 加载文件列表
} catch (Exception e) {
e.printStackTrace();
}
filesTable.select(0); // 默认选中第一行数据
filesTable.notifyListeners(SWT.Selection, null);
Dialog.applyDialogFont(parent);
Point defaultMargins = LayoutConstants.getMargins();
GridLayoutFactory.fillDefaults().numColumns(1).margins(defaultMargins.x, defaultMargins.y)
.generateLayout(contents);
setControl(contents);
validate();
}
private void createPropertiesGroup(Composite contents) {
Group langComposite = new Group(contents, SWT.NONE);
langComposite.setText(Messages.getString("wizard.ReverseConversionWizardPage.langComposite")); //$NON-NLS-1$
langComposite.setLayout(new GridLayout(2, false));
langComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label tgtEncLabel = new Label(langComposite, SWT.NONE);
tgtEncLabel.setText(Messages.getString("wizard.ReverseConversionWizardPage.tgtEncLabel")); //$NON-NLS-1$
tgtEncCombo = new Combo(langComposite, SWT.DROP_DOWN | SWT.READ_ONLY);
tgtEncCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
tgtEncCombo.addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("unchecked")
public void widgetSelected(SelectionEvent arg0) {
ISelection selection = tableViewer.getSelection();
if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Iterator<ConversionConfigBean> iter = structuredSelection.iterator();
while (iter.hasNext()) {
ConversionConfigBean bean = iter.next();
bean.setTargetEncoding(tgtEncCombo.getText());
}
validate();
}
}
});
}
/**
* 转换选项组
* @param contents
* ;
*/
private void createConversionOptionsGroup(Composite contents) {
Group options = new Group(contents, SWT.NONE);
options.setText(Messages.getString("wizard.ReverseConversionWizardPage.options"));
options.setLayout(new GridLayout());
options.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnReplaceTarget = new Button(options, SWT.CHECK);
btnReplaceTarget.setText(Messages.getString("wizard.ReverseConversionWizardPage.btnReplaceTarget"));
btnReplaceTarget.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnReplaceTarget.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) {
conversionConfigBean.setReplaceTarget(btnReplaceTarget.getSelection());
}
validate();
}
});
}
/** XLFHandler 对象 */
XLFHandler xlfHandler = new XLFHandler();
/** 完成 */
private boolean complete = false;
/** 错误信息 */
private String errorMessage = null;
/**
* 验证方法 ;
*/
private void validate() {
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.setTaskName(Messages.getString("wizard.ReverseConversionWizardPage.task1"));
monitor.beginTask(Messages.getString("wizard.ReverseConversionWizardPage.task2"), converterViewModels.size());
IStatus result = Status.OK_STATUS;
int line = 1;
for (ConverterViewModel converterViewModel : converterViewModels) {
String xliff = converterViewModel.getConversionItem().getLocation().toOSString();
IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1);
result = converterViewModel.validateXliffFile(xliff, xlfHandler, subMonitor);
if (!result.isOK()) {
break;
}
result = converterViewModel.validate();
if (!result.isOK()) {
break;
}
line++;
}
monitor.done();
final IStatus validateResult = result;
final int i = line;
if (validateResult.isOK()) {
complete = true;
errorMessage = null;
} else {
complete = false;
errorMessage = MessageFormat.format(Messages.getString("wizard.ReverseConversionWizardPage.msg1"), i) + validateResult.getMessage();
}
}
};
try {
// 验证 xliff 文件比较耗时,需把他放到后台线程进行处理。
// new ProgressMonitorDialog(shell).run(true, true, runnable);
getContainer().run(true, true, runnable);
setErrorMessage(errorMessage);
setPageComplete(complete);
} catch (InvocationTargetException e) {
LOGGER.error("", e);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 创建文件列表区域
* @param contents
* ;
*/
private Composite createFilesGroup(Composite contents) {
Composite filesComposite = new Composite(contents, SWT.NONE);
filesComposite.setLayout(new GridLayout(1, false));
filesComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
filesTable = new Table(filesComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI
| SWT.FULL_SELECTION);
GridData tableData = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH);
tableData.heightHint = 100;
filesTable.setLayoutData(tableData);
filesTable.setLinesVisible(true);
filesTable.setHeaderVisible(true);
filesTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableItem[] selected = filesTable.getSelection();
if (selected.length == 0) {
return;
}
String strTgtEnc = ""; //$NON-NLS-1$
for (int i = 0; i < selected.length; i++) {
String curTgtEnc = selected[i].getText(2);
if (i == 0) {
strTgtEnc = curTgtEnc;
} else {
if (!strTgtEnc.equals(curTgtEnc)) {
strTgtEnc = ""; //$NON-NLS-1$
break;
}
}
}
if (!"".equals(strTgtEnc)) { //$NON-NLS-1$
tgtEncCombo.setText(strTgtEnc);
} else {
tgtEncCombo.deselectAll();
}
}
});
tableViewer = new TableViewer(filesTable);
lineNumberColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
lineNumberColumn.setText(Messages.getString("wizard.ReverseConversionWizardPage.lineNumberColumn"));
xliffColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
xliffColumn.setText(Messages.getString("wizard.ReverseConversionWizardPage.xliffColumn")); //$NON-NLS-1$
tgtEncColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
tgtEncColumn.setText(Messages.getString("wizard.ReverseConversionWizardPage.tgtEncColumn")); //$NON-NLS-1$
targetColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn();
targetColumn.setText(Messages.getString("wizard.ReverseConversionWizardPage.targetColumn")); //$NON-NLS-1$
IValueProperty[] valueProperties = BeanProperties.values(ConversionConfigBean.class, new String[] {
"index","source", "targetEncoding", "target" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ViewerSupport.bind(tableViewer, new WritableList(conversionConfigBeans, ConversionConfigBean.class),
valueProperties);
filesComposite.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent arg0) {
int width = filesTable.getClientArea().width;
lineNumberColumn.setWidth(width * 1 / 10);
targetColumn.setWidth(width * 4 / 10);
tgtEncColumn.setWidth(width * 1 / 10);
xliffColumn.setWidth(width * 4 / 10);
}
});
return filesComposite;
}
/**
* 对 UI 和 View Model 进行绑定 ;
*/
private void bindValue() {
DataBindingContext dbc = new DataBindingContext();
WizardPageSupport.create(this, dbc);
ConversionConfigBean configBean = conversionConfigBeans.get(0);
// bind the target encoding
dbc.bindList(SWTObservables.observeItems(tgtEncCombo), BeansObservables.observeList(configBean, "pageEncoding")); //$NON-NLS-1$
}
/**
* 加载文件数据。
*/
private void loadFiles() {
ArrayList<String> xliffs = new ArrayList<String>(conversionConfigBeans.size());
for (int i = 0; i < conversionConfigBeans.size(); i++) {
String xliff = conversionConfigBeans.get(i).getSource();
xliffs.add(ResourceUtils.toWorkspacePath(xliff));
}
for (int i = 0; i < conversionConfigBeans.size(); i++) {
ConversionConfigBean bean = conversionConfigBeans.get(i);
bean.setIndex((i+1)+"");
// 逆转换时,source 其实是 XLIFF 文件。
String xliff = bean.getSource();
String local = ConverterUtil.toLocalPath(xliff);
// 目标文件
String target;
try {
ConversionResource resource = new ConversionResource(Converter.DIRECTION_REVERSE, local);
target = resource.getTargetPath();
} catch (CoreException e) {
e.printStackTrace();
target = ""; //$NON-NLS-1$
}
// 目标编码
String tgtEncValue = getTgtEncoding(local);
if (tgtEncValue == null) {
tgtEncValue = ""; //$NON-NLS-1$
}
bean.setSource(xliff);
bean.setTargetEncoding(tgtEncValue);
bean.setTarget(target);
}
}
/**
* 取得目标文件的编码
* @param xliffPath
* @return ;
*/
private String getTgtEncoding(String xliffPath) {
XLFHandler handler = new XLFHandler();
Map<String, Object> resultMap = handler.openFile(xliffPath);
if (resultMap == null
|| Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap.get(Constant.RETURNVALUE_RESULT)) {
// 打开文件失败。
return ""; //$NON-NLS-1$
}
List<HashMap<String, String>> documentInfo = handler.getDocumentInfo(xliffPath);
if (documentInfo.size() > 0) {
return documentInfo.get(0).get(DocumentPropertiesKeys.ENCODING);
}
return "";
}
@Override
public void dispose() {
super.dispose();
if (filesTable != null) {
filesTable.dispose();
}
if (conversionConfigBeans != null) {
conversionConfigBeans.clear();
conversionConfigBeans = null;
}
System.gc();
}
}
| 14,994 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionWizard.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ConversionWizard.java | package net.heartsome.cat.convert.ui.wizard;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConversionConfigBean;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.wizard.Wizard;
/**
* 项目正向转换向导
* @author weachy
* @since JDK1.5
*/
public class ConversionWizard extends Wizard {
private List<ConverterViewModel> converterViewModels;
private ArrayList<ConversionConfigBean> conversionConfigBeans;
private ConversionWizardPage page;
private IProject currentProject;
/**
* 正向转换向导构造函数
* @param model
*/
public ConversionWizard(List<ConverterViewModel> models, IProject project) {
this.converterViewModels = models;
this.currentProject = project;
ProjectConfiger configer = ProjectConfigerFactory.getProjectConfiger(project);
Language sourceLanguage = configer.getCurrentProjectConfig().getSourceLang();
List<Language> targetlanguage = configer.getCurrentProjectConfig().getTargetLang();
Collections.sort(targetlanguage, new Comparator<Language>() {
public int compare(Language l1, Language l2) {
return l1.toString().compareTo(l2.toString());
}
});
conversionConfigBeans = new ArrayList<ConversionConfigBean>();
for (ConverterViewModel converterViewModel : converterViewModels) {
IConversionItem conversionItem = converterViewModel.getConversionItem();
String source = ResourceUtils.toWorkspacePath(conversionItem.getLocation());
ConversionConfigBean bean = converterViewModel.getConfigBean();
bean.setSource(source); // 初始化源文件路径
bean.setSrcLang(sourceLanguage.getCode()); // 初始化源语言
bean.setTgtLangList(targetlanguage);
if(targetlanguage != null && targetlanguage.size() > 0){
List<Language> lang = new ArrayList<Language>();
lang.add(targetlanguage.get(0));
bean.setHasSelTgtLangList(lang);
}
conversionConfigBeans.add(bean);
}
setWindowTitle(Messages.getString("wizard.ConversionWizard.title")); //$NON-NLS-1$
}
@Override
public void addPages() {
String title = Messages.getString("wizard.ConversionWizard.pageName"); //$NON-NLS-1$
page = new ConversionWizardPage(title, converterViewModels, conversionConfigBeans, currentProject);
addPage(page);
// TODO 添加预翻译选项设置
// addPage(new TranslationWizardPage(Messages.getString("ConversionWizard.2"))); //$NON-NLS-1$
}
@Override
public boolean performFinish() {
IDialogSettings dialogSettings = Activator.getDefault().getDialogSettings();
dialogSettings.put(ConversionWizardPage.REPLACE_TARGET, page.isReplaceTarget());
dialogSettings.put(ConversionWizardPage.OPEN_PRE_TRANS, page.isOpenPreTrans());
return true;
}
/**
* 返回此向导对应的 view model
* @return ;
*/
public List<ConverterViewModel> getConverterViewModels() {
return converterViewModels;
}
public boolean isOpenPreTranslation(){
if(page != null){
return page.isOpenPreTrans();
}
return false;
}
}
| 3,577 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ReverseConversionWizard.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ReverseConversionWizard.java | package net.heartsome.cat.convert.ui.wizard;
import java.util.List;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.resource.Messages;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.wizard.Wizard;
/**
* 逆向转换向导
* @author weachy
* @since JDK1.5
*/
public class ReverseConversionWizard extends Wizard {
private List<ConverterViewModel> converterViewModels;
private IProject project;
/**
* 正向转换向导构造函数
* @param model
*/
public ReverseConversionWizard(List<ConverterViewModel> models, IProject projct) {
this.converterViewModels = models;
this.project = projct;
setWindowTitle(Messages.getString("wizard.ReverseConversionWizard.title")); //$NON-NLS-1$
// 需要显示 progress monitor
setNeedsProgressMonitor(true);
}
@Override
public void addPages() {
addPage(new ReverseConversionWizardPage(Messages.getString("wizard.ReverseConversionWizard.pageName")));
// TODO 存储翻译到翻译记译库
}
@Override
public boolean performFinish() {
return true;
}
/**
* 返回此向导对应的 view model
* @return ;
*/
public List<ConverterViewModel> getConverterViewModels() {
return converterViewModels;
}
/**
* 返回此向导对应的 Project
* @return ;
*/
public IProject getProject() {
return project;
}
}
| 1,383 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TranslationWizardPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/TranslationWizardPage.java | package net.heartsome.cat.convert.ui.wizard;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* 正向转换的预翻译配置页(该类未被调用,因此未做国际化)
* @author cheney
* @since JDK1.6
*/
public class TranslationWizardPage extends WizardPage {
/**
* 预翻译配置页构建函数
* @param pageName
*/
protected TranslationWizardPage(String pageName) {
super(pageName);
setTitle("翻译相关的设置");
setMessage("翻译相关的设置,待实现。");
}
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
Label label = new Label(composite, SWT.NONE);
label.setText("Test:");
new Text(composite, SWT.BORDER);
GridLayoutFactory.swtDefaults().numColumns(2).generateLayout(composite);
setControl(composite);
}
}
| 1,018 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileTypePreferencePage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/preference/FileTypePreferencePage.java | package net.heartsome.cat.convert.ui.preference;
import net.heartsome.cat.common.ui.HsImageLabel;
import net.heartsome.cat.convert.ui.resource.Messages;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
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.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* 首选项的文件类型页面
* @author peason
* @version
* @since JDK1.6
*/
public class FileTypePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
public FileTypePreferencePage() {
setTitle(Messages.getString("preference.FileTypePreferencePage.title"));
}
public void init(IWorkbench workbench) {
noDefaultAndApplyButton();
}
@Override
protected Control createContents(Composite parent) {
Composite tparent = new Composite(parent, SWT.NONE);
tparent.setLayout(new GridLayout());
tparent.setLayoutData(new GridData(GridData.FILL_BOTH));
HsImageLabel imageLabel = new HsImageLabel(Messages.getString("preference.FileTypePreferencePage.imageLabel"),
null);
imageLabel.createControl(tparent);
imageLabel.computeSize();
return parent;
}
}
| 1,289 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionCompleteAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/action/ConversionCompleteAction.java | package net.heartsome.cat.convert.ui.action;
import java.io.File;
import java.util.Map;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.converter.Converter;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
/**
* 演示文件转换后台线程的转换结果 action
* @author cheney,weachy
* @since JDK1.5
*/
public class ConversionCompleteAction extends Action {
private IStatus status;
private Map<String, String> conversionResult;
/**
* 转换完成 action 的构造函数
* @param name
* action 的显示文本
* @param status
* 转换的结果状态
* @param conversionResult
*/
public ConversionCompleteAction(String name, IStatus status, Map<String, String> conversionResult) {
setText(name);
setToolTipText(name);
this.status = status;
this.conversionResult = conversionResult;
}
@Override
public void run() {
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
Assert.isNotNull(window);
Shell shell = window.getShell();
if (status.getSeverity() == IStatus.ERROR) {
MessageDialog.openError(shell, Messages.getString("action.ConversionCompleteAction.msgTitle1"),
status.getMessage());
} else {
// 转换完成后直接打开编辑器,不再进行弹框提示。
// MessageDialog.openInformation(shell, "文件转换完成", status.getMessage());
final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor";
String xliffFile = conversionResult.get(Converter.ATTR_XLIFF_FILE);
IWorkbenchPage page = window.getActivePage();
Assert.isNotNull(page, Messages.getString("action.ConversionCompleteAction.msg1"));
if (xliffFile != null) {
IEditorDescriptor editorDescriptor = PlatformUI.getWorkbench().getEditorRegistry()
.findEditor(XLIFF_EDITOR_ID);
if (editorDescriptor != null) {
try {
IDE.openEditor(page, new File(xliffFile).toURI(), XLIFF_EDITOR_ID, true);
} catch (PartInitException e) {
MessageDialog.openInformation(shell,
Messages.getString("action.ConversionCompleteAction.msgTitle2"),
Messages.getString("action.ConversionCompleteAction.msg2") + e.getMessage());
e.printStackTrace();
}
}
} else {
String targetFile = conversionResult.get(Converter.ATTR_TARGET_FILE);
if (targetFile == null) {
MessageDialog.openInformation(shell,
Messages.getString("action.ConversionCompleteAction.msgTitle2"), Messages.getString("action.ConversionCompleteAction.msg3"));
} else {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IFile input = root.getFileForLocation(new Path(targetFile));
try {
// 使用外部编辑器(系统默认编辑器)打开文件。
IDE.openEditor(page, input, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
} catch (PartInitException e) {
MessageDialog.openInformation(shell,
Messages.getString("action.ConversionCompleteAction.msgTitle2"),
Messages.getString("action.ConversionCompleteAction.msg4") + e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
| 3,750 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConfigConversionDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/dialog/ConfigConversionDialog.java | package net.heartsome.cat.convert.ui.dialog;
import net.heartsome.cat.convert.ui.model.ConverterUtil;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.converter.Converter;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.layout.LayoutConstants;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
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.Label;
import org.eclipse.swt.widgets.Shell;
/**
* 转换文件配置对话框
* @author cheney
* @since JDK1.6
*/
public class ConfigConversionDialog extends TitleAreaDialog {
private ConverterViewModel converterViewModel;
private ComboViewer supportList;
private Button okButton;
/**
* 构造函数
* @param parentShell
* @param converterViewModel
*/
public ConfigConversionDialog(Shell parentShell, ConverterViewModel converterViewModel) {
super(parentShell);
this.converterViewModel = converterViewModel;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite parentComposite = (Composite) super.createDialogArea(parent);
Composite contents = new Composite(parentComposite, SWT.NONE);
GridLayout layout = new GridLayout();
contents.setLayout(layout);
GridData gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
contents.setLayoutData(gridData);
Composite converterComposite = new Composite(contents, SWT.NONE);
converterComposite.setLayout(new GridLayout(2, false));
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
converterComposite.setLayoutData(gridData);
String direction = converterViewModel.getDirection();
if (direction.equals(Converter.DIRECTION_POSITIVE)) {
supportList = createConvertControl(Messages.getString("dialog.ConfigConversionDialog.direction1"), converterComposite);
} else {
supportList = createConvertControl(Messages.getString("dialog.ConfigConversionDialog.direction2"), converterComposite);
}
supportList.getCombo().setFocus();
bindValue();
Dialog.applyDialogFont(parentComposite);
Point defaultMargins = LayoutConstants.getMargins();
GridLayoutFactory.fillDefaults().numColumns(2).margins(defaultMargins.x, defaultMargins.y).generateLayout(
contents);
return contents;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
okButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
okButton.setEnabled(false);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
}
/**
* 创建文件类型列表
* @param title
* @param composite
* @return ;
*/
private ComboViewer createConvertControl(String title, Composite composite) {
Label positiveConvertLabel = new Label(composite, SWT.NONE);
GridData positiveConvertLabelData = new GridData();
positiveConvertLabelData.horizontalSpan = 2;
positiveConvertLabelData.horizontalAlignment = SWT.CENTER;
positiveConvertLabelData.grabExcessHorizontalSpace = true;
positiveConvertLabel.setLayoutData(positiveConvertLabelData);
positiveConvertLabel.setText(title);
Label suportFormat = new Label(composite, SWT.NONE);
suportFormat.setText(Messages.getString("dialog.ConfigConversionDialog.suportFormat"));
ComboViewer supportList = new ComboViewer(composite, SWT.READ_ONLY);
GridData gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
supportList.getCombo().setLayoutData(gridData);
supportList.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection.isEmpty()) {
okButton.setEnabled(false);
} else {
okButton.setEnabled(true);
}
}
});
return supportList;
}
/**
* 对 UI 和 View Model 进行绑定 ;
*/
private void bindValue() {
DataBindingContext dbc = new DataBindingContext();
ConverterUtil.bindValue(dbc, supportList, converterViewModel);
}
}
| 4,803 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IConversionItemDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/dialog/IConversionItemDialog.java | package net.heartsome.cat.convert.ui.dialog;
import net.heartsome.cat.convert.ui.model.IConversionItem;
/**
* 选择转换项目的适配器接口,具体的实现可以为:在 RCP 环境中为 FileDialog 或 WorkspaceDialog;在 RAP 环境中为文件上传界面。
* @author cheney
* @since JDK1.6
*/
public interface IConversionItemDialog {
/**
* @return 打开转换项目选择对话框,并返回操作结果:用户点击确定按钮则返回 IDialogConstants.OK_ID;
*/
int open();
/**
* 获得转换项目
* @return 返回转换项目,如果用户没有选择任何转换项目,则返回一个空的转换项目;
*/
IConversionItem getConversionItem();
}
| 697 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileDialogFactoryFacade.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/dialog/FileDialogFactoryFacade.java | package net.heartsome.cat.convert.ui.dialog;
import net.heartsome.cat.convert.ui.ImplementationLoader;
import org.eclipse.swt.widgets.Shell;
/**
* 打开文件对话框的 factory facade
* @author cheney
* @since JDK1.6
*/
public abstract class FileDialogFactoryFacade {
private static final FileDialogFactoryFacade IMPL;
static {
IMPL = (FileDialogFactoryFacade) ImplementationLoader.newInstance(FileDialogFactoryFacade.class);
}
/**
* @param shell
* @return 返回具体的文件对话框实现;
*/
public static IConversionItemDialog createFileDialog(final Shell shell, int styled) {
return IMPL.createFileDialogInternal(shell, styled);
}
/**
* @param shell
* @param styled
* @return 返回显示工作空间中的文件的对话框;
*/
public static IConversionItemDialog createWorkspaceDialog(final Shell shell, int styled) {
return IMPL.createWorkspaceDialogInternal(shell, styled);
}
/**
* @param shell
* @return 返回文件对话框的内部实现;
*/
protected abstract IConversionItemDialog createFileDialogInternal(Shell shell, int styled);
/**
* @param shell
* @param styled
* @return 返回显示工作空间中的文件的对话框;;
*/
protected abstract IConversionItemDialog createWorkspaceDialogInternal(Shell shell, int styled);
}
| 1,311 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IConverterCallerImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/extension/IConverterCallerImpl.java | /**
* IConverterCallerImpl.java
*
* Version information :
*
* Date:2012-6-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.convert.ui.extension;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.wizard.ConversionWizard;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.ts.ui.extensionpoint.IConverterCaller;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
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.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class IConverterCallerImpl implements IConverterCaller {
private static final Logger LOGGER = LoggerFactory.getLogger(IConverterCallerImpl.class);
/**
*
*/
public IConverterCallerImpl() {
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ui.extensionpoint.IConverterCaller#openConverter(java.util.List)
*/
public void openConverter(List<IFile> files) {
if (files == null || files.size() == 0) {
return;
}
final Shell shell = Display.getCurrent().getActiveShell();
ArrayList<IFile> list = new ArrayList<IFile>();
ArrayList<IFile> wrongFiles = new ArrayList<IFile>();
for (IFile file : files) {
String fileExtension = file.getFileExtension();
if (getLegalFileExtensions() == null || getLegalFileExtensions().length == 0) { // 未限制后缀名的情况
list.add(file);
} else { // 限制了后缀名的情况
if (fileExtension == null) { // 无后缀名的文件
fileExtension = "";
}
if (CommonFunction.containsIgnoreCase(getLegalFileExtensions(), fileExtension)) {
list.add(file);
} else {
wrongFiles.add(file);
}
}
}
if (!wrongFiles.isEmpty()) {
StringBuffer msg = new StringBuffer(Messages.getString("extension.IConverterCallerImpl.msg1"));
for (IFile iFile : wrongFiles) {
msg.append("\n").append(iFile.getFullPath().toOSString());
}
if (!MessageDialog.openConfirm(shell, Messages.getString("extension.IConverterCallerImpl.msgTitle1"),
msg.toString())) {
return;
}
}
ArrayList<ConverterViewModel> converterViewModels = new ArrayList<ConverterViewModel>();
for (int i = 0; i < list.size(); i++) {
Object adapter = Platform.getAdapterManager().getAdapter(list.get(i), IConversionItem.class);
IConversionItem sourceItem = null;
if (adapter instanceof IConversionItem) {
sourceItem = (IConversionItem) adapter;
}
ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_POSITIVE);
converterViewModel.setConversionItem(sourceItem); // 记住所选择的文件
converterViewModels.add(converterViewModel);
}
IProject project = list.get(0).getProject();
ConversionWizard wizard = new ConversionWizard(converterViewModels, project);
TSWizardDialog dialog = new TSWizardDialog(shell, wizard);
int result = dialog.open();
if (result == IDialogConstants.OK_ID) {
final List<ConverterViewModel> models = wizard.getConverterViewModels();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.setTaskName(Messages.getString("extension.IConverterCallerImpl.task1"));
monitor.beginTask(Messages.getString("extension.IConverterCallerImpl.task2"), models.size());
for (ConverterViewModel converterViewModel : models) {
try {
IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1);
subMonitor.setTaskName(Messages.getString("extension.IConverterCallerImpl.task3")
+ converterViewModel.getConversionItem().getLocation().toOSString());
converterViewModel.convertWithoutJob(subMonitor);
} catch (ConverterException e) {
final String message = e.getMessage();
LOGGER.error("", e);
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell,
Messages.getString("extension.IConverterCallerImpl.msgTitle2"), message);
}
});
} catch (Exception e) {
final String message = e.getMessage();
LOGGER.error("", e);
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell,
Messages.getString("extension.IConverterCallerImpl.msgTitle2"), message);
}
});
}
}
monitor.done();
}
};
try {
new ProgressMonitorDialog(shell).run(true, true, runnable);
} catch (InvocationTargetException e) {
MessageDialog.openInformation(shell, Messages.getString("extension.IConverterCallerImpl.msgTitle2"),
e.getMessage());
LOGGER.error("", e);
} catch (InterruptedException e) {
MessageDialog.openInformation(shell, Messages.getString("extension.IConverterCallerImpl.msgTitle2"),
e.getMessage());
LOGGER.error(e.getMessage());
}
}
}
/**
* 修改支持的文件扩展名字
* @return ;
*/
private String[] getLegalFileExtensions() {
// return new String[] { "html","htm", "inx", "properties", "js", "mif", "doc", "ppt", "xls", "docx", "xlsx",
// "pptx",
// "odg", "ods", "odt", "ods", "odt", "po", "rc", "resx", "rtf", "txt", "ttx", "xml" };
return new String[] { "html", "htm", "inx", "properties", "js", "mif", "doc", "ppt", "xls", "docx", "xlsx",
"pptx", "odg", "ods", "odt", "ods", "odt", "po", "rc", "resx", "rtf", "txt", "ttx", "xml", "sdlxliff",
"xlf", "idml", "mqxlz", "txml" };
}
}
| 6,964 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionResource.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/utils/ConversionResource.java | package net.heartsome.cat.convert.ui.utils;
import java.io.File;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.converter.Converter;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
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.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
/**
* 本类用于管理转换的资源
* @author weachy
* @version
* @since JDK1.5
*/
public class ConversionResource {
private String direction;
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); // 工作空间的 root
private IFile file; // 源文件
private IProject project; // 所在项目
private IPath projectRelativePath; // 项目路径
/**
* 本类用于管理转换的资源
* @param direction
* 转换方向
* @param conversionItem
* 转换项目对象
* @throws CoreException
*/
public ConversionResource(String direction, IConversionItem conversionItem) throws CoreException {
this(direction, conversionItem.getLocation());
}
/**
* 本类用于管理转换的资源
* @param direction
* 转换方向
* @param path
* 绝对路径
* @throws CoreException
*/
public ConversionResource(String direction, String path) throws CoreException {
this(direction, new Path(path));
}
/**
* 本类用于管理转换的资源
* @param direction
* 转换方向
* @param location
* 绝对路径
* @throws CoreException
*/
public ConversionResource(String direction, IPath location) throws CoreException {
this.direction = direction;
file = root.getFileForLocation(location);
if (file != null) {
project = file.getProject();
projectRelativePath = file.getProjectRelativePath();
if (projectRelativePath.segmentCount() > 1) {
projectRelativePath = projectRelativePath.removeFirstSegments(1); // 移除 project 下的第一级目录。
}
} else {
throw new CoreException(new Status(IStatus.WARNING, Activator.PLUGIN_ID, Messages.getString("utils.ConversionResource.msg1") + location.toOSString()));
}
}
/**
* 得到源文件路径
* @return ;
*/
public String getSourcePath() {
if (Converter.DIRECTION_POSITIVE.equals(direction)) {
return file.getFullPath().toOSString();
} else {
throw new RuntimeException(Messages.getString("utils.ConversionResource.msg2") + direction);
}
}
/**
* 得到 XLIFF 文件路径
* @return ;
*/
public String getXliffPath() {
if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换
IPath projectPath = project.getFullPath(); // 得到项目路径
IPath targetPath = projectRelativePath.addFileExtension(CommonFunction.R8XliffExtension); // 添加 hsxliff 后缀名
// 放到 XLIFF 文件夹下
String xliffFilePath = projectPath.append(Constant.FOLDER_XLIFF).append(targetPath).toOSString();
return xliffFilePath;
} else { // 反向转换
return file.getFullPath().toOSString();
}
}
/**
* 得到骨架文件路径
* @return ;
*/
public String getSkeletonPath() {
if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换
IPath projectPath = project.getFullPath(); // 得到项目路径
IPath skeletonPath = projectRelativePath.addFileExtension("skl"); // 添加 skl 后缀名
// 放到 SKL 文件夹下
String skeletonFileFile = projectPath.append(Constant.FOLDER_INTERMEDDIATE).append(Constant.FOLDER_SKL).append(skeletonPath).toOSString();
return skeletonFileFile;
} else { // 反向转换
throw new RuntimeException(Messages.getString("utils.ConversionResource.msg3") + direction);
}
}
/**
* 得到目标文件路径
* @return ;
*/
public String getTargetPath() {
return getTargetPath(Constant.FOLDER_TGT);
}
/**
* 得到目标文件路径
* @param tgtFolder
* 目标文件存放文件夹,默认值为{@link net.heartsome.cat.bean.Constant#FOLDER_TGT},默认情况下建议使用 {@link #getTargetPath()}
* @return ;
*/
public String getTargetPath(String tgtFolder) {
if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换
throw new RuntimeException(Messages.getString("utils.ConversionResource.msg4") + direction);
} else {
IPath projectPath = project.getFullPath(); // 得到项目路径
String fileExtension = projectRelativePath.getFileExtension();
IPath targetPath;
if (CommonFunction.R8XliffExtension.equalsIgnoreCase(fileExtension)) {
targetPath = projectRelativePath.removeFileExtension(); // 去除 .hsxliff 后缀
} else {
targetPath = projectRelativePath;
}
// 放到 Target 文件夹下
String targetFilePath = projectPath.append(tgtFolder).append(targetPath).toOSString();
return targetFilePath;
}
}
/**
* 得到目标文件路径
* @param tgtFolder
* 目标文件存放文件夹,默认值为{@link net.heartsome.cat.bean.Constant#FOLDER_TGT},默认情况下建议使用 {@link #getTargetPath()}
* @return ;
*/
public String getPreviewPath() {
if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换
throw new RuntimeException(Messages.getString("utils.ConversionResource.msg4") + direction);
} else {
IPath projectPath = project.getFullPath(); // 得到项目路径
String fileExtension = projectRelativePath.getFileExtension();
IPath targetPath;
if (CommonFunction.R8XliffExtension.equalsIgnoreCase(fileExtension)) {
targetPath = projectRelativePath.removeFileExtension(); // 去除 .hsxliff 后缀
} else {
targetPath = projectRelativePath;
}
// 放到 Intermediate/other 文件夹下
String targetFilePath = projectPath.append(Constant.FOLDER_INTERMEDDIATE)
.append(Constant.FOLDER_OTHER).append(targetPath).toOSString();
int index = targetFilePath.lastIndexOf(".");
if (index > -1 && index > targetFilePath.lastIndexOf(File.separatorChar)) {
targetFilePath = targetFilePath.substring(0, index) + "_Preview" + targetFilePath.substring(index);
}
return targetFilePath;
}
}
public String getXliffDir() {
if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换
IPath projectPath = project.getFullPath();
String xliffFilePath = projectPath.append(Constant.FOLDER_XLIFF).toOSString();
return xliffFilePath;
} else { // 反向转换
return file.getFullPath().toOSString();
}
}
}
| 6,822 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
EncodingResolver.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/utils/EncodingResolver.java | /*
* Created on 24-nov-2004
*
*/
package net.heartsome.cat.convert.ui.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.util.FileEncodingDetector;
import net.heartsome.util.TextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 编码分析工具
* @author Gonzalo Pennino Greco Copyright (c) 2004 Heartsome Holdings Pte. Ltd. http://www.heartsome.net
*/
public class EncodingResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(EncodingResolver.class);
/**
* This method returns the file encoding
* @param fileName
* @param fileType
* @return
*/
public static String getEncoding(String fileName, String fileType) {
if (fileType == null || fileName == null) {
return null;
} else if (fileType.equals(FileFormatUtils.OO) || fileType.equals(FileFormatUtils.OFF)
|| fileType.equals(FileFormatUtils.PPTX) || fileType.equals(FileFormatUtils.MSEXCEl2007)
|| fileType.equals(FileFormatUtils.MSWORD2007)) {
return "UTF-8";
// fixed bug 424 by john.
} else if (fileType.equals(FileFormatUtils.MIF) || fileType.equals(FileFormatUtils.TEXT)
|| fileType.equals(FileFormatUtils.JS) || fileType.equals(FileFormatUtils.JAVA)
|| fileType.equals(FileFormatUtils.PO)) {
return FileEncodingDetector.detectFileEncoding(new File(fileName));
} else if (fileType.equals(FileFormatUtils.SDL) || fileType.equals(FileFormatUtils.DU)
|| fileType.equals(FileFormatUtils.MQ) ||fileType.equals(FileFormatUtils.WF)) {
return "UTF-8";
}
if (fileType.equals(FileFormatUtils.RTF) || fileType.equals(FileFormatUtils.TRTF)) {
return getRTFEncoding(fileName);
} else if (fileType.equals(FileFormatUtils.XML) || fileType.equals(FileFormatUtils.TTX)
|| fileType.equals(FileFormatUtils.RESX) || fileType.equals(FileFormatUtils.INX)) {
return getXMLEncoding(fileName);
} else if (fileType.equals(FileFormatUtils.RC)) {
return getRCEncoding(fileName);
} else if (fileType.equals(FileFormatUtils.IDML)) {
return getIDMLEncoding(fileName);
} else if (fileType.equals(FileFormatUtils.HTML)) {
return getHTMLEncoding(fileName);
}
return null;
}
private static String getRCEncoding(String fileName) {
try {
FileInputStream input = new FileInputStream(fileName);
// read 4K bytes
int read = 4096;
if (input.available() < read) {
read = input.available();
}
byte[] bytes = new byte[read];
input.read(bytes);
input.close();
String content = new String(bytes);
if (content.indexOf("code_page(") != -1) { //$NON-NLS-1$
String code = content.substring(content.indexOf("code_page(") + 10); //$NON-NLS-1$
code = code.substring(0, code.indexOf(")")); //$NON-NLS-1$
return RTF2JavaEncoding(code);
}
} catch (Exception e) {
return null;
}
return null;
}
/**
* This method returns the most suitable encoding according to the file type
* @param fileType
* @return
*/
public static String getEncoding(String fileType) {
if (fileType == null) {
return null;
} else if (fileType.equals(FileFormatUtils.OO)) {
return "UTF-8"; //$NON-NLS-1$
} else if (fileType.equals(FileFormatUtils.MIF)) {
return "US-ASCII"; //$NON-NLS-1$
} else if (fileType.equals(FileFormatUtils.JAVA)) {
return "ISO-8859-1"; //$NON-NLS-1$
} else if (fileType.equals(FileFormatUtils.TTX)) {
return "UTF-16LE"; //$NON-NLS-1$
} else if (fileType.equals(FileFormatUtils.PO) || fileType.equals(FileFormatUtils.XML)
|| fileType.equals(FileFormatUtils.INX)) {
return "UTF-8"; //$NON-NLS-1$
}
return null;
}
public static boolean isFixedEncoding(String fileType) {
if (fileType.equals(FileFormatUtils.OO) ||
// fileType.equals(FileFormatUtils.MIF) || //Fixed a bug 1651 by john.
fileType.equals(FileFormatUtils.RTF) || fileType.equals(FileFormatUtils.TRTF)) {
return true;
}
return false;
}
private static String getXMLEncoding(String fileName) {
// return UTF-8 as default
String result = "UTF-8"; //$NON-NLS-1$
try {
// check if there is a BOM (byte order mark)
// at the start of the document
FileInputStream inputStream = new FileInputStream(fileName);
byte[] array = new byte[2];
inputStream.read(array);
inputStream.close();
byte[] lt = "<".getBytes(); //$NON-NLS-1$
byte[] feff = { -1, -2 };
byte[] fffe = { -2, -1 };
if (array[0] != lt[0]) {
// there is a BOM, now check the order
if (array[0] == fffe[0] && array[1] == fffe[1]) {
return "UTF-16BE"; //$NON-NLS-1$
}
if (array[0] == feff[0] && array[1] == feff[1]) {
return "UTF-16LE"; //$NON-NLS-1$
}
}
// check declared encoding
FileReader input = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(input);
String line = buffer.readLine();
input.close();
if (line.startsWith("<?")) { //$NON-NLS-1$
line = line.substring(2, line.indexOf("?>")); //$NON-NLS-1$
line = line.replaceAll("\'", "\""); //$NON-NLS-1$ //$NON-NLS-2$
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.startsWith("encoding")) { //$NON-NLS-1$
result = token.substring(token.indexOf("\"") + 1, token.lastIndexOf("\"")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
} catch (Exception e) {
LOGGER.error("", e);
if (Constant.RUNNING_MODE == Constant.MODE_DEBUG) {
e.printStackTrace();
}
try {
File log = File.createTempFile("error", ".log", new File("logs"));
FileWriter writer = new FileWriter(log);
PrintWriter print = new PrintWriter(writer);
e.printStackTrace(print);
writer.close();
print.close();
writer = null;
print = null;
} catch (IOException e2) {
// do nothing
} //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
String[] encodings = TextUtil.getPageCodes();
for (int i = 0; i < encodings.length; i++) {
if (encodings[i].equalsIgnoreCase(result)) {
return encodings[i];
}
}
return result;
}
private static String getRTFEncoding(String fileName) {
try {
FileInputStream input = new FileInputStream(fileName);
// read 200 bytes
int read = 200;
if (input.available() < read) {
read = input.available();
}
byte[] bytes = new byte[read];
input.read(bytes);
input.close();
String content = new String(bytes);
StringTokenizer tk = new StringTokenizer(content, "\\", true); //$NON-NLS-1$
while (tk.hasMoreTokens()) {
String token = tk.nextToken();
if (token.equals("\\")) { //$NON-NLS-1$
token = token + tk.nextToken();
}
if (token.startsWith("\\ansicpg")) { //$NON-NLS-1$
String javaEnc = RTF2JavaEncoding(token.substring(8).trim());
System.out.println("Encoding: " + javaEnc); //$NON-NLS-1$
return javaEnc;
}
}
} catch (Exception e) {
LOGGER.error("", e);
if (Constant.RUNNING_MODE == Constant.MODE_DEBUG) {
e.printStackTrace();
}
try {
File log = File.createTempFile("error", ".log", new File("logs"));
FileWriter writer = new FileWriter(log);
PrintWriter print = new PrintWriter(writer);
e.printStackTrace(print);
writer.close();
print.close();
writer = null;
print = null;
} catch (IOException e2) {
// do nothing
} //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return null;
}
// Encoding not declared. Assume OpenOffice and return its XML encoding
return "UTF-8"; //$NON-NLS-1$
}
private static String RTF2JavaEncoding(String encoding) {
String[] codes = TextUtil.getPageCodes();
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("windows-" + encoding) != -1) { //$NON-NLS-1$
return codes[h];
}
}
if (encoding.equals("10000")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("macroman") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("10006")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("macgreek") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("10007")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("maccyrillic") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("10029")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("maccentraleurope") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("10079")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("maciceland") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("10081")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("macturkish") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("65000")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("utf-7") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("650001")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("utf-8") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("932")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("shift_jis") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("936")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("gbk") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("949")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("euc-kr") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("950")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("big5") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
if (encoding.equals("1361")) { //$NON-NLS-1$
for (int h = 0; h < codes.length; h++) {
if (codes[h].toLowerCase().indexOf("johab") != -1) { //$NON-NLS-1$
return codes[h];
}
}
}
return null;
}
private static String getIDMLEncoding(String fileName) {
String encoding = "UTF-8";
try {
ZipInputStream in = new ZipInputStream(new FileInputStream(fileName));
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("designmap.xml")) {
byte[] array = new byte[1024];
in.read(array);
String strTmp = new String(array);
int index = strTmp.indexOf("<?xml");
if (index != -1) {
int endIndex = strTmp.indexOf("?>", index);
strTmp = strTmp.substring(index, endIndex);
for (String str : strTmp.split(" ")) {
if (str.startsWith("encoding")) {
if (str.indexOf("\"") != -1) {
encoding = str.substring(str.indexOf("\"") + 1, str.lastIndexOf("\""));
} else if (str.indexOf("'") != -1) {
encoding = str.substring(str.indexOf("'") + 1, str.lastIndexOf("'"));
}
break;
}
}
}
in.close();
break;
}
}
} catch (FileNotFoundException e) {
LOGGER.error("", e);
e.printStackTrace();
} catch (IOException e) {
LOGGER.error("", e);
e.printStackTrace();
}
return encoding;
}
private static String getHTMLEncoding(String fileName) {
// return UTF-8 as default
String result = "UTF-8"; //$NON-NLS-1$
try {
FileReader input = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(input);
String line;
Pattern pattern = Pattern.compile("[a-zA-Z-_\\d]+");
while ((line = buffer.readLine()) != null) {
int index = line.indexOf("charset=");
if (index != -1) {
Matcher matcher = pattern.matcher(line.substring(index + "charset=".length()));
if (matcher.find()) {
result = matcher.group();
break;
}
}
}
input.close();
} catch (Exception e) {
LOGGER.error("", e);
e.printStackTrace();
}
String[] encodings = TextUtil.getPageCodes();
for (int i = 0; i < encodings.length; i++) {
if (encodings[i].equalsIgnoreCase(result)) {
return encodings[i];
}
}
// 如果不是有效的编码就返回 UTF-8
return "UTF-8";
}
}
| 12,897 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileFormatUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/utils/FileFormatUtils.java | package net.heartsome.cat.convert.ui.utils;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import net.heartsome.cat.common.core.IPreferenceConstants;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.ConverterBean;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
/**
* 文件格式相关辅助类。<br/>
* 由于 R8 中采用 OSGI 服务的方式将转换器分割成单个插件,因而增加了此类来取代 R7 中的 FileFormats.java。<br/>
* 用以在注册的转换器服务中获取转换器支持的文件类型名、文件拓展名等等。
* @author weachy
* @version
* @since JDK1.5
*/
public class FileFormatUtils {
private static ConverterBean allFileBean = new ConverterBean("All", "All", new String[] { "*.*" });
private static final ConverterViewModel MODEL = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_POSITIVE);
/**
* 得到支持的类型
* @return ;
*/
public static List<ConverterBean> getSupportTypes() {
return MODEL.getSupportTypes();
}
/**
* 得到转换器支持的所有文件类型的拓展名
* @return ;
*/
public static String[] getExtensions() {
List<ConverterBean> list = MODEL.getSupportTypes();
checkAutomaticOO(list);
ArrayList<String> FileFormats = new ArrayList<String>();
for (ConverterBean bean : list) {
String[] extensions = bean.getExtensions();
for (String extension : extensions) {
FileFormats.add(extension);
}
}
return FileFormats.toArray(new String[] {});
}
/**
* 得到所有文件格式
* @return ;
*/
public static String[] getFileFormats() {
List<ConverterBean> list = MODEL.getSupportTypes();
checkAutomaticOO(list);
String[] FileFormats = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
FileFormats[i] = list.get(i).getDescription();
}
Arrays.sort(FileFormats);
return FileFormats;
}
/**
* 得到所有文件过滤拓展名。
* @return ;
*/
public static String[] getFilterExtensions() {
List<ConverterBean> list = MODEL.getSupportTypes();
checkAutomaticOO(list);
list.add(0, allFileBean);
String[] FilterExtensions = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
FilterExtensions[i] = list.get(i).getFilterExtensions();
}
return FilterExtensions;
}
/**
* 得到所有文件过滤条件名。
* @return ;
*/
public static String[] getFilterNames() {
List<ConverterBean> list = MODEL.getSupportTypes();
checkAutomaticOO(list);
list.add(0, allFileBean);
String[] filterNames = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
filterNames[i] = list.get(i).getFilterNames();
}
return filterNames;
}
/**
* 检查是否启用 Open Office
*/
private static void checkAutomaticOO(List<ConverterBean> list) {
IPreferencesService service = Platform.getPreferencesService();
String qualifier = Activator.getDefault().getBundle().getSymbolicName();
boolean automaticOO = service.getBoolean(qualifier, IPreferenceConstants.AUTOMATIC_OO, false, null);
if (!automaticOO) {
list.remove(new ConverterBean("MS Office Document to XLIFF Conveter", null));
}
}
public final static String INX = Messages.getString("utils.FileFormatUtils.INX");
public final static String HTML = Messages.getString("utils.FileFormatUtils.HTML");
/** JavaScript 脚本 (JS) */
public final static String JS = Messages.getString("utils.FileFormatUtils.JS");
/** Java 资源文件 (PROPERTIES) */
public final static String JAVA = Messages.getString("utils.FileFormatUtils.JAVA");
public final static String MIF = Messages.getString("utils.FileFormatUtils.MIF");
public final static String OFF = Messages.getString("utils.FileFormatUtils.OFF");
public final static String OO = Messages.getString("utils.FileFormatUtils.OO");
public final static String TEXT = Messages.getString("utils.FileFormatUtils.TEXT");
/** GNU gettext 可移植对象 (PO) */
public final static String PO = Messages.getString("utils.FileFormatUtils.PO");
/** Windows C/C++ 资源文件 (RC) */
public final static String RC = Messages.getString("utils.FileFormatUtils.RC");
public final static String RESX = Messages.getString("utils.FileFormatUtils.RESX");
public final static String RTF = Messages.getString("utils.FileFormatUtils.RTF");
public final static String TRTF = Messages.getString("utils.FileFormatUtils.TRTF");
/** SDL TRADOStag 双语文件 (TTX) */
public final static String TTX = Messages.getString("utils.FileFormatUtils.TTX");
public final static String XML = Messages.getString("utils.FileFormatUtils.XML");
// public final static String XMLG = Messages.getString("utils.FileFormatUtils.XMLG");
public final static String MS = Messages.getString("utils.FileFormatUtils.MS");
/** trados 2009的文件格式 */
public final static String SDL = Messages.getString("utils.FileFormatUtils.SDL");
/** dejavu X2的文件格式 */
public final static String DU = Messages.getString("utils.FileFormatUtils.DU");
public final static String IDML = Messages.getString("utils.FileFormatUtils.IDML");
/** memoQ 6.0 的文件格式 */
public final static String MQ = Messages.getString("utils.FileFormatUtils.MQ");
public final static String PPTX = Messages.getString("utils.FileFormatUtils.PPTX");
public final static String MSEXCEl2007 = Messages.getString("utils.FileFormatUtils.MSEXCEL");
public final static String MSWORD2007 = Messages.getString("utils.FileFormatUtils.MSWORD2007");
/** wordFast 3 的转换器 */
public final static String WF = Messages.getString("utils.FileFormatUtils.WF");
public static boolean canEmbedSkl(String fileFormat) {
// return !(fileFormat.equals(TRTF) || fileFormat.equals(MS) || fileFormat.equals(OFF) || fileFormat.equals(OO)
// || fileFormat.equals(IDML) || fileFormat.equals(PPTX)|| fileFormat.equals(MSEXCEl2007) || fileFormat.equals(MSWORD2007));
return false; // 所有文件都不嵌入骨架
}
public static String detectFormat(String fileName) {
/**
* 备注,新添加的转换器的后缀名,必须添加到 NewProjectWizardSourceFilePage 中的 "CONVERTEREXTENTION" 处
* robert 2013-04-09
*/
File file = new File(fileName);
if (!file.exists()) {
return null;
}
try {
FileInputStream input = new FileInputStream(file);
byte[] array = new byte[40960];
input.read(array);
input.close();
String string = ""; //$NON-NLS-1$
byte[] feff = { -1, -2 };
byte[] fffe = { -2, -1 };
byte[] efbbbf = {-17,-69,-65}; // utf-8 bom
// there may be a BOM, now check the order
if (array[0] == fffe[0] && array[1] == fffe[1]) {
string = new String(array, 2 ,array.length - 2, "UTF-16BE"); //remove bom info
} else if (array[0] == feff[0] && array[1] == feff[1]) {
string = new String(array, 2 ,array.length - 2, "UTF-16LE"); //remove bom info
} else if(array[0] == efbbbf[0] && array[1] == efbbbf[1] && array[2] == efbbbf[2]){
string = new String(array, 3, array.length - 3, "UTF-8");
}else {
string = new String(array);
}
if (string.startsWith("<MIFFile")) { //$NON-NLS-1$
return MIF;
}
if (string.startsWith("{\\rtf")) { //$NON-NLS-1$
// TODO check all header for Trados styles
if (string.indexOf("tw4win") != -1) { //$NON-NLS-1$
return TRTF;
}
return RTF;
}
if (string.startsWith("<?xml") || string.startsWith('\uFEFF' + "<?xml") || string.startsWith('\uFFFE' + "<?xml")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (string.indexOf("<TRADOStag ") != -1) { //$NON-NLS-1$
return TTX;
}
if (string.indexOf("<docu") != -1 && string.indexOf("<?aid ") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
return INX;
}
if (string.indexOf("xmlns:msdata") != -1 && string.indexOf("<root") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
return RESX;
}
// 这是trados 2009的命名空间,若有此,则为trados 2009的双语文件。 --robert 2012-06-28
if (string.indexOf("xmlns:sdl=\"http://sdl.com/FileTypes/SdlXliff/1.0\"") != -1) {
return SDL;
}
// 这是Deja VU X2的命名空间,若有此,则为Deja VU X2的双语文件。 --robert 2012-07-06
if (string.indexOf("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"") != -1) {
return DU;
}
// 为wordFast的双语文件。 --robert 2012-12-13
if (fileName.endsWith(".txml") && string.indexOf("<txml") != -1) {
return WF;
}
return XML;
}
if (string.startsWith("<!DOCTYPE") || string.startsWith('\uFEFF' + "<!DOCTYPE") || string.startsWith('\uFFFE' + "<!DOCTYPE")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
int index = string.indexOf("-//IETF//DTD HTML"); //$NON-NLS-1$
if (index != -1) {
return HTML;
}
if (string.indexOf("-//W3C//DTD HTML") != -1 || string.indexOf("-//W3C//DTD XHTML") != -1) {
return HTML;
}
return XML;
}
int index = string.toLowerCase().indexOf("<html"); //$NON-NLS-1$
if (index != -1) {
return HTML;
}
if (string.indexOf("msgid") != -1 && string.indexOf("msgstr") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
return PO;
}
if (string.startsWith("PK")) { //$NON-NLS-1$
// might be a zipped file
ZipInputStream in = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = null;
boolean found = false;
boolean hasXML = false;
boolean isContainDesignMap = false;
boolean isContainMimetype = false;
boolean isPPTX = false;
boolean isMsExcel2007 = false;
boolean isMsWord2007 = false;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("content.xml")) { //$NON-NLS-1$
found = true;
break;
}
if (entry.getName().startsWith("ppt/")) {
isPPTX = true;
break;
}
if(entry.getName().startsWith("xl/")){
isMsExcel2007 = true;
break;
}
if (entry.getName().equals("designmap.xml")) {
isContainDesignMap = true;
}
if (entry.getName().startsWith("word/") || entry.getName().startsWith("word\\")) {
isMsWord2007 = true;
}
if (entry.getName().equals("mimetype")) {
isContainMimetype = true;
}
if (entry.getName().matches(".*\\.xml")) { //$NON-NLS-1$
hasXML = true;
}
}
in.close();
if (fileName.toLowerCase().endsWith(".pptx") && isPPTX) {
return PPTX;
}
if(fileName.toLowerCase().endsWith(".xlsx") && isMsExcel2007){
return MSEXCEl2007;
}
if (fileName.toLowerCase().endsWith(".docx") && isMsWord2007) {
return MSWORD2007;
}
if (found) {
return OO;
}
if (fileName.toLowerCase().endsWith(".idml") && isContainDesignMap && isContainMimetype) {
return IDML;
}
if (hasXML) {
return OFF;
}
}
if (string.indexOf("#include") != -1 || //$NON-NLS-1$
string.indexOf("#define") != -1 || //$NON-NLS-1$
string.indexOf("DIALOG") != -1 || //$NON-NLS-1$
string.indexOf("DIALOGEX") != -1 || //$NON-NLS-1$
string.indexOf("MENU") != -1 || //$NON-NLS-1$
string.indexOf("MENUEX") != -1 || //$NON-NLS-1$
string.indexOf("POPUP") != -1 || //$NON-NLS-1$
string.indexOf("STRINGTABLE") != -1 || //$NON-NLS-1$
string.indexOf("AUTO3STATE") != -1 || //$NON-NLS-1$
string.indexOf("AUTOCHECKBOX") != -1 || //$NON-NLS-1$
string.indexOf("AUTORADIOBUTTON") != -1 || //$NON-NLS-1$
string.indexOf("CHECKBOX") != -1 || //$NON-NLS-1$
string.indexOf("COMBOBOX") != -1 || //$NON-NLS-1$
string.indexOf("CONTROL") != -1 || //$NON-NLS-1$
string.indexOf("CTEXT") != -1 || //$NON-NLS-1$
string.indexOf("DEFPUSHBUTTON") != -1 || //$NON-NLS-1$
string.indexOf("GROUPBOX") != -1 || //$NON-NLS-1$
string.indexOf("ICON") != -1 || //$NON-NLS-1$
string.indexOf("LISTBOX") != -1 || //$NON-NLS-1$
string.indexOf("LTEXT") != -1 || //$NON-NLS-1$
string.indexOf("PUSHBOX") != -1 || //$NON-NLS-1$
string.indexOf("PUSHBUTTON") != -1 || //$NON-NLS-1$
string.indexOf("RADIOBUTTON") != -1 || //$NON-NLS-1$
string.indexOf("RTEXT") != -1 || //$NON-NLS-1$
string.indexOf("SCROLLBAR") != -1 || //$NON-NLS-1$
string.indexOf("STATE3") != -1) //$NON-NLS-1$
{
return RC;
}
} catch (Exception e) {
// do nothing
}
if (fileName.endsWith(".properties")) { //$NON-NLS-1$
return JAVA;
}
if (fileName.toLowerCase().endsWith(".rc")) { //$NON-NLS-1$
return RC;
}
if (fileName.endsWith(".txt")) { //$NON-NLS-1$
return TEXT;
}
if (fileName.endsWith(".js")) { //$NON-NLS-1$
return JS;
}
if (fileName.endsWith(".doc") || fileName.endsWith(".xls") || fileName.endsWith(".ppt")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return MS;
}
if (fileName.endsWith(".mqxlz")) {
return MQ;
}
if (fileName.endsWith(".txml")) {
return WF;
}
return null;
}
}
| 13,219 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenReverseConversionDialogHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/handler/OpenReverseConversionDialogHandler.java | package net.heartsome.cat.convert.ui.handler;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.file.XLFValidator;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.common.ui.handlers.AbstractSelectProjectFilesHandler;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.wizard.ReverseConversionWizard;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.ts.core.file.XLFHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
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.widgets.Composite;
import org.eclipse.ui.handlers.HandlerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 打开转换文件配置对话框
* @author weachy
* @since JDK1.5
*/
public class OpenReverseConversionDialogHandler extends AbstractSelectProjectFilesHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(OpenReverseConversionDialogHandler.class);
public Object execute(ExecutionEvent event, List<IFile> list) {
if (list == null || list.size() == 0) {
MessageDialog.openInformation(HandlerUtil.getActiveWorkbenchWindow(event).getShell(),
Messages.getString("handler.OpenReverseConversionDialogHandler.msgTitle1"),
Messages.getString("handler.OpenReverseConversionDialogHandler.msg1"));
return null;
}
// 首先验证是否是合并打开的文件 --robert 2012-10-17
System.out.println(list.get(0).getFullPath().toOSString());
if (isEditor) {
// 针对合并打开
if (list.get(0).getFullPath().toOSString().endsWith(".xlp")) {
List<String> multiFiles = new XLFHandler().getMultiFiles(list.get(0));
if (multiFiles.size() > 0) {
list = new ArrayList<IFile>();
}
for (String filePath : multiFiles) {
list.add(ResourceUtils.fileToIFile(filePath));
}
}
}
List<IFile> lstFiles = new ArrayList<IFile>();
XLFValidator.resetFlag();
for (IFile iFile : list) {
if (!XLFValidator.validateXliffFile(iFile)) {
lstFiles.add(iFile);
}
}
CommonFunction.removeRepeateSelect(list);
XLFValidator.resetFlag();
if (!(list instanceof ArrayList)) {
list = new ArrayList<IFile>(list);
}
list.removeAll(lstFiles);
if (list.size() == 0) {
return null;
}
ArrayList<ConverterViewModel> converterViewModels = new ArrayList<ConverterViewModel>();
for (int i = 0; i < list.size(); i++) {
Object adapter = Platform.getAdapterManager().getAdapter(list.get(i), IConversionItem.class);
IConversionItem sourceItem = null;
if (adapter instanceof IConversionItem) {
sourceItem = (IConversionItem) adapter;
}
ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_REVERSE);
converterViewModel.setConversionItem(sourceItem); // 记住所选择的文件
converterViewModels.add(converterViewModel);
}
IProject project = list.get(0).getProject();
ReverseConversionWizard wizard = new ReverseConversionWizard(converterViewModels, project);
TSWizardDialog dialog = new TSWizardDialog(shell, wizard) {
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.FINISH_ID).setText(Messages.getString("handler.OpenConversionDialogHandler.finishLbl"));
}
};
int result = dialog.open();
if (result == IDialogConstants.OK_ID) {
final List<ConverterViewModel> models = wizard.getConverterViewModels();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.setTaskName(Messages.getString("handler.OpenReverseConversionDialogHandler.task1"));
monitor.beginTask(Messages.getString("handler.OpenReverseConversionDialogHandler.task2"), models.size());
for (ConverterViewModel converterViewModel : models) {
try {
IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1);
subMonitor.setTaskName(Messages.getString("handler.OpenReverseConversionDialogHandler.task3")
+ converterViewModel.getConversionItem().getLocation().toOSString());
converterViewModel.convertWithoutJob(subMonitor);
} catch (ConverterException e) {
// Bug #2485:转换文件失败时,提示框显示有问题
throw new InvocationTargetException(e, e.getMessage());
}
}
monitor.done();
}
};
try {
new ProgressMonitorDialog(shell).run(true, true, runnable);
} catch (InvocationTargetException e) {
MessageDialog.openInformation(shell, Messages.getString("handler.OpenReverseConversionDialogHandler.msgTitle2"), e.getMessage());
LOGGER.error("", e);
} catch (InterruptedException e) {
MessageDialog.openInformation(shell, Messages.getString("handler.OpenReverseConversionDialogHandler.msgTitle2"), e.getMessage());
LOGGER.error("", e);
}
}
return null;
}
@Override
public String[] getLegalFileExtensions() {
return CommonFunction.xlfExtesionArray;
}
}
| 5,904 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PreviewTranslationHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/handler/PreviewTranslationHandler.java | package net.heartsome.cat.convert.ui.handler;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConversionConfigBean;
import net.heartsome.cat.convert.ui.model.ConverterUtil;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.utils.ConversionResource;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.ts.core.file.XLFHandler;
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.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.ide.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 预览翻译 Handler
* @author weachy
* @version 1.1
* @since JDK1.5
*/
public class PreviewTranslationHandler extends AbstractHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(PreviewTranslationHandler.class);
private IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
private Shell shell;
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (editor == null) {
return false;
}
IEditorInput input = editor.getEditorInput();
IFile file = ResourceUtil.getFile(input);
shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
if (file == null) {
MessageDialog.openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg1"));
} else {
String fileExtension = file.getFileExtension();
if (fileExtension != null && CommonFunction.validXlfExtension(fileExtension)) {
ConverterViewModel model = getConverterViewModel(file);
if (model != null) {
// model.convert();
try {
previewFiles(new ArrayList<IFile>(Arrays.asList(new IFile[] { file })));
} catch (Exception e) {
// 修改 当异常没有消息,提示信息为空
MessageDialog.openInformation(shell,
Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg7"));
LOGGER.error("", e);
}
}
} else if (fileExtension != null && "xlp".equalsIgnoreCase(fileExtension)) {
// UNDO 合并打开的预览翻译有问题,是针对合并打开的文件,而不是针对项目所有的文件 robert 2012-07-12
if (file.exists()) {
// IFolder xliffFolder = file.getProject().getFolder(Constant.FOLDER_XLIFF);
// Fixed Bug #2616 预览翻译--合并打开的文件不能进行预览翻译 by Jason
XLFHandler hander = new XLFHandler();
List<String> files = hander.getMultiFiles(file);
List<IFile> ifileList = new ArrayList<IFile>();
for (String tf : files) {
ifileList.add(ResourceUtils.fileToIFile(tf));
}
// if (xliffFolder.exists()) {
// ArrayList<IFile> files = new ArrayList<IFile>();
// try {
// ResourceUtils.getXliffs(xliffFolder, files);
// } catch (CoreException e) {
// throw new ExecutionException(e.getMessage(), e);
// }
previewFiles(ifileList);
// } else {
// MessageDialog
// .openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
// Messages.getString("handler.PreviewTranslationHandler.msg2"));
// }
}
} else {
MessageDialog.openInformation(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg3"));
}
}
return null;
}
/**
* 预览翻译多个文件
* @param files
* 文件集合
* @throws ExecutionException
* ;
*/
private void previewFiles(final List<IFile> files) throws ExecutionException {
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InvocationTargetException {
monitor.setTaskName(Messages.getString("handler.PreviewTranslationHandler.task1"));
monitor.beginTask(Messages.getString("handler.PreviewTranslationHandler.task2"), files.size());
for (IFile file : files) {
IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1);
subMonitor.setTaskName(Messages.getString("handler.PreviewTranslationHandler.task3")
+ file.getLocation().toOSString());
try {
preview(file, subMonitor); // 预览单个文件
} catch (ExecutionException e) {
throw new InvocationTargetException(e, e.getMessage());
}
}
monitor.done();
}
};
try {
new ProgressMonitorDialog(shell).run(true, true, runnable);
} catch (InvocationTargetException e) {
throw new ExecutionException(e.getMessage(), e);
} catch (InterruptedException e) {
throw new ExecutionException(e.getMessage(), e);
}
}
/**
* 预览单个文件
* @param file
* IFile 对象
* @param subMonitor
* 进度监视器
* @throws ExecutionException
* ;
*/
private void preview(IFile file, IProgressMonitor subMonitor) throws ExecutionException {
ConverterViewModel model = getConverterViewModel(file);
if (model != null) {
try {
Map<String, String> result = model.convertWithoutJob(subMonitor);
String targetFile = result.get(Converter.ATTR_TARGET_FILE);
if (targetFile == null) {
MessageDialog.openError(shell, Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg4"));
} else {
final IFile input = root.getFileForLocation(new Path(targetFile));
Display.getDefault().syncExec(new Runnable() {
public void run() {
try {
// 使用外部编辑器(系统默认编辑器)打开文件。
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage();
Assert.isNotNull(page, Messages.getString("handler.PreviewTranslationHandler.msg5"));
IDE.openEditor(page, input, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
} catch (PartInitException e) {
MessageDialog.openInformation(shell,
Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
Messages.getString("handler.PreviewTranslationHandler.msg6") + e.getMessage());
LOGGER.error("", e);
}
}
});
}
} catch (ConverterException e) {
throw new ExecutionException(e.getMessage(), e);
}
}
subMonitor.done();
}
/**
* 得到 ConverterViewModel 对象
* @param file
* 需要预览翻译的文件
* @return
* @throws ExecutionException
* ;
*/
private ConverterViewModel getConverterViewModel(IFile file) throws ExecutionException {
Object adapter = Platform.getAdapterManager().getAdapter(file, IConversionItem.class);
if (adapter instanceof IConversionItem) {
IConversionItem item = (IConversionItem) adapter;
ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_REVERSE); // 逆向转换
converterViewModel.setConversionItem(item);
try {
ConversionResource resource = new ConversionResource(Converter.DIRECTION_REVERSE, item);
String xliffpath = resource.getXliffPath();
String targetPath = resource.getPreviewPath();
ConversionConfigBean configBean = converterViewModel.getConfigBean();
configBean.setSource(xliffpath);
configBean.setTarget(targetPath);
configBean.setTargetEncoding("UTF-8");
configBean.setPreviewMode(true); // 设为预览翻译模式
final IStatus status = converterViewModel.validateXliffFile(ConverterUtil.toLocalPath(xliffpath),
new XLFHandler(), null); // 注:验证的过程中,会为文件类型和骨架文件的路径赋值。
if (status != null && status.isOK()) {
return converterViewModel;
} else {
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell,
Messages.getString("handler.PreviewTranslationHandler.msgTitle"),
status.getMessage());
}
});
throw new ExecutionException(status.getMessage(), status.getException());
}
} catch (CoreException e) {
throw new ExecutionException(e.getMessage(), e);
}
}
return null;
}
}
| 9,823 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenConversionDialogHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/handler/OpenConversionDialogHandler.java | package net.heartsome.cat.convert.ui.handler;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.ui.handlers.AbstractSelectProjectFilesHandler;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.convert.extenstion.IExecutePretranslation;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConverterUtil;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.wizard.ConversionWizard;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.util.Progress;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SafeRunner;
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.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* 打开项目转换文件配置对话框
* @author weachy
* @since JDK1.5
*/
public class OpenConversionDialogHandler extends AbstractSelectProjectFilesHandler {
@Override
public Object execute(ExecutionEvent event, List<IFile> list) {
CommonFunction.removeRepeateSelect(list);
if (list == null || list.size() == 0) {
MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
Messages.getString("handler.OpenConversionDialogHandler.msgTitle1"),
Messages.getString("handler.OpenConversionDialogHandler.msg1"));
return null;
}
ArrayList<ConverterViewModel> converterViewModels = new ArrayList<ConverterViewModel>();
for (int i = 0; i < list.size(); i++) {
Object adapter = Platform.getAdapterManager().getAdapter(list.get(i), IConversionItem.class);
IConversionItem sourceItem = null;
if (adapter instanceof IConversionItem) {
sourceItem = (IConversionItem) adapter;
}
ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(),
Converter.DIRECTION_POSITIVE);
converterViewModel.setConversionItem(sourceItem); // 记住所选择的文件
converterViewModels.add(converterViewModel);
}
IProject project = list.get(0).getProject();
ConversionWizard wizard = new ConversionWizard(converterViewModels, project);
TSWizardDialog dialog = new TSWizardDialog(shell, wizard) {
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.FINISH_ID).setText(Messages.getString("handler.OpenConversionDialogHandler.finishLbl"));
}
};
int result = dialog.open();
if (result == IDialogConstants.OK_ID) {
final List<ConverterViewModel> models = wizard.getConverterViewModels();
final List<IFile> targetFiles = new ArrayList<IFile>();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.setTaskName(Messages.getString("handler.OpenConversionDialogHandler.task1"));
monitor.beginTask(Messages.getString("handler.OpenConversionDialogHandler.task2"), models.size());
for (ConverterViewModel converterViewModel : models) {
try {
IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1);
subMonitor.setTaskName(Messages.getString("handler.OpenConversionDialogHandler.task3")
+ converterViewModel.getConversionItem().getLocation().toOSString());
converterViewModel.convertWithoutJob(subMonitor);
List<File> tgtFileList = converterViewModel.getGenerateTgtFileList();
for(File f : tgtFileList){
IFile tgtIfile = ConverterUtil.localPath2IFile(f.getAbsolutePath());
if (tgtIfile != null) {
targetFiles.add(tgtIfile);
}
}
// 若新转换的 xliff 文件重复,那么关闭已经打开的重复文件,防止文件同步冲突 robert 2013-04-01
Display.getDefault().syncExec(new Runnable() {
public void run() {
CommonFunction.closePointEditor(targetFiles);
}
});
} catch (ConverterException e) {
final String message = e.getMessage();
LOGGER.error("", e);
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell, Messages.getString("handler.OpenConversionDialogHandler.msgTitle2"), message);
}
});
} catch (Exception e) {
final String message = e.getMessage();
LOGGER.error("", e);
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell, Messages.getString("handler.OpenConversionDialogHandler.msgTitle2"), message);
}
});
}
}
monitor.done();
}
};
try {
new ProgressMonitorDialog(shell).run(true, true, runnable);
} catch (InvocationTargetException e) {
MessageDialog.openError(shell, Messages.getString("handler.OpenConversionDialogHandler.msgTitle2"), e.getMessage());
LOGGER.error("", e);
} catch (InterruptedException e) {
MessageDialog.openError(shell, Messages.getString("handler.OpenConversionDialogHandler.msgTitle2"), e.getMessage());
LOGGER.error(e.getMessage());
}
if (wizard.isOpenPreTranslation()) {
// 加载转换器扩展
final IExecutePretranslation[] impls = new IExecutePretranslation[1];
IConfigurationElement[] config2 = Platform.getExtensionRegistry().getConfigurationElementsFor(
"net.heartsome.converter.extension.pretranslation");
try {
for (IConfigurationElement e : config2) {
final Object o = e.createExecutableExtension("class");
if (o instanceof IExecutePretranslation) {
ISafeRunnable runnable1 = new ISafeRunnable() {
public void handleException(Throwable exception) {
LOGGER.error(Messages.getString("handler.OpenConversionDialogHandler.logger1"), exception);
}
public void run() throws Exception {
impls[0] = (IExecutePretranslation) o;
}
};
SafeRunner.run(runnable1);
}
}
} catch (CoreException ex) {
LOGGER.error(Messages.getString("handler.OpenConversionDialogHandler.logger1"), ex);
}
if (impls[0] != null) {
if(targetFiles.size() < 1){
return null;
}
impls[0].executePreTranslation(targetFiles);
}
}
}
return null;
}
@Override
public String[] getLegalFileExtensions() {
return new String[] { "html", "htm", "inx", "properties", "js", "mif", "doc", "ppt", "xls", "docx", "xlsx",
"pptx", "odg", "ods", "odt", "ods", "odt", "po", "rc", "resx", "rtf", "txt", "ttx", "xml", "sdlxliff", "xlf", "idml", "mqxlz", "txml" };
}
}
| 7,482 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterCommandTrigger.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/command/ConverterCommandTrigger.java | package net.heartsome.cat.convert.ui.command;
import java.util.Collections;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.NotEnabledException;
import org.eclipse.core.commands.NotHandledException;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.core.expressions.EvaluationContext;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.ISources;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.commands.ICommandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConverterCommandTrigger {
private static final Logger LOGGER = LoggerFactory.getLogger(ConverterCommandTrigger.class);
/**
* 打开正转换对话框
* @param window
* @param file
* ;
*/
public static void openConversionDialog(IWorkbenchWindow window, IFile file) {
openDialog(window, file, "net.heartsome.cat.convert.ui.commands.openConvertDialogCommand");
}
/**
* 打开逆转换对话框
* @param window
* @param file
* ;
*/
public static void openReverseConversionDialog(IWorkbenchWindow window, IFile file) {
openDialog(window, file, "net.heartsome.cat.convert.ui.commands.openReverseConvertDialogCommand");
}
private static void openDialog(IWorkbenchWindow window, IFile file, String commandId) {
IWorkbench workbench = window.getWorkbench();
ICommandService commandService = (ICommandService) workbench.getService(ICommandService.class);
Command command = commandService.getCommand(commandId);
try {
EvaluationContext context = new EvaluationContext(null, IEvaluationContext.UNDEFINED_VARIABLE);
context.addVariable(ISources.ACTIVE_WORKBENCH_WINDOW_NAME, window);
if (file != null) {
StructuredSelection selection = new StructuredSelection(file);
context.addVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME, selection);
}
command.executeWithChecks(new ExecutionEvent(command, Collections.EMPTY_MAP, null, context));
} catch (ExecutionException e) {
LOGGER.error("", e);
} catch (NotDefinedException e) {
LOGGER.error("", e);
} catch (NotEnabledException e) {
LOGGER.error("", e);
} catch (NotHandledException e) {
LOGGER.error("", e);
}
}
}
| 2,486 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
JobRunnable.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/job/JobRunnable.java | package net.heartsome.cat.convert.ui.job;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.action.IAction;
/**
* 定义此接口来封装需要在 Job 中运行的代码
* @author cheney
* @since JDK1.6
*/
public interface JobRunnable {
/**
* 在 run 方法中包含所要执行的代码
* @param monitor
* 监视器,可以为 NULL
* @return 代码执行的结果;
*/
IStatus run(IProgressMonitor monitor);
/**
* 显示此 runnable 的运行结果,如直接弹出成功或失败对话框,主要用于进度显示对话框没有关闭的情况,即进度显示在模式对话框中。
* @param status
* runnable 运行结果的 status;
*/
void showResults(IStatus status);
/**
* 用于显示 runnable 运行结果的 action,通常是 job 在后台运行完成后,通过在进度显示视图中触发相关的 action 链接来查看结果。
* @param status
* runnable 运行结果的 status
* @return 返回显示 runnable 运行结果的 action;
*/
IAction getRunnableCompletedAction(IStatus status);
}
| 1,158 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
JobFactoryFacade.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/job/JobFactoryFacade.java | package net.heartsome.cat.convert.ui.job;
import net.heartsome.cat.convert.ui.ImplementationLoader;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.widgets.Display;
/**
* 创建 Job 的 factory facade
* @author cheney
* @since JDK1.6
*/
public abstract class JobFactoryFacade {
private static final JobFactoryFacade IMPL;
static {
IMPL = (JobFactoryFacade) ImplementationLoader.newInstance(JobFactoryFacade.class);
}
/**
* 创建 Job
* @param display
* @param name
* @param runnable
* @return ;
*/
public static Job createJob(final Display display, final String name, final JobRunnable runnable) {
return IMPL.createJobInternal(display, name, runnable);
}
/**
* 创建 Job 的内部实现
* @param display
* @param name
* @param runnable
* @return ;
*/
protected abstract Job createJobInternal(Display display, String name, JobRunnable runnable);
}
| 913 | 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.converter.ui/src/net/heartsome/cat/convert/ui/resource/Messages.java | package net.heartsome.cat.convert.ui.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 国际化工具类
* @author peason
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.convert.ui.resource.message"; //$NON-NLS-1$
/** The Constant RESOURCE_BUNDLE. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
/**
* Instantiates a new messages.
*/
private Messages() {
// Do nothing
}
/**
* Gets the string.
* @param key
* the key
* @return the string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| 901 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterNotFoundException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterNotFoundException.java | package net.heartsome.cat.convert.ui.model;
import net.heartsome.cat.converter.ConverterException;
import org.eclipse.core.runtime.IStatus;
/**
* 找不到所需转换器的需捕获异常
* @author cheney
* @since JDK1.6
*/
public class ConverterNotFoundException extends ConverterException {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* 构造函数
* @param status
*/
public ConverterNotFoundException(IStatus status) {
super(status);
}
}
| 500 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterContext.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterContext.java | package net.heartsome.cat.convert.ui.model;
import static net.heartsome.cat.converter.Converter.FALSE;
import static net.heartsome.cat.converter.Converter.TRUE;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import org.eclipse.core.runtime.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 在转换文件的过程,用于构建除用户(UI)设置的其他所需配置信息
* @author cheney
* @since JDK1.6
*/
public class ConverterContext {
private static final Logger LOGGER = LoggerFactory.getLogger(ConverterContext.class);
// 转换器相关配置文件顶层目录的名称
private static final String CONVERTER_ROOT_CONFIG_FOLDER_NAME = "net.heartsome.cat.converter";
/**
* srx 目录
*/
public static String srxFolder;
// 文件路径分割符
private static String fileSeparator = System.getProperty("file.separator");
// 系统的配置文件夹路径
private URL configurationLocation;
// 转换器相关配置文件所在的顶层目录
private String configurationFolderForConverter;
// 转换 xliff 的配置 bean
private ConversionConfigBean configBean;
/**
* catalogue 文件路径
*/
public static String catalogue;
// default srx 文件路径
public static String defaultSrx;
// ini 目录路径
private String iniDir;
static {
URL temp = Platform.getConfigurationLocation().getURL();
if (temp != null) {
String configurationPath = new File(temp.getPath()).getAbsolutePath();
String converterConfigurationPath = configurationPath + fileSeparator
+ CONVERTER_ROOT_CONFIG_FOLDER_NAME + fileSeparator;
srxFolder = converterConfigurationPath + "srx" + fileSeparator;
defaultSrx = srxFolder + "default_rules.srx";
catalogue = converterConfigurationPath + "catalogue" + fileSeparator + "catalogue.xml";
}
}
/**
* 构建函数
* @param configBean
* 用户在 UI 所设置的配置信息
*/
public ConverterContext(ConversionConfigBean configBean) {
this.configBean = configBean;
configurationLocation = Platform.getConfigurationLocation().getURL();
if (configurationLocation != null) {
String configurationPath = new File(configurationLocation.getPath()).getAbsolutePath();
configurationFolderForConverter = configurationPath + fileSeparator + CONVERTER_ROOT_CONFIG_FOLDER_NAME
+ fileSeparator;
iniDir = configurationFolderForConverter + "ini";
}
}
/**
* 转换文件所需要的配置信息
* @return 返回转换文件所需要的配置信息;
*/
public Map<String, String> getConvertConfiguration() {
Map<String, String> configuration = new HashMap<String, String>();
configuration.put(Converter.ATTR_SOURCE_FILE, ConverterUtil.toLocalPath(configBean.getSource()));
configuration.put(Converter.ATTR_XLIFF_FILE, ConverterUtil.toLocalPath(configBean.getTarget()));
configuration.put(Converter.ATTR_SKELETON_FILE, ConverterUtil.toLocalPath(configBean.getSkeleton()));
configuration.put(Converter.ATTR_SOURCE_LANGUAGE, configBean.getSrcLang());
configuration.put(Converter.ATTR_TARGET_LANGUAGE, "");
configuration.put(Converter.ATTR_SOURCE_ENCODING, configBean.getSrcEncoding());
boolean segByElement = configBean.isSegByElement();
configuration.put(Converter.ATTR_SEG_BY_ELEMENT, segByElement ? TRUE : FALSE);
configuration.put(Converter.ATTR_INI_FILE, ConverterUtil.toLocalPath(configBean.getInitSegmenter()));
String srx = configBean.getInitSegmenter();
if (srx == null || srx.trim().equals("")) {
srx = defaultSrx;
}
configuration.put(Converter.ATTR_SRX, srx);
configuration.put(Converter.ATTR_LOCK_XTRANS, configBean.isLockXtrans() ? TRUE : FALSE);
configuration.put(Converter.ATTR_LOCK_100, configBean.isLock100() ? TRUE : FALSE);
configuration.put(Converter.ATTR_LOCK_101, configBean.isLock101() ? TRUE : FALSE);
configuration.put(Converter.ATTR_LOCK_REPEATED, configBean.isLockRepeated() ? TRUE : FALSE);
configuration.put(Converter.ATTR_BREAKONCRLF, configBean.isBreakOnCRLF() ? TRUE : FALSE);
configuration.put(Converter.ATTR_EMBEDSKL, configBean.isEmbedSkl() ? TRUE : FALSE);
configuration = getCommonConvertConfiguration(configuration);
if (LOGGER.isInfoEnabled()) {
printConfigurationInfo(configuration);
}
return configuration;
}
/**
* 逆转换文件所需要的配置信息
* @return 返回逆转换文件所需要的配置信息;
*/
public Map<String, String> getReverseConvertConfiguraion() {
Map<String, String> configuration = new HashMap<String, String>();
configuration.put(Converter.ATTR_XLIFF_FILE, configBean.getTmpXlfPath());
configuration.put(Converter.ATTR_TARGET_FILE, ConverterUtil.toLocalPath(configBean.getTarget()));
configuration.put(Converter.ATTR_SKELETON_FILE, configBean.getSkeleton());
configuration.put(Converter.ATTR_SOURCE_ENCODING, configBean.getTargetEncoding());
configuration.put(Converter.ATTR_IS_PREVIEW_MODE, configBean.isPreviewMode() ? TRUE : FALSE);
configuration = getCommonConvertConfiguration(configuration);
if (LOGGER.isInfoEnabled()) {
printConfigurationInfo(configuration);
}
return configuration;
}
/**
* 设置通用的配置信息
* @param configuration
* @return ;
*/
private Map<String, String> getCommonConvertConfiguration(Map<String, String> configuration) {
configuration.put(Converter.ATTR_CATALOGUE, catalogue);
configuration.put(Converter.ATTR_INIDIR, iniDir);
// 设置 xml 转换器中需要用到的 program folder,指向程序的配置目录
configuration.put(Converter.ATTR_PROGRAM_FOLDER, configurationFolderForConverter);
return configuration;
}
/**
* 打印配置信息
* @param configuration
*/
private void printConfigurationInfo(Map<String, String> configuration) {
Iterator<String> iterator = configuration.keySet().iterator();
StringBuffer buffer = new StringBuffer();
buffer.append("configuration:--------------------\n");
while (iterator.hasNext()) {
String key = iterator.next();
String value = configuration.get(key);
buffer.append("key:" + key + "--value:" + value + "\n");
}
buffer.append("---------------------------------");
System.out.println(buffer.toString());
}
}
| 6,323 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterUtil.java | package net.heartsome.cat.convert.ui.model;
import java.io.File;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.databinding.viewers.IViewerObservableValue;
import org.eclipse.jface.databinding.viewers.ViewersObservables;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ViewerComparator;
/**
* @author cheney
* @since JDK1.6
*/
public final class ConverterUtil {
private static final String PROPERTIES_NAME = "name";
private static final String PROPERTIES_SELECTED_TYPE = "selectedType";
private static IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
/**
* 私有构建函数
*/
private ConverterUtil() {
// 防止创建实例
}
/**
* 对下拉列表和转换器列表进行绑定
* @param context
* @param comboViewer
* @param model
* ;
*/
public static void bindValue(DataBindingContext context, ComboViewer comboViewer, ConverterViewModel model) {
// ViewerSupport.bind(comboViewer, BeansObservables.observeList(
// model, "supportTypes", String.class),
// Properties.selfValue(String.class));
//
//
// context.bindValue(ViewersObservables
// .observeSingleSelection(comboViewer), BeansObservables
// .observeValue(model,
// "selectedType"));
// ObservableListContentProvider viewerContentProvider=new ObservableListContentProvider();
comboViewer.setContentProvider(new ArrayContentProvider());
comboViewer.setComparator(new ViewerComparator());
// IObservableMap[] attributeMaps = BeansObservables.observeMaps(
// viewerContentProvider.getKnownElements(),
// ConverterBean.class, new String[] { "description" });
// comboViewer.setLabelProvider(new ObservableMapLabelProvider(
// attributeMaps));
// comboViewer.setInput(Observables.staticObservableList(model.getSupportTypes(),ConverterBean.class));
comboViewer.setInput(model.getSupportTypes());
IViewerObservableValue selection = ViewersObservables.observeSingleSelection(comboViewer);
IObservableValue observableValue = BeansObservables.observeDetailValue(selection, PROPERTIES_NAME, null);
context.bindValue(observableValue, BeansObservables.observeValue(model, PROPERTIES_SELECTED_TYPE));
}
/**
* 是否为工作空间内的路径
* @param workspacePath
* @return ;
*/
private static boolean isWorkspacePath(String workspacePath) {
IFile file = root.getFileForLocation(URIUtil.toPath(new File(workspacePath).toURI()));
return file == null;
}
/**
* 得到本地文件系统路径
* @param workspacePath
* @return ;
*/
public static String toLocalPath(String workspacePath) {
if (isWorkspacePath(workspacePath)) {
IPath path = Platform.getLocation();
return path.append(workspacePath).toOSString();
} else {
return workspacePath;
}
}
/**
* 得到本地文件。
* @param workspacePath
* @return ;
*/
public static File toLocalFile(String workspacePath) {
if (isWorkspacePath(workspacePath)) {
IPath path = Platform.getLocation();
return path.append(workspacePath).toFile();
} else {
return new File(workspacePath);
}
}
public static IFile localPath2IFile(String localPath){
return root.getFileForLocation(URIUtil.toPath(new File(localPath).toURI()));
}
}
| 3,718 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DefaultConversionItem.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/DefaultConversionItem.java | package net.heartsome.cat.convert.ui.model;
import java.io.File;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
/**
* 默认的转项目实现
* @author cheney
* @since JDK1.6
*/
public class DefaultConversionItem implements IConversionItem {
/**
* 空转换项目
*/
public static final IConversionItem EMPTY_CONVERSION_ITEM = new DefaultConversionItem(Path.EMPTY);
/**
* 转换项目的路径
*/
protected IPath path;
/**
* 相对于转换项目路径的上一层转换项目
*/
protected IConversionItem parent;
/**
* 默认转换项目的构建函数
* @param path
*/
public DefaultConversionItem(IPath path) {
this.path = path;
}
public void refresh() {
// do nothing
}
public boolean contains(ISchedulingRule rule) {
if (this == rule) {
return true;
}
if (!(rule instanceof DefaultConversionItem)) {
return false;
}
DefaultConversionItem defaultConversionItem = (DefaultConversionItem) rule;
// 处理路径相同的情况
return path.equals(defaultConversionItem.path);
}
public boolean isConflicting(ISchedulingRule rule) {
if (!(rule instanceof DefaultConversionItem)) {
return false;
}
DefaultConversionItem defaultConversionItem = (DefaultConversionItem) rule;
// 处理路径相同的情况
return path.equals(defaultConversionItem.path);
}
public IPath getLocation() {
return path;
}
public IConversionItem getParent() {
if (parent == null) {
File temp = path.toFile().getParentFile();
if (temp != null) {
parent = new DefaultConversionItem(new Path(temp.getAbsolutePath()));
}
}
return parent;
}
public String getName() {
return path.toFile().getName();
}
public IConversionItem getProject() {
return getParent();
}
}
| 1,839 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SegMergeInfoBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/SegMergeInfoBean.java | package net.heartsome.cat.convert.ui.model;
/**
* 文本段分割与合并信息的pojo类,此类主要用于在逆转换时,将分割与合并后的文件进行相关处理时的数据单元
* @author robert 2012-11-29
*/
public class SegMergeInfoBean {
/** 当前信息是否是属于合并的 */
private boolean isMerge;
private String phFrag;
private String phID;
private String mergeFirstId;
private String mergeSecondId;
public SegMergeInfoBean(boolean isMerge){
this.isMerge = isMerge;
}
public SegMergeInfoBean(boolean isMerge, String phFrag, String phID, String mergeFirstId, String mergeSecondId){
this.isMerge = isMerge;
this.phFrag = phFrag;
this.phID = phID;
this.mergeFirstId = mergeFirstId;
this.mergeSecondId = mergeSecondId;
}
public boolean isMerge() {
return isMerge;
}
public void setMerge(boolean isMerge) {
this.isMerge = isMerge;
}
public String getPhFrag() {
return phFrag;
}
public void setPhFrag(String phFrag) {
this.phFrag = phFrag;
}
public String getPhID() {
return phID;
}
public void setPhID(String phID) {
this.phID = phID;
}
public String getMergeFirstId() {
return mergeFirstId;
}
public void setMergeFirstId(String mergeFirstId) {
this.mergeFirstId = mergeFirstId;
}
public String getMergeSecondId() {
return mergeSecondId;
}
public void setMergeSecondId(String mergeSecondId) {
this.mergeSecondId = mergeSecondId;
}
}
| 1,438 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterViewModel.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterViewModel.java | package net.heartsome.cat.convert.ui.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.action.ConversionCompleteAction;
import net.heartsome.cat.convert.ui.job.JobFactoryFacade;
import net.heartsome.cat.convert.ui.job.JobRunnable;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.utils.FileFormatUtils;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.util.ConverterTracker;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.ts.core.file.XLFHandler;
import net.heartsome.cat.ts.ui.preferencepage.translation.ITranslationPreferenceConstants;
import net.heartsome.util.TextUtil;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.statushandlers.StatusManager;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.NavException;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* 在界面上显示转换器列表的 View Model
* @author cheney,weachy
* @since JDK1.5
*/
public class ConverterViewModel extends ConverterTracker {
private static final Logger LOGGER = LoggerFactory.getLogger(ConverterViewModel.class.getName());
private ConversionConfigBean configBean;
private IConversionItem conversionItem;
private List<File> generateTgtFileList = new ArrayList<File>();
/**
* UI 跟 转换器之间的 View Model
* @param bundleContext
* @param direction
*/
public ConverterViewModel(BundleContext bundleContext, String direction) {
super(bundleContext, direction);
configBean = new ConversionConfigBean();
}
/**
* 获得转换文件时存储配置信息的对象
* @return ;
*/
public ConversionConfigBean getConfigBean() {
return configBean;
}
@Override
public Map<String, String> convert(Map<String, String> parameters) {
return convert();
}
/**
* 根据用户的选择和配置信息,执行文件的转换功能
* @return ;
*/
public Map<String, String> convert() {
// System.out.print(getConfigBean().toString());
// 以用户最后在配置对话框所选择的源文件为准
JobRunnable runnalbe = new JobRunnable() {
private Map<String, String> conversionResult;
public IStatus run(IProgressMonitor monitor) {
IStatus result = Status.OK_STATUS;
try {
conversionResult = convertWithoutJob(monitor);
} catch (OperationCanceledException e) {
LOGGER.info(Messages.getString("model.ConverterViewModel.logger2"), e);
result = Status.CANCEL_STATUS;
} catch (ConverterException e) {
String msg = Messages.getString("model.ConverterViewModel.logger3");
Object[] args = { getConfigBean().getSource() };
LOGGER.error(new MessageFormat(msg).format(args), e);
result = e.getStatus();
} finally {
ConverterViewModel.this.close();
}
return result;
}
public void showResults(IStatus status) {
IAction action = getRunnableCompletedAction(status);
if (action != null) {
action.run();
}
}
public IAction getRunnableCompletedAction(IStatus status) {
return new ConversionCompleteAction(Messages.getString("model.ConverterViewModel.msg1"), status,
conversionResult);
}
};
Job conversionJob = JobFactoryFacade.createJob(Display.getDefault(), "conversion job", runnalbe);
conversionJob.setUser(true);
conversionJob.setRule(conversionItem.getProject());
conversionJob.schedule();
return null;
}
/**
* 正向转换(只是转换的过程,未放入后台线程,未处理转换结果提示信息);
* @param sourceItem
* @param monitor
* @return ;
* @throws ConverterException
*/
public Map<String, String> convertWithoutJob(IProgressMonitor subMonitor) throws ConverterException {
if (getDirection().equals(Converter.DIRECTION_POSITIVE)) {
return convert(conversionItem, subMonitor);
} else {
return reverseConvert(conversionItem, subMonitor);
}
}
/**
* 正向转换
* @param sourceItem
* @param monitor
* @return ;
*/
private Map<String, String> convert(final IConversionItem sourceItem, IProgressMonitor monitor)
throws ConverterException {
Map<String, String> result = null;
boolean convertFlg = false;
String xliffDir = ConverterUtil.toLocalPath(configBean.getXliffDir());
String targetFile = ConverterUtil.toLocalPath(configBean.getTarget());
String skeletonFile = ConverterUtil.toLocalPath(configBean.getSkeleton());
// 转换前的准备
ConverterContext converterContext = new ConverterContext(configBean);
final Map<String, String> configuration = converterContext.getConvertConfiguration();
// 转换前,生成临时的XLIFF文件,用此文件生成指定目标语言的XLIFF文件
File targetTempFile = null;
try {
targetTempFile = File.createTempFile("tempxlf", "xlf");
} catch (IOException e) {
LOGGER.error(Messages.getString("model.ConverterViewModel.msg10"), e);
}
configuration.put(Converter.ATTR_XLIFF_FILE, targetTempFile.getAbsolutePath());
if (configBean.getFileType().equals(FileFormatUtils.MS)) {
IPreferenceStore ps = net.heartsome.cat.ts.ui.Activator.getDefault().getPreferenceStore();
String path = ps.getString(ITranslationPreferenceConstants.PATH_OF_OPENOFFICE);
String port = ps.getString(ITranslationPreferenceConstants.PORT_OF_OPENOFFICE);
configuration.put("ooPath", path);
configuration.put("ooPort", port);
}
// 创建skeleton文件
File skeleton = new File(skeletonFile);
if (!skeleton.exists()) {
try {
File parent = skeleton.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
skeleton.createNewFile();
} catch (IOException e) {
String message = MessageFormat.format(Messages.getString("model.ConverterViewModel.msg11"), skeletonFile);
LOGGER.error(message, e);
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message+"\n"+e.getMessage());
throw new ConverterException(status);
}
}
try {
// 执行转换
Converter converter = getConverter();
if (converter == null) {
// Build a message
String message = Messages.getString("model.ConverterViewModel.msg2") + configBean.getFileType();
// Build a new IStatus
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message);
throw new ConverterException(status);
}
result = converter.convert(configuration, monitor);
final String alert= result.get("ttx2xlfAlert39238409230481092830");
if (result.containsKey("ttx2xlfAlert39238409230481092830")) {//ttx 转 xlf 时,提示含有未预翻译,不推荐,但没办法。
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openWarning(Display.getCurrent().getActiveShell(), Messages.getString("handler.PreviewTranslationHandler.msgTitle"), alert);
}
});
}
// 处理骨架文件,将骨架文件路径修改为项目相对路径,此路径写入external-file节点的href属性
String projectPath = sourceItem.getProject().getLocation().toOSString();
String sklPath = skeletonFile.replace(projectPath, "");
// 处理目标语言, 创建多个目标语言的文件
List<Language> tgtLang = configBean.getHasSelTgtLangList();
if (tgtLang != null && tgtLang.size() > 0) {
// 解析XLIFF文件
File f = new File(targetTempFile.getAbsolutePath());
FileInputStream is = null;
byte[] b = new byte[(int) f.length()];
try {
is = new FileInputStream(f);
is.read(b);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
VTDGen vg = new VTDGen();
vg.setDoc(b);
try {
vg.parse(true);
} catch (VTDException e) {
String message = Messages.getString("model.ConverterViewModel.msg12");
LOGGER.error(message, e);
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message+"\n"+e.getMessage());
throw new ConverterException(status);
}
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils();
// 生成多个XLIFF文件,只是修改目标语言和骨架文件路径
for (Language lang : tgtLang) {
// 修复 bug 2949 ,当文件名中出现 XLIFF 时,文件名获取失败,下面注释代码为之前的代码。 --robert 2013-04-01
// String[] pathArray = targetFile.split(Constant.FOLDER_XLIFF);
// StringBuffer xlffPath = new StringBuffer(pathArray[0]);
// xlffPath.append(Constant.FOLDER_XLIFF).append(File.separator).append(lang.getCode())
// .append(pathArray[1]);
String fileName = targetFile.substring(xliffDir.length());
StringBuffer xlfPahtSB = new StringBuffer();
xlfPahtSB.append(xliffDir);
xlfPahtSB.append(File.separator);
xlfPahtSB.append(lang.getCode());
xlfPahtSB.append(fileName);
File tmpFile = new File(xlfPahtSB.toString());
generateTgtFileList.add(tmpFile);
if (!tmpFile.exists()) {
File parent = tmpFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
try {
tmpFile.createNewFile();
} catch (IOException e) {
String message = Messages.getString("model.ConverterViewModel.msg13");
LOGGER.error(message, e);
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message+"\n"+e.getMessage());
throw new ConverterException(status);
}
}
try {
vu.bind(vn.duplicateNav());
} catch (NavException e) {
LOGGER.error("", e);
}
XMLModifier xm = vu.update("/xliff/file/@target-language", lang.getCode(),
VTDUtils.CREATE_IF_NOT_EXIST);
xm = vu.update(null, xm, "/xliff/file/header/skl/external-file/@href",
TextUtil.cleanString(sklPath));
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tmpFile);
xm.output(fos); // 写入文件
} catch (Exception e) {
String message = Messages.getString("model.ConverterViewModel.msg13");
LOGGER.error(message, e);
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message+"\n"+e.getMessage());
throw new ConverterNotFoundException(status);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
LOGGER.error("",e);
}
}
}
}
vg.clear();
}
convertFlg = true;
} catch (OperationCanceledException e) {
LOGGER.info("ConverterViewerModel: 取消转换");
} finally {
if (!convertFlg) {
for (File f : generateTgtFileList) {
if (f != null && f.exists()) {
f.delete();
}
}
if(skeleton != null && skeleton.exists()){
skeleton.delete();
}
}
targetTempFile.delete();
sourceItem.refresh();
}
return result;
}
/**
* 获取转换后生成的多个目标文件
* @return ;
*/
public List<File> getGenerateTgtFileList(){
return this.generateTgtFileList;
}
/**
* 逆向转换
* @param sourceItem
* @param monitor
* @return ;
*/
private Map<String, String> reverseConvert(IConversionItem sourceItem, IProgressMonitor monitor)
throws ConverterException {
Map<String, String> result = null;
String sourcePathStr = configBean.getSource();
String targetFile = ConverterUtil.toLocalPath(configBean.getTarget());
boolean convertSuccessful = false;
File target = null;
try {
target = new File(targetFile);
if (!target.exists()) {
try {
File parent = target.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
target.createNewFile();
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("model.ConverterViewModel.logger4");
Object[] args = { targetFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
}
}
Converter converter = getConverter();
if (converter == null) {
// Build a message
String message = Messages.getString("model.ConverterViewModel.msg3") + configBean.getFileType();
// Build a new IStatus
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message);
throw new ConverterNotFoundException(status);
}
ConverterContext converterContext = new ConverterContext(configBean);
final Map<String, String> configuration = converterContext.getReverseConvertConfiguraion();
if (configBean.getFileType().equals("x-msoffice2003")) {
IPreferenceStore ps = net.heartsome.cat.ts.ui.Activator.getDefault().getPreferenceStore();
String path = ps.getString(ITranslationPreferenceConstants.PATH_OF_OPENOFFICE);
String port = ps.getString(ITranslationPreferenceConstants.PORT_OF_OPENOFFICE);
configuration.put("ooPath", path);
configuration.put("ooPort", port);
}
result = converter.convert(configuration, monitor);
convertSuccessful = true;
} catch (OperationCanceledException e) {
// 捕获用户取消操作的异常
LOGGER.info(Messages.getString("model.ConverterViewModel.logger2"), e);
throw e;
} catch (ConverterNotFoundException e) {
// Let the StatusManager handle the Status and provide a hint
StatusManager.getManager().handle(e.getStatus(), StatusManager.LOG | StatusManager.SHOW);
if (LOGGER.isErrorEnabled()) {
LOGGER.error(e.getMessage(), e);
}
throw e;
} catch (ConverterException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(
MessageFormat.format(Messages.getString("model.ConverterViewModel.logger3"), sourcePathStr), e);
}
throw e;
} finally {
if (!convertSuccessful) {
// 在转换失败或用户取消转换时,清除目标文件和骨架文件
if (target != null && target.exists()) {
target.delete();
}
}
sourceItem.refresh();
}
return result;
}
/**
* 验证
* @return ;
*/
public IStatus validate() {
if (direction.equals(Converter.DIRECTION_POSITIVE)) {
return validateConversion();
} else {
return validateReverseConversion();
}
}
/**
* 逆向转换验证
* @return ;
*/
private IStatus validateReverseConversion() {
return configBean.validateReverseConversion();
}
/**
* 验证 xliff 所需要转换的 xliff 文件
* @param xliffPath
* xliff 文件路径
* @param monitor
* @return ;
*/
public IStatus validateXliffFile(String xliffPath, XLFHandler handler, IProgressMonitor monitor) {
IStatus result = new ReverseConversionValidateWithLibrary3().validate(xliffPath, configBean, monitor);
if (!result.isOK()) {
return result;
}
// 验证是否存在 xliff 对应的源文件类型的转换器实现
String fileType = configBean.getFileType();
Converter converter = getConverter(fileType);
if (converter != null) {
result = validateFileNodeInXliff(handler, xliffPath, converter.getType()); // 验证 XLIFF 文件的 file 节点
if (!result.isOK()) {
return result;
}
result = validIsSplitedXliff(handler, xliffPath);
if (!result.isOK()) {
return result;
}
setSelectedType(fileType);
result = Status.OK_STATUS;
} else {
result = ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg3") + fileType);
}
return result;
}
/**
* 验证 XLIFF 文件中的 file 节点
* @param handler
* XLFHandler 实例
* @param xliffPath
* XLIFF 文件路径
* @param type
* 文件类型,(Converter.getType() 的值,XLIIF 文件 file 节点的 datatype 属性值)
* @return ;
*/
private IStatus validateFileNodeInXliff(XLFHandler handler, String xliffPath, String type) {
handler.reset(); // 重置,以便重新使用。
Map<String, Object> resultMap = handler.openFile(xliffPath);
if (resultMap == null
|| Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap.get(Constant.RETURNVALUE_RESULT)) {
// 打开文件失败。
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg4")); //$NON-NLS-1$
}
try {
int fileCount = handler.getFileCountInXliff(xliffPath);
if (fileCount < 1) { // 不存在 file 节点。提示为不合法的 XLIFF
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg4")); //$NON-NLS-1$
} else if (fileCount > 1) { // 多个 file 节点,提示分割。
if (ConverterUtils.isOpenOfficeOrMSOffice2007(type)) {
// 验证源文件是 OpenOffice 和 MSOffice 2007 的XLIFF 的 file 节点信息是否完整
return validateOpenOfficeOrMSOffice2007(handler, xliffPath);
}
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg5")); //$NON-NLS-1$
} else { // 只有一个 file 节点
return Status.OK_STATUS;
}
} catch (Exception e) { // 当前打开了多个 XLIFF 文件,参看 XLFHandler.getFileCountInXliff() 方法
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg5")); //$NON-NLS-1$
}
}
/**
* 验证是否是分割文件,若是,提示不允许通过 robert 2012-06-09
* @param handler
* @param xliffPath
* @return
*/
private IStatus validIsSplitedXliff(XLFHandler handler, String xliffPath) {
if (!handler.validateSplitedXlf(xliffPath)) {
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg6"));
}
return Status.OK_STATUS;
}
/**
* 验证源文件是 OpenOffice 和 MSOffice 2007 的XLIFF 的 file 节点信息是否完整
* @param handler
* @param path
* @return ;
*/
private IStatus validateOpenOfficeOrMSOffice2007(XLFHandler handler, String path) {
if (!handler.validateMultiFileNodes(path)) {
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg7"));
}
return Status.OK_STATUS;
}
/**
* 正向转换验证
* @return ;
*/
private IStatus validateConversion() {
if (selectedType == null || selectedType.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg8"));
}
if (configBean.getFileType().equals(FileFormatUtils.MS)) {
IPreferenceStore ps = net.heartsome.cat.ts.ui.Activator.getDefault().getPreferenceStore();
boolean enableOO = ps.getBoolean(ITranslationPreferenceConstants.ENABLED_OF_OPENOFFICE);
if (!enableOO) {
return ValidationStatus.error(Messages.getString("model.ConverterViewModel.msg9"));
}
}
return configBean.validateConversion();
}
/**
* 在导航视图中所选择的文件
* @param file
* ;
*/
public void setConversionItem(IConversionItem file) {
this.conversionItem = file;
}
/**
* 在导航视图中所选择的文件
* @return ;
*/
public IConversionItem getConversionItem() {
return conversionItem;
}
}
| 19,761 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ReverseConversionValidateWithLibrary3.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ReverseConversionValidateWithLibrary3.java | package net.heartsome.cat.convert.ui.model;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.Vector;
import javax.xml.parsers.ParserConfigurationException;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.xml.Catalogue;
import net.heartsome.xml.Document;
import net.heartsome.xml.Element;
import net.heartsome.xml.SAXBuilder;
import net.heartsome.xml.XMLOutputter;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.databinding.validation.ValidationStatus;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* 使用 heartsome library 3 对文件的逆转换进行验证
* @author cheney
* @since JDK1.6
*/
public class ReverseConversionValidateWithLibrary3 implements ConversionValidateStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(ReverseConversionValidateWithLibrary3.class);
private SAXBuilder builder;
private Document doc;
private Element root;
private List<Element> segments = new Vector<Element>();
// 从 xliff 文件的 file 节点获取目标语言
private String targetLanguage;
// 文件类型
private String dataType;
// 骨架文件路径
private String skl;
public IStatus validate(String path, ConversionConfigBean configuraion, IProgressMonitor monitor) {
long start = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger1"), start);
IStatus result = null;
monitor = Progress.getMonitor(monitor);
monitor.beginTask(Messages.getString("model.ReverseConversionValidateWithLibrary3.task1"), 4);
String xliffFile = path;
try {
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
long startTime = 0;
if (LOGGER.isInfoEnabled()) {
File temp = new File(xliffFile);
if (temp.exists()) {
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger2"), temp.length());
}
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger3"), startTime);
}
// 验证所需要转换的 xliff 文件
readXliff(xliffFile);
monitor.worked(1);
long endTime = 0;
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger4"), endTime);
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger5"), (endTime - startTime));
}
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger6"), startTime);
}
// 获取骨架文件路径
skl = getSkeleton(path);
monitor.worked(1);
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger7"), endTime);
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger8"), (endTime - startTime));
}
if (skl != null && !skl.equals("")) { //$NON-NLS-1$
File sklFile = new File(skl);
if (!sklFile.exists()) {
return ValidationStatus.error(Messages.getString("model.ReverseConversionValidateWithLibrary3.msg1"));
}
}
// 设置骨架文件的路径
configuraion.setSkeleton(skl);
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger9"), startTime);
}
createList(root);
monitor.worked(1);
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger10"), endTime);
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger11"), (endTime - startTime));
}
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
// TODO 确认为什么需要创建一个 xliff 文件副本,并需要确认什么时候删除此副本
File tmpXLFFile = File.createTempFile("tmpXLF", ".hsxliff"); //$NON-NLS-1$ //$NON-NLS-2$
reBuildXlf(xliffFile, tmpXLFFile);
configuraion.setTmpXlfPath(tmpXLFFile.getAbsolutePath());
// 设置文件类型
configuraion.setFileType(dataType);
result = Status.OK_STATUS;
monitor.worked(1);
long end = System.currentTimeMillis();
if (LOGGER.isInfoEnabled()) {
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger12"), end);
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger13"), (end - start));
}
} catch (Exception e) {
// TODO 需要针对不同的异常返回不能的提示信息
String messagePattern = Messages.getString("model.ReverseConversionValidateWithLibrary3.msg2");
String message = MessageFormat.format(messagePattern, new Object[] { xliffFile });
LOGGER.error(message, e);
result = ValidationStatus.error(Messages.getString("model.ReverseConversionValidateWithLibrary3.msg3"), e);
} finally {
if (segments != null) {
segments = null;
}
if (root != null) {
root = null;
}
if (doc != null) {
doc = null;
}
if (builder != null) {
builder = null;
}
monitor.done();
}
return result;
}
/**
* @param xliff
* xliff 文件的路径
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
private void readXliff(String xliff) throws SAXException, IOException, ParserConfigurationException {
builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(ConverterContext.catalogue));
doc = builder.build(xliff);
root = doc.getRootElement();
Element file = root.getChild("file"); //$NON-NLS-1$
dataType = file.getAttributeValue("datatype"); //$NON-NLS-1$
targetLanguage = file.getAttributeValue("target-language", Messages.getString("model.ReverseConversionValidateWithLibrary3.msg4")); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* 构建 xliff 文件副本
* @param tmpXLFFile
* @throws IOException
* ;
*/
private void reBuildXlf(File tmpXLFFile) throws IOException {
long startTime = 0;
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger14"), startTime);
}
for (int i = 0, size = segments.size() - 1; i < size; i++) {
Element e = segments.get(i);
Element src = e.getChild("source"); //$NON-NLS-1$
Element tgt = e.getChild("target"); //$NON-NLS-1$
boolean isApproved = e.getAttributeValue("approved", "no").equalsIgnoreCase("yes"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
List<Node> srcList = src.getContent();
Vector<Node> tmp = new Vector<Node>();
for (int j = 0, jSize = srcList.size(); j < jSize; j++) {
Node o = srcList.get(j);
if (o.getNodeType() == Node.ELEMENT_NODE && o.getNodeName().equals("ph")) { //$NON-NLS-1$
Element el = new Element(o);
if (el.getAttributeValue("id", "").startsWith("hs-merge")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String tmpMergeId = el.getAttributeValue("id", "").substring(8); //$NON-NLS-1$ //$NON-NLS-2$
String[] pairId = tmpMergeId.split("~"); //$NON-NLS-1$
srcList.remove(j);
j--;
jSize--;
int idIndex = pairId[0].indexOf("-"); //$NON-NLS-1$
if (idIndex != -1) {
pairId[0] = pairId[0].substring(0, idIndex);
}
idIndex = pairId[1].indexOf("-"); //$NON-NLS-1$
if (idIndex != -1) {
pairId[1] = pairId[1].substring(0, idIndex);
}
if (!pairId[0].equals(pairId[1])) {
pairId = null;
break;
}
pairId = null;
} else {
srcList.remove(j);
j--;
jSize--;
tmp.add(o);
}
} else {
srcList.remove(j);
j--;
jSize--;
tmp.add(o);
}
}
src.removeAllChildren();
src.setContent(tmp);
tmp = null;
if (tgt == null) {
tgt = new Element("target", doc); //$NON-NLS-1$
tgt.setAttribute(Messages.getString("model.ReverseConversionValidateWithLibrary3.msg5"), targetLanguage); //$NON-NLS-1$
tgt.setAttribute("state", "new"); //$NON-NLS-1$ //$NON-NLS-2$
List<Element> content = e.getChildren();
Vector<Element> newContent = new Vector<Element>();
for (int m = 0; m < content.size(); m++) {
Element tmpEl = content.get(m);
newContent.add(tmpEl);
if (tmpEl.getName().equals("source")) { //$NON-NLS-1$
newContent.add(tgt);
}
tmpEl = null;
}
e.setContent(newContent);
newContent = null;
content = null;
}
List<Node> tgtList = tgt.getContent();
tmp = new Vector<Node>();
for (int j = 0, jSize = tgtList.size(); j < jSize; j++) {
Node o = tgtList.get(j);
if (o.getNodeType() == Node.ELEMENT_NODE && o.getNodeName().equals("ph")) { //$NON-NLS-1$
Element el = new Element(o);
if (el.getAttributeValue("id", "").startsWith("hs-merge")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String tmpMergeId = el.getAttributeValue("id", "").substring(8); //$NON-NLS-1$ //$NON-NLS-2$
String[] pairId = tmpMergeId.split("~"); //$NON-NLS-1$
tgtList.remove(j);
j--;
jSize--;
int idIndex = pairId[0].indexOf("-"); //$NON-NLS-1$
if (idIndex != -1) {
pairId[0] = pairId[0].substring(0, idIndex);
}
idIndex = pairId[1].indexOf("-"); //$NON-NLS-1$
if (idIndex != -1) {
pairId[1] = pairId[1].substring(0, idIndex);
}
if (!pairId[0].equals(pairId[1])) {
pairId = null;
break;
}
pairId = null;
} else {
tgtList.remove(j);
j--;
jSize--;
tmp.add(o);
}
el = null;
} else {
tgtList.remove(j);
j--;
jSize--;
tmp.add(o);
}
}
tgt.removeAllChildren();
tgt.setContent(tmp);
tmp = null;
Element nextEl = segments.get(i + 1);
if (!isApproved && srcList.size() > 0) {
nextEl.setAttribute("approved", "no"); //$NON-NLS-1$ //$NON-NLS-2$
}
Element nextSrc = nextEl.getChild("source"); //$NON-NLS-1$
Element nextTgt = nextEl.getChild("target"); //$NON-NLS-1$
if (nextTgt == null) {
nextTgt = new Element("target", doc); //$NON-NLS-1$
nextTgt.setAttribute("xml:lang", targetLanguage); //$NON-NLS-1$
nextTgt.setAttribute("state", "new"); //$NON-NLS-1$ //$NON-NLS-2$
List<Element> content = nextEl.getChildren();
Vector<Element> newContent = new Vector<Element>();
for (int m = 0; m < content.size(); m++) {
Element tmpEl = content.get(m);
newContent.add(tmpEl);
if (tmpEl.getName().equals("source")) { //$NON-NLS-1$
newContent.add(nextTgt);
}
tmpEl = null;
}
nextEl.setContent(newContent);
newContent = null;
content = null;
}
List<Node> nextSrcContent = nextSrc.getContent();
List<Node> nextTgtContent = nextTgt.getContent();
nextSrc.removeAllChildren();
Vector<Node> newNextSrcContent = new Vector<Node>();
newNextSrcContent.addAll(srcList);
for (int j = 0, jSize = nextSrcContent.size(); j < jSize; j++) {
newNextSrcContent.add(nextSrcContent.get(j));
}
nextSrc.setContent(newNextSrcContent);
newNextSrcContent = null;
nextTgt.removeAllChildren();
Vector<Node> newNextTgtContent = new Vector<Node>();
newNextTgtContent.addAll(tgtList);
for (int j = 0, jSize = nextTgtContent.size(); j < jSize; j++) {
newNextTgtContent.add(nextTgtContent.get(j));
}
nextTgt.setContent(newNextTgtContent);
newNextTgtContent = null;
}
long endTime = 0;
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger15"), endTime);
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger16"), (endTime - startTime));
}
XMLOutputter outputter = new XMLOutputter();
outputter.preserveSpace(true);
FileOutputStream out;
out = new FileOutputStream(tmpXLFFile);
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger17"), startTime);
}
outputter.output(doc, out);
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger18"), endTime);
LOGGER.info(Messages.getString("model.ReverseConversionValidateWithLibrary3.logger19"), (endTime - startTime));
}
out.close();
outputter = null;
}
/**
* <div style='color:red;'>代替上面的 reBuildXlf 方法</div>
* 将要逆转换的 hsxliff 文件生成临时文件,再将这个临时文件进行处理,比如将分割的文本段拆分开来 robert 2012-11-28
* @param tmpXLFFile
*/
private void reBuildXlf(String xliffPath, File tmpXLFFile) {
//先将所有合并的文本段进行恢复成原来的样子
try {
ResourceUtils.copyFile(new File(xliffPath), tmpXLFFile);
VTDGen vg = new VTDGen();
if (!vg.parseFile(xliffPath, true)) {
LOGGER.error(MessageFormat.format("{0} parse error!", xliffPath));
return;
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
AutoPilot childAP = new AutoPilot(vn);
ap.declareXPathNameSpace("hs", "http://www.heartsome.net.cn/2008/XLFExtension");
childAP.declareXPathNameSpace("hs", "http://www.heartsome.net.cn/2008/XLFExtension");
VTDUtils vu = new VTDUtils(vn);
XMLModifier xm = new XMLModifier(vn);
// 先找出所有的分割与合并信息,再依序列号从高到低依次分解,合并信息是<ph id="hs-merge0~1" splitMergeIndex="0"> 这种标记
NavigableMap<Long, SegMergeInfoBean> infoMap = new TreeMap<Long, SegMergeInfoBean>();
ap.selectXPath("/xliff/file/body/descendant::node()" +
"[(name()='group' and @ts='hs-split') or (name()='ph' and contains(@id, 'hs-merge'))]");
int idx = -1;
while(ap.evalXPath() != -1){
String nodeName = vn.toString(vn.getCurrentIndex());
long index = -1;
if ((idx = vn.getAttrVal("splitMergeIndex")) != -1) {
index = Long.parseLong(vn.toString(idx));
}
boolean isMerge = false;
// 如果是 ph 节点,那么这个就是合并信息
if ("ph".equals(nodeName)) {
isMerge = true;
String phFrag = vu.getElementFragment();
String phID = vn.toString(vn.getAttrVal("id"));
String[] tuIds = vn.toString(vn.getAttrVal("id")).replace("hs-merge", "").split("~");
String mergeFirstId = tuIds[0].trim();
String mergeSecondId = tuIds[1].trim();
System.out.println("mergeFirstId = " + mergeFirstId);
System.out.println("mergeSecondId = " + mergeSecondId);
infoMap.put(index, new SegMergeInfoBean(isMerge, phFrag, phID, mergeFirstId, mergeSecondId));
}else {
infoMap.put(index, new SegMergeInfoBean(isMerge));
}
}
for(Entry<Long, SegMergeInfoBean> entry : infoMap.descendingMap().entrySet()){
Long index = entry.getKey();
SegMergeInfoBean bean = entry.getValue();
if (bean.isMerge()) {
resetMerge(ap, vn, vu, xm, index, bean);
}else {
resetSplit(ap, childAP, vn, vu, xm, index);
}
vn = xm.outputAndReparse();
xm.bind(vn);
ap.bind(vn);
childAP.bind(vn);
vu.bind(vn);
}
xm.output(tmpXLFFile.getAbsolutePath());
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建翻译节点列表
* @param rootPara
* ;
*/
private void createList(Element rootPara) {
List<Element> files = rootPara.getChildren();
Iterator<Element> it = files.iterator();
while (it.hasNext()) {
Element el = it.next();
if (el.getName().equals("trans-unit")) { //$NON-NLS-1$
segments.add(el);
} else {
createList(el);
}
}
}
/**
* 获取骨架文件
* @return 骨架文件路径
* @throws IOException
* 在读取骨架文件失败时抛出 IO 异常 ;
*/
private String getSkeleton(String xlfPath) throws IOException {
String result = ""; //$NON-NLS-1$
Element file = root.getChild("file"); //$NON-NLS-1$
Element header = null;
String encoding = "";
if (file != null) {
header = file.getChild("header"); //$NON-NLS-1$
if (header != null) {
// 添加源文件编码的读取
List<Element> propGroups = header.getChildren("hs:prop-group"); //$NON-NLS-1$
for (int i = 0; i < propGroups.size(); i++) {
Element prop = propGroups.get(i);
if (prop.getAttributeValue("name").equals("encoding")) { //$NON-NLS-1$ //$NON-NLS-2$
encoding = prop.getText().trim();
break;
}
}
if (encoding.equals("utf-8")) { //$NON-NLS-1$
encoding = "UTF-8"; //$NON-NLS-1$
}
Element mskl = header.getChild("skl"); //$NON-NLS-1$
if (mskl != null) {
Element external = mskl.getChild("external-file"); //$NON-NLS-1$
IFile xlfIfile = ConverterUtil.localPath2IFile(xlfPath);
if (external != null) {
result = external.getAttributeValue("href"); //$NON-NLS-1$
result = result.replaceAll("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
result = result.replaceAll("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
result = result.replaceAll(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
result = result.replaceAll("'", "\'"); //$NON-NLS-1$ //$NON-NLS-2$
result = result.replaceAll(""", "\""); //$NON-NLS-1$ //$NON-NLS-2$
result = xlfIfile.getProject().getLocation().toOSString()+result;
} else {
Element internal = mskl.getChild("internal-file"); //$NON-NLS-1$
if (internal != null) {
File tmp = File.createTempFile("internal", ".skl", new File(xlfIfile.getProject().getWorkspace().getRoot().getLocation().toOSString())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
tmp.deleteOnExit();
FileOutputStream out = new FileOutputStream(tmp);
List<Node> content = internal.getContent();
for (int i = 0; i < content.size(); i++) {
Node n = content.get(i);
if (n.getNodeType() == Node.TEXT_NODE) {
out.write(n.getNodeValue().getBytes(encoding));
} else if (n.getNodeType() == Node.CDATA_SECTION_NODE) {
// fixed bub 515 by john.
String cdataString = n.getNodeValue();
if (cdataString.endsWith("]]")) { //$NON-NLS-1$
cdataString += ">"; //$NON-NLS-1$
}
out.write(cdataString.getBytes());
}
}
out.close();
return tmp.getAbsolutePath();
}
return result;
}
external = null;
mskl = null;
} else {
return result;
}
} else {
return result;
}
} else {
return result;
}
if (encoding != null) {
if (encoding.equals("")) { //$NON-NLS-1$
List<Element> groups = header.getChildren("hs:prop-group"); //$NON-NLS-1$
for (int i = 0; i < groups.size(); i++) {
Element group = groups.get(i);
List<Element> props = group.getChildren("hs:prop"); //$NON-NLS-1$
for (int k = 0; k < props.size(); k++) {
Element prop = props.get(k);
if (prop.getAttributeValue("prop-type", "").equals("encoding")) { //$NON-NLS-1$
encoding = prop.getText();
}
}
}
}
}
header = null;
file = null;
return result;
}
private void resetMerge(AutoPilot ap, VTDNav vn, VTDUtils vu, XMLModifier xm, Long index, SegMergeInfoBean bean) throws Exception{
String phFrag = bean.getPhFrag();
String phID = bean.getPhID();
String firstId = bean.getMergeFirstId();
String secondId = bean.getMergeSecondId();
String xpath = "/xliff/file/body/descendant::trans-unit/source[ph[@id='" + phID + "' and @splitMergeIndex='" + index + "']]";
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
String srcHeader = vu.getElementHead();
String srcContent = vu.getElementContent();
String curContent = srcContent.substring(0, srcContent.indexOf(phFrag));
String otherSrcContent = srcContent.substring(srcContent.indexOf(phFrag) + phFrag.length(), srcContent.length());
String curSrcFrag = srcHeader + curContent + "</source>";
xm.remove();
xm.insertAfterElement(curSrcFrag.getBytes("UTF-8"));
setDataToOtherTU(vn, xm, true, secondId, otherSrcContent);
System.out.println("-------------");
System.out.println(curContent);
System.out.println(otherSrcContent);
}
vn.pop();
//处理译文
xpath = "/xliff/file/body/descendant::trans-unit/target[ph[@id='" + phID + "' and @splitMergeIndex='" + index + "']]";
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
String tgtHeader = vu.getElementHead();
String tgtContent = vu.getElementContent();
//处理合并标识符在 g 标记内的情况,而源文中未处理的主要原因是因为在源文中,合并标识符是自动生成,且用户不能调动其位置,故而未做处理。
int spltOffset = tgtContent.indexOf(phFrag);
List<Map<String, String>> tagLocationList = getTagLocation(vn, tgtContent);
String srcAddStr1 = "";
String srcAddStr2 = "";
for (Map<String, String> map : tagLocationList) {
String tagHeader = map.get("tagHeader");
String tagTail = map.get("tagTail");
int headerIdx = Integer.parseInt(map.get("headerIdx"));
int tailIdx = Integer.parseInt(map.get("tailIdx"));
if (headerIdx < spltOffset && spltOffset <= tailIdx) {
srcAddStr1 = tagTail + srcAddStr1;
srcAddStr2 += tagHeader;
}
}
String tgtFragment1 = tgtHeader + tgtContent.substring(0, spltOffset) + srcAddStr1 + "</target>";
String otherTgtContent = srcAddStr2 + tgtContent.substring(spltOffset + phFrag.length());
xm.remove();
xm.insertAfterElement(tgtFragment1.getBytes("UTF-8"));
setDataToOtherTU(vn, xm, false, secondId, otherTgtContent);
}
vn.pop();
}
private void resetSplit(AutoPilot ap, AutoPilot childAP, VTDNav vn, VTDUtils vu, XMLModifier xm, Long index) throws Exception {
String xpath = "/xliff/file/body/descendant::group[not(descendant::node()[name()='group']) and @ts='hs-split' and @splitMergeIndex='" + index + "']";
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
String id = vn.toString(vn.getAttrVal("id"));
StringBuffer newSrcFragSB = new StringBuffer();
StringBuffer newTgtFragSB = new StringBuffer();
// 先组装源文
vn.push();
boolean addHeader = false;
childAP.selectXPath("./trans-unit/source");
while(childAP.evalXPath() != -1){
if (!addHeader) {
newSrcFragSB.append(vu.getElementHead() == null ? "" : vu.getElementHead());
addHeader = true;
}
newSrcFragSB.append(vu.getElementContent() == null ? "" : vu.getElementContent());
}
if (newSrcFragSB.length() == 0) {
newSrcFragSB = new StringBuffer("<source/>");
}else {
newSrcFragSB.append("</source>");
}
vn.pop();
// 再组装译文
vn.push();
addHeader = false;
childAP.selectXPath("./trans-unit/target");
while(childAP.evalXPath() != -1){
if (!addHeader) {
newTgtFragSB.append(vu.getElementHead() == null ? "" : vu.getElementHead());
addHeader = true;
}
newTgtFragSB.append(vu.getElementContent() == null ? "" : vu.getElementContent());
}
if (newTgtFragSB.length() == 0) {
newTgtFragSB = new StringBuffer("<target/>");
}else {
newTgtFragSB.append("</target>");
}
vn.pop();
StringBuffer newTUFrag = new StringBuffer();
newTUFrag.append("<trans-unit id=\"" + id + "\" xml:space=\"preserve\">");
newTUFrag.append(newSrcFragSB);
newTUFrag.append(newTgtFragSB);
newTUFrag.append("</trans-unit>");
xm.remove();
xm.insertAfterElement(newTUFrag.toString().getBytes("UTF-8"));
}
}
/**
* 向被合并的空的 tu 中填充值
* @param vn
* @param xm
* @param isSrc
* @param secondId
* @param otherContent
* @throws Exception
*/
private void setDataToOtherTU(VTDNav vn, XMLModifier xm, boolean isSrc, String secondId, String otherContent) throws Exception {
if (otherContent == null || otherContent.length() <= 0) {
return;
}
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "/xliff/file/body/descendant::trans-unit[@id='" + secondId + "']"
+ (isSrc ? "/source" : "/target");
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
xm.insertAfterHead(otherContent.getBytes("UTF-8"));
}
vn.pop();
}
/**
* <div style='color:red'>备注:该方法是从 XLFHandler 类中拷贝的。</div>
* 获取每个标记 header 与 tail 在文本中的 index,此方法主要针对文本段分割,分割点在g、mrk标记里面。robert 2012-11-15
* @param vn
*/
private List<Map<String, String>> getTagLocation(VTDNav vn, String srcContent){
List<Map<String, String>> tagLoctionList = new LinkedList<Map<String,String>>();
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "./descendant::node()";
try {
VTDUtils vu = new VTDUtils(vn);
ap.selectXPath(xpath);
int lastIdx = 0;
while(ap.evalXPath() != -1){
Map<String, String> tagLocationMap = new HashMap<String, String>();
String tagName = vn.toString(vn.getCurrentIndex());
if (!("g".equals(tagName) || "mrk".equals(tagName))) {
continue;
}
String tagHeader = vu.getElementHead();
String tagTail = vu.getElementFragment().replace(tagHeader, "").replace(vu.getElementContent(), "");
int headerIdx = srcContent.indexOf(tagHeader, lastIdx);
int tailIdx = headerIdx + tagHeader.length() + vu.getElementContent().length();
lastIdx = headerIdx;
tagLocationMap.put("tagHeader", tagHeader);
tagLocationMap.put("tagTail", tagTail);
tagLocationMap.put("headerIdx", "" + headerIdx);
tagLocationMap.put("tailIdx", "" + tailIdx);
tagLoctionList.add(tagLocationMap);
}
} catch (Exception e) {
e.printStackTrace();
}
vn.pop();
return tagLoctionList;
}
}
| 26,839 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IConversionItem.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/IConversionItem.java | package net.heartsome.cat.convert.ui.model;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
/**
* 转换过程中表示源、目标或骨架等的转换项目,具体的实现可以是文件或其他形式,定义此接口的目的是适配 org.eclipse.core.resources 中 的 IFile 等接口,org.eclipse.core.resources
* 不包含在 RAP 目标平台中,且 org.eclipse.core.resources 的实现不是多用户的,所以不建议把 org.eclipse.core.resources 及其依赖放到 RAP 平台中直接使用。同时实现
* ISchedulingRule 接口定义资源的访问规则。
* @author cheney
*/
public interface IConversionItem extends ISchedulingRule {
/**
* 刷新 conversion item ;
*/
void refresh();
/**
* @return 返回此转换项目的位置;
*/
IPath getLocation();
/**
* 获得转换项目的父
* @return ;
*/
IConversionItem getParent();
/**
* 获得转换项目所在的项目,如果转换项目不在工作空间中,则直接返回其上一层转换项目
* @return ;
*/
IConversionItem getProject();
/**
* 获得转换项目的名称
* @return ;
*/
String getName();
}
| 1,188 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionConfigBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConversionConfigBean.java | package net.heartsome.cat.convert.ui.model;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.util.CommonFunction;
import net.heartsome.cat.convert.ui.resource.Messages;
import net.heartsome.cat.convert.ui.utils.FileFormatUtils;
import net.heartsome.cat.converter.util.AbstractModelObject;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
* 在转换 xliff 文件时,转换设置对话框中可设置参数对应的实体 bean
* @author cheney
* @since JDK1.6
*/
public class ConversionConfigBean extends AbstractModelObject {
// 序号
private String index;
// 源文件的路径
private String source;
// 目标文件路径
private String target;
// 骨架文件路径
private String skeleton;
//xliff 文件夹路径
private String xliffDir;
// 源文件语言
private String srcLang;
// 源文件编码
private String srcEncoding;
// 目标文件编码
private String targetEncoding;
// 是否按段茖分段
private boolean segByElement;
// SRX 规则文件路径
private String initSegmenter;
// 是否标记为不可翻译
private boolean lockXtrans;
// 是否为 100% 匹配的文本进行进行标记
private boolean lock100;
// 是否为上下文匹配的文本进行进行标记
private boolean lock101;
// 是否为重复的文本段进行标记
private boolean lockRepeated;
// 是否按 CR/LF 分段
private boolean breakOnCRLF;
// 将骨架嵌入 xliff 文件
private boolean embedSkl;
// 如果目标文件已存在,是否覆盖
private boolean replaceTarget;
// 预览模式
private boolean previewMode;
// 文件格式
private List<String> fileFormats;
// 编码列表
private List<String> pageEncoding;
// 目标语言列表
private List<Language> tgtLangList;
private List<Language> hasSelTgtLangList;
// 文件类型
private String fileType;
/** 临时 XLIFF 文件路径,在逆转换时,会根据所选 XLIFF 文件,生成一个无分割/合并文本段的临时 XLIFF 文件,此变量记录临时文件路径 */
private String tmpXlfPath;
/**
* 文件类型
* @return ;
*/
public String getFileType() {
return fileType;
}
/**
* 文件类型
* @param fileType
* ;
*/
public void setFileType(String fileType) {
firePropertyChange("fileType", this.fileType, this.fileType = fileType);
}
/**
* 编码列表
* @return ;
*/
public List<String> getPageEncoding() {
if (pageEncoding == null) {
String[] codeArray = LocaleService.getPageCodes();
pageEncoding = Arrays.asList(codeArray);
}
return pageEncoding;
}
/**
* 编码列表
* @param pageEncoding
* ;
*/
public void setPageEncoding(List<String> pageEncoding) {
this.pageEncoding = pageEncoding;
}
/**
* 将骨架嵌入 xliff 文件
* @return ;
*/
public boolean isEmbedSkl() {
return embedSkl;
}
/**
* 将骨架嵌入 xliff 文件
* @param embedSkl
* ;
*/
public void setEmbedSkl(boolean embedSkl) {
this.embedSkl = embedSkl;
}
/**
* 源文件的路径
* @return ;
*/
public String getSource() {
return source;
}
/**
* 源文件的路径
* @param source
* ;
*/
public void setSource(String source) {
firePropertyChange("source", this.source, this.source = source);
}
/**
* 目标文件路径
* @return ;
*/
public String getTarget() {
return target;
}
/**
* 目标文件路径
* @param target
* ;
*/
public void setTarget(String target) {
firePropertyChange("target", this.target, this.target = target);
}
/**
* 骨架文件路径
* @return ;
*/
public String getSkeleton() {
return skeleton;
}
/**
* 骨架文件路径
* @param skeleton
* ;
*/
public void setSkeleton(String skeleton) {
this.skeleton = skeleton;
}
/**
* 源文件语言
* @return ;
*/
public String getSrcLang() {
return srcLang;
}
/**
* 源文件语言
* @param srcLang
* ;
*/
public void setSrcLang(String srcLang) {
firePropertyChange("srcLang", this.srcLang, this.srcLang = srcLang);
}
/** @return 目标语言 */
public List<Language> getTgtLangList() {
return tgtLangList;
}
/**
* 目标语言
* @param tgtLang
* the tgtLang to set
*/
public void setTgtLangList(List<Language> tgtLangList) {
this.tgtLangList = tgtLangList;
}
/** @return the hasSelTgtLangList */
public List<Language> getHasSelTgtLangList() {
return hasSelTgtLangList;
}
/**
* @param hasSelTgtLangList
* the hasSelTgtLangList to set
*/
public void setHasSelTgtLangList(List<Language> hasSelTgtLangList) {
this.hasSelTgtLangList = hasSelTgtLangList;
}
/**
* 源文件编码
* @return ;
*/
public String getSrcEncoding() {
return srcEncoding;
}
/**
* 源文件编码
* @param srcEncoding
* ;
*/
public void setSrcEncoding(String srcEncoding) {
firePropertyChange("srcEncoding", this.srcEncoding, this.srcEncoding = srcEncoding);
}
/**
* 是否按段茖分段
* @return ;
*/
public boolean isSegByElement() {
return segByElement;
}
/**
* 是否按段茖分段
* @param segByElement
* ;
*/
public void setSegByElement(boolean segByElement) {
this.segByElement = segByElement;
}
/**
* SRX 规则文件路径
* @return ;
*/
public String getInitSegmenter() {
return initSegmenter;
}
/**
* SRX 规则文件路径
* @param initSegmenter
* ;
*/
public void setInitSegmenter(String initSegmenter) {
firePropertyChange("initSegmenter", this.initSegmenter, this.initSegmenter = initSegmenter);
}
/**
* 是否标记为不可翻译
* @return ;
*/
public boolean isLockXtrans() {
return lockXtrans;
}
/**
* 是否标记为不可翻译
* @param lockXtrans
* ;
*/
public void setLockXtrans(boolean lockXtrans) {
this.lockXtrans = lockXtrans;
}
/**
* 是否为 100% 匹配的文本进行进行标记
* @return ;
*/
public boolean isLock100() {
return lock100;
}
/**
* 是否为 100% 匹配的文本进行进行标记
* @param lock100
* ;
*/
public void setLock100(boolean lock100) {
this.lock100 = lock100;
}
/**
* 是否为上下文匹配的文本进行进行标记
* @return ;
*/
public boolean isLock101() {
return lock101;
}
/**
* 是否为上下文匹配的文本进行进行标记
* @param lock101
* ;
*/
public void setLock101(boolean lock101) {
this.lock101 = lock101;
}
/**
* 是否为上下文匹配的文本进行进行标记
* @return ;
*/
public boolean isLockRepeated() {
return lockRepeated;
}
/**
* 是否为上下文匹配的文本进行进行标记
* @param lockRepeated
* ;
*/
public void setLockRepeated(boolean lockRepeated) {
this.lockRepeated = lockRepeated;
}
/**
* 是否按 CR/LF 分段
* @return ;
*/
public boolean isBreakOnCRLF() {
return breakOnCRLF;
}
/**
* 是否按 CR/LF 分段
* @param breakOnCRLF
* ;
*/
public void setBreakOnCRLF(boolean breakOnCRLF) {
this.breakOnCRLF = breakOnCRLF;
}
/**
* 目标文件编码
* @param targetEncoding
* ;
*/
public void setTargetEncoding(String targetEncoding) {
firePropertyChange("targetEncoding", this.targetEncoding, this.targetEncoding = targetEncoding);
}
/**
* 目标文件编码
* @return ;
*/
public String getTargetEncoding() {
return targetEncoding;
}
public String getTmpXlfPath() {
return tmpXlfPath;
}
public void setTmpXlfPath(String tmpXlfPath) {
this.tmpXlfPath = tmpXlfPath;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("configuration:--------------------\n");
buffer.append("source:" + getSource() + "\n");
buffer.append("target:" + getTarget() + "\n");
buffer.append("skeleton:" + getSkeleton() + "\n");
buffer.append("srclang:" + getSrcLang() + "\n");
buffer.append("srcEncoding:" + getSrcEncoding() + "\n");
buffer.append("targetEncoding:" + getTargetEncoding() + "\n");
buffer.append("segByElement:" + isSegByElement() + "\n");
buffer.append("initSegmenter:" + getInitSegmenter() + "\n");
buffer.append("lockXtrans:" + isLockXtrans() + "\n");
buffer.append("lock100:" + isLock100() + "\n");
buffer.append("lock101:" + isLock101() + "\n");
buffer.append("lockRepeated:" + isLockRepeated() + "\n");
buffer.append("breakOnCRLF:" + isBreakOnCRLF() + "\n");
buffer.append("embedSkl:" + isEmbedSkl() + "\n");
buffer.append("--------------------------");
return buffer.toString();
}
/**
* 根据新需求,将xlf文件存放在以目标语言为名称目录中的,用于生成路径
* @return ;
*/
public List<String> generateXlfFilePath() {
String tgtFilePath = ConverterUtil.toLocalPath(getTarget());
// 注释部分为加了语言代码后缀的情况
// String sourceFileName = source.substring(source.lastIndexOf(spearator));
List<String> xlfFilePaths = new ArrayList<String>();
for (Language lang : hasSelTgtLangList) {
// 修复 bug 2949 ,当文件名中出现 XLIFF 时,文件名获取失败,下面注释代码为之前的代码。 --robert 2013-04-01
// String[] pathArray = tgtFilePath.split(Constant.FOLDER_XLIFF);
// StringBuffer xlffPath = new StringBuffer(pathArray[0]);
// xlffPath.append(Constant.FOLDER_XLIFF).append(spearator).append(lang.getCode()).append(pathArray[1]);
String dirName = tgtFilePath.substring(0, tgtFilePath.lastIndexOf(File.separator) + 1);
String fileName = tgtFilePath.substring(tgtFilePath.lastIndexOf(File.separator) + 1, tgtFilePath.length());
StringBuffer xlfPahtSB = new StringBuffer();
xlfPahtSB.append(dirName);
xlfPahtSB.append(lang.getCode());
xlfPahtSB.append(File.separator);
xlfPahtSB.append(fileName);
// File targetTempFile = new File(xlffPath.toString());
// xlffPath = new StringBuffer(targetTempFile.getParentFile().getPath());
// xlffPath.append(spearator);
// int tempInt = sourceFileName.lastIndexOf(".");
// String fileEx = sourceFileName.substring(sourceFileName.lastIndexOf("."));
// String fileName = sourceFileName.substring(1, tempInt);
// xlffPath.append(fileName).append("_").append(lang.getCode()).append(fileEx).append(CommonFunction.R8XliffExtension_1);
// xlffPath.append(sourceFileName).append(CommonFunction.R8XliffExtension_1);
xlfFilePaths.add(xlfPahtSB.toString());
}
return xlfFilePaths;
}
/**
* 正向转换验证
* @return ;
*/
public IStatus validateConversion() {
if (source == null || source.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg1"));
} else {
String localSource = ConverterUtil.toLocalPath(source);
File file = new File(localSource);
if (!file.exists()) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg2"));
}
}
if (target == null || target.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg3"));
} else {
if (!replaceTarget) { // 如果未选择覆盖,判断并提示目标文件是否存在
List<String> xlfFilePaths = generateXlfFilePath();
for (String path : xlfFilePaths) {
File file = new File(path);
if (file.exists()) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg4"));
}
}
}
}
if (srcLang == null || srcLang.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg5"));
}
if (srcEncoding == null || srcEncoding.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg6"));
}
if (initSegmenter == null || initSegmenter.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg7"));
} else {
File file = new File(initSegmenter);
if (!file.exists()) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg8"));
}
}
return Status.OK_STATUS;
}
/**
* 逆向转换验证
* @return ;
*/
public IStatus validateReverseConversion() {
if (target == null || target.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg9"));
} else {
if (!replaceTarget) { // 如果未选择覆盖,判断并提示目标文件是否存在
String localTarget = ConverterUtil.toLocalPath(target);
File file = new File(localTarget);
if (file.exists()) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg10"));
}
}
}
if (targetEncoding == null || targetEncoding.trim().equals("")) {
return ValidationStatus.error(Messages.getString("model.ConversionConfigBean.msg11"));
}
return Status.OK_STATUS;
}
public void setReplaceTarget(boolean replaceTarget) {
this.replaceTarget = replaceTarget;
}
public boolean isReplaceTarget() {
return replaceTarget;
}
public void setFileFormats(List<String> fileFormats) {
this.fileFormats = fileFormats;
}
public List<String> getFileFormats() {
if (fileFormats == null) {
fileFormats = CommonFunction.array2List(FileFormatUtils.getFileFormats());
}
return fileFormats;
}
public boolean isPreviewMode() {
return previewMode;
}
public void setPreviewMode(boolean previewMode) {
this.previewMode = previewMode;
}
/** @return the index */
public String getIndex() {
return index;
}
/**
* @param index
* the index to set
*/
public void setIndex(String index) {
this.index = index;
}
public String getXliffDir() {
return xliffDir;
}
public void setXliffDir(String xliffDir) {
this.xliffDir = xliffDir;
}
}
| 14,143 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionValidateStrategy.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConversionValidateStrategy.java | /**
* ConversionValidateStrategy.java
*
* Version information :
*
* Date:Apr 13, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.convert.ui.model;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
/**
* 验证文件转换的配置信息是否正确的顶层接口。
* @author cheney
* @since JDK1.6
*/
public interface ConversionValidateStrategy {
/**
* 验证文件转换的配置信息
* @param path
* 文件路径
* @param configuraion
* 文件转换配置信息
* @param monitor
* @return 返回验证的结果状态;
*/
IStatus validate(String path, ConversionConfigBean configuraion, IProgressMonitor monitor);
}
| 725 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ColProperties.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/ColProperties.java | package net.heartsome.cat.ts.ui.plugin;
/**
* TBXMaker 插件中列属性的 Bean 类
* @author peason
* @version
* @since JDK1.6
*/
public class ColProperties {
String colName;
public String level;
String language;
String propName;
public String propType;
public static String noteName = "note"; //$NON-NLS-1$
public static String descripName = "descrip"; //$NON-NLS-1$
public static String termNoteName = "termNote"; //$NON-NLS-1$
public static String termName = "term"; //$NON-NLS-1$
public static String conceptLevel = "Concept"; //$NON-NLS-1$
public static String langLevel = "Term"; //$NON-NLS-1$
public ColProperties(String pColName){
colName = pColName;
level = conceptLevel;
propName = descripName;
propType = ""; //$NON-NLS-1$
language = ""; //$NON-NLS-1$
}
public void setColumnType(String plevel, String pLang, String pName, String pType){
level = plevel;
language = pLang;
propName = pName;
propType = pType;
colName = pName + " ("+pLang+")"; //$NON-NLS-1$ //$NON-NLS-2$
}
public String getLanguage() {
return language;
}
public String getLevel() {
return level;
}
public String getPropName() {
return propName;
}
public String getPropType() {
return propType;
}
public String getColName() {
return colName;
}
}
| 1,317 | 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.plugin/src/net/heartsome/cat/ts/ui/plugin/Activator.java | package net.heartsome.cat.ts.ui.plugin;
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.plugin"; //$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,382 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginConfigManage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/PluginConfigManage.java | package net.heartsome.cat.ts.ui.plugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
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.core.Constant;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.ts.core.file.XLFHandler;
import net.heartsome.cat.ts.ui.plugin.bean.PluginConfigBean;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
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.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
/**
* 插件配置管理的公用类
* @author robert 2012-03-07
* @version
* @since JDK1.6
*/
public class PluginConfigManage {
private static final Logger LOGGER = LoggerFactory.getLogger(PluginConfigManage.class);
/** 插件配置文件的路径 */
private String pluginXmlLocation;
/** 菜单栏父菜单的管理类 */
private MenuManager parentManager;
private Shell shell;
@SuppressWarnings("restriction")
public PluginConfigManage() {
pluginXmlLocation = ResourcesPlugin.getWorkspace().getRoot().getLocation()
.append(PluginConstants.PC_pluginConfigLocation).toOSString();
WorkbenchWindow window = (WorkbenchWindow) PlatformUI.getWorkbench().getActiveWorkbenchWindow();
parentManager = window.getMenuBarManager();
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
}
@SuppressWarnings("restriction")
public PluginConfigManage(String pluginXmlLocation) {
this.pluginXmlLocation = pluginXmlLocation;
WorkbenchWindow window = (WorkbenchWindow) PlatformUI.getWorkbench().getActiveWorkbenchWindow();
parentManager = window.getMenuBarManager();
}
/**
* 根据插件配置的数据,获取构造XPath的方法
* @param bean
* @return ;
*/
public String buildXpath(PluginConfigBean bean) {
String name = bean.getName();
String command = bean.getCommandLine();
String input = bean.getInput();
String output = bean.getOutput();
String outputPath = bean.getOutputPath();
String shortcutKey = bean.getShortcutKey();
String xpath = "/shortcuts/plugin[@command='" + command + "' and @input='" + input + "' and @output='" + output
+ "' and @outputpath='" + outputPath + "' and @shortcut-key='" + shortcutKey + "' and text()='" + name
+ "']";
return xpath;
}
/**
* 根据一个pluginConfigBean的实例,组合成添加到XML中的数据
* @param bean
* @return ;
*/
public String buildPluginData(PluginConfigBean bean) {
StringBuffer pluginData = new StringBuffer();
pluginData
.append(MessageFormat
.format("<plugin id=\"{0}\" command=\"{1}\" input=\"{2}\" output=\"{3}\" outputpath=\"{4}\" shortcut-key=\"{5}\">{6}</plugin>",
new Object[] { bean.getId(), bean.getCommandLine(), bean.getInput(), bean.getOutput(),
bean.getOutputPath(), bean.getShortcutKey(), bean.getName() }));
return pluginData.toString();
}
/**
* 从插件配置文件中获取插件配置的相关信息
* @return ;
*/
public List<PluginConfigBean> getPluginCofigData() {
System.out.println(pluginXmlLocation);
List<PluginConfigBean> dataList = new LinkedList<PluginConfigBean>();
File pluginXMl = new File(pluginXmlLocation);
if (!pluginXMl.exists()) {
return dataList;
}
VTDGen vg = new VTDGen();
vg.parseFile(pluginXmlLocation, true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
try {
ap.selectXPath("/shortcuts/plugin");
PluginConfigBean bean;
while (ap.evalXPath() != -1) {
String id = "";
String name = "";
String commandLine = "";
String output = "";
String input = "";
String shortcutKey = "";
String outputPath = "";
int index = -1;
if ((index = vn.getAttrVal("id")) != -1) {
id = vn.toString(index);
}
if ((index = vn.getText()) != -1) {
name = vn.toString(index);
}
if ((index = vn.getAttrVal("command")) != -1) {
commandLine = vn.toString(index);
}
if ((index = vn.getAttrVal("output")) != -1) {
output = vn.toString(index);
}
if ((index = vn.getAttrVal("input")) != -1) {
input = vn.toString(index);
}
if ((index = vn.getAttrVal("shortcut-key")) != -1) {
shortcutKey = vn.toString(index);
}
if ((index = vn.getAttrVal("outputpath")) != -1) {
outputPath = vn.toString(index);
}
bean = new PluginConfigBean(id, name, commandLine, input, output, outputPath, shortcutKey);
dataList.add(bean);
}
} catch (Exception e) {
LOGGER.error("", e);
}
return dataList;
}
public void addPluginMenu(final PluginConfigBean bean) {
for (int i = 0; i < parentManager.getItems().length; i++) {
if ("net.heartsome.cat.ts.ui.menu.plugin".equals(parentManager.getItems()[i].getId())) {
MenuManager pluginMenu = (MenuManager) parentManager.getItems()[i];
// 开始添加新的菜单
Action action = new Action() {
@Override
public void run() {
executePlugin(bean);
}
};
action.setText(bean.getName());
action.setId(bean.getId());
if (!"".equals(bean.getShortcutKey())) {
action.setText(bean.getName() + "\t" + bean.getShortcutKey());
}
pluginMenu.add(action);
pluginMenu.update();
}
}
}
/**
* 删除配置插件的菜单
* @param idList
* ;
*/
public void deletePluginMenu(String deleteId) {
for (int i = 0; i < parentManager.getItems().length; i++) {
if ("net.heartsome.cat.ts.ui.menu.plugin".equals(parentManager.getItems()[i].getId())) {
MenuManager pluginMenu = (MenuManager) parentManager.getItems()[i];
// 开始删除已经添加的菜单
for (int j = 0; j < pluginMenu.getItems().length; j++) {
String actionId = pluginMenu.getItems()[j].getId();
if (deleteId.equals(actionId)) {
pluginMenu.remove(actionId);
}
}
pluginMenu.update();
}
}
}
public void updataPluginMenu(PluginConfigBean bean) {
String id = bean.getId();
for (int i = 0; i < parentManager.getItems().length; i++) {
if ("net.heartsome.cat.ts.ui.menu.plugin".equals(parentManager.getItems()[i].getId())) {
MenuManager pluginMenu = (MenuManager) parentManager.getItems()[i];
// 开始删除已经添加的菜单
for (int j = 0; j < pluginMenu.getItems().length; j++) {
String actionId = pluginMenu.getItems()[j].getId();
if (id.equals(actionId)) {
pluginMenu.remove(id);
pluginMenu.update();
addPluginMenu(bean);
}
}
}
}
}
/**
* 运行自定义的插件
* @param bean
* ;
*/
@SuppressWarnings("unchecked")
public void executePlugin(PluginConfigBean bean) {
String commandLine = bean.getCommandLine();
if (commandLine == null || "".equals(commandLine)) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg1"));
return;
}
try {
// 当输出(进程)为当前文档时
if (bean.getOutput().equals(PluginConstants.SEGMENT)) {
// 先检查是否有已经打开的文件,若没有,退出插件执行
XLIFFEditorImplWithNatTable nattable = XLIFFEditorImplWithNatTable.getCurrent();
if (nattable == null) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg2"));
return;
}
XLFHandler handler = nattable.getXLFHandler();
List<String> selectRowIds = nattable.getSelectedRowIds();
if (selectRowIds.size() <= 0) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg3"));
return;
}
if (selectRowIds.size() > 1) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg4"));
}
String rowId = selectRowIds.get(0);
sendSegment(bean, handler, rowId);
// 执行后返回的文件
String returnContent = runPlugin(bean);
// 如果返回为交换文件,则更新当前文本段
if (bean.getInput().equals(PluginConstants.EXCHANGEFILE)) {
handler.updateAndSave(rowId, "", returnContent);
// 更新完后,要刷新界面。此处未做,滞留。
}
}
// 当输出(进程)为当前文档时
if (bean.getOutput().equals(PluginConstants.DOCUMENT)) {
XLFHandler handler;
IFile selectIFile = null;
// 先检查是否有已经打开的文件,若没有,退出插件执行
XLIFFEditorImplWithNatTable nattable = XLIFFEditorImplWithNatTable.getCurrent();
if (nattable == null) {
// 如果当前没有打开的文件,那么获取左边导航框中选中的文件
ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService()
.getSelection();
if (selection == null || selection.isEmpty() || !(selection instanceof StructuredSelection)) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg5"));
return;
}
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Iterator<Object> selectIt = structuredSelection.iterator();
if (selectIt.hasNext()) {
Object object = selectIt.next();
if (object instanceof IFile) {
selectIFile = (IFile) object;
String fileExtension = selectIFile.getFileExtension();
if (!CommonFunction.validXlfExtension(fileExtension)) {
MessageDialog.openInformation(shell,
Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg5"));
return;
}
}
}
handler = new XLFHandler();
// 打开该xliff文件
Map<String, Object> resultMap = handler.openFile(selectIFile.getLocation().toOSString());
if (resultMap == null
|| Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap
.get(Constant.RETURNVALUE_RESULT)) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg5"));
return;
}
} else {
handler = nattable.getXLFHandler();
selectIFile = ResourceUtil.getFile(nattable.getEditorInput());
// IEditorInput fileInput = nattable.getEditorInput();
}
sendDocument(bean, selectIFile);
if (bean.getInput().equals(PluginConstants.DOCUMENT)) {
// 重新解析该文件
Map<String, Object> resultMap = handler.openFile(selectIFile.getLocation().toOSString());
if (resultMap == null
|| Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap
.get(Constant.RETURNVALUE_RESULT)) {
MessageDialog.openError(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg6"));
return;
}
}
}
// 当输出(进程)为空时
if (bean.getOutput().equals(PluginConstants.NONE)) {
runPlugin(bean);
}
} catch (Exception e) {
LOGGER.error("", e);
MessageDialog.openError(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg7"));
}
}
/**
* 将当前值传送到目标文件或者插件(针对进程为segment的,因此一定要有交换文件)
* @param bean
* ;
*/
public void sendSegment(PluginConfigBean bean, XLFHandler handler, String selectedRowId) {
// 如果交换文件并没有设置 ,则退出程序
String outputPath = bean.getOutputPath();
if (outputPath == null || outputPath.equals("")) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg8"));
return;
}
// 备注:在发送内容之前,没有进行对当前文本段的保存,这是一个滞留问题
// 获取选中的trans-unit节点的完整内容
String transUnitStr = handler.getTUFragByRowId(selectedRowId);
FileOutputStream output;
try {
output = new FileOutputStream(outputPath);
output.write(transUnitStr.getBytes("UTF-8"));
output.close();
} catch (Exception e) {
LOGGER.error("", e);
}
}
public void sendDocument(PluginConfigBean bean, IFile curXliff) {
String curXliffLocation = curXliff.getLocation().toOSString();
File f = new File(curXliffLocation);
if (!f.exists()) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
MessageFormat.format(Messages.getString("plugin.PluginConfigManage.msg9"), curXliff.getFullPath()
.toOSString()));
return;
}
String commandLine = bean.getCommandLine();
String[] cmdArray = { commandLine, curXliffLocation };
try {
Process pluginProcess = Runtime.getRuntime().exec(cmdArray);
if (bean.getInput().equals(PluginConstants.EXCHANGEFILE)) {
pluginProcess.waitFor();
}
} catch (Exception e) {
LOGGER.error("", e);
}
}
/**
* 开始执行程序
* @param bean
* @return
* @throws Exception
* ;
*/
public String runPlugin(PluginConfigBean bean) throws Exception {
String commandLine = bean.getCommandLine();
if (commandLine == null || "".equals(commandLine)) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg1"));
return null;
}
String output = bean.getOutput();
String input = bean.getInput();
if (output.equals(PluginConstants.NONE)) {
Runtime.getRuntime().exec(commandLine);
return null;
} else if (output.equals(PluginConstants.SEGMENT)) {
String fileName = bean.getOutputPath();
if (fileName == null || fileName.equals("")) {
MessageDialog.openInformation(shell, Messages.getString("plugin.PluginConfigManage.msgTitle"),
Messages.getString("plugin.PluginConfigManage.msg8"));
return null;
}
String[] cmdArray = { commandLine, fileName };
Process pluginProcess = Runtime.getRuntime().exec(cmdArray);
if (input.equals(PluginConstants.EXCHANGEFILE)) {
pluginProcess.waitFor();
InputStreamReader inReader = new InputStreamReader(new FileInputStream(fileName));
BufferedReader b = new BufferedReader(inReader);
StringBuffer responseSB = new StringBuffer();
String line;
while ((line = b.readLine()) != null) {
responseSB.append(line + "\n");
}
inReader.close();
b.close();
return responseSB.toString();
}
}
return "";
}
}
| 15,510 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AboutComposite.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/AboutComposite.java | package net.heartsome.cat.ts.ui.plugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
/**
* 关于面板(第一行为标题,第二行为 Logo,第三行为版本信息,第四行为版权信息,第五行为网址信息)
* @author peason
* @version
* @since JDK1.6
*/
public final class AboutComposite {
/** 父面板 */
private Composite parent;
/** 第一行标题 */
private String name;
/** Logo 图片路径 */
private String imagePath;
/** 版本信息 */
private String version;
private Cursor cursorHand = new Cursor(Display.getDefault(), SWT.CURSOR_HAND);
/**
* 构造方法
* @param parent
* 父面板
* @param style
* 样式
* @param name
* 第一行标题
* @param imagePath
* Logo 图片路径
* @param version
* 版本信息
*/
public AboutComposite(Composite parent, int style, String name, String imagePath, String version) {
this.parent = parent;
this.name = name;
this.imagePath = imagePath;
this.version = version;
init();
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
if(cursorHand != null && !cursorHand.isDisposed()){
cursorHand.dispose();
}
}
});
}
/**
* 初始化界面
* ;
*/
private void init() {
Color white = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
parent.setBackground(white);
GridData data = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
Label lblName = new Label(parent, SWT.CENTER);
lblName.setText(name);
lblName.setLayoutData(data);
lblName.setBackground(white);
Image image = new Image(Display.getDefault(), imagePath);
Label lblImage = new Label(parent, SWT.CENTER);
lblImage.setImage(image);
lblImage.setLayoutData(new GridData(GridData.FILL_BOTH));
lblImage.setBackground(white);
Label lblVersion = new Label(parent, SWT.CENTER);
lblVersion.setText(version);
lblVersion.setLayoutData(data);
lblVersion.setBackground(white);
new Label(parent, SWT.None).setForeground(white);
Label lblCopyRight = new Label(parent, SWT.CENTER);
lblCopyRight.setText(PluginConstants.PLUGIN_COPY_RIGHT);
lblCopyRight.setLayoutData(data);
lblCopyRight.setBackground(white);
Label lblWebSite = new Label(parent, SWT.CENTER);
lblWebSite.setText(PluginConstants.PLUGIN_WEB_SITE);
lblWebSite.setLayoutData(data);
lblWebSite.setBackground(white);
lblWebSite.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
lblWebSite.setCursor(cursorHand);
lblWebSite.addMouseListener(new MouseListener() {
public void mouseUp(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
Program.launch(PluginConstants.PLUGIN_WEB_SITE);
}
public void mouseDoubleClick(MouseEvent e) {
}
});
}
}
| 3,278 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginConstants.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/PluginConstants.java | package net.heartsome.cat.ts.ui.plugin;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
/**
* 常量类
* @author peason
* @version
* @since JDK1.6
*/
public interface PluginConstants {
/** 版权信息 */
String PLUGIN_COPY_RIGHT = Messages.getString("plugin.PluginConstants.right");
/** 网址信息 */
String PLUGIN_WEB_SITE = "http://www.heartsome.net";
/** XSL Transformation 的 Logo 路径 */
String LOGO_XSL_PATH = "icons/XSLConverter.png";
/** XSL Transformation 菜单项显示的图片路径 */
String LOGO_XSL_MENU_PATH = "icons/XSLMenu.png";
/** TBXMaker 的 Logo 路径 */
String LOGO_TBXMAKER_PATH = "icons/CSV2TBXConverter.png";
/** TBXMaker 菜单项显示的图片路径 */
String LOGO_TBXMAKER_MENU_PATH = "icons/CSV2TBXMenu.png";
/** TBXMaker 对话框中打开 CSV 文件的工具栏图片路径 */
String PIC_OPEN_CSV_PATH = "icons/open.png";
/** TBXMaker 对话框中保存为 TBX 文件的工具栏图片路径 */
String PIC_EXPORT_TBX_PATH = "icons/save.png";
/** TBXMaker 对话框中删除列的工具栏图片路径 */
String PIC_DELETE_COLUMN_PATH = "icons/remove.png";
/** TBXMaker 对话框中选择列属性的工具栏图片路径 */
String PIC_SET_COLUMN_PATH = "icons/sellang.png";
/** TBXMaker 对话框中帮助内容的工具栏图片路径 */
String PIC_HELP_PATH = "icons/help.png";
/** 插件配置相关信息所存放的文件相对工作空间的路径--robert */
String PC_pluginConfigLocation = ".metadata/.preference/pluginConfig.xml";
/** CSV 2 TMX Converter 的 Logo 路径 */
String LOGO_CSV2TMX_PATH = "icons/CSV2TMXConverter.png";
/** CSV 2 TMX Converter 菜单项的 Logo 路径 */
String LOGO_CSV2TMX_MENU_PATH = "icons/CSV2TMXMenu.png";
/** CSV 2 TMX Converter 的版本 */
public static final String CSV2TMX_VERSION = "1.1.0";
/** 插件配置中,输入或输出的值(对应返回与进程):当前文档 --robert */
String DOCUMENT = "document";
/** 插件配置中,输入或输出的值(对应返回与进程):当前文本 --robert */
String SEGMENT = "seg";
/** 插件配置中,输入或输出的值(对应返回与进程):已经转换文件 --robert */
String EXCHANGEFILE = "file";
/** 插件配置中,输入或输出的值(对应返回与进程):空 --robert */
String NONE = "none";
/** MARTIF 2 TBX Converter 的 Logo 路径 */
String LOGO_MARTIF2TBX_PATH = "icons/MARTIF2TBXConverter.png";
/** MARTIF 2 TBX Converter 菜单项显示的图片路径 */
String LOGO_MARTIF2TBX_MENU_PATH = "icons/MARTIF2TBXMenu.png";
/** java properties viewer 的 Logo 路径 */
String LOGO_PROERTIESVIEWER_PATH = "icons/JPropViewer.png";
/** java properties viewer 菜单项显示的图片路径 */
String LOGO_PROERTIESVIEWER_MENU_PATH = "icons/JPropViewerMenu.png";
/** RTFCleaner 的 Logo 路径 */
String LOGO_RTFCLEANER_PATH = "icons/RTFCleaner.png";
/** RTFCleaner 菜单项显示的图片路径 */
String LOGO_RTFCLEANER_MENU_PATH = "icons/RTFCleanerMenu.png";
/** tmx to txt converter 的 Logo 路径 */
String LOGO_TMX2TXTCONVERTER_PATH = "icons/TMX2TXTConverter.png";
/** tmx to txt converter 菜单项显示的图片路径 */
String LOGO_TMX2TXTCONVERTER_MENU_PATH = "icons/TMX2TXTConverterMenu.png";
/** TMX Validator 的 Logo 路径 */
String LOGO_TMXVALIDATOR_PATH = "icons/TMXValidator.png";
/** TMX Validator 菜单项显示的图片路径 */
String LOGO_TMXVALIDATOR_MENU_PATH = "icons/TMXValidatorMenu.png";
/** TBXMaker 对话框中清理无效字符 工具栏图片路径 */
String PIC_clearChar_PATH = "icons/chars.png";
/** 以下为帮助中的图片路径 */
String HELP_TOC_CLOSED = "icons/help/Normal/tocclosed.png";
String HELP_TOC_OPEN = "icons/help/Normal/tocopen.png";
String HELP_BOOK_CLOSED = "icons/help/Normal/bookclosed.png";
String HELP_BOOK_OPEN = "icons/help/Normal/bookopen.png";
String HELP_OPEN_FILE = "icons/help/Normal/open.png";
String HELP_BACK = "icons/help/Normal/back.png";
String HELP_FORWARD = "icons/help/Normal/forward.png";
String HELP_FIND = "icons/help/Normal/find.png";
String HELP_TOPIC = "icons/help/Normal/topic.png";
String HELP_SPLASH = "icons/help/Splash/about.png";
}
| 4,265 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TMXValidator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/TMXValidator.java | package net.heartsome.cat.ts.ui.plugin;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.core.Utils;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.Assert;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* TMX文件验证
* @author robert 2012-03-14
* @version
* @since JDK1.6
*/
public class TMXValidator {
private static final Logger LOGGER = LoggerFactory.getLogger(TMXValidator.class);
private Map<String, VTDNav> vnMap = new HashMap<String, VTDNav>();
private Color red;
/** 当前处理TMX文件的版本号 */
private String version;
private Hashtable<String, String> languages;
private Hashtable<String, String> countries;
private Hashtable<String, String> tuids;
private int balance;
private Hashtable<String, String> ids;
public TMXValidator(String tmxLocation, Shell shell) {
red = Display.getDefault().getSystemColor(SWT.COLOR_RED);
}
public void validate(String tmxLocation, StyledText styledText) {
try {
if (!parseXML(tmxLocation)) {
String parseErrorTip = MessageFormat.format(Messages.getString("plugin.TMXValidator.msg1"), tmxLocation);
styledText.append(parseErrorTip);
StyleRange range = new StyleRange(0, parseErrorTip.length(), red, null);
styledText.setStyleRange(range);
return;
}
styledText.append(Messages.getString("plugin.TMXValidator.msg2") + tmxLocation + "\n");
if (!validTmxRoot(tmxLocation)) {
String validErrorTipe = Messages.getString("plugin.TMXValidator.msg3");
StyleRange range = new StyleRange(styledText.getText().length(), validErrorTipe.length(), red, null);
styledText.append(validErrorTipe);
styledText.setStyleRange(range);
return;
}
version = getAttribute(tmxLocation, "/tmx/@version", "");
// 备注: --robert undone 此处有关于文档类型的验证
// 创建临时文件
File tmpFile = createTmpFile(tmxLocation);
String tempLocation = tmpFile.getAbsolutePath();
styledText.append(Messages.getString("plugin.TMXValidator.msg4"));
if (!parseXML(tempLocation)) {
String parseErrorTip = MessageFormat.format(Messages.getString("plugin.TMXValidator.msg5"), tempLocation);
StyleRange range = new StyleRange(styledText.getText().length(), parseErrorTip.length(), red, null);
styledText.append(parseErrorTip);
styledText.setStyleRange(range);
return;
}
styledText.append(Messages.getString("plugin.TMXValidator.msg6"));
//加载语言与国家
languages = TextUtil.plugin_loadLanguages();
countries = TextUtil.plugin_loadCoutries();
//判断源语言
String srcLanguage = getAttribute(tmxLocation, "/tmx/header/@srclang", null);
if (srcLanguage == null) {
throw new Exception(Messages.getString("plugin.TMXValidator.msg7"));
}
if (!"*all*".equals(srcLanguage) && !checkLang(srcLanguage)) {
throw new Exception(MessageFormat.format(Messages.getString("plugin.TMXValidator.msg8"), srcLanguage));
}
styledText.append(MessageFormat.format(Messages.getString("plugin.TMXValidator.msg9"), srcLanguage));
if (!srcLanguage.equals("*all*")) { //$NON-NLS-1$
validSrcLanguage(tmxLocation, srcLanguage);
}
tuids = new Hashtable<String, String>();
recurse(tmxLocation);
styledText.append("==================\n");
styledText.append(Messages.getString("plugin.TMXValidator.msg10"));
styledText.append("==================\n");
} catch (Exception e) {
LOGGER.error("", e);
e.printStackTrace();
String errorTip = e.getMessage();
StyleRange range = new StyleRange(styledText.getText().length(), errorTip.length(), red, null);
styledText.append(errorTip);
styledText.setStyleRange(range);
}
}
/**
* 解析TMX文件 ;
*/
private boolean parseXML(String xmlLocation){
VTDGen vg = new VTDGen();
boolean result = vg.parseFile(xmlLocation, true);
if (result) {
VTDNav vtdNav = vg.getNav();
vnMap.put(xmlLocation, vtdNav);
}
return result;
}
/**
* 通过验证指定文件的头元素是否是TMX,来验证该文件是不是一个TMX文件
* @return
* @throws Exception ;
*/
private boolean validTmxRoot(String tmxLocation) throws Exception{
VTDNav vn = vnMap.get(tmxLocation);
AutoPilot ap = new AutoPilot(vn);
Assert.isNotNull(vn, MessageFormat.format(Messages.getString("plugin.TMXValidator.msg11"), tmxLocation));
ap.selectXPath("/tmx");
if (ap.evalXPath() != -1) {
return true;
}
return false;
}
/**
* 获取属性值
* @param xpath
* @param defaultValue
* @return
* @throws Exception ;
*/
private String getAttribute(String tmxLocation, String xpath, String defaultValue) throws Exception {
VTDNav vn = vnMap.get(tmxLocation);
vn.push();
AutoPilot ap = new AutoPilot(vn);
Assert.isNotNull(vn, MessageFormat.format(Messages.getString("plugin.TMXValidator.msg11"), tmxLocation));
ap.selectXPath(xpath);
int index;
if ((index = ap.evalXPath()) != -1) {
return vn.toString(index + 1);
}
vn.pop();
return defaultValue;
}
/**
* 获取属性值
* @param xpath
* @param defaultValue
* @return
* @throws Exception ;
*/
private String getAttribute(VTDNav vn, String attriName, String defaultValue) throws Exception {
vn.push();
int index;
if ((index = vn.getAttrVal(attriName)) != -1) {
return vn.toString(index);
}
vn.pop();
return defaultValue;
}
/**
* 创建一个用于编辑的临时TMX文件
*/
public File createTmpFile(String tmxLocation) throws Exception {
File tmpFile = null;
File folder = null;
File curFolder = new File(".");
if (Utils.OS_WINDOWS == Utils.getCurrentOS()) {
folder = new File(curFolder.getAbsoluteFile() + Utils.getFileSeparator() + "~$temp");
if (!folder.exists()) {
folder.mkdirs();
}
folder.deleteOnExit();
String sets = "attrib +H \"" + folder.getAbsolutePath() + "\"";
// 运行命令串
Runtime.getRuntime().exec(sets);
} else {
folder = new File(curFolder.getAbsoluteFile() + Utils.getFileSeparator() + ".temp");
if (!folder.exists()) {
folder.mkdirs();
}
folder.deleteOnExit();
}
tmpFile = File.createTempFile("tmp", ".TMX", folder);
tmpFile.deleteOnExit();
VTDNav vn = vnMap.get(tmxLocation);
Assert.isNotNull(vn, MessageFormat.format(Messages.getString("plugin.TMXValidator.msg11"), tmxLocation));
XMLModifier xm = new XMLModifier(vn);
save(xm, tmpFile);
return tmpFile;
}
/**
* 循环每一个tu节点,进一步判断源语言
* @param tmxLocation
*/
private void validSrcLanguage(String tmxLocation, String srcLanguage) throws Exception {
VTDNav vn = vnMap.get(tmxLocation);
Assert.isNotNull(vn, MessageFormat.format(Messages.getString("plugin.TMXValidator.msg11"), tmxLocation));
AutoPilot ap = new AutoPilot(vn);
AutoPilot tuvAp = new AutoPilot(vn);
ap.selectXPath("/tmx/body/tu");
int index;
while (ap.evalXPath() != -1) {
boolean found = false;
vn.push();
tuvAp.selectXPath("./tuv");
while(tuvAp.evalXPath() != -1){
String lang = "";
if ((index = vn.getAttrVal("xml:lang")) != -1) {
lang = vn.toString(index);
}
if ("".equals(lang)) {
if (version.equals("1.1") || version.equals("1.2")) {
if ((index = vn.getAttrVal("lang")) != -1) { //$NON-NLS-1$
lang = vn.toString(index);
}
} else {
throw new Exception(Messages.getString("plugin.TMXValidator.msg12"));
}
}
if (lang.equals("")) {
throw new Exception(Messages.getString("plugin.TMXValidator.msg12"));
}
if (lang.equals(srcLanguage)) {
found = true;
}
}
if (!found) {
throw new Exception(MessageFormat.format(Messages.getString("plugin.TMXValidator.msg13"), srcLanguage));
}
vn.pop();
}
}
/**
* 验证所有节点的属性与seg节点的内容
* @param tmxLocation
* @throws Exception ;
*/
private void recurse(String tmxLocation) throws Exception {
VTDNav vn = vnMap.get(tmxLocation);
Assert.isNotNull(vn, MessageFormat.format(Messages.getString("plugin.TMXValidator.msg11"), tmxLocation));
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/tmx//*");
VTDUtils vu = new VTDUtils(vn);
Map<String, String> attributesMap;
// 先验证所有的属性值
while (ap.evalXPath() != -1) {
attributesMap = getAllAttributes(vn);
checkAttribute(attributesMap, vu);
}
// 再验证seg节点下的内容
ap.resetXPath();
ap.selectXPath("/tmx/body/tu/tuv/seg");
while (ap.evalXPath() != -1) {
balance = 0;
ids = null;
ids = new Hashtable<String, String>();
String segFrag = vu.getElementFragment();
vn.push();
AutoPilot segChildAP = new AutoPilot(vn);
segChildAP.selectXPath("./*");
while (segChildAP.evalXPath() != -1) {
String nodeName = vu.getCurrentElementName();
System.out.println("nodeName = " + nodeName);
if ("bpt".equals(nodeName)) { //$NON-NLS-1$
balance += 1;
if (version.equals("1.4")) { //$NON-NLS-1$
String s = getAttribute(vn, "i", ""); //$NON-NLS-1$
if (!ids.containsKey(s)) {
ids.put(s, "1");
} else {
if (ids.get(s).equals("-1")) {
ids.put(s, "0");
} else {
throw new Exception(Messages.getString("plugin.TMXValidator.msg14") + "\n" + segFrag + "\n");
}
}
}
}
if ("ept".equals(nodeName)) { //$NON-NLS-1$
balance -= 1;
if (version.equals("1.4")) { //$NON-NLS-1$
String s = getAttribute(vn, "i", ""); //$NON-NLS-1$
if (!ids.containsKey(s)) {
ids.put(s, "-1");
} else {
if (ids.get(s).equals("1")) {
ids.put(s, "0");
} else {
throw new Exception(Messages.getString("plugin.TMXValidator.msg15") + "\n" + segFrag + "\n");
}
}
}
}
}
vn.pop();
if (balance != 0) {
throw new Exception(Messages.getString("plugin.TMXValidator.msg16") + "\n" + vu.getElementFragment() + "\n");
}
if (ids.size() > 0) {
@SuppressWarnings("rawtypes")
Enumeration en = ids.keys();
while (en.hasMoreElements()) {
if (!ids.get(en.nextElement()).equals("0")) { //$NON-NLS-1$
throw new Exception(Messages.getString("plugin.TMXValidator.msg17") + "\n" + vu.getElementFragment()
+ "\n");
}
}
}
}
}
private void checkAttribute(Map<String, String> attributesMap, VTDUtils vu) throws Exception{
Iterator<Entry<String, String>> it = attributesMap.entrySet().iterator();
while(it.hasNext()){
Entry<String, String> entry = it.next();
String name = entry.getKey();
String value = entry.getValue();
if (name.equals("lang") || name.equals("adminlang") || name.equals("xml:lang")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (!checkLang(value)) {
throw new Exception(MessageFormat.format(Messages.getString("plugin.TMXValidator.msg18"), value) + "\n" + vu.getElementFragment() + "\n");
}
}
if ( name.equals("lastusagedate") || name.equals("changedate") || name.equals("creationdate")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (!checkDate(value)) {
throw new Exception(MessageFormat.format(Messages.getString("plugin.TMXValidator.msg19"), value) + "\n" + vu.getElementFragment() + "\n");
}
}
if (name.equals("tuid")) { //$NON-NLS-1$
if (!tuids.containsKey(value)) {
tuids.put(value, "");
} else {
throw new Exception(MessageFormat.format(Messages.getString("plugin.TMXValidator.msg20"), value) + "\n" + vu.getElementFragment() + "\n");
}
}
}
}
/**
* 获取所有属性
* @param vn
* @return
* @throws Exception ;
*/
private Map<String, String> getAllAttributes(VTDNav vn) throws Exception {
vn.push();
AutoPilot apAttributes = new AutoPilot(vn);
Map<String, String> attributes = new HashMap<String, String>();
apAttributes.selectXPath("./@*");
int inx = -1;
while ((inx = apAttributes.evalXPath()) != -1) {
String name = vn.toString(inx);
inx = vn.getAttrVal(name);
String value = inx != -1 ? vn.toString(inx) : "";
attributes.put(name, value);
}
vn.pop();
return attributes;
}
private boolean save(XMLModifier xm, File file) {
try {
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
return true;
} catch (Exception e) {
LOGGER.error("", e);
}
return false;
}
private boolean checkDate(String date) {
// YYYYMMDDThhmmssZ
if (date.length() != 16) {
return false;
}
if (date.charAt(8) != 'T') {
return false;
}
if (date.charAt(15) != 'Z') {
return false;
}
try {
int year = Integer.parseInt("" + date.charAt(0) + date.charAt(1) + date.charAt(2) + date.charAt(3)); //$NON-NLS-1$
if (year < 0) {
return false;
}
int month = Integer.parseInt("" + date.charAt(4) + date.charAt(5)); //$NON-NLS-1$
if (month < 1 || month > 12) {
return false;
}
int day = Integer.parseInt("" + date.charAt(6) + date.charAt(7)); //$NON-NLS-1$
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day < 1 || day > 31) {
return false;
}
break;
case 4:
case 6:
case 9:
case 11:
if (day < 1 || day > 30) {
return false;
}
break;
case 2:
// check for leap years
if (year % 4 == 0) {
if (year % 100 == 0) {
// not all centuries are leap years
if (year % 400 == 0) {
if (day < 1 || day > 29) {
return false;
}
} else {
// not leap year
if (day < 1 || day > 28) {
return false;
}
}
}
if (day < 1 || day > 29) {
return false;
}
} else if (day < 1 || day > 28) {
return false;
}
}
int hour = Integer.parseInt("" + date.charAt(9) + date.charAt(10)); //$NON-NLS-1$
if (hour < 0 || hour > 23) {
return false;
}
int min = Integer.parseInt("" + date.charAt(11) + date.charAt(12)); //$NON-NLS-1$
if (min < 0 || min > 59) {
return false;
}
int sec = Integer.parseInt("" + date.charAt(13) + date.charAt(14)); //$NON-NLS-1$
if (sec < 0 || sec > 59) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
private boolean checkLang(String lang) {
if (lang.startsWith("x-") || lang.startsWith("X-")) { //$NON-NLS-1$ //$NON-NLS-2$
return true;
}
// Accepted formats are:
// xx: ISO 639-1
// xxx: ISO 639-2
// xx-YY: ISO-639-1 + ISO3166-1
// xxx-YY: ISO-639-2 + ISO3166-1
int len = lang.length();
if (len != 2 && len != 3 && len != 5 && len != 6) {
return false;
}
if (!isAlpha(lang.charAt(0)) || !isAlpha(lang.charAt(1))) {
return false;
}
if (len == 5 && lang.charAt(2) != '-') {
return false;
}
if (len == 5 && (!isAlpha(lang.charAt(3)) || !isAlpha(lang.charAt(4)))) {
return false;
}
if (len == 6 && lang.charAt(3) != '-') {
return false;
}
if (len == 6 && (!isAlpha(lang.charAt(2)) || !isAlpha(lang.charAt(4)) || !isAlpha(lang.charAt(5)))) {
return false;
}
String[] parts = lang.split("-"); //$NON-NLS-1$
if (!languages.containsKey(parts[0].toLowerCase())) {
return false;
}
if (parts.length == 2) {
if (!countries.containsKey(parts[1].toUpperCase())) {
return false;
}
}
return true;
}
private boolean isAlpha(char c) {
return (c>='a' && c<='z') || (c>='A' && c<='Z');
}
}
| 16,183 | 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.plugin/src/net/heartsome/cat/ts/ui/plugin/TableViewerLabelProvider.java | package net.heartsome.cat.ts.ui.plugin;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
/**
* TableViewer的标签提供者
* @author robert 2012-03-10
* @version
* @since JDK1.6
*/
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;
}
}
| 654 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginConfigBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/bean/PluginConfigBean.java | package net.heartsome.cat.ts.ui.plugin.bean;
/**
* 插件配置的bean
* @author robert 2012-03-03
* @version
* @since JDK1.6
*/
public class PluginConfigBean {
/** 插件的ID */
private String id;
/** 插件的名称 */
private String name;
/** 插件的命令行 */
private String commandLine;
/** 输出 */
private String output;
/** 输入 */
private String input;
/** 快捷键 */
private String shortcutKey;
/** 交换文件 */
private String outputPath;
public PluginConfigBean() {
}
public PluginConfigBean(String id, String name, String commandLine, String input, String output, String outputPath, String shortcutKey){
this.id = id;
this.name = name;
this.commandLine = commandLine;
this.output = output;
this.input = input;
this.shortcutKey = shortcutKey;
this.outputPath = outputPath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCommandLine() {
return commandLine;
}
public void setCommandLine(String commandLine) {
this.commandLine = commandLine;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getShortcutKey() {
return shortcutKey;
}
public void setShortcutKey(String shortcutKey) {
this.shortcutKey = shortcutKey;
}
public String getOutputPath() {
return outputPath;
}
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PluginConfigBean) {
PluginConfigBean bean = (PluginConfigBean) obj;
if (bean.getName().equals(this.name) && bean.getCommandLine().equals(this.commandLine)
&& bean.getInput().equals(this.input) && bean.getOutput().equals(this.output)
&& bean.getOutputPath().equals(this.outputPath) && bean.getShortcutKey().equals(this.shortcutKey)) {
return true;
}
}
return false;
}
}
| 2,183 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Martif2TBXConverterDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/Martif2TBXConverterDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.Martif2Tbx;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
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.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
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.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MARTIF to TBX Converter 对话框
* @author peason
* @version
* @since JDK1.6
*/
public class Martif2TBXConverterDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);
/** Logo 图片路径 */
private String imagePath;
/** Martif 路径文本框 */
private Text txtMartif;
/** Martif 文件选择按钮 */
private Button btnMartifBrowse;
/** TBX 路径文本框 */
private Text txtTBX;
/** TBX 文件选择按钮 */
private Button btnTBXBrowse;
/**
* 构造方法
* @param parentShell
*/
public Martif2TBXConverterDialog(Shell parentShell) {
super(parentShell);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.Martif2TBXConverterDialog.title"));
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_MARTIF2TBX_PATH);
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout(3, false));
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(400, 160).grab(true, true).applyTo(tparent);
createMenu();
PluginUtil.createLabel(tparent, Messages.getString("dialog.Martif2TBXConverterDialog.txtMartif"));
txtMartif = new Text(tparent, SWT.BORDER);
txtMartif.setEditable(false);
txtMartif.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnMartifBrowse = new Button(tparent, SWT.None);
btnMartifBrowse.setText(Messages.getString("dialog.Martif2TBXConverterDialog.btnMartifBrowse"));
PluginUtil.createLabel(tparent, Messages.getString("dialog.Martif2TBXConverterDialog.txtTBX"));
txtTBX = new Text(tparent, SWT.BORDER);
txtTBX.setEditable(false);
txtTBX.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnTBXBrowse = new Button(tparent, SWT.None);
btnTBXBrowse.setText(Messages.getString("dialog.Martif2TBXConverterDialog.btnTBXBrowse"));
initListener();
tparent.layout();
getShell().layout();
return tparent;
}
/**
* 创建菜单 ;
*/
private void createMenu() {
Menu menu = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menu);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Menu fileMenu = new Menu(menu);
MenuItem fileItem = new MenuItem(menu, SWT.CASCADE);
fileItem.setText(Messages.getString("dialog.Martif2TBXConverterDialog.fileMenu"));
fileItem.setMenu(fileMenu);
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText(Messages.getString("dialog.Martif2TBXConverterDialog.exitItem"));
exitItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
close();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Menu helpMenu = new Menu(menu);
MenuItem helpItem = new MenuItem(menu, SWT.CASCADE);
helpItem.setText(Messages.getString("dialog.Martif2TBXConverterDialog.helpMenu"));
helpItem.setMenu(helpMenu);
MenuItem aboutItem = new MenuItem(helpMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.Martif2TBXConverterDialog.aboutItem"));
String imgPath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_MARTIF2TBX_MENU_PATH);
aboutItem.setImage(new Image(Display.getDefault(), imgPath));
aboutItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
AboutDialog dialog = new AboutDialog(getShell(), Messages
.getString("dialog.Martif2TBXConverterDialog.dialogName"), imagePath, Messages
.getString("dialog.Martif2TBXConverterDialog.dialogVersion"));
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
private void initListener() {
btnMartifBrowse.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
dialog.setText(Messages.getString("dialog.Martif2TBXConverterDialog.dialogTitle1"));
String extensions[] = { "*.mtf", "*" }; //$NON-NLS-1$ //$NON-NLS-2$
String names[] = {
Messages.getString("dialog.Martif2TBXConverterDialog.names1"), Messages.getString("dialog.Martif2TBXConverterDialog.names2") }; //$NON-NLS-1$ //$NON-NLS-2$
dialog.setFilterNames(names);
dialog.setFilterExtensions(extensions);
String fileSep = System.getProperty("file.separator");
if (txtMartif.getText() != null && !txtMartif.getText().trim().equals("")) {
dialog.setFilterPath(txtMartif.getText().substring(0, txtMartif.getText().lastIndexOf(fileSep)));
dialog.setFileName(txtMartif.getText().substring(txtMartif.getText().lastIndexOf(fileSep) + 1));
} else {
dialog.setFilterPath(System.getProperty("user.home"));
}
String filePath = dialog.open();
if (filePath != null) {
txtMartif.setText(filePath);
txtTBX.setText(filePath + ".tbx");
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
btnTBXBrowse.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
dialog.setText(Messages.getString("dialog.Martif2TBXConverterDialog.dialogTitle2"));
String extensions[] = { "*.tbx", "*" }; //$NON-NLS-1$ //$NON-NLS-2$
String names[] = {
Messages.getString("dialog.Martif2TBXConverterDialog.filters1"), Messages.getString("dialog.Martif2TBXConverterDialog.filters2") }; //$NON-NLS-1$ //$NON-NLS-2$
dialog.setFilterNames(names);
dialog.setFilterExtensions(extensions);
String fileSep = System.getProperty("file.separator");
if (txtTBX.getText() != null && !txtTBX.getText().trim().equals("")) {
dialog.setFilterPath(txtTBX.getText().substring(0, txtTBX.getText().lastIndexOf(fileSep)));
dialog.setFileName(txtTBX.getText().substring(txtTBX.getText().lastIndexOf(fileSep) + 1));
} else {
dialog.setFilterPath(System.getProperty("user.home"));
}
String filePath = dialog.open();
if (filePath != null) {
txtTBX.setText(filePath);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.OK_ID).setText(Messages.getString("dialog.Martif2TBXConverterDialog.ok"));
getButton(IDialogConstants.CANCEL_ID).setText(Messages.getString("dialog.Martif2TBXConverterDialog.cancel"));
getDialogArea().getParent().layout();
getShell().layout();
}
@Override
protected void okPressed() {
String martifPath = txtMartif.getText();
if (martifPath == null || martifPath.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.Martif2TBXConverterDialog.msgTitle"),
Messages.getString("dialog.Martif2TBXConverterDialog.msg1"));
return;
}
String tbxPath = txtTBX.getText();
if (tbxPath == null || tbxPath.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.Martif2TBXConverterDialog.msgTitle"),
Messages.getString("dialog.Martif2TBXConverterDialog.msg2"));
return;
}
Martif2Tbx converter = new Martif2Tbx();
try {
converter.convertFile(martifPath, tbxPath);
MessageDialog.openInformation(getShell(), Messages.getString("dialog.Martif2TBXConverterDialog.msgTitle"),
Messages.getString("dialog.Martif2TBXConverterDialog.msg3"));
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
MessageDialog.openInformation(getShell(), Messages.getString("dialog.Martif2TBXConverterDialog.msgTitle"),
e.getMessage());
return;
}
}
}
| 9,122 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ColumnTypeDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/ColumnTypeDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.ts.ui.plugin.ColProperties;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.TBXTemplateUtil;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* TBXMaker -> 列属性对话框
* @author peason
* @version
* @since JDK1.6
*/
public class ColumnTypeDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);
/** 列数 */
private int size;
/** ColProperties 集合 */
private Vector<ColProperties> colTypes;
/** Logo 图片路径 */
private String imgPath;
/** 语言下拉框集合 */
private Combo[] arrCmbLangs;
/** 类型下拉框集合 */
private Combo[] arrCmbPropsName;
/** 属性下拉框集合 */
private Combo[] arrCmbPropsType;
/** 列类型下拉框集合 */
private Combo[] arrCmbPropsLevel;
/** 列类型集合 */
private String[] levelValues = new String[] { ColProperties.conceptLevel, ColProperties.langLevel };
/** 列类型为 Concept 的类型集合 */
private String[] conceptPropValues = new String[] { ColProperties.descripName, ColProperties.noteName };
/** 列类型为 Tem 的类型集合 */
private String[] TranslationPropValues = new String[] { ColProperties.termName, ColProperties.termNoteName,
ColProperties.descripName };
private String[] conceptPropTypeValues;
private String[] termDescripPropTypeValues;
private String[] termTermNotePropTypeValues;
/** 加载配置按钮 */
private Button btnLoadConfiguration;
/** 保存配置按钮 */
private Button btnSaveConfiguration;
protected ColumnTypeDialog(Shell parentShell, Vector<ColProperties> colTypes, TBXTemplateUtil template,
String imgPath) {
super(parentShell);
this.colTypes = colTypes;
size = colTypes.size();
this.imgPath = imgPath;
loadPropTypeValue(template);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.ColumnTypeDialog.title"));
newShell.setImage(new Image(Display.getDefault(), imgPath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout());
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(750, 400).grab(true, true).applyTo(tparent);
ScrolledComposite cmpScrolled = new ScrolledComposite(tparent, SWT.V_SCROLL);
cmpScrolled.setAlwaysShowScrollBars(false);
cmpScrolled.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
cmpScrolled.setExpandHorizontal(true);
cmpScrolled.setShowFocusedControl(true);
Composite cmpContent = new Composite(cmpScrolled, SWT.None);
cmpScrolled.setContent(cmpContent);
cmpContent.setLayout(new GridLayout(5, false));
arrCmbLangs = new Combo[size];
arrCmbPropsName = new Combo[size];
arrCmbPropsType = new Combo[size];
arrCmbPropsLevel = new Combo[size];
new Label(cmpContent, SWT.None).setText(Messages.getString("dialog.ColumnTypeDialog.column1"));
new Label(cmpContent, SWT.None).setText(Messages.getString("dialog.ColumnTypeDialog.column2"));
new Label(cmpContent, SWT.None).setText(Messages.getString("dialog.ColumnTypeDialog.column3"));
new Label(cmpContent, SWT.None).setText(Messages.getString("dialog.ColumnTypeDialog.column4"));
new Label(cmpContent, SWT.None).setText(Messages.getString("dialog.ColumnTypeDialog.column5"));
for (int i = 0; i < size; i++) {
ColProperties type = colTypes.get(i);
new Label(cmpContent, SWT.None).setText(type.getColName() + " : ");
arrCmbPropsLevel[i] = new Combo(cmpContent, SWT.READ_ONLY);
arrCmbPropsLevel[i].setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL
| GridData.FILL_BOTH));
arrCmbPropsName[i] = new Combo(cmpContent, SWT.READ_ONLY);
GridData data = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH);
data.widthHint = 120;
arrCmbPropsName[i].setLayoutData(data);
arrCmbPropsType[i] = new Combo(cmpContent, SWT.READ_ONLY);
data = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH);
data.widthHint = 150;
arrCmbPropsType[i].setLayoutData(data);
arrCmbLangs[i] = new Combo(cmpContent, SWT.READ_ONLY);
arrCmbLangs[i].setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL
| GridData.FILL_BOTH));
arrCmbPropsLevel[i].setItems(levelValues);
arrCmbPropsLevel[i].select(0);
String propLevel = type.getLevel();
if (!propLevel.equals("")) { //$NON-NLS-1$
arrCmbPropsLevel[i].setText(propLevel);
if (propLevel.equals(ColProperties.conceptLevel)) {
arrCmbLangs[i].setEnabled(false);
arrCmbPropsName[i].setItems(conceptPropValues);
arrCmbPropsName[i].select(0);
arrCmbPropsType[i].setItems(conceptPropTypeValues);
arrCmbPropsType[i].select(0);
}
if (propLevel.equals(ColProperties.langLevel)) {
arrCmbLangs[i].setEnabled(true);
arrCmbPropsName[i].setItems(TranslationPropValues);
arrCmbPropsName[i].select(0);
arrCmbPropsType[i].setItems(termDescripPropTypeValues);
arrCmbPropsType[i].select(0);
}
}
// fixed a bug 2339 by John.
String propName = type.getPropName();
if (!propName.equals("")) { //$NON-NLS-1$
arrCmbPropsName[i].setText(propName);
}
// Update content for Prop Type combo
String propType = type.getPropType();
if (!propType.equals("")) { //$NON-NLS-1$
arrCmbPropsType[i].setText(propType);
}
if (!propLevel.equals("")) { //$NON-NLS-1$
if (propLevel.equals(ColProperties.conceptLevel)) {
arrCmbPropsType[i].setEnabled(propName.equals(ColProperties.descripName));
arrCmbPropsType[i].setItems(conceptPropTypeValues);
arrCmbPropsType[i].select(0);
}
if (propLevel.equals(ColProperties.langLevel)) {
arrCmbPropsType[i].setEnabled(!propName.equals(ColProperties.termName));
if (propName.equals(ColProperties.descripName)) {
arrCmbPropsType[i].setItems(termDescripPropTypeValues);
} else {
arrCmbPropsType[i].setItems(termTermNotePropTypeValues);
}
arrCmbPropsType[i].select(0);
}
}
// Update content for Language Combo
arrCmbLangs[i].setItems(LocaleService.getLanguages());
arrCmbLangs[i].select(0);
String lang = type.getLanguage();
if (!lang.equals("")) { //$NON-NLS-1$
arrCmbLangs[i].setText(LocaleService.getLanguage(lang));
}
final int idx = i;
arrCmbPropsName[idx].addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String level = arrCmbPropsLevel[idx].getText();
String name = arrCmbPropsName[idx].getText();
if (name.equals(ColProperties.termName)) {
arrCmbPropsType[idx].setEnabled(false);
arrCmbPropsType[idx].setItems(conceptPropTypeValues);
arrCmbPropsType[idx].select(0);
return;
}
if (name.equals(ColProperties.termNoteName)) {
arrCmbPropsType[idx].setEnabled(true);
arrCmbPropsType[idx].setItems(termTermNotePropTypeValues);
arrCmbPropsType[idx].select(0);
return;
}
if (name.equals(ColProperties.noteName)) {
arrCmbLangs[idx].setEnabled(false);
arrCmbPropsType[idx].setEnabled(false);
return;
}
if (name.equals(ColProperties.descripName)) {
arrCmbPropsType[idx].setEnabled(true);
if (level.equals(ColProperties.conceptLevel)) {
arrCmbPropsType[idx].setItems(conceptPropTypeValues);
} else {
arrCmbPropsType[idx].setItems(termDescripPropTypeValues);
}
arrCmbPropsType[idx].select(0);
return;
}
arrCmbPropsType[idx].setEnabled(false);
}
});
arrCmbPropsLevel[idx].addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String level = arrCmbPropsLevel[idx].getText();
String name = arrCmbPropsName[idx].getText();
if (level.equals(ColProperties.conceptLevel)) {
arrCmbLangs[idx].setEnabled(false);
arrCmbPropsName[idx].setItems(conceptPropValues);
arrCmbPropsName[idx].select(0);
arrCmbPropsType[idx].setEnabled(true);
arrCmbPropsType[idx].setItems(conceptPropTypeValues);
arrCmbPropsType[idx].select(0);
}
if (level.equals(ColProperties.langLevel)) {
arrCmbLangs[idx].setEnabled(true);
arrCmbPropsName[idx].setItems(TranslationPropValues);
arrCmbPropsName[idx].select(0);
arrCmbPropsType[idx].setEnabled(false);
if (name.equals(ColProperties.descripName)) {
arrCmbPropsType[idx].setItems(termDescripPropTypeValues);
} else {
arrCmbPropsType[idx].setItems(termTermNotePropTypeValues);
}
arrCmbPropsType[idx].select(0);
}
}
});
}
cmpContent.setSize(cmpContent.computeSize(SWT.DEFAULT, SWT.DEFAULT));
return tparent;
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
btnLoadConfiguration = createButton(parent, 22,
Messages.getString("dialog.ColumnTypeDialog.btnLoadConfiguration"), false);
btnSaveConfiguration = createButton(parent, 23,
Messages.getString("dialog.ColumnTypeDialog.btnSaveConfiguration"), false);
super.createButtonsForButtonBar(parent);
initListener();
}
/**
* 初始化加载配置和保存配置按钮的监听 ;
*/
private void initListener() {
btnLoadConfiguration.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
fd.setText(Messages.getString("dialog.ColumnTypeDialog.fdTitle"));
String extensions[] = { "*.ctc", "*" }; //$NON-NLS-1$ //$NON-NLS-2$
String[] names = {
Messages.getString("dialog.ColumnTypeDialog.filterName1"), Messages.getString("dialog.ColumnTypeDialog.filterName2") }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(extensions);
fd.setFilterNames(names);
fd.setFilterPath(System.getProperty("user.home"));
String name = fd.open();
if (name == null) {
return;
}
try {
VTDGen vg = new VTDGen();
if (vg.parseFile(name, true)) {
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/CSV2TBX-configuration");
ap.evalXPath();
int count = vu.getChildElementsCount();
if (count != arrCmbLangs.length) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.ColumnTypeDialog.msgTitle"),
Messages.getString("dialog.ColumnTypeDialog.msg1"));
return;
}
String xpath = "/CSV2TBX-configuration/item";
ap.selectXPath(xpath);
int i = 0;
while (ap.evalXPath() != -1) {
String propLevel = vu.getCurrentElementAttribut("propLevel", "");
String propType = vu.getCurrentElementAttribut("propType", ""); //$NON-NLS-1$ //$NON-NLS-2$
String lang = vu.getCurrentElementAttribut("propLang", ""); //$NON-NLS-1$ //$NON-NLS-2$
String propName = vu.getCurrentElementAttribut("propName", "");
arrCmbPropsLevel[i].setItems(levelValues);
arrCmbPropsLevel[i].select(0);
// Update contents for Level combo
if (!propLevel.equals("")) { //$NON-NLS-1$
arrCmbPropsLevel[i].setText(propLevel);
if (propLevel.equals(ColProperties.conceptLevel)) {
arrCmbLangs[i].setEnabled(false);
arrCmbPropsName[i].setItems(conceptPropValues);
arrCmbPropsName[i].select(0);
arrCmbPropsType[i].setItems(conceptPropTypeValues);
arrCmbPropsType[i].select(0);
}
if (propLevel.equals(ColProperties.langLevel)) {
arrCmbLangs[i].setEnabled(true);
arrCmbPropsName[i].setItems(TranslationPropValues);
arrCmbPropsName[i].select(0);
arrCmbPropsType[i].setItems(termDescripPropTypeValues);
arrCmbPropsType[i].select(0);
}
}
// Update content for Prop Name combo
if (!propName.equals("")) { //$NON-NLS-1$
arrCmbPropsName[i].setText(propName);
}
if (!propLevel.equals("")) { //$NON-NLS-1$
if (propLevel.equals(ColProperties.conceptLevel)) {
arrCmbPropsType[i].setEnabled(propName.equals(ColProperties.descripName));
arrCmbPropsType[i].setItems(conceptPropTypeValues);
arrCmbPropsType[i].select(0);
}
if (propLevel.equals(ColProperties.langLevel)) {
arrCmbPropsType[i].setEnabled(!propName.equals(ColProperties.termName));
if (propName.equals(ColProperties.descripName)) {
arrCmbPropsType[i].setItems(termDescripPropTypeValues);
} else {
arrCmbPropsType[i].setItems(termTermNotePropTypeValues);
}
arrCmbPropsType[i].select(0);
}
}
// Update content for Prop Type combo
if (!propType.equals("")) { //$NON-NLS-1$
arrCmbPropsType[i].setText(propType);
}
// Update content for Language Combo
arrCmbLangs[i].setItems(LocaleService.getLanguages());
arrCmbLangs[i].select(0);
if (!lang.equals("")) { //$NON-NLS-1$
arrCmbLangs[i].setText(lang);
}
i++;
}
}
} catch (XPathParseException e) {
LOGGER.error(Messages.getString("dialog.ColumnTypeDialog.logger1"), e);
} catch (NavException e) {
LOGGER.error(Messages.getString("dialog.ColumnTypeDialog.logger1"), e);
} catch (XPathEvalException e) {
LOGGER.error(Messages.getString("dialog.ColumnTypeDialog.logger1"), e);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
btnSaveConfiguration.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(getShell(), SWT.SAVE);
fd.setText(Messages.getString("dialog.ColumnTypeDialog.savefdTitle"));
String extensions[] = { "*.ctc", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
String[] names = {
Messages.getString("dialog.ColumnTypeDialog.filterName1"), Messages.getString("dialog.ColumnTypeDialog.filterName2") }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(extensions);
fd.setFilterNames(names);
fd.setFilterPath(System.getProperty("user.home"));
String name = fd.open();
if (name == null) {
return;
}
try {
FileOutputStream output = new FileOutputStream(name);
output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
output.write("<CSV2TBX-configuration>\n".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < arrCmbLangs.length; i++) {
String strItem = "<item propLang=\"" + arrCmbLangs[i].getText() //$NON-NLS-1$
+ "\" propName=\"" + arrCmbPropsName[i].getText() //$NON-NLS-1$
+ "\" propType=\"" + arrCmbPropsType[i].getText() //$NON-NLS-1$
+ "\" propLevel=\"" + arrCmbPropsLevel[i].getText() //$NON-NLS-1$
+ "\"/>\n"; //$NON-NLS-1$
output.write(strItem.getBytes("UTF-8")); //$NON-NLS-1$
}
output.write("</CSV2TBX-configuration>\n".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
output.close();
} catch (FileNotFoundException e1) {
LOGGER.error(Messages.getString("dialog.ColumnTypeDialog.logger2"), e);
} catch (UnsupportedEncodingException e1) {
LOGGER.error(Messages.getString("dialog.ColumnTypeDialog.logger2"), e);
} catch (IOException e1) {
LOGGER.error(Messages.getString("dialog.ColumnTypeDialog.logger2"), e);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
/**
* 根据提供的模板加载各个属性值
* @param template
* ;
*/
private void loadPropTypeValue(TBXTemplateUtil template) {
Vector<String> values = new Vector<String>();
for (int i = 0; i < template.getItemCount(); i++) {
String itemLevels = template.getItemLevels(i);
String specName = template.getSpecName(i);
if ((itemLevels.indexOf(TBXTemplateUtil.lsLevel) >= 0 || itemLevels.trim().equals("")) && //$NON-NLS-1$
specName.equals(TBXTemplateUtil.descripSpec)) {
values.add(template.getItemDescription(i));
}
}
termDescripPropTypeValues = new String[values.size()];
for (int i = 0; i < termDescripPropTypeValues.length; i++) {
termDescripPropTypeValues[i] = values.get(i);
}
values = new Vector<String>();
for (int i = 0; i < template.getItemCount(); i++) {
String itemLevels = template.getItemLevels(i);
String specName = template.getSpecName(i);
if ((itemLevels.indexOf(TBXTemplateUtil.lsLevel) >= 0 || itemLevels.trim().equals("")) && //$NON-NLS-1$
specName.equals(TBXTemplateUtil.termNoteSpec)) {
values.add(template.getItemDescription(i));
}
}
termTermNotePropTypeValues = new String[values.size()];
for (int i = 0; i < termTermNotePropTypeValues.length; i++) {
termTermNotePropTypeValues[i] = values.get(i);
}
values = new Vector<String>();
for (int i = 0; i < template.getItemCount(); i++) {
String itemLevels = template.getItemLevels(i);
String specName = template.getSpecName(i);
if ((itemLevels.indexOf(TBXTemplateUtil.teLevel) >= 0 || itemLevels.trim().equals("")) && //$NON-NLS-1$
specName.equals(TBXTemplateUtil.descripSpec)) {
values.add(template.getItemDescription(i));
}
}
conceptPropTypeValues = new String[values.size()];
for (int i = 0; i < conceptPropTypeValues.length; i++) {
conceptPropTypeValues[i] = values.get(i);
}
}
private String[] getUserLangs() {
Hashtable<String, String> langTable = new Hashtable<String, String>();
for (int c = 0; c < size; c++) {
String propLevel1 = arrCmbPropsLevel[c].getText();
if (propLevel1.equals(ColProperties.langLevel)) {
langTable.put(LocaleService.getLanguageCodeByLanguage(arrCmbLangs[c].getText()),
LocaleService.getLanguageCodeByLanguage(arrCmbLangs[c].getText()));
}
}
String[] result = new String[langTable.size()];
Enumeration<String> keys = langTable.keys();
int index = 0;
while (keys.hasMoreElements()) {
result[index++] = keys.nextElement();
}
return result;
}
public boolean verifyColProperties() {
// Verify Unknown Properties
for (int i = 0; i < size; i++) {
String propName = arrCmbPropsName[i].getText();
if (propName.equals("")) { //$NON-NLS-1$
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ColumnTypeDialog.msgTitle"),
Messages.getString("dialog.ColumnTypeDialog.msg2") + propName);
return false;
}
}
// Verify duplicated columns
for (int i = 0; i < size; i++) {
String lang1 = LocaleService.getLanguageCodeByLanguage(arrCmbLangs[i].getText());
String propName1 = arrCmbPropsName[i].getText();
String propType1 = arrCmbPropsType[i].getText();
String level1 = arrCmbPropsLevel[i].getText();
if (level1.equals(ColProperties.conceptLevel)) {
continue;
}
for (int j = 0; j < size; j++) {
if (i == j) {
continue;
}
String lang2 = LocaleService.getLanguageCodeByLanguage(arrCmbLangs[j].getText());
String propName2 = arrCmbPropsName[j].getText();
String propType2 = arrCmbPropsType[j].getText();
String level2 = arrCmbPropsLevel[i].getText();
if (level2.equals(ColProperties.conceptLevel)) {
continue;
}
if (lang1.equals(lang2)) {
if (propName1.equals(propName2) && propType1.equals(propType2)) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.ColumnTypeDialog.msgTitle"),
Messages.getString("dialog.ColumnTypeDialog.msg3") + lang1);
return false;
}
}
}
}
// Verify That a Term was defined for each language
String[] langs = getUserLangs();
for (int l = 0; l < langs.length; l++) {
boolean existTerm = false;
for (int i = 0; i < size; i++) {
String lang1 = LocaleService.getLanguageCodeByLanguage(arrCmbLangs[i].getText());
String propName1 = arrCmbPropsName[i].getText();
if (lang1.equals(langs[l]) && propName1.equals(ColProperties.termName)) {
existTerm = true;
break;
}
}
if (!existTerm) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ColumnTypeDialog.msgTitle"),
Messages.getString("dialog.ColumnTypeDialog.msg4") + langs[l]);
return false;
}
}
return true;
}
@Override
protected void okPressed() {
if (!verifyColProperties()) {
return;
}
for (int i = 0; i < size; i++) {
ColProperties type = colTypes.get(i);
String propLevel = arrCmbPropsLevel[i].getText();
String lang = LocaleService.getLanguageCodeByLanguage(arrCmbLangs[i].getText());
String propName = arrCmbPropsName[i].getText();
String propType = arrCmbPropsType[i].getText();
type.setColumnType(propLevel, lang, propName, propType);
}
close();
}
}
| 22,370 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ProgressDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/ProgressDialog.java | /*
* Created on 01-dic-2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package net.heartsome.cat.ts.ui.plugin.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
/**
* @author Gonzalo
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class ProgressDialog {
public static short NO_BARS = 0;
public static short SINGLE_BAR = 1;
public static short DOUBLE_BARS = 2;
public static short TRIPLE_BARS = 3;
Shell shell;
Shell proShell;
private Label mainLabel;
private ProgressBar mainBar;
private Label progressLabel;
private ProgressBar progressBar;
private Label thirdLabel;
private ProgressBar thirdBar;
private Display display;
private Label titleLabel;
public ProgressDialog(Shell currentShell, String title,
String progressMessage, short style) {
display = currentShell.getDisplay();
proShell = new Shell(display, SWT.BORDER | SWT.APPLICATION_MODAL | SWT.NO_TRIM);
proShell.setCursor(new Cursor(proShell.getDisplay(), SWT.CURSOR_WAIT));
proShell.setLayout(new GridLayout());
Point location = currentShell.getLocation();
Point size = currentShell.getSize();
location.x = location.x + size.x/3;
location.y = location.y + size.y/3;
proShell.setLocation(location);
shell = currentShell;
shell.setCursor(new Cursor(proShell.getDisplay(), SWT.CURSOR_WAIT));
Composite holder = new Composite(proShell,SWT.BORDER);
holder.setLayout(new GridLayout());
holder.setLayoutData(new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL));
titleLabel = new Label(holder, SWT.BOLD);
titleLabel.setText(title);
titleLabel.setBackground(new Color(display,0x52,0x81,0x83)); // dull green
titleLabel.setForeground(new Color(display,0xFF,0xFF,0xFF)); // white
titleLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL));
if (style > DOUBLE_BARS) {
thirdLabel = new Label(holder, SWT.NONE);
GridData data = new GridData(GridData.GRAB_HORIZONTAL
| GridData.FILL_HORIZONTAL);
data.widthHint = 200;
thirdLabel.setLayoutData(data);
thirdLabel.setText(progressMessage);
thirdBar = new ProgressBar(holder, SWT.NONE);
data = new GridData(GridData.GRAB_HORIZONTAL
| GridData.FILL_HORIZONTAL);
data.widthHint = 200;
thirdBar.setLayoutData(data);
thirdBar.setMinimum(0);
thirdBar.setMaximum(100);
}
if (style > SINGLE_BAR) {
mainLabel = new Label(holder, SWT.NONE);
GridData data = new GridData(GridData.GRAB_HORIZONTAL
| GridData.FILL_HORIZONTAL);
data.widthHint = 200;
mainLabel.setLayoutData(data);
if (style == 2){
mainLabel.setText(progressMessage);
}
mainBar = new ProgressBar(holder, SWT.NONE);
data = new GridData(GridData.GRAB_HORIZONTAL
| GridData.FILL_HORIZONTAL);
data.widthHint = 200;
mainBar.setLayoutData(data);
mainBar.setMinimum(0);
mainBar.setMaximum(100);
}
progressLabel = new Label(holder, SWT.NONE);
GridData data = new GridData(GridData.GRAB_HORIZONTAL
| GridData.FILL_HORIZONTAL);
data.widthHint = 200;
progressLabel.setLayoutData(data);
progressLabel.setText(progressMessage);
if ( style != NO_BARS) {
progressBar = new ProgressBar(holder, SWT.NONE);
data = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
data.widthHint = 200;
progressBar.setLayoutData(data);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
}
proShell.pack();
}
public void open() {
proShell.open();
display.update();
}
public void updateMain(int value) {
mainBar.setSelection(value);
mainBar.setToolTipText(Integer.toString(mainBar.getSelection()) + "%"); //$NON-NLS-1$
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void updateProgress(int value) {
progressBar.setSelection(value);
progressBar.setToolTipText(Integer.toString(progressBar.getSelection()) + "%"); //$NON-NLS-1$
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void updateProgressMessage(String message) {
progressLabel.setText(message);
shell.layout();
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void updateThirdProgress(int value) {
thirdBar.setSelection(value);
thirdBar.setToolTipText(Integer.toString(thirdBar.getSelection()) + "%"); //$NON-NLS-1$
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void updateThirdMessage(String message) {
thirdLabel.setText(message);
shell.layout();
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void updateMainMessage(String message) {
mainLabel.setText(message);
shell.layout();
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void updateTitle(String message) {
titleLabel.setText(message);
shell.layout();
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void updateProgress(int value, String message) {
progressBar.setSelection(value);
progressLabel.setText(message);
display.update();
while (display.readAndDispatch()) {
// do nothing
}
}
public void showFinish(String finishMessage) {
progressLabel.setText(finishMessage);
shell.layout();
display.update();
shell.setCursor(new Cursor(proShell.getDisplay(), SWT.CURSOR_ARROW));
proShell.setCursor(new Cursor(proShell.getDisplay(), SWT.CURSOR_ARROW));
}
public void close() {
shell.setCursor(new Cursor(proShell.getDisplay(), SWT.CURSOR_ARROW));
proShell.close();
proShell.dispose();
}
public boolean isDisposed() {
return proShell.isDisposed();
}
public Shell getShell() {
return proShell;
}
} | 7,243 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CSV2TMXConverterDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/CSV2TMXConverterDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
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.util.Util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
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.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
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;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CSV to TMX Converter 对话框
* @author peason
* @version
* @since JDK1.6
*/
public class CSV2TMXConverterDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);
/** 表格对象,用于展示 CSV 文件的内容 */
private Table table;
/** 显示行数的标签 */
private Label lblRowCount;
/** 显示列数的标签 */
private Label lblColCount;
/** Logo 图片路径 */
private String imagePath;
/** CSV 文件路径 */
private String csvPath;
/** CSV 文件的列分隔符 */
private String colSeparator;
/** CSV 文件的文本定界符 */
private String textDelimiter;
/** CSV 文件的字符集 */
private String encoding;
/** CSV 文件的列数 */
private int cols;
/** CSV 文件的行数 */
private int rows;
/** 导出 CSV 文件时所用到的流对象 */
private FileOutputStream output;
/**
* 构造方法
* @param parentShell
*/
public CSV2TMXConverterDialog(Shell parentShell) {
super(parentShell);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.CSV2TMXConverterDialog.title"));
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_CSV2TMX_PATH);
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridLayoutFactory.swtDefaults().spacing(0, 0).numColumns(1).applyTo(tparent);
GridDataFactory.fillDefaults().hint(750, 500).align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(tparent);
createMenu();
createToolBar(tparent);
table = new Table(tparent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite cmpStatus = new Composite(tparent, SWT.BORDER);
cmpStatus.setLayout(new GridLayout(2, true));
cmpStatus.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
lblRowCount = new Label(cmpStatus, SWT.None);
lblRowCount.setText(MessageFormat.format(Messages.getString("dialog.CSV2TMXConverterDialog.lblRowCount"), 0));
lblRowCount.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
lblColCount = new Label(cmpStatus, SWT.None);
lblColCount.setText(MessageFormat.format(Messages.getString("dialog.CSV2TMXConverterDialog.lblColCount"), 0));
lblColCount.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
tparent.layout();
getShell().layout();
return tparent;
}
/**
* 创建菜单 ;
*/
private void createMenu() {
Menu menu = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menu);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Menu fileMenu = new Menu(menu);
MenuItem fileItem = new MenuItem(menu, SWT.CASCADE);
fileItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.fileMenu"));
fileItem.setMenu(fileMenu);
MenuItem openItem = new MenuItem(fileMenu, SWT.PUSH);
openItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.openItem"));
String openCSVPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_OPEN_CSV_PATH);
openItem.setImage(new Image(Display.getDefault(), openCSVPath));
openItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
openFile();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
MenuItem exportItem = new MenuItem(fileMenu, SWT.PUSH);
exportItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.exportItem"));
String exportPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_EXPORT_TBX_PATH);
exportItem.setImage(new Image(Display.getDefault(), exportPath));
exportItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
export();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.exitItem"));
exitItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
close();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Menu taskMenu = new Menu(menu);
MenuItem taskItem = new MenuItem(menu, SWT.CASCADE);
taskItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.taskMenu"));
taskItem.setMenu(taskMenu);
MenuItem deleteColItem = new MenuItem(taskMenu, SWT.PUSH);
deleteColItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.deleteColItem"));
String deleteColPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_DELETE_COLUMN_PATH);
deleteColItem.setImage(new Image(Display.getDefault(), deleteColPath));
deleteColItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
removeColumn();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
MenuItem colPropertyItem = new MenuItem(taskMenu, SWT.PUSH);
colPropertyItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.colPropertyItem"));
String setColPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_SET_COLUMN_PATH);
colPropertyItem.setImage(new Image(Display.getDefault(), setColPath));
colPropertyItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
selectLanguage();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Menu helpMenu = new Menu(menu);
MenuItem helpItem = new MenuItem(menu, SWT.CASCADE);
helpItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.helpMenu"));
helpItem.setMenu(helpMenu);
MenuItem helpContentItem = new MenuItem(helpMenu, SWT.PUSH);
helpContentItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.helpContentItem"));
String helpPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_HELP_PATH);
helpContentItem.setImage(new Image(Display.getDefault(), helpPath));
helpContentItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
displayHelp();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
MenuItem aboutItem = new MenuItem(helpMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.CSV2TMXConverterDialog.aboutItem"));
String imgPath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_CSV2TMX_MENU_PATH);
aboutItem.setImage(new Image(Display.getDefault(), imgPath));
aboutItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
AboutDialog dialog = new AboutDialog(getShell(), Messages
.getString("dialog.CSV2TMXConverterDialog.aboutItemName"), imagePath, Messages
.getString("dialog.CSV2TMXConverterDialog.version") + " " + PluginConstants.CSV2TMX_VERSION);
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
/**
* 创建工具栏
* @param parent
* ;
*/
private void createToolBar(Composite parent) {
Composite cmpToolBar = new Composite(parent, SWT.None);
GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(3).equalWidth(false).applyTo(cmpToolBar);
cmpToolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
ToolBar toolBar = new ToolBar(cmpToolBar, SWT.NO_FOCUS | SWT.FLAT);
ToolItem openToolItem = new ToolItem(toolBar, SWT.PUSH);
openToolItem.setToolTipText(Messages.getString("dialog.CSV2TMXConverterDialog.openToolItem"));
String openCSVPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_OPEN_CSV_PATH);
openToolItem.setImage(new Image(Display.getDefault(), openCSVPath));
openToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
openFile();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
ToolItem exporToolItem = new ToolItem(toolBar, SWT.PUSH);
exporToolItem.setToolTipText(Messages.getString("dialog.CSV2TMXConverterDialog.exporToolItem"));
String exportPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_EXPORT_TBX_PATH);
exporToolItem.setImage(new Image(Display.getDefault(), exportPath));
exporToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
export();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
ToolItem deleteColToolItem = new ToolItem(toolBar, SWT.PUSH);
deleteColToolItem.setToolTipText(Messages.getString("dialog.CSV2TMXConverterDialog.deleteColToolItem"));
String deleteColPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_DELETE_COLUMN_PATH);
deleteColToolItem.setImage(new Image(Display.getDefault(), deleteColPath));
deleteColToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
removeColumn();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
ToolItem setColToolItem = new ToolItem(toolBar, SWT.PUSH);
setColToolItem.setToolTipText(Messages.getString("dialog.CSV2TMXConverterDialog.setColToolItem"));
String setColPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_SET_COLUMN_PATH);
setColToolItem.setImage(new Image(Display.getDefault(), setColPath));
setColToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
selectLanguage();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new Label(cmpToolBar, SWT.None)
.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
ToolBar helpToolBar = new ToolBar(cmpToolBar, SWT.NO_FOCUS | SWT.FLAT);
ToolItem helpToolItem = new ToolItem(helpToolBar, SWT.RIGHT);
helpToolItem.setToolTipText(Messages.getString("dialog.CSV2TMXConverterDialog.helpToolBar"));
String helpPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_HELP_PATH);
helpToolItem.setImage(new Image(Display.getDefault(), helpPath));
helpToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
displayHelp();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
private void displayHelp() {
String curLang = CommonFunction.getSystemLanguage();
if (Util.isWindows()) {
String help = "help" + File.separator + "csvconvdocs" + File.separator + "csvconverter.chm";
if (curLang.equalsIgnoreCase("zh")) {
help = "help" + File.separator + "csvconvdocs" + File.separator + "csvconverter_zh-cn.chm";
}
Program.launch(PluginUtil.getConfigurationFilePath(help));
} else {
String help = "help" + File.separator + "csvconvdocs" + File.separator + "en" + File.separator + "toc.xml";
if (curLang.equalsIgnoreCase("zh")) {
help = "help" + File.separator + "csvconvdocs" + File.separator + "zh-cn" + File.separator + "toc.xml";
}
PluginHelpDialog dialog = new PluginHelpDialog(getShell(), PluginUtil.getConfigurationFilePath(help),
Messages.getString("dialog.CSV2TMXConverterDialog.helpDialogTitle"));
dialog.open();
}
}
/**
* 打开 CSV 文件 ;
*/
private void openFile() {
CSVSettingDialog dialog = new CSVSettingDialog(getShell(), false, imagePath, null);
if (dialog.open() == IDialogConstants.OK_ID) {
csvPath = dialog.getCsvPath();
colSeparator = dialog.getColSeparator();
textDelimiter = dialog.getTextDelimiter();
encoding = dialog.getEncoding();
try {
cols = maxColumns();
if (cols < 2) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.CSV2TMXConverterDialog.msgTitle"),
Messages.getString("dialog.CSV2TMXConverterDialog.msg1"));
return;
}
rows = 0;
int width = (table.getClientArea().width - table.getBorderWidth() * 2 - table.getVerticalBar()
.getSize().x) / cols;
if (width < 100) {
width = 100;
}
table.removeAll();
int count = table.getColumnCount();
for (int i = 0; i < count; i++) {
table.getColumn(0).dispose();
}
for (int i = 0; i < cols; i++) {
new TableColumn(table, SWT.NONE);
table.getColumn(i).setWidth(width);
table.getColumn(i).setText("" + (i + 1)); //$NON-NLS-1$
}
fillTable();
table.layout(true);
lblRowCount.setText(MessageFormat.format(
Messages.getString("dialog.CSV2TMXConverterDialog.lblRowCount"), rows));
lblColCount.setText(MessageFormat.format(
Messages.getString("dialog.CSV2TMXConverterDialog.lblColCount"), cols));
} catch (IOException e) {
LOGGER.error(Messages.getString("dialog.CSV2TMXConverterDialog.logger1"), e);
} catch (Exception e) {
LOGGER.error(Messages.getString("dialog.CSV2TMXConverterDialog.logger1"), e);
}
}
}
/**
* 导出为 TMX 文件 ;
*/
private void export() {
if (table.getColumnCount() < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.CSV2TMXConverterDialog.msgTitle"),
Messages.getString("dialog.CSV2TMXConverterDialog.msg2"));
return;
}
Vector<String> languages = new Vector<String>(cols);
for (int i = 0; i < cols; i++) {
languages.add(table.getColumn(i).getText());
}
if (!LocaleService.verifyLanguages(languages)) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.CSV2TMXConverterDialog.msgTitle"),
Messages.getString("dialog.CSV2TMXConverterDialog.msg3"));
return;
}
ExportDialog exportDialog = new ExportDialog(getShell(), csvPath, languages);
if (exportDialog.open() == IDialogConstants.OK_ID) {
String exportFile = exportDialog.getFilePath();
if (exportFile == null) {
return;
}
try {
File f = new File(exportFile);
if (!f.exists() || f.isDirectory()) {
f.createNewFile();
}
output = new FileOutputStream(f);
String version = exportDialog.getTmxVersion();
writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //$NON-NLS-1$
writeString("<tmx version=\"" + version + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
writeString("<header \n" + //$NON-NLS-1$
" creationtool=\"CSVConverter\" \n" + //$NON-NLS-1$
" creationtoolversion=\"" + PluginConstants.CSV2TMX_VERSION + "\" \n" + //$NON-NLS-1$ //$NON-NLS-2$
" srclang=\"" + exportDialog.getLang() + "\" \n" + //$NON-NLS-1$ //$NON-NLS-2$
" adminlang=\"en\" \n" + //$NON-NLS-1$
" datatype=\"xml\" \n" + //$NON-NLS-1$
" o-tmf=\"CSV\" \n" + //$NON-NLS-1$
" segtype=\"block\"\n" + //$NON-NLS-1$
">\n" + //$NON-NLS-1$
"</header>\n"); //$NON-NLS-1$
writeString("<body>\n"); //$NON-NLS-1$
for (int r = 0; r < rows; r++) {
int count = 0;
StringBuffer tuBuffer = new StringBuffer("<tu tuid=\"" + createId() + "\">\n");
TableItem item = table.getItem(r);
for (int c = 0; c < cols; c++) {
String string = item.getText(c);
if (!string.trim().equals("")) { //$NON-NLS-1$
if (version.equals("1.1") || version.equals("1.2")) { //$NON-NLS-1$ //$NON-NLS-2$
tuBuffer.append("<tuv lang=\"" + languages.get(c) + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
tuBuffer.append("<tuv xml:lang=\"" + languages.get(c) + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
tuBuffer.append("<seg>" + TextUtil.cleanString(string.trim()) + "</seg>\n</tuv>\n"); //$NON-NLS-1$ //$NON-NLS-2$
count++;
}
}
tuBuffer.append("</tu>\n"); //$NON-NLS-1$
if (count > 0) {
writeString(tuBuffer.toString());
}
}
writeString("</body>\n"); //$NON-NLS-1$
writeString("</tmx>\n"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), Messages.getString("dialog.CSV2TMXConverterDialog.msgTitle"),
Messages.getString("dialog.CSV2TMXConverterDialog.msg4"));
} catch (FileNotFoundException e) {
LOGGER.error(Messages.getString("dialog.CSV2TMXConverterDialog.logger2"), e);
} catch (IOException e) {
LOGGER.error(Messages.getString("dialog.CSV2TMXConverterDialog.logger2"), e);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
LOGGER.error(Messages.getString("dialog.CSV2TMXConverterDialog.logger2"), e);
}
}
}
}
/**
* 删除列 ;
*/
private void removeColumn() {
if (cols < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.CSV2TMXConverterDialog.msgTitle"),
Messages.getString("dialog.CSV2TMXConverterDialog.msg2"));
return;
}
Vector<String> columns = new Vector<String>();
int count = table.getColumnCount();
for (int i = 0; i < count; i++) {
columns.add(table.getColumn(i).getText());
}
ColumnRemoveDialog removeDialog = new ColumnRemoveDialog(getShell(), columns, imagePath);
if (removeDialog.open() == IDialogConstants.OK_ID) {
Vector<String> columnVector = removeDialog.getColumnVector();
if (columnVector.size() == columns.size()) {
return;
}
for (int i = 0; i < count; i++) {
TableColumn col = table.getColumn(i);
boolean found = false;
for (int j = 0; j < columnVector.size(); j++) {
if (col.getText().equals(columnVector.get(j))) {
found = true;
break;
}
}
if (!found) {
table.getColumn(i).dispose();
count--;
i--;
}
}
cols = table.getColumnCount();
lblColCount.setText(MessageFormat.format(
Messages.getString("dialog.CSV2TMXConverterDialog.lblColCount"), cols)); //$NON-NLS-1$
int width = (table.getClientArea().width - table.getBorderWidth() * 2 - table.getVerticalBar().getSize().x)
/ cols;
if (width < 100) {
width = 100;
}
for (int i = 0; i < cols; i++) {
TableColumn column = table.getColumn(i);
column.setWidth(width);
}
}
}
/**
* 选择语言 ;
*/
private void selectLanguage() {
if (cols < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.CSV2TMXConverterDialog.msgTitle"),
Messages.getString("dialog.CSV2TMXConverterDialog.msg4"));
return;
}
Vector<String> languages = new Vector<String>(cols);
for (int i = 0; i < cols; i++) {
languages.add(table.getColumn(i).getText());
}
LanguageSettingDialog langDialog = new LanguageSettingDialog(getShell(), languages);
if (langDialog.open() == IDialogConstants.OK_ID) {
languages = langDialog.getResultLang();
for (int i = 0; i < cols; i++) {
table.getColumn(i).setText(languages.get(i));
}
}
}
/**
* @throws IOException
* @throws UnsupportedEncodingException
*/
private void fillTable() throws UnsupportedEncodingException, IOException {
InputStreamReader input = new InputStreamReader(new FileInputStream(csvPath), encoding);
BufferedReader buffer = new BufferedReader(input);
String line;
while ((line = buffer.readLine()) != null) {
createItems(line);
}
}
private String createId() {
Date now = new Date();
long lng = now.getTime();
// wait until we are in the next millisecond
// before leaving to ensure uniqueness
Date next = new Date();
while (next.getTime() == lng) {
next = null;
next = new Date();
}
return "" + lng; //$NON-NLS-1$
}
/**
* @param line
*/
private void createItems(String line) {
int size = line.length();
if (size == 0) {
return;
}
if (countColumns(line) != cols) {
return;
}
StringBuffer buffer = new StringBuffer();
Vector<String> vector = new Vector<String>();
String[] strings = new String[cols];
boolean inDelimiters = false;
for (int i = 0; i < size; i++) {
String c = "" + line.charAt(i); //$NON-NLS-1$
if (c.equals(textDelimiter)) {
inDelimiters = !inDelimiters;
continue;
}
if (!inDelimiters && c.equals(colSeparator)) {
vector.add(buffer.toString());
buffer = null;
buffer = new StringBuffer();
continue;
}
buffer.append(c);
}
if (!buffer.toString().equals("")) { //$NON-NLS-1$
vector.add(buffer.toString());
}
for (int i = 0; i < vector.size(); i++) {
strings[i] = vector.get(i);
}
for (int i = vector.size(); i < cols; i++) {
strings[i] = ""; //$NON-NLS-1$
}
TableItem item = new TableItem(table, SWT.NONE);
item.setText(strings);
rows++;
}
private int maxColumns() throws IOException {
int max = 0;
InputStreamReader input = new InputStreamReader(new FileInputStream(csvPath), encoding);
BufferedReader buffer = new BufferedReader(input);
Hashtable<String, Integer> table1 = new Hashtable<String, Integer>();
String line = buffer.readLine();
while (line != null) {
int i = countColumns(line);
if (table1.containsKey("" + i)) { //$NON-NLS-1$
int count = table1.get("" + i).intValue() + 1; //$NON-NLS-1$
table1.put("" + i, new Integer(count)); //$NON-NLS-1$
} else {
table1.put("" + i, new Integer(1)); //$NON-NLS-1$
}
line = buffer.readLine();
}
Enumeration<String> e = table1.keys();
String key = ""; //$NON-NLS-1$
while (e.hasMoreElements()) {
String s = e.nextElement();
int value = table1.get(s).intValue();
if (value > max) {
max = value;
key = s;
}
}
return Integer.parseInt(key);
}
private int countColumns(String line) {
int size = line.length();
if (size == 0) {
return 0;
}
int count = 1;
boolean inDelimiters = false;
for (int i = 0; i < size; i++) {
String c = "" + line.charAt(i); //$NON-NLS-1$
if (c.equals(textDelimiter)) {
inDelimiters = !inDelimiters;
}
if (!inDelimiters && c.equals(colSeparator)) {
count++;
}
}
return count;
}
/**
* @param string
* @throws IOException
* @throws UnsupportedEncodingException
*/
private void writeString(String string) throws UnsupportedEncodingException, IOException {
output.write(string.getBytes("UTF-8")); //$NON-NLS-1$
}
/**
* 导出为 TMX 文件对话框
* @author peason
* @version
* @since JDK1.6
*/
class ExportDialog extends Dialog {
/** 导出文件路径 */
private String filePath;
/** 语言集合 */
private Vector<String> languages;
/** 路径文本框 */
private Text txtFile;
/** 源语言下拉框 */
private Combo cmbLang;
/** TMX 版本下拉框 */
private Combo cmbTMXVersion;
/** 源语言 */
private String lang;
/** TMX 版本 */
private String tmxVersion;
protected ExportDialog(Shell parentShell, String filePath, Vector<String> languages) {
super(parentShell);
this.filePath = filePath;
this.languages = languages;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.title"));
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout(3, false));
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(350, 150).grab(true, true).applyTo(tparent);
new Label(tparent, SWT.None).setText(Messages
.getString("dialog.CSV2TMXConverterDialog.ExportDialog.lblTMX"));
txtFile = new Text(tparent, SWT.BORDER);
txtFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
txtFile.setEditable(false);
if (filePath != null) {
if (filePath.indexOf(".") != -1) {
txtFile.setText(filePath.substring(0, filePath.lastIndexOf(".")) + ".tmx");
} else {
txtFile.setText(filePath + ".tmx");
}
filePath = txtFile.getText();
}
Button btnBrowse = new Button(tparent, SWT.None);
btnBrowse.setText(Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.btnBrowse"));
btnBrowse.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
dialog.setText(Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.dialogTitle"));
String extensions[] = { "*.tmx", "*" }; //$NON-NLS-1$ //$NON-NLS-2$
String names[] = {
Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.filterName1"), Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.filterName2") }; //$NON-NLS-1$ //$NON-NLS-2$
dialog.setFilterNames(names);
dialog.setFilterExtensions(extensions);
String fileSep = System.getProperty("file.separator");
if (txtFile.getText() != null && !txtFile.getText().trim().equals("")) {
dialog.setFilterPath(txtFile.getText().substring(0, txtFile.getText().lastIndexOf(fileSep)));
dialog.setFileName(txtFile.getText().substring(txtFile.getText().lastIndexOf(fileSep) + 1));
} else {
dialog.setFilterPath(System.getProperty("user.home"));
}
filePath = dialog.open();
if (filePath != null) {
txtFile.setText(filePath);
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
Group optionsGrp = new Group(tparent, SWT.None);
optionsGrp.setText(Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.optionsGrp"));
GridDataFactory.fillDefaults().span(3, 1).align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(optionsGrp);
optionsGrp.setLayout(new GridLayout(2, false));
createLabel(optionsGrp, Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.src"));
cmbLang = new Combo(optionsGrp, SWT.READ_ONLY);
cmbLang.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
String langList[] = new String[languages.size() + 1];
langList[0] = "*all*";
for (int i = 0; i < languages.size(); i++) {
langList[i + 1] = languages.get(i);
}
cmbLang.setItems(langList);
cmbLang.select(0);
createLabel(optionsGrp, Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.versionTMX"));
cmbTMXVersion = new Combo(optionsGrp, SWT.READ_ONLY);
cmbTMXVersion.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
String levels[] = { "TMX 1.4", "TMX 1.3", "TMX 1.2", "TMX 1.1" };
cmbTMXVersion.setItems(levels);
cmbTMXVersion.select(0);
return tparent;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.OK_ID).setText(
Messages.getString("dialog.CSV2TMXConverterDialog.ExportDialog.ok"));
}
@Override
protected void okPressed() {
setLang(cmbLang.getText());
String version = "";
if (cmbTMXVersion.getSelectionIndex() == 0) {
version = "1.4";
} else if (cmbTMXVersion.getSelectionIndex() == 1) {
version = "1.3";
} else if (cmbTMXVersion.getSelectionIndex() == 2) {
version = "1.2";
} else if (cmbTMXVersion.getSelectionIndex() == 3) {
version = "1.1";
}
setTmxVersion(version);
close();
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getTmxVersion() {
return tmxVersion;
}
public void setTmxVersion(String tmxVersion) {
this.tmxVersion = tmxVersion;
}
/**
* 获得导出路径
* @return ;
*/
public String getFilePath() {
return filePath;
}
}
/**
* 创建 Label,文本右对齐
* @param parent
* 父控件
* @param text
* Label 上显示的文本
*/
private void createLabel(Composite parent, String text) {
Label lbl = new Label(parent, SWT.None);
lbl.setText(text);
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(lbl);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
Composite cmpTemp = parent.getParent();
parent.dispose();
cmpTemp.layout();
}
/**
* 选择语言对话框
* @author peason
* @version
* @since JDK1.6
*/
class LanguageSettingDialog extends Dialog {
/** 语言集合 */
private Vector<String> languages;
/** 列数 */
private int size;
/** 所设置的语言 */
private Vector<String> resultLang;
/** 语言下拉框集合 */
private Combo[] arrCmbLangs;
/**
* 构造方法
* @param parentShell
* @param languages
* 语言集合
*/
protected LanguageSettingDialog(Shell parentShell, Vector<String> languages) {
super(parentShell);
this.languages = languages;
size = languages.size();
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.CSV2TMXConverterDialog.LanguageSettingDialog.title"));
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout());
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(300, 250).grab(true, true).applyTo(tparent);
ScrolledComposite cmpScrolled = new ScrolledComposite(tparent, SWT.V_SCROLL);
cmpScrolled.setAlwaysShowScrollBars(false);
cmpScrolled.setLayoutData(new GridData(GridData.FILL_BOTH));
cmpScrolled.setExpandHorizontal(true);
cmpScrolled.setShowFocusedControl(true);
Composite cmpContent = new Composite(cmpScrolled, SWT.None);
cmpScrolled.setContent(cmpContent);
cmpContent.setLayout(new GridLayout(2, false));
cmpContent.setLayoutData(new GridData(GridData.FILL_BOTH));
arrCmbLangs = new Combo[size];
for (int i = 0; i < size; i++) {
createLabel(cmpContent, languages.get(i) + " : ");
arrCmbLangs[i] = new Combo(cmpContent, SWT.READ_ONLY);
arrCmbLangs[i].setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
arrCmbLangs[i].setItems(LocaleService.getLanguages());
String name = LocaleService.getLanguage(languages.get(i));
if (!name.equals(languages.get(i))) {
arrCmbLangs[i].setText(name);
}
}
cmpContent.setSize(cmpContent.computeSize(SWT.DEFAULT, SWT.DEFAULT));
return tparent;
}
@Override
protected void okPressed() {
resultLang = new Vector<String>();
for (int i = 0; i < size; i++) {
String string = arrCmbLangs[i].getText();
if (string.equals("")) { //$NON-NLS-1$
resultLang.add(languages.get(i));
} else {
resultLang.add(LocaleService.getLanguageCodeByLanguage(string));
}
}
close();
}
public Vector<String> getResultLang() {
return resultLang;
}
}
}
| 32,891 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TBXMakerDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/TBXMakerDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.ui.plugin.Activator;
import net.heartsome.cat.ts.ui.plugin.ColProperties;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
import net.heartsome.cat.ts.ui.plugin.util.TBXTemplateUtil;
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.util.Util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
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.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
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;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TBXMaker 对话框
* @author peason
* @version
* @since JDK1.6
*/
public class TBXMakerDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);
/** 表格对象,用于展示 CSV 文件的内容 */
private Table table;
/** 显示行数的标签 */
private Label lblRowCount;
/** 显示列数的标签 */
private Label lblColCount;
/** Logo 图片路径 */
private String imagePath;
/** CSV 文件路径 */
private String csvPath;
/** CSV 文件的列分隔符 */
private String colSeparator;
/** CSV 文件的文本定界符 */
private String textDelimiter;
/** CSV 文件的字符集 */
private String encoding;
/** CSV 文件的主语言 */
private String lang;
/** CSV 文件的 XCS 模板 */
private String xcsTemplate;
/** CSV 文件的列数 */
private int cols;
/** CSV 文件的行数 */
private int rows;
/** 导出 CSV 文件时所用到的流对象 */
private FileOutputStream output;
/** XCS 模板 */
private TBXTemplateUtil template;
/**
* 构造方法
* @param parentShell
*/
public TBXMakerDialog(Shell parentShell) {
super(parentShell);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.TBXMakerDialog.title"));
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_TBXMAKER_PATH);
newShell.setImage(Activator.getImageDescriptor(PluginConstants.LOGO_TBXMAKER_PATH).createImage());
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
// tparent.setLayout(new GridLayout());
GridLayoutFactory.swtDefaults().spacing(0, 0).numColumns(1).applyTo(tparent);
GridDataFactory.fillDefaults().hint(750, 500).align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(tparent);
createMenu();
createToolBar(tparent);
table = new Table(tparent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite cmpStatus = new Composite(tparent, SWT.BORDER);
cmpStatus.setLayout(new GridLayout(2, true));
cmpStatus.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
lblRowCount = new Label(cmpStatus, SWT.None);
lblRowCount.setText(MessageFormat.format(Messages.getString("dialog.TBXMakerDialog.lblRowCount"), 0));
lblRowCount.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
lblColCount = new Label(cmpStatus, SWT.None);
lblColCount.setText(MessageFormat.format(Messages.getString("dialog.TBXMakerDialog.lblColCount"), 0));
lblColCount.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
tparent.layout();
getShell().layout();
return tparent;
}
/**
* 创建菜单 ;
*/
private void createMenu() {
Menu menu = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menu);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Menu fileMenu = new Menu(menu);
MenuItem fileItem = new MenuItem(menu, SWT.CASCADE);
fileItem.setText(Messages.getString("dialog.TBXMakerDialog.fileMenu"));
fileItem.setMenu(fileMenu);
MenuItem openCSVItem = new MenuItem(fileMenu, SWT.PUSH);
openCSVItem.setText(Messages.getString("dialog.TBXMakerDialog.openCSVItem"));
openCSVItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_OPEN_CSV_PATH).createImage());
openCSVItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
openFile();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
MenuItem exportTBXItem = new MenuItem(fileMenu, SWT.PUSH);
exportTBXItem.setText(Messages.getString("dialog.TBXMakerDialog.exportTBXItem"));
exportTBXItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_EXPORT_TBX_PATH).createImage());
exportTBXItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
export();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText(Messages.getString("dialog.TBXMakerDialog.exitItem"));
exitItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
close();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Menu taskMenu = new Menu(menu);
MenuItem taskItem = new MenuItem(menu, SWT.CASCADE);
taskItem.setText(Messages.getString("dialog.TBXMakerDialog.taskMenu"));
taskItem.setMenu(taskMenu);
MenuItem deleteColItem = new MenuItem(taskMenu, SWT.PUSH);
deleteColItem.setText(Messages.getString("dialog.TBXMakerDialog.deleteColItem"));
deleteColItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_DELETE_COLUMN_PATH).createImage());
deleteColItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
removeColumn();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
MenuItem colPropertyItem = new MenuItem(taskMenu, SWT.PUSH);
colPropertyItem.setText(Messages.getString("dialog.TBXMakerDialog.colPropertyItem"));
colPropertyItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_SET_COLUMN_PATH).createImage());
colPropertyItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setColumnType();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Menu helpMenu = new Menu(menu);
MenuItem helpItem = new MenuItem(menu, SWT.CASCADE);
helpItem.setText(Messages.getString("dialog.TBXMakerDialog.helpMenu"));
helpItem.setMenu(helpMenu);
MenuItem helpContentItem = new MenuItem(helpMenu, SWT.PUSH);
helpContentItem.setText(Messages.getString("dialog.TBXMakerDialog.helpContentItem"));
helpContentItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_HELP_PATH).createImage());
helpContentItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
displayHelp();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
MenuItem aboutItem = new MenuItem(helpMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.TBXMakerDialog.aboutItem"));
aboutItem.setImage(Activator.getImageDescriptor(PluginConstants.LOGO_TBXMAKER_MENU_PATH).createImage());
aboutItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
AboutDialog dialog = new AboutDialog(getShell(), Messages
.getString("dialog.TBXMakerDialog.aboutItemName"), imagePath, Messages
.getString("dialog.TBXMakerDialog.aboutItemVersion"));
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
/**
* 创建工具栏
* @param parent
* ;
*/
private void createToolBar(Composite parent) {
Composite cmpToolBar = new Composite(parent, SWT.None);
GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(3).equalWidth(false).applyTo(cmpToolBar);
cmpToolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
ToolBar toolBar = new ToolBar(cmpToolBar, SWT.NO_FOCUS | SWT.FLAT);
ToolItem openToolItem = new ToolItem(toolBar, SWT.PUSH);
openToolItem.setToolTipText(Messages.getString("dialog.TBXMakerDialog.openToolItem"));
openToolItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_OPEN_CSV_PATH).createImage());
openToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
openFile();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
ToolItem exporToolItem = new ToolItem(toolBar, SWT.PUSH);
exporToolItem.setToolTipText(Messages.getString("dialog.TBXMakerDialog.exporToolItem"));
exporToolItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_EXPORT_TBX_PATH).createImage());
exporToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
export();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
ToolItem deleteColToolItem = new ToolItem(toolBar, SWT.PUSH);
deleteColToolItem.setToolTipText(Messages.getString("dialog.TBXMakerDialog.deleteColToolItem"));
deleteColToolItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_DELETE_COLUMN_PATH).createImage());
deleteColToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
removeColumn();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
ToolItem setColToolItem = new ToolItem(toolBar, SWT.PUSH);
setColToolItem.setToolTipText(Messages.getString("dialog.TBXMakerDialog.setColToolItem"));
setColToolItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_SET_COLUMN_PATH).createImage());
setColToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setColumnType();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new Label(cmpToolBar, SWT.None)
.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
ToolBar helpToolBar = new ToolBar(cmpToolBar, SWT.NO_FOCUS | SWT.FLAT);
ToolItem helpToolItem = new ToolItem(helpToolBar, SWT.RIGHT);
helpToolItem.setToolTipText(Messages.getString("dialog.TBXMakerDialog.helpToolItem"));
helpToolItem.setImage(Activator.getImageDescriptor(PluginConstants.PIC_HELP_PATH).createImage());
helpToolItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
displayHelp();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
Composite cmpTemp = parent.getParent();
parent.dispose();
cmpTemp.layout();
}
private void displayHelp() {
String curLang = CommonFunction.getSystemLanguage();
StringBuffer sbHelp = new StringBuffer("help");
if (Util.isWindows()) {
sbHelp.append(File.separator).append("csv2tbxdoc").append(File.separator);
if (curLang.equalsIgnoreCase("zh")) {
sbHelp.append("tbxmaker_zh-cn.chm");
} else {
sbHelp.append("tbxmaker.chm");
}
Program.launch(PluginUtil.getConfigurationFilePath(sbHelp.toString()));
} else {
sbHelp.append(File.separator).append("csv2tbxdoc").append(File.separator);
if (curLang.equalsIgnoreCase("zh")) {
sbHelp.append("zh-cn");
} else {
sbHelp.append("en");
}
sbHelp.append(File.separator).append("toc.xml");
PluginHelpDialog dialog = new PluginHelpDialog(getShell(), PluginUtil.getConfigurationFilePath(sbHelp.toString()),
Messages.getString("dialog.TBXMakerDialog.helpDialogTitle"));
dialog.open();
}
}
/**
* 打开 CSV 文件 ;
*/
private void openFile() {
String[] templates = TBXTemplateUtil.getTemplateFiles(PluginUtil.getCataloguePath(),
PluginUtil.getTemplatePath());
CSVSettingDialog dialog = new CSVSettingDialog(getShell(), true, imagePath, templates);
if (dialog.open() == IDialogConstants.OK_ID) {
csvPath = dialog.getCsvPath();
colSeparator = dialog.getColSeparator();
textDelimiter = dialog.getTextDelimiter();
encoding = dialog.getEncoding();
lang = dialog.getLang();
xcsTemplate = dialog.getXcsTemplate();
try {
template = new TBXTemplateUtil(xcsTemplate, PluginUtil.getTemplatePath(), "");
cols = maxColumns();
if (cols < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TBXMakerDialog.msgTitle"),
Messages.getString("dialog.TBXMakerDialog.msg1"));
return;
}
rows = 0;
int width = (table.getClientArea().width - table.getBorderWidth() * 2 - table.getVerticalBar()
.getSize().x) / cols;
if (width < 100) {
width = 100;
}
table.removeAll();
int count = table.getColumnCount();
for (int i = 0; i < count; i++) {
table.getColumn(0).dispose();
}
for (int i = 0; i < cols; i++) {
TableColumn col = new TableColumn(table, SWT.NONE);
col.setData(new ColProperties("" + (i + 1))); //$NON-NLS-1$
table.getColumn(i).setWidth(width);
table.getColumn(i).setText("" + (i + 1)); //$NON-NLS-1$
}
fillTable();
table.layout(true);
lblRowCount
.setText(MessageFormat.format(Messages.getString("dialog.TBXMakerDialog.lblRowCount"), rows));
lblColCount
.setText(MessageFormat.format(Messages.getString("dialog.TBXMakerDialog.lblColCount"), cols));
} catch (IOException e) {
LOGGER.error(Messages.getString("dialog.TBXMakerDialog.logger1"), e);
} catch (Exception e) {
LOGGER.error(Messages.getString("dialog.TBXMakerDialog.logger1"), e);
}
}
}
/**
* 导出文件 ;
*/
private void export() {
if (cols < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TBXMakerDialog.msgTitle"),
Messages.getString("dialog.TBXMakerDialog.msg2"));
return;
}
String[] langs = getUserLangs();
if (langs.length < 1) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TBXMakerDialog.msgTitle"),
Messages.getString("dialog.TBXMakerDialog.msg3"));
return;
}
ExportDialog exportDialog = new ExportDialog(getShell(), csvPath);
if (exportDialog.open() == IDialogConstants.OK_ID) {
String exportFile = exportDialog.getFilePath();
if (exportFile == null) {
return;
}
try {
File f = new File(exportFile);
if (!f.exists() || f.isDirectory()) {
f.createNewFile();
}
output = new FileOutputStream(f);
rows = table.getItemCount();
writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //$NON-NLS-1$
writeString("<!DOCTYPE martif PUBLIC \"ISO 12200:1999A//DTD MARTIF core (DXFcdV04)//EN\" \"TBXcdv04.dtd\">\n"); //$NON-NLS-1$
writeString("<martif type=\"TBX\" xml:lang=\"" + lang + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
writeString("<martifHeader><fileDesc><sourceDesc><p>CSV to TBX Converter</p></sourceDesc></fileDesc>\n"); //$NON-NLS-1$
writeString("<encodingDesc><p type=\"DCSName\">" + template.getTemplateFileName() + "</p></encodingDesc>\n"); //$NON-NLS-1$ //$NON-NLS-2$
writeString("</martifHeader>\n<text>\n<body>\n"); //$NON-NLS-1$
for (int r = 0; r < rows; r++) {
TableItem item = table.getItem(r);
if (checkConcept(langs, item)) {
writeString("<termEntry id=\"" + createId() + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
writeConceptLevelProps(item);
for (int l = 0; l < langs.length; l++) {
if (checkTerm(langs[l], item)) {
writeString("<langSet id=\"" + createId() + "\" xml:lang=\"" + langs[l] + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
writeString("<tig>\n"); //$NON-NLS-1$
writeLangLevel(langs[l], item);
writeString("</tig>\n"); //$NON-NLS-1$
writeString("</langSet>\n"); //$NON-NLS-1$
}
}
writeString("</termEntry>\n"); //$NON-NLS-1$
}
}
writeString("</body>\n"); //$NON-NLS-1$
writeString("</text>\n"); //$NON-NLS-1$
writeString("</martif>"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TBXMakerDialog.msgTitle"),
Messages.getString("dialog.TBXMakerDialog.msg4"));
} catch (FileNotFoundException e) {
LOGGER.error(Messages.getString("dialog.TBXMakerDialog.logger2"), e);
} catch (IOException e) {
LOGGER.error(Messages.getString("dialog.TBXMakerDialog.logger2"), e);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
LOGGER.error(Messages.getString("dialog.TBXMakerDialog.logger2"), e);
}
}
}
}
/**
* 删除列 ;
*/
private void removeColumn() {
if (cols < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TBXMakerDialog.msgTitle"),
Messages.getString("dialog.TBXMakerDialog.msg2"));
return;
}
Vector<String> columns = new Vector<String>();
int count = table.getColumnCount();
for (int i = 0; i < count; i++) {
columns.add(table.getColumn(i).getText());
}
ColumnRemoveDialog removeDialog = new ColumnRemoveDialog(getShell(), columns, imagePath);
if (removeDialog.open() == IDialogConstants.OK_ID) {
Vector<String> columnVector = removeDialog.getColumnVector();
if (columnVector.size() == columns.size()) {
return;
}
for (int i = 0; i < count; i++) {
TableColumn col = table.getColumn(i);
boolean found = false;
for (int j = 0; j < columnVector.size(); j++) {
if (col.getText().equals(columnVector.get(j))) {
found = true;
break;
}
}
if (!found) {
table.getColumn(i).dispose();
count--;
i--;
}
}
lblColCount.setText(MessageFormat.format(
Messages.getString("dialog.TBXMakerDialog.lblColCount"), table.getColumnCount())); //$NON-NLS-1$
cols = table.getColumnCount();
int width = (table.getClientArea().width - table.getBorderWidth() * 2 - table.getVerticalBar().getSize().x)
/ cols;
if (width < 100) {
width = 100;
}
for (int i = 0; i < cols; i++) {
TableColumn column = table.getColumn(i);
column.setWidth(width);
}
}
}
/**
* 设置列属性 ;
*/
private void setColumnType() {
if (cols < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TBXMakerDialog.msgTitle"),
Messages.getString("dialog.TBXMakerDialog.msg2"));
return;
}
Vector<ColProperties> colTypes = new Vector<ColProperties>(cols);
for (int i = 0; i < cols; i++) {
colTypes.add((ColProperties) table.getColumn(i).getData());
}
ColumnTypeDialog selector = new ColumnTypeDialog(getShell(), colTypes, template, imagePath);
if (selector.open() == IDialogConstants.OK_ID) {
for (int i = 0; i < cols; i++) {
TableColumn col = table.getColumn(i);
ColProperties type = colTypes.get(i);
if (!type.getColName().equals("") && !type.getLanguage().equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
col.setText(type.getColName());
}
}
}
}
private void writeConceptLevelProps(TableItem item) throws IOException {
// Write concept level descrips
for (int c = 0; c < cols; c++) {
ColProperties properties = (ColProperties) table.getColumn(c).getData();
if (properties.getLevel().equals(ColProperties.conceptLevel)
&& properties.getPropName().equals(ColProperties.descripName)) {
String descrip = item.getText(c);
if (!descrip.trim().equals("")) { //$NON-NLS-1$
writeString("<descrip type=\"" + properties.propType + "\">" + TextUtil.cleanString(descrip).trim() + "</descrip>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
for (int c = 0; c < cols; c++) {
ColProperties properties = (ColProperties) table.getColumn(c).getData();
if (properties.getLevel().equals(ColProperties.conceptLevel)
&& properties.getPropName().equals(ColProperties.noteName)) {
String note = item.getText(c);
if (!note.trim().equals("")) { //$NON-NLS-1$
writeString("<note>" + TextUtil.cleanString(note).trim() + "</note>\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
private void writeLangLevelProps(String lang, TableItem item) throws IOException {
// Write concept level descrips
for (int c = 0; c < cols; c++) {
ColProperties properties = (ColProperties) table.getColumn(c).getData();
if (properties.getLevel().equals(ColProperties.langLevel)
&& properties.getPropName().equals(ColProperties.termNoteName)
&& properties.getLanguage().equals(lang)) {
String termNote = item.getText(c);
if (!termNote.trim().equals("")) { //$NON-NLS-1$
writeString("<termNote type=\"" + properties.propType + "\">" + TextUtil.cleanString(termNote).trim() + "</termNote>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
for (int c = 0; c < cols; c++) {
ColProperties properties = (ColProperties) table.getColumn(c).getData();
if (properties.getLevel().equals(ColProperties.langLevel)
&& properties.getPropName().equals(ColProperties.descripName)
&& properties.getLanguage().equals(lang)) {
String termNote = item.getText(c);
if (!termNote.trim().equals("")) { //$NON-NLS-1$
writeString("<descrip type=\"" + properties.propType + "\">" + TextUtil.cleanString(termNote).trim() + "</descrip>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
}
private void writeLangLevel(String lang, TableItem item) throws IOException {
// Write Term data
for (int c = 0; c < cols; c++) {
ColProperties properties = (ColProperties) table.getColumn(c).getData();
if (properties.getLevel().equals(ColProperties.langLevel)
&& properties.getPropName().equals(ColProperties.termName) && properties.getLanguage().equals(lang)) {
String term = item.getText(c);
writeString("<term>" + TextUtil.cleanString(term).trim() + "</term>\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
writeLangLevelProps(lang, item);
}
private String createId() {
Date now = new Date();
long lng = now.getTime();
// wait until we are in the next millisecond
// before leaving to ensure uniqueness
Date next = new Date();
while (next.getTime() == lng) {
next = null;
next = new Date();
}
return "_" + lng; //$NON-NLS-1$
}
private boolean checkConcept(String[] langs, TableItem item) {
for (int l = 0; l < langs.length; l++) {
if (checkTerm(langs[l], item)) {
return true;
}
}
return false;
}
/**
* This method check if the term contains valid text
* @param lang
* @param item
* @return
*/
private boolean checkTerm(String lang, TableItem item) {
// Write Term data
for (int c = 0; c < cols; c++) {
ColProperties properties = (ColProperties) table.getColumn(c).getData();
if (properties.getLevel().equals(ColProperties.langLevel)
&& properties.getPropName().equals(ColProperties.termName) && properties.getLanguage().equals(lang)) {
String term = item.getText(c);
return !term.trim().equals(""); //$NON-NLS-1$
}
}
return false;
}
private String[] getUserLangs() {
Hashtable<String, String> langTable = new Hashtable<String, String>();
for (int c = 0; c < cols; c++) {
ColProperties properties = (ColProperties) table.getColumn(c).getData();
if (properties.level.equals(ColProperties.langLevel)) {
langTable.put(properties.getLanguage(), ""); //$NON-NLS-1$
}
}
String[] result = new String[langTable.size()];
Enumeration<String> keys = langTable.keys();
int index = 0;
while (keys.hasMoreElements()) {
result[index] = keys.nextElement();
index++;
}
return result;
}
private void writeString(String string) throws UnsupportedEncodingException, IOException {
output.write(string.getBytes("UTF-8"));
}
private int maxColumns() throws IOException {
int max = 0;
InputStreamReader input = new InputStreamReader(new FileInputStream(csvPath), encoding);
BufferedReader buffer = new BufferedReader(input);
Hashtable<String, Integer> table1 = new Hashtable<String, Integer>();
String line = buffer.readLine();
while (line != null) {
int i = countColumns(line);
if (table1.containsKey("" + i)) {
int count = table1.get("" + i).intValue() + 1;
table1.put("" + i, new Integer(count));
} else {
table1.put("" + i, new Integer(1));
}
line = buffer.readLine();
}
Enumeration<String> e = table1.keys();
String key = "";
while (e.hasMoreElements()) {
String s = e.nextElement();
int value = table1.get(s).intValue();
if (value > max) {
max = value;
key = s;
}
}
return Integer.parseInt(key);
}
private int countColumns(String line) {
int size = line.length();
if (size == 0) {
return 0;
}
int count = 1;
boolean inDelimiters = false;
for (int i = 0; i < size; i++) {
String c = "" + line.charAt(i);
if (c.equals(textDelimiter)) {
inDelimiters = !inDelimiters;
}
if (!inDelimiters && c.equals(colSeparator)) {
count++;
}
}
return count;
}
private void fillTable() throws UnsupportedEncodingException, IOException {
InputStreamReader input = new InputStreamReader(new FileInputStream(csvPath), encoding);
BufferedReader buffer = new BufferedReader(input);
String line;
while ((line = buffer.readLine()) != null) {
createItems(line);
}
}
private void createItems(String line) {
int size = line.length();
if (size == 0) {
return;
}
if (countColumns(line) != cols) {
return;
}
StringBuffer buffer = new StringBuffer();
Vector<String> vector = new Vector<String>();
String[] strings = new String[cols];
boolean inDelimiters = false;
for (int i = 0; i < size; i++) {
String c = "" + line.charAt(i); //$NON-NLS-1$
if (c.equals(textDelimiter)) {
inDelimiters = !inDelimiters;
continue;
}
if (!inDelimiters && c.equals(colSeparator)) {
vector.add(buffer.toString());
buffer = null;
buffer = new StringBuffer();
continue;
}
buffer.append(c);
}
if (!buffer.toString().equals("")) { //$NON-NLS-1$
vector.add(buffer.toString());
}
for (int i = 0; i < vector.size(); i++) {
strings[i] = vector.get(i);
}
for (int i = vector.size(); i < cols; i++) {
strings[i] = ""; //$NON-NLS-1$
}
TableItem item = new TableItem(table, SWT.NONE);
item.setText(strings);
rows++;
}
@Override
protected boolean isResizable() {
return true;
}
/**
* 导出为 TBX 文件的对话框
* @author peason
* @version
* @since JDK1.6
*/
class ExportDialog extends Dialog {
/** 导出文件路径 */
private String filePath;
/** 路径文本框 */
private Text txtFile;
/**
* 构造方法
* @param parentShell
* @param filePath
* 默认导出路径
*/
protected ExportDialog(Shell parentShell, String filePath) {
super(parentShell);
this.filePath = filePath;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.TBXMakerDialog.ExportDialog.title"));
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout(3, false));
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(400, 50).grab(true, true).applyTo(tparent);
new Label(tparent, SWT.None).setText(Messages.getString("dialog.TBXMakerDialog.ExportDialog.lblTBX"));
txtFile = new Text(tparent, SWT.BORDER);
txtFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
txtFile.setEditable(false);
if (filePath != null) {
if (filePath.indexOf(".") != -1) {
txtFile.setText(filePath.substring(0, filePath.lastIndexOf(".")) + ".tbx");
} else {
txtFile.setText(filePath + ".tbx");
}
filePath = txtFile.getText();
}
Button btnBrowse = new Button(tparent, SWT.None);
btnBrowse.setText(Messages.getString("dialog.TBXMakerDialog.ExportDialog.btnBrowse"));
btnBrowse.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
dialog.setText(Messages.getString("dialog.TBXMakerDialog.ExportDialog.dialogTitle"));
String extensions[] = { "*.tbx", "*" }; //$NON-NLS-1$ //$NON-NLS-2$
String names[] = {
Messages.getString("dialog.TBXMakerDialog.ExportDialog.names1"), Messages.getString("dialog.TBXMakerDialog.ExportDialog.names2") }; //$NON-NLS-1$ //$NON-NLS-2$
dialog.setFilterNames(names);
dialog.setFilterExtensions(extensions);
String fileSep = System.getProperty("file.separator");
if (txtFile.getText() != null && !txtFile.getText().trim().equals("")) {
dialog.setFilterPath(txtFile.getText().substring(0, txtFile.getText().lastIndexOf(fileSep)));
dialog.setFileName(txtFile.getText().substring(txtFile.getText().lastIndexOf(fileSep) + 1));
} else {
dialog.setFilterPath(System.getProperty("user.home"));
}
filePath = dialog.open();
if (filePath != null) {
txtFile.setText(filePath);
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
return tparent;
}
/**
* 获得导出路径
* @return ;
*/
public String getFilePath() {
return filePath;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.OK_ID).setText(Messages.getString("dialog.TBXMakerDialog.ok"));
}
}
}
| 31,161 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TMXValidatorDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/TMXValidatorDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.StringTokenizer;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.TMXValidator;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 插件TMX Validator,
* @author robert 2012-03-14
* @version
* @since JDK1.6
*/
public class TMXValidatorDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(TMXValidatorDialog.class);
private String openFilePath;
private String clearCharPath;
private StyledText styledText;
private Color red;
private Cursor cursorWait = new Cursor(Display.getDefault(), SWT.CURSOR_WAIT);
private Cursor cursorArrow = new Cursor(Display.getDefault(), SWT.CURSOR_ARROW);
private String imagePath;
public TMXValidatorDialog(Shell parentShell) {
super(parentShell);
openFilePath = PluginUtil.getAbsolutePath(PluginConstants.PIC_OPEN_CSV_PATH);
clearCharPath = PluginUtil.getAbsolutePath(PluginConstants.PIC_clearChar_PATH);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.TMXValidatorDialog.title")); //$NON-NLS-1$
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_TMXVALIDATOR_PATH);
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
parent.dispose();
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridDataFactory.fillDefaults().grab(true, true).hint(500, 450).applyTo(tparent);
GridLayoutFactory.fillDefaults().spacing(0, 0).extendedMargins(8, 8, 0, 8).applyTo(tparent);
createMenu(tparent);
createToolBar(tparent);
styledText = new StyledText(tparent, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(100, 100).grab(true, true).applyTo(styledText);
styledText.setText("");
tparent.layout();
getShell().layout();
return tparent;
}
private void createMenu(Composite tparent) {
Menu menuBar = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menuBar);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
// 文件菜单
Menu fileMenu = new Menu(menuBar);
MenuItem fileItem = new MenuItem(menuBar, SWT.CASCADE);
fileItem.setText(Messages.getString("dialog.TMXValidatorDialog.fileMenu"));
fileItem.setMenu(fileMenu);
MenuItem openFileItem = new MenuItem(fileMenu, SWT.PUSH);
openFileItem.setText(Messages.getString("dialog.TMXValidatorDialog.openFileItem"));
openFileItem.setImage(new Image(Display.getDefault(), openFilePath));
openFileItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openFile();
}
});
MenuItem clearCharItem = new MenuItem(fileMenu, SWT.PUSH);
clearCharItem.setText(Messages.getString("dialog.TMXValidatorDialog.clearCharItem"));
clearCharItem.setImage(new Image(Display.getDefault(), clearCharPath));
clearCharItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
cleanCharacters();
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem quitItem = new MenuItem(fileMenu, SWT.PUSH);
quitItem.setText(Messages.getString("dialog.TMXValidatorDialog.quitItem"));
quitItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
close();
}
});
// 帮助菜单
Menu helpMenu = new Menu(menuBar);
MenuItem helpItem = new MenuItem(menuBar, SWT.CASCADE);
helpItem.setText(Messages.getString("dialog.TMXValidatorDialog.helpMenu"));
helpItem.setMenu(helpMenu);
MenuItem aboutItem = new MenuItem(helpMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.TMXValidatorDialog.aboutItem"));
String aboutPath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_TMXVALIDATOR_MENU_PATH);
aboutItem.setImage(new Image(Display.getDefault(), aboutPath));
aboutItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
AboutDialog dialog = new AboutDialog(getShell(), Messages
.getString("dialog.TMXValidatorDialog.aboutItemName"), imagePath, Messages
.getString("dialog.TMXValidatorDialog.version"));
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
private void createToolBar(Composite tparent) {
Composite toolBarCmp = new Composite(tparent, SWT.NONE);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(toolBarCmp);
GridLayoutFactory.fillDefaults().numColumns(1).applyTo(toolBarCmp);
ToolBar toolBar = new ToolBar(toolBarCmp, SWT.NO_FOCUS | SWT.FLAT);
ToolItem openItem = new ToolItem(toolBar, SWT.PUSH);
openItem.setToolTipText(Messages.getString("dialog.TMXValidatorDialog.openItem"));
openItem.setImage(new Image(Display.getDefault(), openFilePath));
openItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openFile();
}
});
ToolItem clearCharsItem = new ToolItem(toolBar, SWT.PUSH);
clearCharsItem.setImage(new Image(Display.getDefault(), clearCharPath));
clearCharsItem.setToolTipText(Messages.getString("dialog.TMXValidatorDialog.clearCharsItem"));
clearCharsItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
cleanCharacters();
}
});
}
/**
* 打开文件
*/
private void openFile() {
FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
String[] extensions = { "*.tmx", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(extensions);
String[] names = { Messages.getString("dialog.TMXValidatorDialog.names1"),
Messages.getString("dialog.TMXValidatorDialog.names2") };
fd.setFilterNames(names);
String name = fd.open();
if (name != null) {
validate(name);
}
}
private void validate(String tmxLocation) {
getShell().setCursor(cursorWait);
styledText.setText("");
TMXValidator validator = new TMXValidator(tmxLocation, getShell());
validator.validate(tmxLocation, styledText);
getShell().setCursor(cursorArrow);
}
private void cleanCharacters() {
FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
String[] extensions = { "*.tmx", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(extensions);
String[] names = { Messages.getString("dialog.TMXValidatorDialog.names1"),
Messages.getString("dialog.TMXValidatorDialog.names2") };
fd.setFilterNames(names);
String name = fd.open();
if (name != null) {
red = Display.getDefault().getSystemColor(SWT.COLOR_RED);
styledText.setText("");
styledText.append(Messages.getString("dialog.TMXValidatorDialog.styledText1"));
getShell().setCursor(cursorWait);
try {
} catch (Exception e) {
LOGGER.error("", e);
String errorTip = e.getMessage();
if (errorTip == null) {
errorTip = MessageFormat.format(Messages.getString("dialog.TMXValidatorDialog.msg1"), name);
}
StyleRange range = new StyleRange(styledText.getText().length(), errorTip.length(), red, null);
styledText.append(errorTip);
styledText.setStyleRange(range);
}
styledText.append(Messages.getString("dialog.TMXValidatorDialog.styledText2"));
getShell().setCursor(cursorArrow);
}
}
void clean(String name) throws Exception {
FileInputStream stream = new FileInputStream(name);
String encoding = getXMLEncoding(name);
InputStreamReader input = new InputStreamReader(stream, encoding);
BufferedReader buffer = new BufferedReader(input);
FileOutputStream output = new FileOutputStream(name + ".tmp"); //$NON-NLS-1$
String line = buffer.readLine();
while (line != null) {
line = validChars(line) + "\n"; //$NON-NLS-1$
output.write(line.getBytes(encoding));
line = buffer.readLine();
}
output.close();
input.close();
String backup = name + ".bak"; //$NON-NLS-1$
if (name.indexOf(".") != -1 && name.lastIndexOf(".") < name.length()) {
backup = name.substring(0, name.lastIndexOf(".")) + ".~" + name.substring(name.lastIndexOf(".") + 1);
}
File f = new File(backup);
if (f.exists()) {
f.delete();
}
File original = new File(name);
original.renameTo(f);
File ok = new File(name + ".tmp"); //$NON-NLS-1$
original = null;
original = new File(name);
ok.renameTo(original);
}
private static String getXMLEncoding(String fileName) throws Exception {
// return UTF-8 as default
String result = "UTF-8"; //$NON-NLS-1$
// check if there is a BOM (byte order mark)
// at the start of the document
FileInputStream inputStream = new FileInputStream(fileName);
byte[] array = new byte[2];
inputStream.read(array);
inputStream.close();
byte[] lt = "<".getBytes(); //$NON-NLS-1$
byte[] feff = { -1, -2 };
byte[] fffe = { -2, -1 };
if (array[0] != lt[0]) {
// there is a BOM, now check the order
if (array[0] == fffe[0] && array[1] == fffe[1]) {
return "UTF-16BE"; //$NON-NLS-1$
}
if (array[0] == feff[0] && array[1] == feff[1]) {
return "UTF-16LE"; //$NON-NLS-1$
}
}
// check declared encoding
FileReader input = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(input);
String line = buffer.readLine();
input.close();
if (line.startsWith("<?")) { //$NON-NLS-1$
line = line.substring(2, line.indexOf("?>")); //$NON-NLS-1$
line = line.replaceAll("\'", "\""); //$NON-NLS-1$ //$NON-NLS-2$
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.startsWith("encoding")) { //$NON-NLS-1$
result = token.substring(token.indexOf("\"") + 1, token.lastIndexOf("\"")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
if (result.equals("utf-8")) { //$NON-NLS-1$
result = "UTF-8"; //$NON-NLS-1$
}
return result;
}
private String validChars(String input) {
// Valid: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
// [#x10000-#x10FFFF]
// Discouraged: [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
//
StringBuffer buffer = new StringBuffer();
char c;
int length = input.length();
for (int i = 0; i < length; i++) {
c = input.charAt(i);
if ((c == '\t' || c == '\n' || c == '\r' || (c >= '\u0020' && c <= '\uD7DF') || (c >= '\uE000' && c <= '\uFFFD'))) {
// normal character
buffer.append(c);
} else if ((c >= '\u007F' && c <= '\u0084') || (c >= '\u0086' && c <= '\u009F')
|| (c >= '\uFDD0' && c <= '\uFDDF')) {
// Control character
buffer.append("&#x" + Integer.toHexString(c) + ";"); //$NON-NLS-1$ //$NON-NLS-2$
} else if ((c >= '\uDC00' && c <= '\uDFFF') || (c >= '\uD800' && c <= '\uDBFF')) {
// Multiplane character
buffer.append(input.substring(i, i + 1));
}
}
return buffer.toString();
}
@Override
public boolean close() {
if(cursorWait != null && !cursorWait.isDisposed()){
cursorWait.dispose();
}
if(cursorArrow != null && !cursorArrow.isDisposed()){
cursorArrow.dispose();
}
return super.close();
}
}
| 12,718 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
HelpSearchDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/HelpSearchDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
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.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 peason
* @version
* @since JDK1.6
*/
public class HelpSearchDialog extends Dialog {
boolean cancelled;
boolean caseSensitive;
String searchText;
public HelpSearchDialog(Shell parent) {
super(parent);
setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.HelpSearchDialog.title"));
}
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout());
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(tparent);
Composite top = new Composite(tparent, SWT.NONE);
top.setLayout(new GridLayout(2, false));
top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
Label lblSearch = new Label(top, SWT.NONE);
lblSearch.setText(Messages.getString("dialog.HelpSearchDialog.lblSearch"));
final Text text = new Text(top, SWT.BORDER);
GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
data.widthHint = 250;
text.setLayoutData(data);
searchText = "";
text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent arg0) {
searchText = text.getText();
}
});
final Button btnSensitive = new Button(tparent, SWT.CHECK);
btnSensitive.setText(Messages.getString("dialog.HelpSearchDialog.btnSensitive"));
btnSensitive.setSelection(true);
caseSensitive = true;
btnSensitive.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
caseSensitive = btnSensitive.getSelection();
}
});
return tparent;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.OK_ID).setText(Messages.getString("dialog.HelpSearchDialog.ok"));
}
public String getText() {
return searchText;
}
public boolean isSensitive() {
return caseSensitive;
}
}
| 2,928 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TMX2TXTConverterDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/TMX2TXTConverterDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
import net.heartsome.cat.ts.util.ProgressIndicatorManager;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.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.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.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
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.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
/**
* 插件TMX to TXT Converter
* @author robert 2012-03-10
* @version
* @since JDK1.6 备注:--robert undone (没有完成帮助文档的完善,关于获取seg节点下的内容的问题,VTD中有BUG未解决);
*/
public class TMX2TXTConverterDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(TMX2TXTConverterDialog.class);
private Text tmxTxt;
private Text txtTxt;
private VTDNav vn;
private FileOutputStream output;
/** TMX文件TU节点的个数 */
private int tuNodesCount;
/** 进度条的前进刻度 */
private int workInterval = 10;
private String imagePath;
public TMX2TXTConverterDialog(Shell parentShell) {
super(parentShell);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.TMX2TXTConverterDialog.title"));
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_TMX2TXTCONVERTER_PATH);
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.OK_ID).setText(Messages.getString("dialog.TMX2TXTConverterDialog.ok"));
getButton(IDialogConstants.CANCEL_ID).setText(Messages.getString("dialog.TMX2TXTConverterDialog.cancel"));
parent.layout();
getDialogArea().getParent().layout();
getShell().layout();
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridDataFactory.fillDefaults().grab(true, true).hint(450, 190).applyTo(tparent);
createMenu(tparent);
createContent(tparent);
tparent.layout();
getShell().layout();
return tparent;
}
@Override
protected void okPressed() {
convert();
super.okPressed();
}
private void createMenu(Composite tparent) {
Menu menuBar = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menuBar);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
// 文件菜单
Menu fileMenu = new Menu(menuBar);
MenuItem fileItem = new MenuItem(menuBar, SWT.CASCADE);
fileItem.setText(Messages.getString("dialog.TMX2TXTConverterDialog.fileMenu"));
fileItem.setMenu(fileMenu);
MenuItem quitItem = new MenuItem(fileMenu, SWT.PUSH);
quitItem.setText(Messages.getString("dialog.TMX2TXTConverterDialog.quitItem"));
quitItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
close();
}
});
// 帮助菜单
Menu helpMenu = new Menu(menuBar);
MenuItem helpItem = new MenuItem(menuBar, SWT.CASCADE);
helpItem.setText(Messages.getString("dialog.TMX2TXTConverterDialog.helpMenu"));
helpItem.setMenu(helpMenu);
MenuItem aboutItem = new MenuItem(helpMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.TMX2TXTConverterDialog.aboutItem"));
String aboutPath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_TMX2TXTCONVERTER_MENU_PATH);
aboutItem.setImage(new Image(Display.getDefault(), aboutPath));
aboutItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
AboutDialog dialog = new AboutDialog(getShell(), Messages
.getString("dialog.TMX2TXTConverterDialog.aboutItemName"), imagePath, Messages
.getString("dialog.TMX2TXTConverterDialog.version"));
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
private void createContent(Composite tparent) {
Composite contentCmp = new Composite(tparent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(contentCmp);
GridLayoutFactory.fillDefaults().numColumns(3).applyTo(contentCmp);
GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false);
Label tmxLbl = new Label(contentCmp, SWT.NONE);
tmxLbl.setText(Messages.getString("dialog.TMX2TXTConverterDialog.tmxLbl"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(tmxLbl);
tmxTxt = new Text(contentCmp, SWT.BORDER);
tmxTxt.setLayoutData(textData);
Button tmxBrowseBtn = new Button(contentCmp, SWT.NONE);
tmxBrowseBtn.setText(Messages.getString("dialog.TMX2TXTConverterDialog.tmxBrowseBtn"));
tmxBrowseBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
selecteTMXFile();
}
});
Label txtLbl = new Label(contentCmp, SWT.NONE);
txtLbl.setText(Messages.getString("dialog.TMX2TXTConverterDialog.txtLbl"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(txtLbl);
txtTxt = new Text(contentCmp, SWT.BORDER);
txtTxt.setLayoutData(textData);
Button txtBrowseBtn = new Button(contentCmp, SWT.NONE);
txtBrowseBtn.setText(Messages.getString("dialog.TMX2TXTConverterDialog.txtBrowseBtn"));
txtBrowseBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
selecteTXTFile();
}
});
}
/**
* 选择TMX文件
*/
private void selecteTMXFile() {
FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
String[] extensions = { "*.tmx", "*.*" };
fd.setFilterExtensions(extensions);
String[] names = { Messages.getString("dialog.TMX2TXTConverterDialog.TMXNames1"),
Messages.getString("dialog.TMX2TXTConverterDialog.TMXNames2") };
fd.setFilterNames(names);
String file = fd.open();
if (file != null) {
tmxTxt.setText(file);
if (txtTxt.getText().equals("")) {
txtTxt.setText(file.substring(0, file.lastIndexOf(".")) + ".txt");
}
}
}
/**
* 选择TXT文件 ;
*/
private void selecteTXTFile() {
FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
String[] extensions = { "*.txt", "*.*" };
fd.setFilterExtensions(extensions);
String[] names = { Messages.getString("dialog.TMX2TXTConverterDialog.TXTNames1"),
Messages.getString("dialog.TMX2TXTConverterDialog.TXTNames2") };
fd.setFilterNames(names);
String file = fd.open();
if (file != null) {
txtTxt.setText(file);
}
}
/**
* 开始转换
*/
private void convert() {
final String tmxLocation = tmxTxt.getText();
if (tmxLocation.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TMX2TXTConverterDialog.msgTitle"),
Messages.getString("dialog.TMX2TXTConverterDialog.msg1"));
return;
}
final String txtLocation = txtTxt.getText();
if (txtLocation.equals("")) { //$NON-NLS-1$
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TMX2TXTConverterDialog.msgTitle"),
Messages.getString("dialog.TMX2TXTConverterDialog.msg2"));
return;
}
File txtFile = new File(txtLocation);
if (txtFile.exists()) {
boolean response = MessageDialog.openConfirm(getShell(),
Messages.getString("dialog.TMX2TXTConverterDialog.msgTitle2"),
MessageFormat.format(Messages.getString("dialog.TMX2TXTConverterDialog.msg3"), txtLocation));
if (!response) {
return;
}
} else if (!txtFile.getParentFile().exists()) {
txtFile.getParentFile().mkdirs();
}
Job job = new Job(Messages.getString("dialog.TMX2TXTConverterDialog.job")) {
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask(Messages.getString("dialog.TMX2TXTConverterDialog.task"), 10);
// 先解析文件,花费一格
int openResult = openFile(tmxLocation, monitor);
if (openResult == 0) {
return Status.CANCEL_STATUS;
} else if (openResult == -2) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TMX2TXTConverterDialog.msgTitle"),
Messages.getString("dialog.TMX2TXTConverterDialog.msg4"));
}
});
return Status.CANCEL_STATUS;
} else if (openResult == -1) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TMX2TXTConverterDialog.msgTitle"),
Messages.getString("dialog.TMX2TXTConverterDialog.msg5"));
}
});
return Status.CANCEL_STATUS;
}
if (!validVersion(tmxLocation)) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TMX2TXTConverterDialog.msgTitle"),
Messages.getString("dialog.TMX2TXTConverterDialog.msg6"));
}
});
return Status.CANCEL_STATUS;
}
if ((tuNodesCount = getTUCount(tmxLocation)) <= 0) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TMX2TXTConverterDialog.msgTitle"),
Messages.getString("dialog.TMX2TXTConverterDialog.msg7"));
}
});
return Status.CANCEL_STATUS;
}
try {
output = new FileOutputStream(txtLocation);
byte[] bom = new byte[3];
bom[0] = (byte) 0xEF;
bom[1] = (byte) 0xBB;
bom[2] = (byte) 0xBF;
output.write(bom);
writeHeader();
monitor.worked(1);
IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 8,
SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
return processTU(tmxLocation, txtLocation, subMonitor);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("", e);
}
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 file
* @param monitor
* @param totalWork
* @return ;
*/
private int openFile(String tmxLocation, IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
// 解析文件并获取索引
VTDGen vg = new VTDGen();
if (vg.parseFile(tmxLocation, true)) {
vn = vg.getNav();
if (monitor.isCanceled()) {
return 0; // 终止程序的执行
}
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/tmx");
if (ap.evalXPath() == -1) {
return -2; // 解析的文件不符合TMX标准
}
monitor.worked(1);
return 1; // TMX文件解析成功
} else {
return -1; // 解析失败
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("", e);
}
return -1;
}
/**
* 验证TMX文件是不是1.4版本的,如果不是,退出程序
* @param txmLocation
* @return ;
*/
private boolean validVersion(String tmxLocation) {
Assert.isNotNull(vn,
MessageFormat.format(Messages.getString("dialog.TMX2TXTConverterDialog.msg8"), tmxLocation));
AutoPilot ap = new AutoPilot(vn);
try {
ap.selectXPath("/tmx");
if (ap.evalXPath() != -1) {
int index;
if ((index = vn.getAttrVal("version")) != -1) {
if ("1.4".equals(vn.toString(index))) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("", e);
}
return false;
}
private void writeHeader() throws UnsupportedEncodingException, IOException {
writeString("<TWBExportFile version=\"7.0\" generator=\"TMX to TXT Converter\" build=\"1.0-1\">\r\n"); //$NON-NLS-1$
writeString("<RTF Preamble>\r\n"); //$NON-NLS-1$
writeString("<FontTable>\r\n"); //$NON-NLS-1$
writeString("{\\fonttbl \r\n"); //$NON-NLS-1$
writeString("{\\f1 \\fmodern\\fprq1 \\fcharset0 Courier New;}\r\n"); //$NON-NLS-1$
writeString("{\\f2 \\fswiss\\fprq2 \\fcharset0 Arial;}\r\n"); //$NON-NLS-1$
writeString("{\\f3 \\fcharset128 MS Mincho;}}\r\n"); //$NON-NLS-1$
writeString("{\\f4 \\fcharset134 SimSun;}\r\n"); //$NON-NLS-1$
writeString("{\\f5 \\fcharset136 MingLiU;}\r\n"); //$NON-NLS-1$
writeString("{\\f6 \\fcharset129 Gulim;}\r\n"); //$NON-NLS-1$
writeString("{\\f7 \\froman\\fprq2 \\fcharset238 Times New Roman CE;}\r\n"); //$NON-NLS-1$
writeString("{\\f8 \\froman\\fprq2 \\fcharset204 Times New Roman Cyr;}\r\n"); //$NON-NLS-1$
writeString("{\\f9 \\froman\\fprq2 \\fcharset161 Times New Roman Greek;}\r\n"); //$NON-NLS-1$
writeString("{\\f10 \\froman\\fprq2 \\fcharset162 Times New Roman Tur;}\r\n"); //$NON-NLS-1$
writeString("{\\f11 \\froman\\fprq2 \\fcharset177 Times New Roman (Hebrew);}\r\n"); //$NON-NLS-1$
writeString("{\\f12 \\froman\\fprq2 \\fcharset178 Times New Roman (Arabic);}\r\n"); //$NON-NLS-1$
writeString("{\\f13 \\froman\\fprq2 \\fcharset186 Times New Roman Baltic;}\r\n"); //$NON-NLS-1$
writeString("{\\f14 \\froman\\fprq2 \\fcharset222 Angsana New;}\r\n"); //$NON-NLS-1$
writeString("<StyleSheet>\r\n"); //$NON-NLS-1$
writeString("{\\stylesheet \r\n"); //$NON-NLS-1$
writeString("{\\St \\s0 {\\StN Normal}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs1 {\\StB \\v\\f1\\fs24\\sub\\cf12 }{\\StN tw4winMark}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs2 {\\StB \\cf4\\fs40\\f1 }{\\StN tw4winError}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs3 {\\StB \\f1\\cf11\\lang1024 }{\\StN tw4winPopup}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs4 {\\StB \\f1\\cf10\\lang1024 }{\\StN tw4winJump}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs5 {\\StB \\f1\\cf15\\lang1024 }{\\StN tw4winExternal}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs6 {\\StB \\f1\\cf6\\lang1024 }{\\StN tw4winInternal}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs7 {\\StB \\cf2 }{\\StN tw4winTerm}}\r\n"); //$NON-NLS-1$
writeString("{\\St \\cs8 {\\StB \\f1\\cf13\\lang1024 }{\\StN DO_NOT_TRANSLATE}}}\r\n"); //$NON-NLS-1$
writeString("</RTF Preamble>\r\n"); //$NON-NLS-1$
}
private void writeString(String string) throws UnsupportedEncodingException, IOException {
output.write(string.getBytes("UTF-8"));
}
/**
* 开始获取tmx中的tu节点进行添加到TXT文件中
* @param txtLocation
* @param monitor
* ;
*/
private IStatus processTU(String tmxLocation, String txtLocation, IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", tuNodesCount % workInterval == 0 ? tuNodesCount / workInterval : tuNodesCount
/ workInterval + 1);
try {
int travelIndex = 0;
AutoPilot ap = new AutoPilot(vn);
AutoPilot tuvAp = new AutoPilot(vn);
AutoPilot segAp = new AutoPilot(vn);
AutoPilot segChildAp = new AutoPilot(vn);
Assert.isNotNull(vn,
MessageFormat.format(Messages.getString("dialog.TMX2TXTConverterDialog.msg8"), tmxLocation));
ap.selectXPath("/tmx/body/tu");
segAp.selectXPath("./seg");
segChildAp.selectXPath("./*");
while (ap.evalXPath() != -1) {
travelIndex++;
writeString("<TrU>\r\n");
String creationdate = getAttributeValue("creationdate", "");
if (!creationdate.equals("")) {
writeString("<CrD>" + creationdate.substring(6, 8) + creationdate.substring(4, 6)
+ creationdate.substring(0, 4) + ", " + creationdate.substring(9, 11) + ":"
+ creationdate.substring(11, 13) + ":" + creationdate.substring(13, 15) + "\r\n");
}
String creationid = getAttributeValue("creationid", "");
if (creationid.equals("")) {
writeString("<CrU>" + System.getProperty("user.name").replaceAll("\\s", "") + "\r\n");
} else {
writeString("<CrU>" + creationid + "\r\n");
}
String changedate = getAttributeValue("changedate", "");
if (!changedate.equals("")) {
writeString("<ChD>" + changedate.substring(6, 8) + changedate.substring(4, 6)
+ changedate.substring(0, 4) + ", " + changedate.substring(9, 11) + ":"
+ changedate.substring(11, 13) + ":" + changedate.substring(13, 15) + "\r\n");
}
String changeid = getAttributeValue("changeid", "");
if (!changeid.equals("")) {
writeString("<ChU>" + changeid + "\r\n");
}
// 开始遍历TU节点的子节点:tuv
tuvAp.selectXPath("./tuv");
while (tuvAp.evalXPath() != -1) {
String lang = getAttributeValue("xml:lang", null).toLowerCase();
String font = "\\f1";
if (lang.matches("ja.*")) {
// Japanese
font = "\\f3";
}
if (lang.matches("zh.*")) {
// Simplified Chinese
font = "\\f4";
}
if (lang.matches("zh.tw")) {
// Traditional Chinese
font = "\\f5";
}
if (lang.matches("ko.*")) {
// Korean
font = "\\f6";
}
if (lang.matches("pl.*") || lang.matches("cs.*") || lang.matches("bs.*") || lang.matches("sk.*")
|| lang.matches("sl.*") || lang.matches("hu.*")) {
// Eastern European
font = "\\f7";
}
if (lang.matches("ru.*") || lang.matches("bg.*") || lang.matches("mk.*") || lang.matches("sr.*")
|| lang.matches("be.*") || lang.matches("uk.*")) {
// Russian
font = "\\f8";
}
if (lang.matches("el.*")) {
// Greek
font = "\\f9";
}
if (lang.matches("tr.*")) {
// Turkish
font = "\\f10";
}
if (lang.matches("he.*") || lang.matches("yi.*")) {
// Hebrew
font = "\\f11";
}
if (lang.matches("ar.*")) {
// Arabic
font = "\\f12";
}
if (lang.matches("lv.*") || lang.matches("lt.*")) {
// Baltic
font = "\\f13";
}
if (lang.matches("th.*")) {
// Thai
font = "\\f14";
}
// 开始遍历tuv节点的子节点seg
StringBuffer segSB = new StringBuffer();
vn.push();
if (segAp.evalXPath() != -1) {
if (vn.getText() != -1) {
segSB.append(cleanString(vn.toString(vn.getText())));
} else {
vn.push();
while (segChildAp.evalXPath() != -1) {
String nodeName = vn.toString(vn.getCurrentIndex());
if ("ph".equals(nodeName) || "bpt".equals(nodeName) || "ept".equals(nodeName)) {
segSB.append("{\\cs6" + font + "\\cf6\\lang1024 ");
String value = "";
if (vn.getText() != -1) {
value = vn.toString(vn.getText());
}
segSB.append(cleanString(value));
segSB.append("}");
} else {
System.out.println("vn.getTokenType(vn.getCurrentIndex()) = "
+ vn.getTokenType(vn.getCurrentIndex()));
}
}
vn.pop();
}
writeString("<Seg L=" + lang.toUpperCase() + ">" + segSB.toString() + "\r\n");
}
vn.pop();
segAp.resetXPath();
segChildAp.resetXPath();
}
writeString("</TrU>\r\n");
if (!monitorWork(monitor, travelIndex, false)) {
return Status.CANCEL_STATUS;
}
}
if (!monitorWork(monitor, travelIndex, true)) {
return Status.CANCEL_STATUS;
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("", e);
}
monitor.done();
return Status.OK_STATUS;
}
/**
* 获取属性值
* @param attributeName
* @param defaultValue
* @return
* @throws NavException
* ;
*/
private String getAttributeValue(String attributeName, String defaultValue) throws NavException {
int index = vn.getAttrVal(attributeName);
if (index != -1) {
return vn.toString(index);
}
return defaultValue;
}
/**
* 获取TMX文件的TU节点的总数
* @return ;
*/
private int getTUCount(String tmxLocation) {
AutoPilot ap = new AutoPilot(vn);
Assert.isNotNull(vn,
MessageFormat.format(Messages.getString("dialog.TMX2TXTConverterDialog.msg8"), tmxLocation));
try {
ap.selectXPath("count(/tmx/body/tu)");
return (int) ap.evalXPathToNumber();
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("", e);
}
return 0;
}
private String cleanString(String value) {
value = replaceToken(value, "\\", "\\\'5C"); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2002', "\\enspace "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2003', "\\emspace "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2005', "\\qmspace "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2014', "\\emdash "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2013', "\\endash "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2018', "\\lquote "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2019', "\\rquote "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u201C', "\\ldblquote "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u201D', "\\rdblquote "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "{", "\\{"); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "}", "\\}"); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u0009', "\\tab "); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u00A0', "\\~"); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u2011', "\\_"); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "" + '\u00AD', "\\-"); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "\n", ""); //$NON-NLS-1$ //$NON-NLS-2$
value = replaceToken(value, "\r", ""); //$NON-NLS-1$ //$NON-NLS-2$
return value;
}
private String replaceToken(String string, String token, String newText) {
int index = string.indexOf(token);
while (index != -1) {
String before = string.substring(0, index);
String after = string.substring(index + token.length());
if (token.endsWith(" ") && after.length() > 0 && Character.isSpaceChar(after.charAt(0))) { //$NON-NLS-1$
after = after.substring(1);
}
string = before + newText + after;
index = string.indexOf(token, index + newText.length());
}
return string;
}
/**
* 进度条前进处理类,若返回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;
}
}
| 24,762 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
JavaPropertiesViewerDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/JavaPropertiesViewerDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.Vector;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.TableViewerLabelProvider;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.viewers.ArrayContentProvider;
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.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 插件java properties viewer
* @author robert 2012-03-10
* @version
* @since JDK1.6 备注:--robert undone (没有完成帮助文档的完善);
*/
public class JavaPropertiesViewerDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaPropertiesViewerDialog.class);
private TableViewer tableViewer;
private Table table;
private String openFilePath;
private String imagePath;
public JavaPropertiesViewerDialog(Shell parentShell) {
super(parentShell);
openFilePath = PluginUtil.getAbsolutePath(PluginConstants.PIC_OPEN_CSV_PATH);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.JavaPropertiesViewerDialog.title"));
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_PROERTIESVIEWER_PATH);
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
// super.createButtonsForButtonBar(parent);
parent.dispose();
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridDataFactory.fillDefaults().grab(true, true).hint(800, 700).applyTo(tparent);
GridLayoutFactory.fillDefaults().spacing(0, 0).extendedMargins(8, 8, 0, 8).applyTo(tparent);
createMenu(tparent);
createToolBar(tparent);
createTableViewer(tparent);
tparent.layout();
getShell().layout();
return tparent;
}
private void createMenu(Composite tparent) {
Menu menuBar = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menuBar);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
// 文件菜单
Menu fileMenu = new Menu(menuBar);
MenuItem fileItem = new MenuItem(menuBar, SWT.CASCADE);
fileItem.setText(Messages.getString("dialog.JavaPropertiesViewerDialog.fileMenu"));
fileItem.setMenu(fileMenu);
MenuItem openFileItem = new MenuItem(fileMenu, SWT.PUSH);
openFileItem.setText(Messages.getString("dialog.JavaPropertiesViewerDialog.openFileItem"));
openFileItem.setImage(new Image(Display.getDefault(), openFilePath));
openFileItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openFile();
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem quitItem = new MenuItem(fileMenu, SWT.PUSH);
quitItem.setText(Messages.getString("dialog.JavaPropertiesViewerDialog.quitItem"));
quitItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
close();
}
});
// 帮助菜单
Menu helpMenu = new Menu(menuBar);
MenuItem helpItem = new MenuItem(menuBar, SWT.CASCADE);
helpItem.setText(Messages.getString("dialog.JavaPropertiesViewerDialog.helpMenu"));
helpItem.setMenu(helpMenu);
MenuItem aboutItem = new MenuItem(helpMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.JavaPropertiesViewerDialog.aboutItem"));
String aboutPath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_PROERTIESVIEWER_MENU_PATH);
aboutItem.setImage(new Image(Display.getDefault(), aboutPath));
aboutItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
AboutDialog dialog = new AboutDialog(getShell(), Messages
.getString("dialog.JavaPropertiesViewerDialog.aboutItemName"), imagePath, Messages
.getString("dialog.JavaPropertiesViewerDialog.version"));
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
private void createToolBar(Composite tparent) {
Composite toolBarCmp = new Composite(tparent, SWT.NONE);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).applyTo(toolBarCmp);
GridLayoutFactory.fillDefaults().numColumns(1).applyTo(toolBarCmp);
ToolBar toolBar = new ToolBar(toolBarCmp, SWT.NO_FOCUS | SWT.FLAT);
ToolItem openItem = new ToolItem(toolBar, SWT.PUSH);
openItem.setToolTipText(Messages.getString("dialog.JavaPropertiesViewerDialog.toolBar"));
openItem.setImage(new Image(Display.getDefault(), openFilePath));
openItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openFile();
}
});
}
private void createTableViewer(Composite tparent) {
tableViewer = new TableViewer(tparent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.MULTI
| SWT.BORDER);
table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
GridDataFactory.fillDefaults().grab(true, true).applyTo(table);
String[] columnNames = new String[] { Messages.getString("dialog.JavaPropertiesViewerDialog.columnNames1"),
Messages.getString("dialog.JavaPropertiesViewerDialog.columnNames2") };
int[] columnAlignments = new int[] { SWT.LEFT, SWT.LEFT };
for (int i = 0; i < columnNames.length; i++) {
TableColumn tableColumn = new TableColumn(table, columnAlignments[i]);
tableColumn.setText(columnNames[i]);
tableColumn.setWidth(50);
}
tableViewer.setLabelProvider(new TableViewerLabelProvider());
tableViewer.setContentProvider(new ArrayContentProvider());
// 让列表列宽动态变化
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.48, 0.48, };
for (int i = 0; i < columns.length; i++)
columns[i].setWidth((int) (table.getBounds().width * columnWidths[i]));
}
});
}
});
}
/**
* 打开文件
*/
private void openFile() {
FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
String[] extensions = { "*.properties", "*.*" };
String[] names = { Messages.getString("dialog.JavaPropertiesViewerDialog.names1"),
Messages.getString("dialog.JavaPropertiesViewerDialog.names2") };
fd.setFilterNames(names);
fd.setFilterExtensions(extensions);
String fileLocation = fd.open();
if (fileLocation == null) {
return;
}
PropertyResourceBundle bundle;
try {
bundle = new PropertyResourceBundle(new FileInputStream(fileLocation));
Vector<String> vector = getKeys(fileLocation);
Iterator<String> keys = vector.iterator();
List<String[]> data = new LinkedList<String[]>();
while (keys.hasNext()) {
String key = keys.next();
String value = bundle.getString(key);
data.add(new String[] { key, value });
}
tableViewer.setInput(data);
} catch (Exception e) {
LOGGER.error("", e);
}
}
private Vector<String> getKeys(String inputFile) throws IOException {
FileInputStream stream = new FileInputStream(inputFile);
InputStreamReader input = new InputStreamReader(stream, "UTF-8"); // ISO8859-1
BufferedReader buffer = new BufferedReader(input);
Vector<String> result = new Vector<String>();
String line;
while ((line = buffer.readLine()) != null) {
if (line.trim().length() == 0) {
// no text in this line
// segment separator
} else if (line.trim().startsWith("#")) {
// this line is a comment
// send to skeleton
} else {
String tmp = line;
if (line.trim().endsWith("\\")) {
do {
line = buffer.readLine();
tmp += "\n" + line;
} while (line != null && line.trim().endsWith("\\"));
}
int index = tmp.indexOf("=");
if (index != -1) {
String key = tmp.substring(0, index).trim();
result.add(key);
} else {
// this line may be wrong,
// ignore and continue
}
}
}
input.close();
return result;
}
}
| 9,608 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginConfigurationDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/PluginConfigurationDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import net.heartsome.cat.ts.ui.plugin.PluginConfigManage;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.bean.PluginConfigBean;
import net.heartsome.cat.ts.ui.plugin.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.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
public class PluginConfigurationDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(PluginConfigurationDialog.class);
private Button addBtn;
private Button editBtn;
private Button deleteBtn;
private TableViewer tableViewer;
private Table table;
private String pluginXmlLocation;
private PluginConfigManage manage;
public PluginConfigurationDialog(Shell parentShell) {
super(parentShell);
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
pluginXmlLocation = root.getLocation().append(PluginConstants.PC_pluginConfigLocation).toOSString();
manage = new PluginConfigManage(pluginXmlLocation);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.PluginConfigurationDialog.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("dialog.PluginConfigurationDialog.addBtn"), false);
editBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID,
Messages.getString("dialog.PluginConfigurationDialog.editBtn"), false);
deleteBtn = createButton(leftCmp, IDialogConstants.CLIENT_ID,
Messages.getString("dialog.PluginConfigurationDialog.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(1).applyTo(bottomCmp);
createButton(bottomCmp, IDialogConstants.CANCEL_ID,
Messages.getString("dialog.PluginConfigurationDialog.cancel"), true).setFocus();
initListener();
return buttonCmp;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridDataFactory.fillDefaults().hint(500, 400).minSize(500, 400).applyTo(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("dialog.PluginConfigurationDialog.columnNames1"),
Messages.getString("dialog.PluginConfigurationDialog.columnNames2"),
Messages.getString("dialog.PluginConfigurationDialog.columnNames3"),
Messages.getString("dialog.PluginConfigurationDialog.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);
}
// 让列表列宽动态变化
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.28, 0.28, 0.20, 0.20 };
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) {
editPuginConfig();
}
});
refreshTable(null);
return tparent;
}
public void initListener() {
addBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
PluginConfigManageDialog dialog = new PluginConfigManageDialog(getShell(), true);
int result = dialog.open();
if (result == IDialogConstants.OK_ID) {
refreshTable(dialog.getCurPluginBean());
}
}
});
editBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
editPuginConfig();
}
});
deleteBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
deletePluginData();
}
});
}
@Override
protected void okPressed() {
super.okPressed();
}
public void editPuginConfig() {
ISelection selection = tableViewer.getSelection();
if (selection != null && !selection.isEmpty() && selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Iterator<PluginConfigBean> it = structuredSelection.iterator();
if (it.hasNext()) {
PluginConfigBean configBean = it.next();
PluginConfigManageDialog dialog = new PluginConfigManageDialog(getShell(), false);
dialog.create();
dialog.setEditInitData(configBean);
int result = dialog.open();
if (result == IDialogConstants.OK_ID) {
refreshTable(dialog.getCurPluginBean());
}
}
} else {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.PluginConfigurationDialog.msgTitle"),
Messages.getString("dialog.PluginConfigurationDialog.msg1"));
}
}
private void refreshTable(PluginConfigBean bean) {
tableViewer.setInput(manage.getPluginCofigData());
if (bean != null) {
tableViewer.setSelection(new StructuredSelection(bean));
}
}
private void deletePluginData() {
ISelection selection = tableViewer.getSelection();
if (selection != null && !selection.isEmpty() && selection instanceof StructuredSelection) {
boolean response = MessageDialog.openConfirm(getShell(),
Messages.getString("dialog.PluginConfigurationDialog.msgTitle2"),
Messages.getString("dialog.PluginConfigurationDialog.msg2"));
if (!response) {
return;
}
StructuredSelection structuredSelection = (StructuredSelection) selection;
@SuppressWarnings("unchecked")
Iterator<PluginConfigBean> it = structuredSelection.iterator();
VTDGen vg = new VTDGen();
vg.parseFile(pluginXmlLocation, true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
try {
XMLModifier xm = new XMLModifier(vn);
while (it.hasNext()) {
PluginConfigBean configBean = it.next();
String xpath = manage.buildXpath(configBean);
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
xm.remove();
manage.deletePluginMenu(configBean.getId());
}
ap.resetXPath();
}
FileOutputStream fos = new FileOutputStream(pluginXmlLocation);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
refreshTable(null);
} catch (Exception e) {
LOGGER.error("", e);
}
} else {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.PluginConfigurationDialog.msgTitle"),
Messages.getString("dialog.PluginConfigurationDialog.msg3"));
}
}
/**
* 语言规则列表标签提供器
* @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 PluginConfigBean) {
PluginConfigBean bean = (PluginConfigBean) element;
switch (columnIndex) {
case 0:
return bean.getName();
case 1:
return bean.getCommandLine();
case 2:
return bean.getOutput();
case 3:
return bean.getInput();
default:
return null;
}
}
return null;
}
}
}
| 11,133 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginHelpDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/PluginHelpDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.ts.ui.plugin.Activator;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
import net.heartsome.xml.Catalogue;
import net.heartsome.xml.Document;
import net.heartsome.xml.Element;
import net.heartsome.xml.SAXBuilder;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeAdapter;
import org.eclipse.swt.events.TreeEvent;
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.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.xml.sax.SAXException;
/**
* 插件中的帮助链接对话框
* @author peason
* @version
* @since JDK1.6
*/
public class PluginHelpDialog extends Dialog {
private SashForm mainSash;
private Tree tree;
private Browser browser;
private Hashtable<TreeItem, String> hashTable;
private String currentFilePath;
private String helpFilePath;
private FileOutputStream fosSearch;
private boolean isFound;
private String title;
protected PluginHelpDialog(Shell parentShell, String helpFile, String title) {
super(parentShell);
this.helpFilePath = helpFile;
this.title = title;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
if (title == null) {
newShell.setText(Messages.getString("dialog.PluginHelpDialog.title"));
} else {
newShell.setText(title);
}
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridLayoutFactory.swtDefaults().spacing(0, 0).numColumns(1).applyTo(tparent);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(tparent);
createMenu();
createToolBar(tparent);
mainSash = new SashForm(tparent, SWT.NONE);
mainSash.setOrientation(SWT.HORIZONTAL);
GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
mainSash.setLayout(layout);
mainSash.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL
| GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
Composite navigation = new Composite(mainSash, SWT.BORDER);
navigation.setLayout(new GridLayout(1, false));
navigation.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
tree = new Tree(navigation, SWT.NONE);
tree.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
if (tree.getSelectionCount() > 0) {
TreeItem item = tree.getSelection()[0];
String url = hashTable.get(item);
if (url != null && !url.equals("")) {
browser.setUrl(url);
browser.update();
}
}
}
});
tree.addTreeListener(new TreeAdapter() {
public void treeCollapsed(TreeEvent e) {
TreeItem item = (TreeItem) e.item;
if (item != null && item.getData() != null) {
if (item.getData().equals("toc")) {
item.setImage(Activator.getImageDescriptor(PluginConstants.HELP_TOC_CLOSED).createImage());
}
if (item.getData().equals("book")) {
item.setImage(Activator.getImageDescriptor(PluginConstants.HELP_BOOK_CLOSED).createImage());
}
}
}
public void treeExpanded(TreeEvent e) {
TreeItem item = (TreeItem) e.item;
if (item != null && item.getData() != null) {
if (item.getData().equals("toc")) {
item.setImage(Activator.getImageDescriptor(PluginConstants.HELP_TOC_OPEN).createImage());
}
if (item.getData().equals("book")) {
item.setImage(Activator.getImageDescriptor(PluginConstants.HELP_BOOK_OPEN).createImage());
}
}
}
});
tree.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
Composite contents = new Composite(mainSash, SWT.BORDER);
contents.setLayout(new GridLayout(1, false));
contents.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
browser = new Browser(contents, SWT.NONE);
browser.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
mainSash.setWeights(new int[] { 30, 70 });
hashTable = new Hashtable<TreeItem, String>();
if (!helpFilePath.equals("")) {
loadTree(helpFilePath);
}
return tparent;
}
private void createMenu() {
final Menu mainMenu = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(mainMenu);
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Menu fileMenu = new Menu(mainMenu);
MenuItem fileMenuItem = new MenuItem(mainMenu, SWT.CASCADE);
fileMenuItem.setText(Messages.getString("dialog.PluginHelpDialog.fileMenuItem"));
fileMenuItem.setMenu(fileMenu);
MenuItem openFileItem = new MenuItem(fileMenu, SWT.PUSH);
openFileItem.setText(Messages.getString("dialog.PluginHelpDialog.openFileItem"));
openFileItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
openFile();
}
});
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText(Messages.getString("dialog.PluginHelpDialog.exitItem"));
exitItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
close();
}
});
MenuItem editMenu = new MenuItem(mainMenu, SWT.CASCADE);
editMenu.setText(Messages.getString("dialog.PluginHelpDialog.editMenu"));
Menu eMenu = new Menu(editMenu);
editMenu.setMenu(eMenu);
MenuItem searchItem = new MenuItem(eMenu, SWT.PUSH);
searchItem.setText(Messages.getString("dialog.PluginHelpDialog.searchItem"));
searchItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
searchText();
}
});
MenuItem goMenu = new MenuItem(mainMenu, SWT.CASCADE);
goMenu.setText(Messages.getString("dialog.PluginHelpDialog.goMenu"));
Menu gMenu = new Menu(goMenu);
goMenu.setMenu(gMenu);
MenuItem backItem = new MenuItem(gMenu, SWT.PUSH);
backItem.setText(Messages.getString("dialog.PluginHelpDialog.backItem"));
backItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
goBack();
}
});
MenuItem forwardItem = new MenuItem(gMenu, SWT.PUSH);
forwardItem.setText(Messages.getString("dialog.PluginHelpDialog.forwardItem"));
forwardItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
goForward();
}
});
new MenuItem(gMenu, SWT.SEPARATOR);
MenuItem homeItem = new MenuItem(gMenu, SWT.PUSH);
homeItem.setText(Messages.getString("dialog.PluginHelpDialog.homeItem"));
homeItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
goHome();
}
});
MenuItem helpMenu = new MenuItem(mainMenu, SWT.CASCADE);
helpMenu.setText(Messages.getString("dialog.PluginHelpDialog.helpMenu"));
Menu hMenu = new Menu(helpMenu);
helpMenu.setMenu(hMenu);
MenuItem aboutItem = new MenuItem(hMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.PluginHelpDialog.aboutItem"));
aboutItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
AboutDialog aboutDialog = new AboutDialog(getShell());
aboutDialog.open();
}
});
}
/**
* 创建工具栏
* @param parent
* ;
*/
private void createToolBar(Composite parent) {
Composite cmpToolBar = new Composite(parent, SWT.None);
GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(1).applyTo(cmpToolBar);
cmpToolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
ToolBar toolBar = new ToolBar(cmpToolBar, SWT.NO_FOCUS | SWT.FLAT);
ToolItem openItem = new ToolItem(toolBar, SWT.PUSH | SWT.FLAT);
openItem.setImage(Activator.getImageDescriptor(PluginConstants.HELP_OPEN_FILE).createImage()); //$NON-NLS-1$
openItem.setToolTipText(Messages.getString("dialog.PluginHelpDialog.openFileItem"));
openItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
openFile();
}
});
new ToolItem(toolBar, SWT.SEPARATOR);
ToolItem backItem = new ToolItem(toolBar, SWT.PUSH | SWT.FLAT);
backItem.setImage(Activator.getImageDescriptor(PluginConstants.HELP_BACK).createImage());
backItem.setToolTipText(Messages.getString("dialog.PluginHelpDialog.backItem"));
backItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
goBack();
}
});
ToolItem forwardItem = new ToolItem(toolBar, SWT.PUSH | SWT.FLAT);
forwardItem.setImage(Activator.getImageDescriptor(PluginConstants.HELP_FORWARD).createImage());
forwardItem.setToolTipText(Messages.getString("dialog.PluginHelpDialog.forwardItem"));
forwardItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
goForward();
}
});
new ToolItem(toolBar, SWT.SEPARATOR);
ToolItem searchItem = new ToolItem(toolBar, SWT.PUSH | SWT.FLAT);
searchItem.setImage(Activator.getImageDescriptor(PluginConstants.HELP_FIND).createImage());
searchItem.setToolTipText(Messages.getString("dialog.PluginHelpDialog.searchItem")); //$NON-NLS-1$
searchItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
searchText();
}
});
}
private void loadTree(String helpFile) {
try {
tree.removeAll();
hashTable.clear();
File file = new File(helpFile);
String basePath = "";
if (!file.isAbsolute()) {
helpFile = file.getCanonicalPath();
file = new File(helpFile);
}
basePath = file.getParent();
currentFilePath = helpFile;
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(PluginUtil.getCataloguePath()));
Document document = builder.build(helpFile);
Element root = document.getRootElement();
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText(root.getAttributeValue("title"));
getShell().setText(root.getAttributeValue("title"));
recurseTree(root, item, basePath);
item.setExpanded(true);
String url = root.getAttributeValue("url");
if (!url.equals("")) {
File f = new File(url);
if (!f.exists()) {
url = basePath + "/" + url;
}
browser.setUrl(new File(url).toURI().toURL().toString());
hashTable.put(item, url);
}
} catch (Exception e) {
}
}
private void recurseTree(Element elementParent, TreeItem itemParent, String basePath) throws Exception {
List<Element> children = elementParent.getChildren();
for (int i = 0; i < children.size(); i++) {
Element element = children.get(i);
String url = element.getAttributeValue("url", "");
TreeItem item = new TreeItem(itemParent, SWT.NONE);
if (url.startsWith(".")) {
// relative path
url = CommonFunction.getAbsolutePath(basePath, url);
}
if (!url.toLowerCase().startsWith("http:")) {
File f = new File(url);
if (!f.exists() || !f.isAbsolute()) {
url = CommonFunction.getAbsolutePath(basePath, url);
}
}
item.setData(element.getName());
if (element.getName().equals("toc")) {
item.setImage(Activator.getImageDescriptor(PluginConstants.HELP_TOC_CLOSED).createImage());
item.setText(element.getText());
if (url.startsWith(".")) {
url = CommonFunction.getAbsolutePath(basePath, url);
}
loadToc(item, new File(url).getCanonicalPath());
}
if (element.getName().equals("book")) {
item.setImage(Activator.getImageDescriptor(PluginConstants.HELP_BOOK_CLOSED).createImage());
item.setText(element.getAttributeValue("title"));
recurseTree(element, item, basePath);
if (!url.equals("")) {
hashTable.put(item, new File(url).toURI().toURL().toString());
}
}
if (element.getName().equals("item")) {
item.setImage(Activator.getImageDescriptor(PluginConstants.HELP_TOPIC).createImage());
item.setText(element.getText());
hashTable.put(item, new File(url).toURI().toURL().toString());
}
}
}
private void loadToc(TreeItem itemParent, String tocFile) throws Exception {
File file = new File(tocFile);
String basePath = "";
if (file.exists()) {
basePath = file.getParent();
}
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(PluginUtil.getCataloguePath()));
Document document = builder.build(tocFile);
Element root = document.getRootElement();
recurseTree(root, itemParent, basePath);
String url = root.getAttributeValue("url");
if (!url.equals("")) {
File f = new File(url);
if (!f.exists()) {
url = basePath + "/" + url;
}
hashTable.put(itemParent, new File(url).toURI().toURL().toString());
}
}
private void openFile() {
FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN);
String[] extensions = { "*.xml", "*.*" };
String[] filterNames = { Messages.getString("dialog.PluginHelpDialog.filterNames0"),
Messages.getString("dialog.PluginHelpDialog.filterNames1") };
fileDialog.setFilterExtensions(extensions);
fileDialog.setFilterNames(filterNames);
fileDialog.setFilterPath(System.getProperty("user.home"));
String name = fileDialog.open();
if (name == null) {
return;
}
File file = new File(name);
getShell().setText(file.getName());
loadTree(file.getAbsolutePath());
}
private void searchText() {
HelpSearchDialog searchDialog = new HelpSearchDialog(getShell());
if (searchDialog.open() == IDialogConstants.OK_ID) {
String text = searchDialog.getText();
boolean sensitive = searchDialog.isSensitive();
if (!sensitive) {
text = text.toLowerCase();
}
try {
isFound = false;
File f = new File("searchresult.html"); //$NON-NLS-1$
fosSearch = new FileOutputStream(f);
f.deleteOnExit();
writeString("<html>\n");
writeString("<head>\n");
writeString("<title>" + Messages.getString("dialog.PluginHelpDialog.searchTitle") + "</title>\n");
writeString("</head>\n");
writeString("<body>\n");
ProgressDialog progressDialog = new ProgressDialog(getShell(),
Messages.getString("dialog.PluginHelpDialog.progressDialogTitle"),
Messages.getString("dialog.PluginHelpDialog.progressMessage"), ProgressDialog.SINGLE_BAR);
progressDialog.open();
Enumeration<TreeItem> keys = hashTable.keys();
int count = hashTable.size();
int i = 0;
while (keys.hasMoreElements()) {
String url = hashTable.get(keys.nextElement());
String file = url.substring(url.lastIndexOf("/")); //$NON-NLS-1$
progressDialog.updateProgressMessage(file);
searchFile(url, text, sensitive);
progressDialog.updateProgress((i * 100) / count);
i++;
}
progressDialog.close();
if (!isFound) {
writeString("<p><b>" + Messages.getString("dialog.PluginHelpDialog.searchNone") + "</b></p>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
writeString("</body>\n"); //$NON-NLS-1$
writeString("</html>"); //$NON-NLS-1$
fosSearch.close();
browser.setUrl(f.toURI().toURL().toString());
} catch (Exception e) {
}
}
}
private void searchFile(String file, String text, boolean sensitive) throws SAXException, IOException,
ParserConfigurationException {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(PluginUtil.getCataloguePath())); //$NON-NLS-1$
if (!file.startsWith("file:")) { //$NON-NLS-1$
if (!file.startsWith("http:")) { //$NON-NLS-1$
File f = new File(file);
file = f.toURI().toURL().toString();
}
}
URL url = new URL(file);
Document doc = builder.build(url);
Element root = doc.getRootElement();
searchElement(root, file, text, sensitive);
}
private void searchElement(Element root, String file, String text, boolean sensitive)
throws UnsupportedEncodingException, IOException {
List<Element> children = root.getChildren();
Iterator<Element> it = children.iterator();
while (it.hasNext()) {
Element e = it.next();
if (!e.getAttributeValue("id", "").equals("")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String txt = e.getTextNormalize();
if (!sensitive) {
txt = txt.toLowerCase();
}
if (txt.indexOf(text) != -1) {
if (e.getName().equals("p") //$NON-NLS-1$
|| e.getName().equals("title") //$NON-NLS-1$
|| e.getName().equals("h1") //$NON-NLS-1$
|| e.getName().equals("h2") //$NON-NLS-1$
|| e.getName().equals("h3") //$NON-NLS-1$
|| e.getName().equals("h4") //$NON-NLS-1$
|| e.getName().equals("h5") //$NON-NLS-1$
|| e.getName().equals("h6")) { //$NON-NLS-1$
writeString("<a href=\"" + file + "#" + e.getAttributeValue("id") + "\">" + file + "</a>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
writeString("<br/>"); //$NON-NLS-1$
writeString(e.getTextNormalize());
writeString("<hr/>"); //$NON-NLS-1$
isFound = true;
}
}
}
searchElement(e, file, text, sensitive);
}
}
private void writeString(String string) throws UnsupportedEncodingException, IOException {
fosSearch.write(string.getBytes("UTF-8")); //$NON-NLS-1$
}
protected void goHome() {
if (currentFilePath != null && !currentFilePath.equals("")) { //$NON-NLS-1$
loadTree(currentFilePath);
}
}
protected void goForward() {
browser.forward();
}
protected void goBack() {
browser.back();
}
class AboutDialog extends Dialog {
protected AboutDialog(Shell parentShell) {
super(parentShell);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.PluginHelpDialog.AboutDialog.title"));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout());
tparent.setLayoutData(new GridData(GridData.FILL_BOTH));
Label logo = new Label(tparent, SWT.BORDER);
logo.setImage(Activator.getImageDescriptor(PluginConstants.HELP_SPLASH).createImage());
return tparent;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
Composite cmp = parent.getParent();
parent.dispose();
cmp.layout();
}
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
Composite cmp = parent.getParent();
parent.dispose();
cmp.layout();
}
}
| 19,842 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CSVSettingDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/CSVSettingDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.ui.composite.LanguageLabelProvider;
import net.heartsome.cat.ts.ui.plugin.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.jface.viewers.ArrayContentProvider;
import org.eclipse.nebula.jface.tablecomboviewer.TableComboViewer;
import org.eclipse.nebula.widgets.tablecombo.TableCombo;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* 打开 CSV 文件对话框
* @author peason
* @version
* @since JDK1.6
*/
public class CSVSettingDialog extends Dialog {
/** 列分隔符集合 */
private String[] arrColSeparator = { "", ",", ";", ":", "|", "Tab" };
/** 文本定界符集合 */
private String[] arrTextDelimiter = { "", "\"", "'" };
private boolean isTBXConverter;
/** Logo 图片路径 */
private String imgPath;
/** XCS 模板文件名集合 */
private String[] xcsTemplates;
/** CSV 文本框 */
private Text txtCSV;
/** 浏览按钮 */
private Button btnBrowse;
/** 列分隔符下拉框,可编辑 */
private Combo cmbColSeparator;
/** 文本定界符下拉框,可编辑 */
private Combo cmbTextDelimiter;
/** 字符集下拉框 */
private Combo cmbEncoding;
/** 主语言下拉框 */
private TableComboViewer cmbLang;
/** XCS 模板下拉框 */
private Combo cmbXCSTemplate;
/** CSV 路径 */
private String csvPath;
/** 列分隔符 */
private String colSeparator;
/** 文本定界符 */
private String textDelimiter;
/** 字符集下拉框 */
private String encoding;
/** 主语言 */
private String lang;
/** XCS 模板 */
private String xcsTemplate;
/**
* 构造方法
* @param parentShell
* @param isTBXConverter
* 是否是 TBX 转换器
* @param imgPath
* Logo 图片路径
* @param xcsTemplates
* xcs 模板集合
*/
protected CSVSettingDialog(Shell parentShell, boolean isTBXConverter, String imgPath, String[] xcsTemplates) {
super(parentShell);
this.isTBXConverter = isTBXConverter;
this.imgPath = imgPath;
this.xcsTemplates = xcsTemplates;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.CSVSettingDialog.title"));
newShell.setImage(new Image(Display.getDefault(), imgPath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridLayoutFactory.fillDefaults().numColumns(1).extendedMargins(5, 5, 5, 5).applyTo(tparent);
int height = 160;
if (isTBXConverter) {
height = 230;
}
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(320, height).grab(true, true).applyTo(tparent);
Composite cmpSelFile = new Composite(tparent, SWT.None);
GridLayoutFactory.fillDefaults().numColumns(3).equalWidth(false).extendedMargins(0, 0, 0, 0)
.applyTo(cmpSelFile);
GridDataFactory.fillDefaults().applyTo(cmpSelFile);
new Label(cmpSelFile, SWT.None).setText(Messages.getString("dialog.CSVSettingDialog.lblFile"));
txtCSV = new Text(cmpSelFile, SWT.BORDER);
txtCSV.setEditable(false);
txtCSV.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnBrowse = new Button(cmpSelFile, SWT.None);
btnBrowse.setText(Messages.getString("dialog.CSVSettingDialog.btnBrowse"));
btnBrowse.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
dialog.setText(Messages.getString("dialog.CSVSettingDialog.dialogTitle"));
String[] extensions = { "*.csv", "*.txt", "*" };
String[] filters = { Messages.getString("dialog.CSVSettingDialog.filters1"),
Messages.getString("dialog.CSVSettingDialog.filters2"),
Messages.getString("dialog.CSVSettingDialog.filters3") };
dialog.setFilterExtensions(extensions);
dialog.setFilterNames(filters);
String fileSep = System.getProperty("file.separator");
if (txtCSV.getText() != null && !txtCSV.getText().trim().equals("")) {
dialog.setFilterPath(txtCSV.getText().substring(0, txtCSV.getText().lastIndexOf(fileSep)));
dialog.setFileName(txtCSV.getText().substring(txtCSV.getText().lastIndexOf(fileSep) + 1));
} else {
dialog.setFilterPath(System.getProperty("user.home"));
}
String name = dialog.open();
if (name != null) {
txtCSV.setText(name);
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
Composite cmpContent = new Composite(tparent, SWT.NONE);
cmpContent.setLayout(new GridLayout(2, false));
cmpContent.setLayoutData(new GridData(GridData.FILL_BOTH));
createLabel(cmpContent, Messages.getString("dialog.CSVSettingDialog.cmbColSeparator"));
cmbColSeparator = new Combo(cmpContent, SWT.NONE);
cmbColSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
cmbColSeparator.setItems(arrColSeparator);
cmbColSeparator.select(1);
createLabel(cmpContent, Messages.getString("dialog.CSVSettingDialog.cmbTextDelimiter"));
cmbTextDelimiter = new Combo(cmpContent, SWT.NONE);
cmbTextDelimiter.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
cmbTextDelimiter.setItems(arrTextDelimiter);
cmbTextDelimiter.setText("\"");
cmbTextDelimiter.setTextLimit(1);
createLabel(cmpContent, Messages.getString("dialog.CSVSettingDialog.cmbEncoding"));
cmbEncoding = new Combo(cmpContent, SWT.READ_ONLY);
cmbEncoding.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
String[] arrEncoding = LocaleService.getPageCodes();
cmbEncoding.setItems(arrEncoding);
cmbEncoding.select(indexOf(arrEncoding, "UTF-8"));
if (isTBXConverter) {
createLabel(cmpContent, Messages.getString("dialog.CSVSettingDialog.cmbLang"));
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));
ArrayList<Language> languages = new ArrayList<Language>(LocaleService.getDefaultLanguage().values());
Collections.sort(languages, new Comparator<Language>() {
public int compare(Language o1, Language o2) {
return o1.toString().compareTo(o2.toString());
}
});
cmbLang.setContentProvider(new ArrayContentProvider());
cmbLang.setLabelProvider(new LanguageLabelProvider());
cmbLang.setInput(languages);
cmbLang.getTableCombo().select(0);
createLabel(cmpContent, Messages.getString("dialog.CSVSettingDialog.cmbXCSTemplate"));
cmbXCSTemplate = new Combo(cmpContent, SWT.READ_ONLY);
cmbXCSTemplate.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (xcsTemplates.length > 0) {
cmbXCSTemplate.setItems(xcsTemplates);
cmbXCSTemplate.select(0);
}
}
return tparent;
}
/**
* 创建 Label,文本右对齐
* @param parent
* 父控件
* @param text
* Label 上显示的文本
*/
private void createLabel(Composite parent, String text) {
Label lbl = new Label(parent, SWT.None);
lbl.setText(text);
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(lbl);
}
/**
* 获取字符串 string 在数组 array 中的索引
* @param array
* @param string
* @return ;
*/
public int indexOf(String[] array, String string) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(string)) {
return i;
}
}
return -1;
}
@Override
protected void okPressed() {
String strCSVPath = txtCSV.getText();
if (strCSVPath == null || strCSVPath.trim().equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.CSVSettingDialog.msgTitle"),
Messages.getString("dialog.CSVSettingDialog.msg1"));
return;
}
setCsvPath(strCSVPath);
if (isTBXConverter) {
String strMainLang = TextUtil.getLanguageCode(cmbLang.getTableCombo().getText());
if (strMainLang == null || strMainLang.trim().equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.CSVSettingDialog.msgTitle"),
Messages.getString("dialog.CSVSettingDialog.msg2"));
return;
}
setLang(strMainLang);
setXcsTemplate(cmbXCSTemplate.getText());
}
String colSeparator = cmbColSeparator.getText();
if (colSeparator.equals("Tab")) {
colSeparator = "\t";
}
setColSeparator(colSeparator);
setTextDelimiter(cmbTextDelimiter.getText());
setEncoding(cmbEncoding.getText());
close();
}
public String getCsvPath() {
return csvPath;
}
public void setCsvPath(String csvPath) {
this.csvPath = csvPath;
}
public String getColSeparator() {
return colSeparator;
}
public void setColSeparator(String colSeparator) {
this.colSeparator = colSeparator;
}
public String getTextDelimiter() {
return textDelimiter;
}
public void setTextDelimiter(String textDelimiter) {
this.textDelimiter = textDelimiter;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getXcsTemplate() {
return xcsTemplate;
}
public void setXcsTemplate(String xcsTemplate) {
this.xcsTemplate = xcsTemplate;
}
}
| 10,554 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RTFCleanerDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/RTFCleanerDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.File;
import java.text.MessageFormat;
import java.util.Hashtable;
import java.util.Vector;
import net.heartsome.cat.ts.ui.plugin.AboutComposite;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
import net.heartsome.cat.ts.ui.plugin.util.RTFCleaner;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
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.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
/**
* RTFCleaner 对话框
* @author peason
* @version
* @since JDK1.6
*/
public class RTFCleanerDialog extends Dialog {
/** Logo 图片路径 */
private String imagePath;
/**
* 构造方法
* @param parentShell
*/
public RTFCleanerDialog(Shell parentShell) {
super(parentShell);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.RTFCleanerDialog.title"));
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_RTFCLEANER_PATH);
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout());
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(230, 330).grab(true, true).applyTo(tparent);
createMenu();
createToolBar(tparent);
Composite cmpAbout = new Composite(tparent, SWT.None);
cmpAbout.setLayout(new GridLayout());
cmpAbout.setLayoutData(new GridData(GridData.FILL_BOTH));
new AboutComposite(cmpAbout, SWT.BORDER, Messages.getString("dialog.RTFCleanerDialog.aboutName"), imagePath,
Messages.getString("dialog.RTFCleanerDialog.aboutVersion"));
tparent.layout();
getShell().layout();
return tparent;
}
/**
* 创建菜单 ;
*/
private void createMenu() {
Menu menu = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menu);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Menu fileMenu = new Menu(menu);
MenuItem fileItem = new MenuItem(menu, SWT.CASCADE);
fileItem.setMenu(fileMenu);
fileItem.setText(Messages.getString("dialog.RTFCleanerDialog.fileMenu"));
MenuItem addStylesItem = new MenuItem(fileMenu, SWT.PUSH);
addStylesItem.setText(Messages.getString("dialog.RTFCleanerDialog.addStylesItem"));
addStylesItem.setImage(new Image(Display.getDefault(), PluginUtil
.getAbsolutePath(PluginConstants.PIC_OPEN_CSV_PATH)));
addStylesItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
handleFile();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText(Messages.getString("dialog.RTFCleanerDialog.exitItem"));
exitItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
close();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
/**
* 创建工具栏
* @param parent
* 父控件
*/
private void createToolBar(Composite parent) {
ToolBar toolBar = new ToolBar(parent, SWT.NO_FOCUS | SWT.None);
toolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
ToolItem addStyleItem = new ToolItem(toolBar, SWT.PUSH);
addStyleItem.setToolTipText(Messages.getString("dialog.RTFCleanerDialog.addStyleItem"));
addStyleItem.setImage(new Image(Display.getDefault(), PluginUtil
.getAbsolutePath(PluginConstants.PIC_OPEN_CSV_PATH)));
addStyleItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
handleFile();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
/**
* 处理 RTF 文件 ;
*/
private void handleFile() {
FileDialog dialog = new FileDialog(getShell(), SWT.MULTI);
dialog.setText(Messages.getString("dialog.RTFCleanerDialog.dialogTitle"));
String[] extensions = { "*.rtf", "*" };
String[] filters = { Messages.getString("dialog.RTFCleanerDialog.filters1"),
Messages.getString("dialog.RTFCleanerDialog.filters2") };
dialog.setFilterExtensions(extensions);
dialog.setFilterNames(filters);
dialog.setFilterPath(System.getProperty("user.home"));
dialog.open();
String[] arrSource = dialog.getFileNames();
if (arrSource == null || arrSource.length == 0) {
return;
}
int errors = 0;
for (int i = 0; i < arrSource.length; i++) {
File f = new File(dialog.getFilterPath() + System.getProperty("file.separator") + arrSource[i]); //$NON-NLS-1$
Hashtable<String, String> params = new Hashtable<String, String>();
params.put("source", f.getAbsolutePath()); //$NON-NLS-1$
params.put("output", f.getAbsolutePath()); //$NON-NLS-1$
Vector<String> result = RTFCleaner.run(params);
if (!"0".equals(result.get(0))) { //$NON-NLS-1$
String msg = MessageFormat.format(Messages.getString("dialog.RTFCleanerDialog.msg1"), arrSource[i])
+ (String) result.get(1);
MessageDialog.openInformation(getShell(), Messages.getString("dialog.RTFCleanerDialog.msgTitle"), msg);
errors++;
}
}
if (errors < arrSource.length) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.RTFCleanerDialog.msgTitle"),
Messages.getString("dialog.RTFCleanerDialog.msg2"));
}
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
Composite cmp = parent.getParent();
parent.dispose();
cmp.layout();
}
}
| 6,476 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ColumnRemoveDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/ColumnRemoveDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.util.Vector;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.List;
import org.eclipse.swt.widgets.Shell;
/**
* TBXMaker -> 删除列对话框
* @author peason
* @version
* @since JDK1.6
*/
public class ColumnRemoveDialog extends Dialog {
/** 初始列的集合 */
private Vector<String> allColumnVector;
/** 删除列后剩余的列集合 */
private Vector<String> columnVector;
/** Logo 图片路径 */
private String imgPath;
/** 显示列的列表 */
private List listColumn;
/**
* 构造方法
* @param parentShell
* @param allColumnVector
* @param imgPath
*/
protected ColumnRemoveDialog(Shell parentShell, Vector<String> allColumnVector, String imgPath) {
super(parentShell);
this.allColumnVector = allColumnVector;
this.imgPath = imgPath;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.ColumnRemoveDialog.title"));
newShell.setImage(new Image(Display.getDefault(), imgPath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout());
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(150, 200).grab(true, true).applyTo(tparent);
listColumn = new List(tparent, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.MULTI);
listColumn.setLayoutData(new GridData(GridData.FILL_BOTH));
for (int i = 0; i < allColumnVector.size(); i++) {
listColumn.add(allColumnVector.get(i));
}
Button btnRemove = new Button(tparent, SWT.None);
btnRemove.setText(Messages.getString("dialog.ColumnRemoveDialog.btnRemove"));
GridDataFactory.swtDefaults().align(SWT.CENTER, SWT.CENTER).applyTo(btnRemove);
btnRemove.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
int total = listColumn.getItemCount();
int selCount = listColumn.getSelectionCount();
if (selCount == 0) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ColumnRemoveDialog.msgTitle"),
Messages.getString("dialog.ColumnRemoveDialog.msg1"));
return;
}
if ((total - selCount) < 2) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ColumnRemoveDialog.msgTitle"),
Messages.getString("dialog.ColumnRemoveDialog.msg2"));
return;
}
listColumn.remove(listColumn.getSelectionIndices());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
return tparent;
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected void okPressed() {
columnVector = new Vector<String>();
String[] items = listColumn.getItems();
for (int i = 0; i < items.length; i++) {
columnVector.add(items[i]);
}
close();
}
public Vector<String> getColumnVector() {
return columnVector;
}
public void setColumnVector(Vector<String> columnVector) {
this.columnVector = columnVector;
}
}
| 3,658 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AboutDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/AboutDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import net.heartsome.cat.ts.ui.plugin.AboutComposite;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* 关于对话框(表头为"关于...",第一行为标题,第二行为 Logo,第三行为版本信息,第四行为版权信息,第五行为网址信息)
* @author peason
* @version
* @since JDK1.6
*/
public class AboutDialog extends Dialog {
/** 第一行标题 */
private String name;
/** Logo 图片路径 */
private String imagePath;
/** 版本信息 */
private String version;
/**
* 构造方法
* @param parentShell
* @param name
* 第一行标题
* @param imagePath
* Logo 图片路径
* @param version
* 版本信息
*/
protected AboutDialog(Shell parentShell, String name, String imagePath, String version) {
super(parentShell);
this.name = name;
this.imagePath = imagePath;
this.version = version;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.AboutDialog.title"));
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
GridLayoutFactory.fillDefaults().numColumns(1).extendedMargins(0, 0, 5, 5).spacing(0, 0).applyTo(parent);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(200, 250).grab(true, true).applyTo(parent);
new AboutComposite(parent, SWT.BORDER, name, imagePath, version);
return parent;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
Composite cmp = parent.getParent();
parent.dispose();
cmp.layout();
}
}
| 2,074 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginConfigManageDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/PluginConfigManageDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import net.heartsome.cat.ts.ui.plugin.PluginConfigManage;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.bean.PluginConfigBean;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.bindings.keys.KeySequence;
import org.eclipse.jface.bindings.keys.KeySequenceText;
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.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.internal.keys.model.KeyController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* 插件配置管理,包括添加与修改插件
* @author robert 2012-03-05
* @version
* @since JDK1.6
*/
public class PluginConfigManageDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(PluginConfigManageDialog.class);
private boolean isAdd;
private IWorkspaceRoot root;
private String pluginXmlLocation;
/** 当前已经添加或正在修改的插件配置pojo */
private PluginConfigBean curPluginBean;
private PluginConfigManage manage = new PluginConfigManage();
private Text nameTxt;
private Text commandTxt;
private Color WHITE;
private Color ORANGE;
private Color BUTTON;
private Combo keyCmb;
private boolean errors;
private KeySequenceText fKeySequenceText;
private Text keyTxt;
@SuppressWarnings("restriction")
private KeyController keyController;
private Text switchTxt;
private Button switchBrowseBtn;
/** 当前文本段 */
private Button outputSegemntBtn;
/** 当前文档 */
private Button outputDocumentBtn;
/** 空白 */
private Button outputBlankBtn;
/** 已更新的交换文件 */
private Button inputUpdateFileBtn;
/** 已更新的文档 */
private Button inputUpdateDocuBtn;
/** 空白 */
private Button inputBlankBtn;
public PluginConfigManageDialog(Shell parentShell, boolean isAdd) {
super(parentShell);
this.isAdd = isAdd;
root = ResourcesPlugin.getWorkspace().getRoot();
pluginXmlLocation = root.getLocation().append(PluginConstants.PC_pluginConfigLocation).toOSString();
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(isAdd ? Messages.getString("dialog.PluginConfigManageDialog.title1") : Messages
.getString("dialog.PluginConfigManageDialog.title2"));
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
GridDataFactory.fillDefaults().grab(true, true).hint(500, 350).minSize(500, 350).applyTo(tparent);
// 插件基本信息,包括名称,命令行之类的东西
Composite pluginInfoCmp = new Composite(tparent, SWT.BORDER);
GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(pluginInfoCmp);
GridLayoutFactory.swtDefaults().numColumns(3).applyTo(pluginInfoCmp);
Label nameLbl = new Label(pluginInfoCmp, SWT.NONE);
nameLbl.setText(Messages.getString("dialog.PluginConfigManageDialog.nameLbl"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(nameLbl);
nameTxt = new Text(pluginInfoCmp, SWT.BORDER);
GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, SWT.DEFAULT)
.applyTo(nameTxt);
Label commandLbl = new Label(pluginInfoCmp, SWT.NONE);
commandLbl.setText(Messages.getString("dialog.PluginConfigManageDialog.commandLbl"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(commandLbl);
commandTxt = new Text(pluginInfoCmp, SWT.BORDER);
GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(commandTxt);
Button browseBtn = new Button(pluginInfoCmp, SWT.NONE);
browseBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.browseBtn"));
browseBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String[] extensions = { "*.exe", "*.*" };
String[] names = { Messages.getString("dialog.PluginConfigManageDialog.names1"),
Messages.getString("dialog.PluginConfigManageDialog.names2") };
String fileLocation = browseFile(Messages.getString("dialog.PluginConfigManageDialog.dialogTitle"),
extensions, names);
commandTxt.setText(fileLocation == null ? "" : fileLocation);
}
});
createShortcutKeyGoup(tparent);
createProcessesAddReturnGroup(tparent);
createSwitchCmp(tparent);
initListener();
return tparent;
}
/**
* 创建快捷键面板
* @param tparent
* ;
*/
private void createShortcutKeyGoup(Composite tparent) {
Group group = new Group(tparent, SWT.None);
group.setText(Messages.getString("dialog.PluginConfigManageDialog.group"));
GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(group);
GridLayoutFactory.swtDefaults().numColumns(2).applyTo(group);
Label keyLbl = new Label(group, SWT.NONE);
keyLbl.setText(Messages.getString("dialog.PluginConfigManageDialog.keyLbl"));
keyTxt = new Text(group, SWT.BORDER);
GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(keyTxt);
fKeySequenceText = new KeySequenceText(keyTxt);
fKeySequenceText.setKeyStrokeLimit(4);
fKeySequenceText.addPropertyChangeListener(new IPropertyChangeListener() {
public final void propertyChange(final PropertyChangeEvent event) {
if (!event.getOldValue().equals(event.getNewValue())) {
final KeySequence keySequence = fKeySequenceText.getKeySequence();
if (!keySequence.isComplete()) {
return;
}
keyTxt.setSelection(keyTxt.getTextLimit());
}
}
});
}
/**
* 创建进程与返回两个group
* @param tparent
* ;
*/
private void createProcessesAddReturnGroup(Composite tparent) {
Composite prCmp = new Composite(tparent, SWT.NONE);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(prCmp);
GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(true).applyTo(prCmp);
GridData buttonData = new GridData(SWT.FILL, SWT.CENTER, true, false);
// 进程,相当于界面上的输出
Group processGroup = new Group(prCmp, SWT.None);
processGroup.setText(Messages.getString("dialog.PluginConfigManageDialog.processGroup"));
GridDataFactory.fillDefaults().grab(true, true).applyTo(processGroup);
GridLayoutFactory.swtDefaults().numColumns(1).applyTo(processGroup);
outputSegemntBtn = new Button(processGroup, SWT.RADIO);
outputSegemntBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.outputSegemntBtn"));
outputSegemntBtn.setLayoutData(buttonData);
outputDocumentBtn = new Button(processGroup, SWT.RADIO);
outputDocumentBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.outputDocumentBtn"));
outputDocumentBtn.setLayoutData(buttonData);
outputBlankBtn = new Button(processGroup, SWT.RADIO);
outputBlankBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.outputBlankBtn"));
outputBlankBtn.setLayoutData(buttonData);
// 返回(相当于界面上的输入)
Group returnGroup = new Group(prCmp, SWT.None);
returnGroup.setText(Messages.getString("dialog.PluginConfigManageDialog.returnGroup"));
GridDataFactory.fillDefaults().grab(true, true).applyTo(returnGroup);
GridLayoutFactory.swtDefaults().numColumns(1).applyTo(returnGroup);
inputUpdateFileBtn = new Button(returnGroup, SWT.RADIO);
inputUpdateFileBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.inputUpdateFileBtn"));
inputUpdateFileBtn.setLayoutData(buttonData);
inputUpdateDocuBtn = new Button(returnGroup, SWT.RADIO);
inputUpdateDocuBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.inputUpdateDocuBtn"));
inputUpdateDocuBtn.setLayoutData(buttonData);
inputBlankBtn = new Button(returnGroup, SWT.RADIO);
inputBlankBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.inputBlankBtn"));
inputBlankBtn.setLayoutData(buttonData);
// 当前文本段的事件
outputSegemntBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
inputUpdateFileBtn.setEnabled(true);
inputUpdateDocuBtn.setEnabled(false);
inputUpdateDocuBtn.setSelection(false);
inputBlankBtn.setEnabled(true);
switchTxt.setEnabled(true);
switchBrowseBtn.setEnabled(true);
}
});
// 当前文档的事件
outputDocumentBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
inputUpdateFileBtn.setEnabled(false);
inputUpdateFileBtn.setSelection(false);
inputUpdateDocuBtn.setEnabled(true);
inputBlankBtn.setEnabled(true);
switchTxt.setEnabled(false);
switchTxt.setText("");
switchBrowseBtn.setEnabled(false);
}
});
// 进程中空格按钮的事件
outputBlankBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
inputUpdateFileBtn.setEnabled(false);
inputUpdateFileBtn.setSelection(false);
inputUpdateDocuBtn.setEnabled(false);
inputUpdateDocuBtn.setSelection(false);
inputBlankBtn.setEnabled(false);
inputBlankBtn.setSelection(false);
switchTxt.setEnabled(false);
switchTxt.setText("");
switchBrowseBtn.setEnabled(false);
}
});
}
private void createSwitchCmp(Composite tparent) {
Composite cmp = new Composite(tparent, SWT.NONE);
GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(cmp);
GridLayoutFactory.swtDefaults().numColumns(3).applyTo(cmp);
Label switchLbl = new Label(cmp, SWT.NONE);
switchLbl.setText(Messages.getString("dialog.PluginConfigManageDialog.switchLbl"));
switchTxt = new Text(cmp, SWT.BORDER);
GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(switchTxt);
switchBrowseBtn = new Button(cmp, SWT.NONE);
switchBrowseBtn.setText(Messages.getString("dialog.PluginConfigManageDialog.switchBrowseBtn"));
switchBrowseBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String fileLocation = browseFile(Messages.getString("dialog.PluginConfigManageDialog.dialogTitle2"),
null, null);
switchTxt.setText(fileLocation == null ? "" : fileLocation);
}
});
}
@Override
protected void okPressed() {
String id = "" + System.currentTimeMillis();
String name = nameTxt.getText().trim();
String command = commandTxt.getText().trim();
if ("".equals(name) || name == null) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.PluginConfigManageDialog.msgTitle"),
Messages.getString("dialog.PluginConfigManageDialog.msg1"));
return;
}
if ("".equals(command) || command == null) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.PluginConfigManageDialog.msgTitle"),
Messages.getString("dialog.PluginConfigManageDialog.msg2"));
return;
}
String input = "";
String output = "";
if (inputUpdateFileBtn.getSelection()) {
input = PluginConstants.EXCHANGEFILE;
} else if (inputUpdateDocuBtn.getSelection()) {
input = PluginConstants.DOCUMENT;
} else if (inputBlankBtn.getSelection()) {
input = PluginConstants.NONE;
}
if (outputSegemntBtn.getSelection()) {
output = PluginConstants.SEGMENT;
} else if (outputDocumentBtn.getSelection()) {
output = PluginConstants.DOCUMENT;
} else if (outputBlankBtn.getSelection()) {
output = PluginConstants.NONE;
}
String shortcutKey = keyTxt.getText().trim();
String outputPath = switchTxt.getText().trim();
PluginConfigBean pluginBean = new PluginConfigBean(id, name, command, input, output, outputPath, shortcutKey);
if (isAdd) {
if (!addPluginData(pluginBean)) {
return;
} else {
manage.addPluginMenu(pluginBean);
}
} else {
// 修改之后的数据,ID是不能变的。
pluginBean.setId(curPluginBean.getId());
// 执行修改操作
editPlugindata(pluginBean);
}
curPluginBean = pluginBean;
super.okPressed();
}
/**
* 选择文件
* @param title
* @param extensions
* @param names
* @return ;
*/
private String browseFile(String title, String[] extensions, String[] names) {
FileDialog fd = new FileDialog(getShell(), SWT.OPEN);
fd.setText(title);
if (extensions != null) {
fd.setFilterExtensions(extensions);
}
if (names != null) {
fd.setFilterNames(names);
}
return fd.open();
}
/**
* 给所有的按钮添加事件 ;
*/
private void initListener() {
}
/**
* 添加插件配置信息到插件文件 ;
*/
private boolean addPluginData(PluginConfigBean pluginBean) {
File pluginXMl = new File(pluginXmlLocation);
if (!pluginXMl.getParentFile().exists()) {
pluginXMl.getParentFile().mkdirs();
}
pluginXMl = new File(pluginXmlLocation);
try {
// 如果配置文件不存在,则创建
if (!pluginXMl.exists()) {
OutputStream output = new FileOutputStream(pluginXmlLocation);
output.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n".getBytes("UTF-8"));
output.write("<shortcuts>\n</shortcuts>".getBytes("UTF-8"));
output.close();
}
} catch (Exception e) {
LOGGER.error("", e);
}
// 开始存放文件
try {
VTDGen vg = new VTDGen();
vg.parseFile(pluginXmlLocation, true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath(manage.buildXpath(pluginBean));
if (ap.evalXPath() != -1) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.PluginConfigManageDialog.msgTitle"),
Messages.getString("dialog.PluginConfigManageDialog.msg3"));
return false;
}
ap.resetXPath();
// 先判断此次添加的数据是否存在
String addData = manage.buildPluginData(pluginBean);
ap.selectXPath("/shortcuts");
if (ap.evalXPath() != -1) {
XMLModifier xm = new XMLModifier(vn);
xm.insertBeforeTail(addData + "\n");
FileOutputStream fos = new FileOutputStream(pluginXmlLocation);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
}
} catch (Exception e) {
LOGGER.error("", e);
}
return true;
}
public PluginConfigBean getCurPluginBean() {
return curPluginBean;
}
/**
* 初始化编辑数据
* @param pluginBean
* ;
*/
public void setEditInitData(PluginConfigBean pluginBean) {
nameTxt.setText(pluginBean.getName());
commandTxt.setText(pluginBean.getCommandLine());
switchTxt.setText(pluginBean.getOutputPath());
keyTxt.setText(pluginBean.getShortcutKey());
String output = pluginBean.getOutput();
if (output.equals(PluginConstants.SEGMENT)) {
outputSegemntBtn.setSelection(true);
} else if (output.equals(PluginConstants.DOCUMENT)) {
outputDocumentBtn.setSelection(true);
} else if (output.equals(PluginConstants.NONE)) {
outputBlankBtn.setSelection(true);
}
String input = pluginBean.getInput();
if (input.equals(PluginConstants.EXCHANGEFILE)) {
inputUpdateFileBtn.setSelection(true);
} else if (input.equals(PluginConstants.DOCUMENT)) {
inputUpdateDocuBtn.setSelection(true);
} else if (input.equals(PluginConstants.NONE)) {
inputBlankBtn.setSelection(true);
}
// 当前文本段的事件
if (outputSegemntBtn.getSelection()) {
inputUpdateFileBtn.setEnabled(true);
inputUpdateDocuBtn.setEnabled(false);
inputUpdateDocuBtn.setSelection(false);
inputBlankBtn.setEnabled(true);
switchTxt.setEnabled(true);
switchBrowseBtn.setEnabled(true);
}
// 当前文档的事件
if (outputDocumentBtn.getSelection()) {
inputUpdateFileBtn.setEnabled(false);
inputUpdateFileBtn.setSelection(false);
inputUpdateDocuBtn.setEnabled(true);
inputBlankBtn.setEnabled(true);
switchTxt.setEnabled(false);
switchTxt.setText("");
switchBrowseBtn.setEnabled(false);
}
// 进程中空格按钮的事件
if (outputBlankBtn.getSelection()) {
inputUpdateFileBtn.setEnabled(false);
inputUpdateFileBtn.setSelection(false);
inputUpdateDocuBtn.setEnabled(false);
inputUpdateDocuBtn.setSelection(false);
inputBlankBtn.setEnabled(false);
inputBlankBtn.setSelection(false);
switchTxt.setEnabled(false);
switchTxt.setText("");
switchBrowseBtn.setEnabled(false);
}
curPluginBean = pluginBean;
}
private void editPlugindata(PluginConfigBean bean) {
VTDGen vg = new VTDGen();
vg.parseFile(pluginXmlLocation, true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
try {
ap.selectXPath(manage.buildXpath(curPluginBean));
XMLModifier xm = new XMLModifier(vn);
while (ap.evalXPath() != -1) {
xm.remove();
xm.insertAfterElement(manage.buildPluginData(bean));
manage.updataPluginMenu(bean);
}
FileOutputStream fos = new FileOutputStream(pluginXmlLocation);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
} catch (Exception e) {
LOGGER.error("", e);
}
}
}
| 18,317 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
XSLTransformationDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/dialog/XSLTransformationDialog.java | package net.heartsome.cat.ts.ui.plugin.dialog;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import net.heartsome.cat.ts.ui.plugin.PluginConstants;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.cat.ts.ui.plugin.util.PluginUtil;
import net.heartsome.xml.Catalogue;
import net.heartsome.xml.HSErrorHandler;
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.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
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.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/**
* XSL Transformation 对话框
* @author peason
* @version
* @since JDK1.6
*/
public class XSLTransformationDialog extends Dialog {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);
/** 源文件文本框 */
private Text txtSource;
/** 源文件浏览按钮 */
private Button btnSource;
/** XSL 样式表文本框 */
private Text txtXSL;
/** XSL 样式表浏览按钮 */
private Button btnXSL;
/** 已转变文件文本框 */
private Text txtTarget;
/** 已转变文件浏览按钮 */
private Button btnTarget;
/** 是否打开文件复选框 */
private Button btnOpenFile;
/** Logo 图片路径 */
private String imagePath;
public XSLTransformationDialog(Shell parentShell) {
super(parentShell);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.XSLTransformationDialog.title"));
imagePath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_XSL_PATH);
newShell.setImage(new Image(Display.getDefault(), imagePath));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout(3, false));
GridDataFactory.fillDefaults().hint(450, 230).align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(tparent);
createMenu();
Label lblSource = new Label(tparent, SWT.None);
lblSource.setText(Messages.getString("dialog.XSLTransformationDialog.lblSource"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(lblSource);
txtSource = new Text(tparent, SWT.BORDER);
txtSource.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
txtSource.setEditable(false);
btnSource = new Button(tparent, SWT.None);
btnSource.setText(Messages.getString("dialog.XSLTransformationDialog.btnSource"));
Label lblXSL = new Label(tparent, SWT.None);
lblXSL.setText(Messages.getString("dialog.XSLTransformationDialog.lblXSL"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(lblXSL);
txtXSL = new Text(tparent, SWT.BORDER);
txtXSL.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
txtXSL.setEditable(false);
btnXSL = new Button(tparent, SWT.None);
btnXSL.setText(Messages.getString("dialog.XSLTransformationDialog.btnXSL"));
Label lblTarget = new Label(tparent, SWT.None);
lblTarget.setText(Messages.getString("dialog.XSLTransformationDialog.lblTarget"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(lblTarget);
txtTarget = new Text(tparent, SWT.BORDER);
txtTarget.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
txtTarget.setEditable(false);
btnTarget = new Button(tparent, SWT.None);
btnTarget.setText(Messages.getString("dialog.XSLTransformationDialog.btnTarget"));
btnOpenFile = new Button(tparent, SWT.CHECK);
btnOpenFile.setText(Messages.getString("dialog.XSLTransformationDialog.btnOpenFile"));
GridDataFactory.fillDefaults().span(3, 1).align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(btnOpenFile);
initListener();
tparent.layout();
getShell().layout();
return tparent;
}
/**
* 创建菜单 ;
*/
private void createMenu() {
Menu menu = new Menu(getShell(), SWT.BAR);
getShell().setMenuBar(menu);
getShell().pack();
Rectangle screenSize = Display.getDefault().getClientArea();
Rectangle frameSize = getShell().getBounds();
getShell().setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
Menu fileMenu = new Menu(menu);
MenuItem fileItem = new MenuItem(menu, SWT.CASCADE);
fileItem.setText(Messages.getString("dialog.XSLTransformationDialog.fileItem"));
fileItem.setMenu(fileMenu);
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText(Messages.getString("dialog.XSLTransformationDialog.exitItem"));
exitItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
close();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Menu helpMenu = new Menu(menu);
MenuItem helpItem = new MenuItem(menu, SWT.CASCADE);
helpItem.setText(Messages.getString("dialog.XSLTransformationDialog.helpMenu"));
helpItem.setMenu(helpMenu);
MenuItem aboutItem = new MenuItem(helpMenu, SWT.PUSH);
aboutItem.setText(Messages.getString("dialog.XSLTransformationDialog.aboutItem"));
String imgPath = PluginUtil.getAbsolutePath(PluginConstants.LOGO_XSL_MENU_PATH);
aboutItem.setImage(new Image(Display.getDefault(), imgPath));
aboutItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
AboutDialog dialog = new AboutDialog(getShell(), Messages
.getString("dialog.XSLTransformationDialog.aboutItemName"), imagePath, Messages
.getString("dialog.XSLTransformationDialog.aboutItemVersion"));
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
/**
* 初始化浏览按钮的监听 ;
*/
private void initListener() {
btnSource.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
openFileDialog(
txtSource,
SWT.OPEN,
Messages.getString("dialog.XSLTransformationDialog.fileDialogTitle1"),
new String[] { "*.hsxliff", "*.sdlxliff", "*.tmx", "*.tbx", "*.xml", "*" }, //$extension$
new String[] { Messages.getString("dialog.XSLTransformationDialog.filters1"),
Messages.getString("dialog.XSLTransformationDialog.filters2"),
Messages.getString("dialog.XSLTransformationDialog.filters3"),
Messages.getString("dialog.XSLTransformationDialog.filters4"),
Messages.getString("dialog.XSLTransformationDialog.filters5"),
Messages.getString("dialog.XSLTransformationDialog.filters6") });
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
btnXSL.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
openFileDialog(
txtXSL,
SWT.OPEN,
Messages.getString("dialog.XSLTransformationDialog.fileDialogTitle2"),
new String[] { "*.xsl", "*.xml", "*" },
new String[] { Messages.getString("dialog.XSLTransformationDialog.filters7"),
Messages.getString("dialog.XSLTransformationDialog.filters5"),
Messages.getString("dialog.XSLTransformationDialog.filters6") });
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
btnTarget.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
openFileDialog(txtTarget, SWT.SAVE,
Messages.getString("dialog.XSLTransformationDialog.fileDialogTitle3"), new String[] { "*" },
new String[] { Messages.getString("dialog.XSLTransformationDialog.filters6") });
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
/**
* 打开文件对话框
* @param txt
* 显示路径文本框
* @param style
* 对话框样式
* @param title
* 对话框标题
* @param extensions
* @param filterNames
* ;
*/
private void openFileDialog(Text txt, int style, String title, String[] extensions, String[] filterNames) {
FileDialog dialog = new FileDialog(getShell(), style);
dialog.setText(title);
dialog.setFilterExtensions(extensions);
dialog.setFilterNames(filterNames);
String fileSep = System.getProperty("file.separator");
if (txt.getText() != null && !txt.getText().trim().equals("")) {
dialog.setFilterPath(txt.getText().substring(0, txt.getText().lastIndexOf(fileSep)));
dialog.setFileName(txt.getText().substring(txt.getText().lastIndexOf(fileSep) + 1));
} else {
dialog.setFilterPath(System.getProperty("user.home"));
}
String path = dialog.open();
if (path != null) {
txt.setText(path);
}
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
getButton(IDialogConstants.OK_ID).setText(Messages.getString("dialog.XSLTransformationDialog.ok"));
getButton(IDialogConstants.CANCEL_ID).setText(Messages.getString("dialog.XSLTransformationDialog.cancel"));
getDialogArea().getParent().layout();
getShell().layout();
}
@Override
protected void okPressed() {
String strSourcePath = txtSource.getText();
String strXSLPath = txtXSL.getText();
String strTargetPath = txtTarget.getText();
if (strSourcePath.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.XSLTransformationDialog.msgTitle"),
Messages.getString("dialog.XSLTransformationDialog.msg1"));
return;
}
if (strXSLPath.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.XSLTransformationDialog.msgTitle"),
Messages.getString("dialog.XSLTransformationDialog.msg2"));
return;
}
if (strTargetPath.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.XSLTransformationDialog.msgTitle"),
Messages.getString("dialog.XSLTransformationDialog.msg3"));
return;
}
try {
transform(strSourcePath, strXSLPath, strTargetPath);
MessageDialog.openInformation(getShell(), Messages.getString("dialog.XSLTransformationDialog.msgTitle"),
Messages.getString("dialog.XSLTransformationDialog.msg4"));
if (btnOpenFile.getSelection()) {
if (!Program.launch(strTargetPath)) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.XSLTransformationDialog.msgTitle"),
Messages.getString("dialog.XSLTransformationDialog.msg5"));
}
}
close();
} catch (Exception e) {
LOGGER.error(Messages.getString("dialog.XSLTransformationDialog.logger1"), e);
}
}
/**
* 转换文件
* @param strSourcePath
* 源文件路径
* @param strXSLPath
* XSL 文件路径
* @param strTargetPath
* 转变文件路径
* @throws Exception
* ;
*/
private void transform(String strSourcePath, String strXSLPath, String strTargetPath) throws Exception {
TransformerFactory tfactory = TransformerFactory.newInstance();
String catalogPath = PluginUtil.getCataloguePath();
if (tfactory.getFeature(SAXSource.FEATURE)) {
// Standard way of creating an XMLReader in JAXP 1.1.
SAXParserFactory pfactory = SAXParserFactory.newInstance();
pfactory.setNamespaceAware(true); // Very important!
// Turn on validation.
// pfactory.setValidating(true);
// Get an XMLReader.
XMLReader reader = pfactory.newSAXParser().getXMLReader();
reader.setEntityResolver(new Catalogue(catalogPath));
// Instantiate an error handler (see the Handler inner class below)
// that will report any
// errors or warnings that occur as the XMLReader is parsing the XML
// input.
reader.setErrorHandler(new HSErrorHandler());
// Standard way of creating a transformer from a URL.
Transformer t = tfactory.newTransformer(new StreamSource(strXSLPath));
// Specify a SAXSource that takes both an XMLReader and a URL.
SAXSource source = new SAXSource(reader, new InputSource(strSourcePath));
// Transform to a file.
t.transform(source, new StreamResult(strTargetPath));
} else {
throw new Exception(Messages.getString("dialog.XSLTransformationDialog.msg6")); //$NON-NLS-1$
}
}
}
| 13,046 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CSV2TMXConverterHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/handler/CSV2TMXConverterHandler.java | package net.heartsome.cat.ts.ui.plugin.handler;
import net.heartsome.cat.ts.ui.plugin.dialog.CSV2TMXConverterDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* CSV to TMX Converter 的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class CSV2TMXConverterHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
CSV2TMXConverterDialog dialog = new CSV2TMXConverterDialog(HandlerUtil.getActiveShell(event));
dialog.open();
return null;
}
}
| 683 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginConfigurationHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/handler/PluginConfigurationHandler.java | package net.heartsome.cat.ts.ui.plugin.handler;
import net.heartsome.cat.ts.ui.plugin.dialog.PluginConfigurationDialog;
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;
public class PluginConfigurationHandler extends AbstractHandler{
public Object execute(ExecutionEvent event) throws ExecutionException {
Shell shell = HandlerUtil.getActiveShell(event);
PluginConfigurationDialog dialog = new PluginConfigurationDialog(shell);
dialog.open();
return null;
}
}
| 659 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/handler/PluginHandler.java | package net.heartsome.cat.ts.ui.plugin.handler;
import net.heartsome.cat.ts.ui.plugin.dialog.JavaPropertiesViewerDialog;
import net.heartsome.cat.ts.ui.plugin.dialog.TMX2TXTConverterDialog;
import net.heartsome.cat.ts.ui.plugin.dialog.TMXValidatorDialog;
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;
/**
* 四个插件的菜单触发类(Java Properties Viewer, RTFCleaner, TMX to TXT Converter, TMXValidator)
* @author robert 2012-03-09
* @version
* @since JDK1.6
*/
public class PluginHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
//插件的参数
String pluginID = event.getParameter("net.heartsome.cat.ts.ui.plugin.pluginID");
Shell shell = HandlerUtil.getActiveShell(event);
//Java Properties Viewer插件
if ("PropertiesViewer".equals(pluginID)) {
JavaPropertiesViewerDialog dialog = new JavaPropertiesViewerDialog(shell);
dialog.open();
}else if ("TMX2TXTConverter".equals(pluginID)) {
//TMX to TXT converter
TMX2TXTConverterDialog dialog = new TMX2TXTConverterDialog(shell);
dialog.open();
}else if ("TMXValidator".equals(pluginID)) {
TMXValidatorDialog dialog = new TMXValidatorDialog(shell);
dialog.open();
}
return null;
}
}
| 1,445 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Martif2TBXConverterHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/handler/Martif2TBXConverterHandler.java | package net.heartsome.cat.ts.ui.plugin.handler;
import net.heartsome.cat.ts.ui.plugin.dialog.Martif2TBXConverterDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* MARTIF to TBX Converter 的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class Martif2TBXConverterHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
Martif2TBXConverterDialog dialog = new Martif2TBXConverterDialog(HandlerUtil.getActiveShell(event));
dialog.open();
return null;
}
}
| 698 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TBXMakerHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/handler/TBXMakerHandler.java | package net.heartsome.cat.ts.ui.plugin.handler;
import net.heartsome.cat.ts.ui.plugin.dialog.TBXMakerDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* TBXMaker 的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class TBXMakerHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
TBXMakerDialog dialog = new TBXMakerDialog(HandlerUtil.getActivePart(event).getSite().getShell());
dialog.open();
return null;
}
}
| 659 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RTFCleanerHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/handler/RTFCleanerHandler.java | package net.heartsome.cat.ts.ui.plugin.handler;
import net.heartsome.cat.ts.ui.plugin.dialog.RTFCleanerDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* RTFCleaner 的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class RTFCleanerHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
RTFCleanerDialog dialog = new RTFCleanerDialog(HandlerUtil.getActiveShell(event));
dialog.open();
return null;
}
}
| 649 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
XSLTransformationHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/handler/XSLTransformationHandler.java | package net.heartsome.cat.ts.ui.plugin.handler;
import net.heartsome.cat.ts.ui.plugin.dialog.XSLTransformationDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* XSL Transformation 的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class XSLTransformationHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
XSLTransformationDialog dialog = new XSLTransformationDialog(HandlerUtil.getActivePart(event).getSite().getShell());
dialog.open();
return null;
}
}
| 705 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RTFCleaner.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/util/RTFCleaner.java | package net.heartsome.cat.ts.ui.plugin.util;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Hashtable;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 清理 RTF 文件(与 R7 中 net.heartsome.plugin.rtfcleaner.RTFCleaner
* 类代码一样)
* @author peason
* @version
* @since JDK1.6
*/
public class RTFCleaner {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);
private static FileInputStream input;
private static FileOutputStream output;
private static String content;
private static Hashtable<String, String> styles;
private static Hashtable<String, String> chars;
private static int EOFStyles;
/**
* 私有构造方法
*/
private RTFCleaner() {
// do not instantiate this class
}
public static Vector<String> run(Hashtable<String, String> table) {
Vector<String> result = new Vector<String>();
try {
String inputFile = table.get("source"); //$NON-NLS-1$
String outputFile = table.get("output"); //$NON-NLS-1$
// read the file into a String
input = new FileInputStream(inputFile);
int size = input.available();
byte[] array = new byte[size];
input.read(array);
content = new String(array, "US-ASCII"); //$NON-NLS-1$
array = null;
input.close();
content = content.replaceAll("\\\\\\{", "\uE001"); //$NON-NLS-1$ //$NON-NLS-2$
content = content.replaceAll("\\\\\\}", "\uE002"); //$NON-NLS-1$ //$NON-NLS-2$
content = content.replaceAll("\\\\\\\\", "\uE003"); //$NON-NLS-1$ //$NON-NLS-2$
buildStyleSheet();
fillChars();
String leftPart = content.substring(0, EOFStyles);
content = content.substring(EOFStyles);
removeHidden();
output = new FileOutputStream(outputFile);
leftPart = leftPart.replaceAll("\uE001", "\\\\{"); //$NON-NLS-1$ //$NON-NLS-2$
leftPart = leftPart.replaceAll("\uE002", "\\\\}"); //$NON-NLS-1$ //$NON-NLS-2$
leftPart = leftPart.replaceAll("\uE003", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$
output.write(leftPart.getBytes("US-ASCII")); //$NON-NLS-1$
content = content.replaceAll("\uE001", "\\\\{"); //$NON-NLS-1$ //$NON-NLS-2$
content = content.replaceAll("\uE002", "\\\\}"); //$NON-NLS-1$ //$NON-NLS-2$
content = content.replaceAll("\uE003", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$
output.write(content.getBytes("US-ASCII")); //$NON-NLS-1$
output.close();
result.add("0"); //$NON-NLS-1$
} catch (Exception e) {
LOGGER.error(Messages.getString("util.RTFCleaner.logger1"), e);
result.add("1"); //$NON-NLS-1$
result.add(e.getMessage());
}
return result;
}
/**
* 初始化 chars 变量
* ;
*/
private static void fillChars() {
chars = new Hashtable<String, String>();
chars.put("\\emdash", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\endash", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\lquote", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\rquote", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\ldblquote", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\rdblquote", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\tab", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\enspace", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\emspace", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\qmspace", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\~", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\_", ""); //$NON-NLS-1$ //$NON-NLS-2$
chars.put("\\-", ""); //$NON-NLS-1$ //$NON-NLS-2$
}
private static void removeHidden() throws Exception {
Stack<Boolean> stack = new Stack<Boolean>();
stack.push(new Boolean(false));
boolean inHidden = false;
StringTokenizer tk = new StringTokenizer(content, "{}\\", true); //$NON-NLS-1$
StringBuffer buffer = new StringBuffer();
while (tk.hasMoreTokens()) {
String token = tk.nextToken();
if (token.equals("{")) { //$NON-NLS-1$
stack.push(new Boolean(inHidden));
buffer.append(token);
continue;
}
if (token.equals("}")) { //$NON-NLS-1$
if (!stack.isEmpty()) {
inHidden = stack.pop().booleanValue();
} else {
throw new Exception(Messages.getString("util.RTFCleaner.msg1")); //$NON-NLS-1$
}
buffer.append(token);
continue;
}
if (token.equals("\\")) { //$NON-NLS-1$
token = token + tk.nextToken();
}
if (token.equals("\\*")) { //$NON-NLS-1$
token = token + tk.nextToken() + tk.nextToken();
}
if (token.matches("\\\\pard.*")) { //$NON-NLS-1$
inHidden = false;
stack.pop();
stack.push(new Boolean(false));
}
String control = getControl(token);
if (control.equals("\\v0")) { //$NON-NLS-1$
inHidden = false;
}
if (control.equals("\\v")) { //$NON-NLS-1$
control = ""; //$NON-NLS-1$
inHidden = true;
}
if (styles.containsKey(control)) {
inHidden = true;
}
if (inHidden) {
if (control.matches("\\\\uc.*")) { //$NON-NLS-1$
control = ""; //$NON-NLS-1$
} else if (control.matches("\\\\u[0-9]+.*")) { //$NON-NLS-1$
control = ""; //$NON-NLS-1$
} else if (control.matches("\\\\\'.*")) { //$NON-NLS-1$
control = ""; //$NON-NLS-1$
} else if (chars.containsKey(control)) {
control = ""; //$NON-NLS-1$
}
buffer.append(control);
} else {
buffer.append(token);
}
}
content = buffer.toString();
}
private static String getControl(String token) {
StringBuffer buffer = new StringBuffer();
int i = 0;
for (; i < token.length(); i++) {
char c = token.charAt(i);
if (c == '\\' || c == '*') {
buffer.append(c);
} else {
break;
}
}
for (; i < token.length(); i++) {
char c = token.charAt(i);
if (c == '\'') {
buffer.append(c);
buffer.append(token.charAt(i + 1));
buffer.append(token.charAt(i + 2));
return buffer.toString();
}
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
break;
}
buffer.append(c);
}
for (; i < token.length(); i++) {
char c = token.charAt(i);
if ((c >= '0' && c <= '9') || c == '-') {
buffer.append(c);
} else {
break;
}
}
return buffer.toString();
}
private static void buildStyleSheet() {
int i = content.indexOf('{', content.indexOf("\\stylesheet") + 11); //$NON-NLS-1$
int level = 0;
StringBuffer buffer = new StringBuffer();
styles = new Hashtable<String, String>();
while (level >= 0) {
char c = content.charAt(i++);
buffer.append(c);
if (c == '{') {
level++;
}
if (c == '}') {
level--;
}
if (level == 0) {
String style = buffer.toString().trim();
if (style.matches(".*\\\\v[^0].*")) { //$NON-NLS-1$
StringTokenizer tk = new StringTokenizer(style, "\\"); //$NON-NLS-1$
while (tk.hasMoreElements()) {
String token = tk.nextToken();
if (token.matches(".*cs[0-9]+.*")) { //$NON-NLS-1$
styles.put("\\" + token.trim(), ""); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
buffer = null;
buffer = new StringBuffer();
}
}
EOFStyles = i;
}
}
| 7,100 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PluginUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/util/PluginUtil.java | package net.heartsome.cat.ts.ui.plugin.util;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import net.heartsome.cat.ts.ui.plugin.Activator;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 工具类
* @author peason
* @version
* @since JDK1.6
*/
public class PluginUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);
/**
* 根据相对路径获取绝对路径
* @param relativePath
* @return ;
*/
public static String getAbsolutePath(String relativePath) {
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL defaultUrl = buddle.getEntry(relativePath);
String imagePath = relativePath;
try {
imagePath = new File(FileLocator.toFileURL(defaultUrl).getPath()).getAbsolutePath();
} catch (IOException e) {
LOGGER.error(Messages.getString("util.PluginUtil.logger1"), e);
e.printStackTrace();
}
return imagePath;
}
/**
* 获取 catalogue.xml 所在路径
* @return ;
*/
public static String getCataloguePath() {
String path = Platform.getConfigurationLocation().getURL().getPath();
String catalogPath = path + "net.heartsome.cat.converter" + System.getProperty("file.separator") + "catalogue"
+ System.getProperty("file.separator") + "catalogue.xml";
return catalogPath;
}
/**
* 获取 XCS 模板所在路径
* @return ;
*/
public static String getTemplatePath() {
String path = Platform.getConfigurationLocation().getURL().getPath();
String templatePath = path + "net.heartsome.cat.converter" + System.getProperty("file.separator") + "templates";
return templatePath;
}
public static String getConfigurationFilePath(String filePath) {
StringBuffer configPath = new StringBuffer(
new File(Platform.getConfigurationLocation().getURL().getPath()).getAbsolutePath());
return configPath.append(File.separator).append("net.heartsome.cat.ts.ui.plugin").append(File.separator).append(filePath).toString();
}
/**
* 创建 Label,文本右对齐
* @param parent
* 父控件
* @param text
* Label 上显示的文本
*/
public static void createLabel(Composite parent, String text) {
Label lbl = new Label(parent, SWT.None);
lbl.setText(text);
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).grab(false, false).applyTo(lbl);
}
}
| 2,682 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Martif2Tbx.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/ts/net.heartsome.cat.ts.ui.plugin/src/net/heartsome/cat/ts/ui/plugin/util/Martif2Tbx.java | package net.heartsome.cat.ts.ui.plugin.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import net.heartsome.cat.ts.ui.plugin.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* 将 MARTIF 文件转换为 TBX 文件(参考了 R7 中 net.heartsome.plugin.martif2tbx.model.Martif2Tbx
* 类的代码,将其改成了 VTD 实现)
* @author peason
* @version
* @since JDK1.6
*/
public class Martif2Tbx {
/** tbx 标准中的语言属性名称 */
private static String tbxLangDescriptor = "xml:lang";
/** martif 标准中的语言属性名称 */
private static String martifLangDescriptor = "lang";
/** id 属性名称 */
private static String idDescriptor = "id";
/** TBX 文件输出流 */
private FileOutputStream fos;
/**
* 构造方法
*/
public Martif2Tbx() {
}
/**
* 创建 TBX 文件,初始化 fos 对象
* @param mainLanguage
* 语言代码
* @param tbxFilePath
* tbx 文件路径
* @throws Exception
* ;
*/
private void createDocument(String mainLanguage, String tbxFilePath) throws Exception {
fos = new FileOutputStream(tbxFilePath);
writeString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
writeString("<!DOCTYPE martif PUBLIC \"TBXcoreStructureDTD-v-1-0.DTT\" >\n");
String str = "<martif type=\"TBX\" ";
if (mainLanguage == null) {
mainLanguage = "";
}
str += tbxLangDescriptor + "=\"" + mainLanguage + "\"";
str += ">\n";
writeString(str);
writeString("<martifHeader>\n");
}
private void writeString(String input) throws UnsupportedEncodingException, IOException {
fos.write(input.getBytes("UTF-8"));
}
/**
* 删除 martif 文件中的 Doctype
* @param input
* martif 文件路径
* @param output
* 临时文件路径
* @throws Exception
* ;
*/
private void removeDocTypeDeclaration(String input, String output) throws Exception {
FileInputStream is = new FileInputStream(input);
FileOutputStream os = new FileOutputStream(output);
int size = is.available();
byte[] array = new byte[size];
is.read(array);
String file = new String(array, "UTF-8");
// remove xml declaration and doctype
int begin = file.indexOf("<" + "martif");
if (begin != -1) {
os.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>".getBytes("UTF-8"));
os.write(file.substring(begin).getBytes("UTF-8"));
} else {
throw new Exception(Messages.getString("util.Martif2Tbx.msg1"));
}
is.close();
os.close();
}
/**
* 将 martif 文件转换为 TBX 文件
* @param filename
* martif 路径及文件名
* @param output
* tbx 文件路径及文件名
* @throws Exception
* ;
*/
public void convertFile(String filename, String output) throws Exception {
File temp = File.createTempFile("tmp", ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
removeDocTypeDeclaration(filename, temp.getAbsolutePath());
VTDGen vg = new VTDGen();
if (vg.parseFile(temp.getAbsolutePath(), true)) {
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/martif");
if (ap.evalXPath() == -1) {
throw new Exception(Messages.getString("util.Martif2Tbx.msg1"));
}
String lang = vu.getCurrentElementAttribut(martifLangDescriptor, null);
createDocument(lang, output);
ap.selectXPath("/martif/martifHeader");
if (ap.evalXPath() != -1) {
vn.push();
String martifRevisionDesc = vu.getChildContent("revisionDesc");
if (martifRevisionDesc != null) {
writeString("<tbxRevisionDesc>\n");
writeString(martifRevisionDesc);
writeString("</tbxRevisionDesc>\n");
}
vn.pop();
vn.push();
String martifDatabaseDesc = vu.getChildContent("databaseDesc");
if (martifDatabaseDesc != null) {
writeString("<tbxdatabaseDesc>\n");
writeString(martifDatabaseDesc);
writeString("</tbxdatabaseDesc>\n");
}
writeString("</martifHeader>\n");
vn.pop();
}
ap.selectXPath("/martif/text/body/termEntry");
writeString("<text>\n");
writeString("<body>\n");
AutoPilot ap3 = new AutoPilot(vn);
while (ap.evalXPath() != -1) {
String id = vu.getCurrentElementAttribut(idDescriptor, null);
String termEntry = "<termEntry ";
if (id != null) {
termEntry += idDescriptor + "=\"" + id + "\"";
}
termEntry += ">\n";
writeString(termEntry);
vn.push();
ap3.selectXPath("./*");
while (ap3.evalXPath() != -1) {
String name = vu.getCurrentElementName();
if (name.equals("note")) {
String note = vu.getElementFragment();
if (note != null) {
writeString(note);
writeString("\n");
}
} else if (name.equals("langSet")) {
String language = vu.getCurrentElementAttribut(martifLangDescriptor, "");
writeString("<langSet " + tbxLangDescriptor + "=\"" + language + "\">\n");
AutoPilot ap4 = new AutoPilot(vn);
ap4.selectXPath("./ntig/termGrp/*");
writeString("<ntig>\n");
writeString("<termGrp>\n");
while (ap4.evalXPath() != -1) {
String nodeName = vu.getCurrentElementName();
if (nodeName.equals("term")) {
writeString(vu.getElementFragment());
writeString("\n");
} else {
String type = vu.getCurrentElementAttribut("type", "");
if (!type.equals("")) {
writeString("<termNote type=\"" + type + "\">\n");
writeString(vu.getElementContent());
writeString("</termNote>\n");
}
}
}
writeString("</termGrp>\n");
writeString("</ntig>\n");
writeString("</langSet>\n");
} else {
// String xpath2 = "./*[not(name()='note' or name()='langSet')]";
int index = -1;
if ((index = vn.getAttrVal("type")) != -1) {
String type = vn.toString(index);
String content = getChildElementPureText(vn);
writeString("<descrip type=\"" + type + "\">\n");
writeString(content);
writeString("</descrip>\n");
}
}
}
writeString("</termEntry>\n");
vn.pop();
}
writeString("</body>\n");
writeString("</text>\n");
writeString("</maritif>");
}
}
/**
* 得到当前子节点的纯文本。实体会被转义。若无文本内容返回 null。
* @exception XPathParseException
* ,XPathEvalException,NavException
*/
public String getChildElementPureText(VTDNav vn) throws XPathParseException, XPathEvalException, NavException {
String txtNode = ".//text()";
AutoPilot ap = new AutoPilot(vn);
StringBuilder result = new StringBuilder();
ap.selectXPath(txtNode);
int txtIndex = -1;
boolean isNull = true;
while ((txtIndex = ap.evalXPath()) != -1) {
result.append(vn.toString(txtIndex));
if (isNull) {
isNull = false;
}
}
return isNull ? null : result.toString();
}
}
| 7,206 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.